From 02c3c6d3e69ccc8ccdc12e0101c5d267ecba4f3d Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 13:03:57 -0600 Subject: [PATCH 01/20] use cobra/viper and move cmd/pilosa to server subcommand --- cmd/pilosa/main.go | 190 +---------------- cmd/root.go | 14 ++ cmd/server.go | 90 ++++++++ glide.lock | 50 ++++- glide.yaml | 2 + server/server.go | 197 ++++++++++++++++++ .../main_test.go => server/server_test.go | 10 +- 7 files changed, 360 insertions(+), 193 deletions(-) create mode 100644 cmd/root.go create mode 100644 cmd/server.go create mode 100644 server/server.go rename cmd/pilosa/main_test.go => server/server_test.go (99%) diff --git a/cmd/pilosa/main.go b/cmd/pilosa/main.go index 4f7474996..255aef606 100644 --- a/cmd/pilosa/main.go +++ b/cmd/pilosa/main.go @@ -1,197 +1,15 @@ package main import ( - "errors" - "flag" "fmt" - "io" - "math/rand" "os" - "os/signal" - "path/filepath" - "runtime/pprof" - "strings" - "time" - "github.com/BurntSushi/toml" - "github.com/pilosa/pilosa" -) - -// Version and BuildTime hold the version/build time information passed in at compile time. -var ( - Version string - BuildTime string -) - -func init() { - if Version == "" { - Version = "v0.0.0" - } - if BuildTime == "" { - BuildTime = "not recorded" - } - - rand.Seed(time.Now().UTC().UnixNano()) -} - -const ( - // DefaultDataDir is the default data directory. - DefaultDataDir = "~/.pilosa" + "github.com/pilosa/pilosa/cmd" ) func main() { - m := NewMain() - m.Server.Handler.Version = Version - fmt.Fprintf(m.Stderr, "Pilosa %s, build time %s\n", Version, BuildTime) - - // Parse command line arguments. - if err := m.ParseFlags(os.Args[1:]); err != nil { - fmt.Fprintln(m.Stderr, err) - os.Exit(2) - } - - // Start CPU profiling. - if m.CPUProfile != "" { - f, err := os.Create(m.CPUProfile) - if err != nil { - fmt.Fprintf(m.Stderr, "create cpu profile: %v", err) - os.Exit(1) - } - defer f.Close() - - fmt.Fprintln(m.Stderr, "Starting cpu profile") - pprof.StartCPUProfile(f) - time.AfterFunc(m.CPUTime, func() { - fmt.Fprintln(m.Stderr, "Stopping cpu profile") - pprof.StopCPUProfile() - f.Close() - }) - } - - // Execute the program. - if err := m.Run(); err != nil { - fmt.Fprintln(m.Stderr, err) - fmt.Fprintln(m.Stderr, "stopping profile") - os.Exit(1) - } - - // First SIGKILL causes server to shut down gracefully. - c := make(chan os.Signal, 2) - signal.Notify(c, os.Interrupt) - sig := <-c - fmt.Fprintf(m.Stderr, "Received %s; gracefully shutting down...\n", sig.String()) - - // Second signal causes a hard shutdown. - go func() { <-c; os.Exit(1) }() - - if err := m.Close(); err != nil { - fmt.Fprintln(m.Stderr, err) - os.Exit(1) + if err := cmd.RootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(-1) } } - -// Main represents the main program execution. -type Main struct { - Server *pilosa.Server - - // Configuration options. - ConfigPath string - Config *pilosa.Config - - // Profiling options. - CPUProfile string - CPUTime time.Duration - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewMain returns a new instance of Main. -func NewMain() *Main { - return &Main{ - Server: pilosa.NewServer(), - Config: pilosa.NewConfig(), - - Stdin: os.Stdin, - Stdout: os.Stdout, - Stderr: os.Stderr, - } -} - -// Run executes the main program execution. -func (m *Main) Run(args ...string) error { - // Notify user of config file. - if m.ConfigPath != "" { - fmt.Fprintf(m.Stdout, "Using config: %s\n", m.ConfigPath) - } - - // Setup logging output. - m.Server.LogOutput = m.Stderr - - // Configure index. - fmt.Fprintf(m.Stderr, "Using data from: %s\n", m.Config.DataDir) - m.Server.Index.Path = m.Config.DataDir - m.Server.Index.Stats = pilosa.NewExpvarStatsClient() - - // Build cluster from config file. - m.Server.Host = m.Config.Host - m.Server.Cluster = m.Config.PilosaCluster() - - // Set configuration options. - m.Server.AntiEntropyInterval = time.Duration(m.Config.AntiEntropy.Interval) - - // Initialize server. - if err := m.Server.Open(); err != nil { - return err - } - - fmt.Fprintf(m.Stderr, "Listening as http://%s\n", m.Server.Host) - - return nil -} - -// Close shuts down the server. -func (m *Main) Close() error { - return m.Server.Close() -} - -// ParseFlags parses command line flags from args. -func (m *Main) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosa", flag.ContinueOnError) - fs.StringVar(&m.CPUProfile, "cpuprofile", "", "cpu profile") - fs.DurationVar(&m.CPUTime, "cputime", 30*time.Second, "cpu profile duration") - fs.StringVar(&m.ConfigPath, "config", "", "config path") - fs.SetOutput(m.Stderr) - if err := fs.Parse(args); err != nil { - return err - } - - // Load config, if specified. - if m.ConfigPath != "" { - if _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil { - return err - } - } - - // Use default data directory if one is not specified. - if m.Config.DataDir == "" { - m.Config.DataDir = DefaultDataDir - } - - // Expand home directory. - prefix := "~" + string(filepath.Separator) - if strings.HasPrefix(m.Config.DataDir, prefix) { - // u, err := user.Current() - HomeDir := os.Getenv("HOME") - /*if err != nil { - return err - } else*/if HomeDir == "" { - return errors.New("data directory not specified and no home dir available") - } - m.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix)) - } - - return nil -} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 000000000..91d866a18 --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,14 @@ +package cmd + +import "github.com/spf13/cobra" + +var RootCmd = &cobra.Command{ + Use: "pilosa", + Short: "pilosa - A Distributed In-memory Binary Bitmap Index", + Long: `Pilosa is a fast index to turbocharge your database. + +This binary contains Pilosa itself, as well as common +tools for administering pilosa, importing/exporting data, +backing up, and more. Complete documentation is available +at http://pilosa.com/docs`, // TODO - is documentation actually there? +} diff --git a/cmd/server.go b/cmd/server.go new file mode 100644 index 000000000..cc8bbec49 --- /dev/null +++ b/cmd/server.go @@ -0,0 +1,90 @@ +package cmd + +import ( + "fmt" + "log" + "os" + "os/signal" + "runtime/pprof" + "time" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/server" +) + +var serve = server.NewMain() + +var serveCmd = &cobra.Command{ + Use: "server", + Short: "server - run the pilosa server", + Long: `pilosa server runs Pilosa. + +It will load existing data from the configured +directory, and start listening client connections +on the configured port.`, + Run: func(cmd *cobra.Command, args []string) { + serve.Server.Handler.Version = server.Version + fmt.Fprintf(serve.Stderr, "Pilosa %s, build time %s\n", server.Version, server.BuildTime) + + // Parse command line arguments. + if err := serve.ParseFlags(os.Args[1:]); err != nil { + fmt.Fprintln(serve.Stderr, err) + os.Exit(2) + } + + // Start CPU profiling. + if serve.CPUProfile != "" { + f, err := os.Create(serve.CPUProfile) + if err != nil { + fmt.Fprintf(serve.Stderr, "create cpu profile: %v", err) + os.Exit(1) + } + defer f.Close() + + fmt.Fprintln(serve.Stderr, "Starting cpu profile") + pprof.StartCPUProfile(f) + time.AfterFunc(serve.CPUTime, func() { + fmt.Fprintln(serve.Stderr, "Stopping cpu profile") + pprof.StopCPUProfile() + f.Close() + }) + } + + // Execute the program. + if err := serve.Run(); err != nil { + fmt.Fprintln(serve.Stderr, err) + fmt.Fprintln(serve.Stderr, "stopping profile") + os.Exit(1) + } + + // First SIGKILL causes server to shut down gracefully. + c := make(chan os.Signal, 2) + signal.Notify(c, os.Interrupt) + sig := <-c + fmt.Fprintf(serve.Stderr, "Received %s; gracefully shutting down...\n", sig.String()) + + // Second signal causes a hard shutdown. + go func() { <-c; os.Exit(1) }() + + if err := serve.Close(); err != nil { + fmt.Fprintln(serve.Stderr, err) + os.Exit(1) + } + + }, +} + +func init() { + serveCmd.Flags().StringVarP(&serve.ConfigPath, "config", "c", "", "Configuration file to read from") + serveCmd.Flags().StringVarP(&serve.CPUProfile, "cpuprofile", "", "", "Where to store CPU profile") + serveCmd.Flags().DurationVarP(&serve.CPUTime, "cputime", "", 30*time.Second, "CPU profile duration") + + err := viper.BindPFlags(serveCmd.Flags()) + if err != nil { + log.Fatalf("Error binding server flags: %v", err) + } + + RootCmd.AddCommand(serveCmd) +} diff --git a/glide.lock b/glide.lock index af94d5502..001257bf1 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 469de49a1736f34a11e9b0e490f7c1da1d8cb0219fed4bf3ad9e71344ca7f58a -updated: 2017-02-09T17:03:01.816613507-06:00 +hash: 7de62dbaf3cc1dc4959f4f6d8213102cb182b4dd7a87b3ac29260ad6bc1b0cef +updated: 2017-03-03T12:25:48.088390296-06:00 imports: - name: github.com/boltdb/bolt version: 4b1ebc1869ad66568b313d0dc410e2be72670dda @@ -13,6 +13,8 @@ imports: version: 346938d642f2ec3594ed81d874461961cd0faa76 subpackages: - spew +- name: github.com/fsnotify/fsnotify + version: 7d7316ed6e1ed2de075aab8dfc76de5d158d66e1 - name: github.com/gogo/protobuf version: a9cd0c35b97daf74d0ebf3514c5254814b2703b4 subpackages: @@ -23,10 +25,54 @@ imports: - lru - name: github.com/golang/protobuf version: 888eb0692c857ec880338addf316bd662d5e630e + subpackages: + - proto +- name: github.com/hashicorp/hcl + version: 630949a3c5fa3c613328e1b8256052cbc2327c9b + subpackages: + - hcl/ast + - hcl/parser + - hcl/scanner + - hcl/strconv + - hcl/token + - json/parser + - json/scanner + - json/token +- name: github.com/inconshreveable/mousetrap + version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 +- name: github.com/magiconair/properties + version: b3b15ef068fd0b17ddf408a23669f20811d194d2 +- name: github.com/mitchellh/mapstructure + version: db1efb556f84b25a0a13a04aad883943538ad2e0 +- name: github.com/pelletier/go-buffruneio + version: c37440a7cf42ac63b919c752ca73a85067e05992 +- name: github.com/pelletier/go-toml + version: 13d49d4606eb801b8f01ae542b4afc4c6ee3d84a - name: github.com/satori/go.uuid version: 879c5887cd475cd7864858769793b2ceb0d44feb +- name: github.com/spf13/afero + version: 9be650865eab0c12963d8753212f4f9c66cdcf12 + subpackages: + - mem +- name: github.com/spf13/cast + version: 4f1683a2242a92e62d6ff705a30e435cbf2b50a3 +- name: github.com/spf13/cobra + version: fcd0c5a1df88f5d6784cb4feead962c3f3d0b66c +- name: github.com/spf13/jwalterweatherman + version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 +- name: github.com/spf13/pflag + version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7 +- name: github.com/spf13/viper + version: 7538d73b4eb9511d85a9f1dfef202eeb8ac260f4 - name: golang.org/x/sys version: c200b10b5d5e122be351b67af224adc6128af5bf subpackages: - unix +- name: golang.org/x/text + version: 5a42fa2464759cbb7ee0af9de00b54d69f09a29c + subpackages: + - transform + - unicode/norm +- name: gopkg.in/yaml.v2 + version: a3f3340b5840cee44f372bddb5880fcbc419b46a testImports: [] diff --git a/glide.yaml b/glide.yaml index 10c8509d0..1c4f35dae 100644 --- a/glide.yaml +++ b/glide.yaml @@ -27,3 +27,5 @@ import: - package: github.com/golang/protobuf - package: github.com/satori/go.uuid version: ^1.1.0 +- package: github.com/spf13/cobra +- package: github.com/spf13/viper diff --git a/server/server.go b/server/server.go new file mode 100644 index 000000000..bb151a37d --- /dev/null +++ b/server/server.go @@ -0,0 +1,197 @@ +package server + +import ( + "errors" + "flag" + "fmt" + "io" + "math/rand" + "os" + "os/signal" + "path/filepath" + "runtime/pprof" + "strings" + "time" + + "github.com/BurntSushi/toml" + "github.com/pilosa/pilosa" +) + +// Version and BuildTime hold the version/build time information passed in at compile time. +var ( + Version string + BuildTime string +) + +func init() { + if Version == "" { + Version = "v0.0.0" + } + if BuildTime == "" { + BuildTime = "not recorded" + } + + rand.Seed(time.Now().UTC().UnixNano()) +} + +const ( + // DefaultDataDir is the default data directory. + DefaultDataDir = "~/.pilosa" +) + +func mainz() { + serve := NewMain() + serve.Server.Handler.Version = Version + fmt.Fprintf(serve.Stderr, "Pilosa %s, build time %s\n", Version, BuildTime) + + // Parse command line arguments. + if err := serve.ParseFlags(os.Args[1:]); err != nil { + fmt.Fprintln(serve.Stderr, err) + os.Exit(2) + } + + // Start CPU profiling. + if serve.CPUProfile != "" { + f, err := os.Create(serve.CPUProfile) + if err != nil { + fmt.Fprintf(serve.Stderr, "create cpu profile: %v", err) + os.Exit(1) + } + defer f.Close() + + fmt.Fprintln(serve.Stderr, "Starting cpu profile") + pprof.StartCPUProfile(f) + time.AfterFunc(serve.CPUTime, func() { + fmt.Fprintln(serve.Stderr, "Stopping cpu profile") + pprof.StopCPUProfile() + f.Close() + }) + } + + // Execute the program. + if err := serve.Run(); err != nil { + fmt.Fprintln(serve.Stderr, err) + fmt.Fprintln(serve.Stderr, "stopping profile") + os.Exit(1) + } + + // First SIGKILL causes server to shut down gracefully. + c := make(chan os.Signal, 2) + signal.Notify(c, os.Interrupt) + sig := <-c + fmt.Fprintf(serve.Stderr, "Received %s; gracefully shutting down...\n", sig.String()) + + // Second signal causes a hard shutdown. + go func() { <-c; os.Exit(1) }() + + if err := serve.Close(); err != nil { + fmt.Fprintln(serve.Stderr, err) + os.Exit(1) + } +} + +// Main represents the main program execution. +type Main struct { + Server *pilosa.Server + + // Configuration options. + ConfigPath string + Config *pilosa.Config + + // Profiling options. + CPUProfile string + CPUTime time.Duration + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewMain returns a new instance of Main. +func NewMain() *Main { + return &Main{ + Server: pilosa.NewServer(), + Config: pilosa.NewConfig(), + + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run executes the main program execution. +func (m *Main) Run(args ...string) error { + // Notify user of config file. + if m.ConfigPath != "" { + fmt.Fprintf(m.Stdout, "Using config: %s\n", m.ConfigPath) + } + + // Setup logging output. + m.Server.LogOutput = m.Stderr + + // Configure index. + fmt.Fprintf(m.Stderr, "Using data from: %s\n", m.Config.DataDir) + m.Server.Index.Path = m.Config.DataDir + m.Server.Index.Stats = pilosa.NewExpvarStatsClient() + + // Build cluster from config file. + m.Server.Host = m.Config.Host + m.Server.Cluster = m.Config.PilosaCluster() + + // Set configuration options. + m.Server.AntiEntropyInterval = time.Duration(m.Config.AntiEntropy.Interval) + + // Initialize server. + if err := m.Server.Open(); err != nil { + return err + } + + fmt.Fprintf(m.Stderr, "Listening as http://%s\n", m.Server.Host) + + return nil +} + +// Close shuts down the server. +func (m *Main) Close() error { + return m.Server.Close() +} + +// ParseFlags parses command line flags from args. +func (m *Main) ParseFlags(args []string) error { + fs := flag.NewFlagSet("pilosa", flag.ContinueOnError) + fs.StringVar(&m.CPUProfile, "cpuprofile", "", "cpu profile") + fs.DurationVar(&m.CPUTime, "cputime", 30*time.Second, "cpu profile duration") + fs.StringVar(&m.ConfigPath, "config", "", "config path") + fs.SetOutput(m.Stderr) + if err := fs.Parse(args); err != nil { + return err + } + + // Load config, if specified. + if m.ConfigPath != "" { + if _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil { + return err + } + } + + // Use default data directory if one is not specified. + if m.Config.DataDir == "" { + m.Config.DataDir = DefaultDataDir + } + + // Expand home directory. + prefix := "~" + string(filepath.Separator) + if strings.HasPrefix(m.Config.DataDir, prefix) { + // u, err := user.Current() + HomeDir := os.Getenv("HOME") + /*if err != nil { + return err + } else*/if HomeDir == "" { + return errors.New("data directory not specified and no home dir available") + } + m.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix)) + } + + return nil +} diff --git a/cmd/pilosa/main_test.go b/server/server_test.go similarity index 99% rename from cmd/pilosa/main_test.go rename to server/server_test.go index 184f5c334..bb772ab45 100644 --- a/cmd/pilosa/main_test.go +++ b/server/server_test.go @@ -1,4 +1,4 @@ -package main_test +package server_test import ( "bytes" @@ -18,7 +18,7 @@ import ( "github.com/BurntSushi/toml" "github.com/pilosa/pilosa" - main "github.com/pilosa/pilosa/cmd/pilosa" + "github.com/pilosa/pilosa/server" ) // Ensure program can process queries and maintain consistency. @@ -304,7 +304,7 @@ path = "/path/to/plugins" // Main represents a test wrapper for main.Main. type Main struct { - *main.Main + *server.Main Stdin bytes.Buffer Stdout bytes.Buffer @@ -318,7 +318,7 @@ func NewMain() *Main { panic(err) } - m := &Main{Main: main.NewMain()} + m := &Main{Main: server.NewMain()} m.Config.DataDir = path m.Config.Host = "localhost:0" m.Main.Stdin = &m.Stdin @@ -356,7 +356,7 @@ func (m *Main) Reopen() error { // Create new main with the same config. config := m.Config - m.Main = main.NewMain() + m.Main = server.NewMain() m.Config = config // Run new program. From ed43eca004396b001124cf8955267f9db7c13a71 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 13:35:06 -0600 Subject: [PATCH 02/20] move "config" to subcommand --- cmd/config.go | 29 ++++++++++++++++++++++ cmd/pilosactl/main.go | 57 ------------------------------------------- ctl/config.go | 43 ++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 57 deletions(-) create mode 100644 cmd/config.go create mode 100644 ctl/config.go diff --git a/cmd/config.go b/cmd/config.go new file mode 100644 index 000000000..72202ffe3 --- /dev/null +++ b/cmd/config.go @@ -0,0 +1,29 @@ +package cmd + +import ( + "context" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/pilosa/pilosa/ctl" +) + +var conf = ctl.NewConfigCommand(os.Stdin, os.Stdout, os.Stderr) + +var confCmd = &cobra.Command{ + Use: "config", + Short: "config - prints the default configuration", + Long: `config prints the default configuration to stdout +`, + Run: func(cmd *cobra.Command, args []string) { + if err := conf.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + RootCmd.AddCommand(confCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index 88fa6fea5..8327839fe 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -96,7 +96,6 @@ Usage: The commands are: - config prints the default configuration import imports data from a CSV file export exports data to a CSV file sort sorts a data file for optimal import speed @@ -126,8 +125,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "config": - m.Cmd = NewConfigCommand(m.Stdin, m.Stdout, m.Stderr) case "import": m.Cmd = pilosactl.NewImportCommand(m.Stdin, m.Stdout, m.Stderr) case "export": @@ -167,60 +164,6 @@ type Command interface { Run(context.Context) error } -// ConfigCommand represents a command for printing a default config. -type ConfigCommand struct { - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewConfigCommand returns a new instance of ConfigCommand. -func NewConfigCommand(stdin io.Reader, stdout, stderr io.Writer) *ConfigCommand { - return &ConfigCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *ConfigCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - if err := fs.Parse(args); err != nil { - return err - } - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *ConfigCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl config - -Prints the default configuration file to standard out. -`) -} - -// Run executes the main program execution. -func (cmd *ConfigCommand) Run(ctx context.Context) error { - fmt.Fprintln(cmd.Stdout, strings.TrimSpace(` -data-dir = "~/.pilosa" -host = "localhost:15000" - -[cluster] -replicas = 1 - -[[cluster.node]] -host = "localhost:15000" - -[plugins] -path = "" -`)+"\n") - return nil -} - // ExportCommand represents a command for bulk exporting data from a server. type ExportCommand struct { // Remote host and port. diff --git a/ctl/config.go b/ctl/config.go new file mode 100644 index 000000000..516069e2d --- /dev/null +++ b/ctl/config.go @@ -0,0 +1,43 @@ +package ctl + +import ( + "context" + "fmt" + "io" + "strings" +) + +// ConfigCommand represents a command for printing a default config. +type ConfigCommand struct { + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewConfigCommand returns a new instance of ConfigCommand. +func NewConfigCommand(stdin io.Reader, stdout, stderr io.Writer) *ConfigCommand { + return &ConfigCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// Run executes the main program execution. +func (cmd *ConfigCommand) Run(ctx context.Context) error { + fmt.Fprintln(cmd.Stdout, strings.TrimSpace(` +data-dir = "~/.pilosa" +host = "localhost:15000" + +[cluster] +replicas = 1 + +[[cluster.node]] +host = "localhost:15000" + +[plugins] +path = "" +`)+"\n") + return nil +} From e349dca06ac1bae7561f13f2a8407e215fdaa284 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 14:11:12 -0600 Subject: [PATCH 03/20] move import to subcommand --- cmd/import.go | 50 ++++++++++++++++++++++++++++++++++++ cmd/pilosactl/main.go | 3 --- {pilosactl => ctl}/import.go | 40 +---------------------------- 3 files changed, 51 insertions(+), 42 deletions(-) create mode 100644 cmd/import.go rename {pilosactl => ctl}/import.go (78%) diff --git a/cmd/import.go b/cmd/import.go new file mode 100644 index 000000000..af1a7fcd5 --- /dev/null +++ b/cmd/import.go @@ -0,0 +1,50 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/ctl" +) + +var importer = ctl.NewImportCommand(os.Stdin, os.Stdout, os.Stderr) + +var importCmd = &cobra.Command{ + Use: "import", + Short: "import - import data to pilosa", + Long: `Bulk imports one or more CSV files to a host's database and frame. The bits +of the CSV file are grouped by slice for the most efficient import. + +The format of the CSV file is: + + BITMAPID,PROFILEID,[TIME] + +The file should contain no headers. The TIME column is optional and can be +omitted. If it is present then its format should be YYYY-MM-DDTHH:MM. +`, + Run: func(cmd *cobra.Command, args []string) { + importer.Paths = args + if err := importer.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + importCmd.Flags().StringVarP(&importer.Host, "host", "", "localhost:15000", "host:port of Pilosa.") + importCmd.Flags().StringVarP(&importer.Database, "database", "d", "", "Pilosa database to import into.") + importCmd.Flags().StringVarP(&importer.Frame, "frame", "f", "", "Frame to import into.") + importCmd.Flags().IntVarP(&importer.BufferSize, "buffer-size", "s", 10000000, "Number of bits to buffer/sort before importing.") + + err := viper.BindPFlags(importCmd.Flags()) + if err != nil { + log.Fatalf("Error binding import flags: %v", err) + } + + RootCmd.AddCommand(importCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index 8327839fe..8b0980815 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -22,7 +22,6 @@ import ( "unsafe" "github.com/pilosa/pilosa" - "github.com/pilosa/pilosa/pilosactl" "github.com/pilosa/pilosa/roaring" ) @@ -125,8 +124,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "import": - m.Cmd = pilosactl.NewImportCommand(m.Stdin, m.Stdout, m.Stderr) case "export": m.Cmd = NewExportCommand(m.Stdin, m.Stdout, m.Stderr) case "sort": diff --git a/pilosactl/import.go b/ctl/import.go similarity index 78% rename from pilosactl/import.go rename to ctl/import.go index 9d4ad63f4..39e46eb3d 100644 --- a/pilosactl/import.go +++ b/ctl/import.go @@ -1,17 +1,14 @@ -package pilosactl +package ctl import ( "context" "encoding/csv" "errors" - "flag" "fmt" "io" - "io/ioutil" "log" "os" "strconv" - "strings" "time" "github.com/pilosa/pilosa" @@ -56,41 +53,6 @@ func (cmd *ImportCommand) String() string { return fmt.Sprint(*cmd) } -// ParseFlags parses command line flags from args. -func (cmd *ImportCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") - fs.StringVar(&cmd.Database, "d", "", "database") - fs.StringVar(&cmd.Frame, "f", "", "frame") - fs.IntVar(&cmd.BufferSize, "buffer-size", cmd.BufferSize, "buffer size") - if err := fs.Parse(args); err != nil { - return err - } - - // Extract the import paths. - cmd.Paths = fs.Args() - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *ImportCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl import -host HOST -d database -f frame paths - -Bulk imports one or more CSV files to a host's database and frame. The bits -of the CSV file are grouped by slice for the most efficient import. - -The format of the CSV file is: - - BITMAPID,PROFILEID,[TIME] - -The file should contain no headers. The TIME column is optional and can be -omitted. If it is present then its format should be YYYY-MM-DDTHH:MM. -`) -} - // Run executes the main program execution. func (cmd *ImportCommand) Run(ctx context.Context) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) From 362539fe2dd4ecb906248e6375f85d87573148fc Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 14:18:52 -0600 Subject: [PATCH 04/20] make export a subcommand --- cmd/export.go | 49 ++++++++++++++++++ cmd/pilosactl/main.go | 116 ------------------------------------------ ctl/export.go | 91 +++++++++++++++++++++++++++++++++ 3 files changed, 140 insertions(+), 116 deletions(-) create mode 100644 cmd/export.go create mode 100644 ctl/export.go diff --git a/cmd/export.go b/cmd/export.go new file mode 100644 index 000000000..16afd2475 --- /dev/null +++ b/cmd/export.go @@ -0,0 +1,49 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/ctl" +) + +var exporter = ctl.NewExportCommand(os.Stdin, os.Stdout, os.Stderr) + +var exportCmd = &cobra.Command{ + Use: "export", + Short: "export - export data from pilosa", + Long: ` +Bulk exports a fragment to a CSV file. If the OUTFILE is not specified then +the output is written to STDOUT. + +The format of the CSV file is: + + BITMAPID,PROFILEID + +The file does not contain any headers. +`, + Run: func(cmd *cobra.Command, args []string) { + if err := exporter.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + exportCmd.Flags().StringVarP(&exporter.Host, "host", "", "localhost:15000", "host:port of Pilosa.") + exportCmd.Flags().StringVarP(&exporter.Database, "database", "d", "", "Pilosa database to export into.") + exportCmd.Flags().StringVarP(&exporter.Frame, "frame", "f", "", "Frame to export into.") + exportCmd.Flags().StringVarP(&exporter.Frame, "output-file", "o", "", "File to write export to - default stdout") + + err := viper.BindPFlags(exportCmd.Flags()) + if err != nil { + log.Fatalf("Error binding export flags: %v", err) + } + + RootCmd.AddCommand(exportCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index 8b0980815..a1524bc35 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -95,8 +95,6 @@ Usage: The commands are: - import imports data from a CSV file - export exports data to a CSV file sort sorts a data file for optimal import speed backup backs up a frame to an archive file restore restores a frame from an archive file @@ -124,8 +122,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "export": - m.Cmd = NewExportCommand(m.Stdin, m.Stdout, m.Stderr) case "sort": m.Cmd = NewSortCommand(m.Stdin, m.Stdout, m.Stderr) case "backup": @@ -161,118 +157,6 @@ type Command interface { Run(context.Context) error } -// ExportCommand represents a command for bulk exporting data from a server. -type ExportCommand struct { - // Remote host and port. - Host string - - // Name of the database & frame to export from. - Database string - Frame string - - // Filename to export to. - Path string - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewExportCommand returns a new instance of ExportCommand. -func NewExportCommand(stdin io.Reader, stdout, stderr io.Writer) *ExportCommand { - return &ExportCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *ExportCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") - fs.StringVar(&cmd.Database, "d", "", "database") - fs.StringVar(&cmd.Frame, "f", "", "frame") - fs.StringVar(&cmd.Path, "o", "", "output file") - if err := fs.Parse(args); err != nil { - return err - } - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *ExportCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl export -host HOST -d database -f frame -o OUTFILE - -Bulk exports a fragment to a CSV file. If the OUTFILE is not specified then -the output is written to STDOUT. - -The format of the CSV file is: - - BITMAPID,PROFILEID - -The file does not contain any headers. -`) -} - -// Run executes the main program execution. -func (cmd *ExportCommand) Run(ctx context.Context) error { - logger := log.New(cmd.Stderr, "", log.LstdFlags) - - // Validate arguments. - if cmd.Database == "" { - return pilosa.ErrDatabaseRequired - } else if cmd.Frame == "" { - return pilosa.ErrFrameRequired - } - - // Use output file, if specified. - // Otherwise use STDOUT. - var w io.Writer = cmd.Stdout - if cmd.Path != "" { - f, err := os.Create(cmd.Path) - if err != nil { - return err - } - defer f.Close() - - w = f - } - - // Create a client to the server. - client, err := pilosa.NewClient(cmd.Host) - if err != nil { - return err - } - - // Determine slice count. - maxSlices, err := client.MaxSliceByDatabase(ctx) - if err != nil { - return err - } - - // Export each slice. - for slice := uint64(0); slice <= maxSlices[cmd.Database]; slice++ { - logger.Printf("exporting slice: %d", slice) - if err := client.ExportCSV(ctx, cmd.Database, cmd.Frame, slice, w); err != nil { - return err - } - } - - // Close writer, if applicable. - if w, ok := w.(io.Closer); ok { - if err := w.Close(); err != nil { - return err - } - } - - return nil -} - // SortCommand represents a command for sorting import data. type SortCommand struct { // Filename to sort diff --git a/ctl/export.go b/ctl/export.go new file mode 100644 index 000000000..f19c7123f --- /dev/null +++ b/ctl/export.go @@ -0,0 +1,91 @@ +package ctl + +import ( + "context" + "io" + "log" + "os" + + "github.com/pilosa/pilosa" +) + +// ExportCommand represents a command for bulk exporting data from a server. +type ExportCommand struct { + // Remote host and port. + Host string + + // Name of the database & frame to export from. + Database string + Frame string + + // Filename to export to. + Path string + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewExportCommand returns a new instance of ExportCommand. +func NewExportCommand(stdin io.Reader, stdout, stderr io.Writer) *ExportCommand { + return &ExportCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// Run executes the main program execution. +func (cmd *ExportCommand) Run(ctx context.Context) error { + logger := log.New(cmd.Stderr, "", log.LstdFlags) + + // Validate arguments. + if cmd.Database == "" { + return pilosa.ErrDatabaseRequired + } else if cmd.Frame == "" { + return pilosa.ErrFrameRequired + } + + // Use output file, if specified. + // Otherwise use STDOUT. + var w io.Writer = cmd.Stdout + if cmd.Path != "" { + f, err := os.Create(cmd.Path) + if err != nil { + return err + } + defer f.Close() + + w = f + } + + // Create a client to the server. + client, err := pilosa.NewClient(cmd.Host) + if err != nil { + return err + } + + // Determine slice count. + maxSlices, err := client.MaxSliceByDatabase(ctx) + if err != nil { + return err + } + + // Export each slice. + for slice := uint64(0); slice <= maxSlices[cmd.Database]; slice++ { + logger.Printf("exporting slice: %d", slice) + if err := client.ExportCSV(ctx, cmd.Database, cmd.Frame, slice, w); err != nil { + return err + } + } + + // Close writer, if applicable. + if w, ok := w.(io.Closer); ok { + if err := w.Close(); err != nil { + return err + } + } + + return nil +} From 312a9a533430eafefddd79bcc58a919f0e09d2fe Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 14:38:44 -0600 Subject: [PATCH 05/20] move sort to subcommand --- cmd/pilosactl/main.go | 164 ------------------------------------------ cmd/sort.go | 45 ++++++++++++ ctl/sort.go | 138 +++++++++++++++++++++++++++++++++++ 3 files changed, 183 insertions(+), 164 deletions(-) create mode 100644 cmd/sort.go create mode 100644 ctl/sort.go diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index a1524bc35..e3052ac12 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -1,20 +1,15 @@ package main import ( - "bufio" "context" - "encoding/csv" "errors" "flag" "fmt" "io" "io/ioutil" - "log" "math/rand" "os" "path/filepath" - "sort" - "strconv" "strings" "syscall" "text/tabwriter" @@ -95,7 +90,6 @@ Usage: The commands are: - sort sorts a data file for optimal import speed backup backs up a frame to an archive file restore restores a frame from an archive file inspect inspects fragment data files @@ -122,8 +116,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "sort": - m.Cmd = NewSortCommand(m.Stdin, m.Stdout, m.Stderr) case "backup": m.Cmd = NewBackupCommand(m.Stdin, m.Stdout, m.Stderr) case "restore": @@ -157,120 +149,6 @@ type Command interface { Run(context.Context) error } -// SortCommand represents a command for sorting import data. -type SortCommand struct { - // Filename to sort - Path string - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewSortCommand returns a new instance of SortCommand. -func NewSortCommand(stdin io.Reader, stdout, stderr io.Writer) *SortCommand { - return &SortCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *SortCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - if err := fs.Parse(args); err != nil { - return err - } - - // Extract the data path. - if fs.NArg() == 0 { - return errors.New("path required") - } else if fs.NArg() > 1 { - return errors.New("only one path allowed") - } - cmd.Path = fs.Arg(0) - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *SortCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl sort PATH - -Sorts the import data at PATH into the optimal sort order for importing. - -The format of the CSV file is: - - BITMAPID,PROFILEID - -The file should contain no headers. -`) -} - -// Run executes the main program execution. -func (cmd *SortCommand) Run(ctx context.Context) error { - // Open file for reading. - f, err := os.Open(cmd.Path) - if err != nil { - return err - } - defer f.Close() - - // Read rows as bits. - r := csv.NewReader(f) - r.FieldsPerRecord = -1 - a := make([]pilosa.Bit, 0, 1000000) - for { - bitmapID, profileID, timestamp, err := readCSVRow(r) - if err == io.EOF { - break - } else if err == errBlank { - continue - } else if err != nil { - return err - } - a = append(a, pilosa.Bit{BitmapID: bitmapID, ProfileID: profileID, Timestamp: timestamp}) - } - - // Sort bits by position. - sort.Sort(pilosa.BitsByPos(a)) - - // Rewrite to STDOUT. - w := bufio.NewWriter(cmd.Stdout) - buf := make([]byte, 0, 1024) - for _, bit := range a { - // Write CSV to buffer. - buf = buf[:0] - buf = strconv.AppendUint(buf, bit.BitmapID, 10) - - buf = append(buf, ',') - buf = strconv.AppendUint(buf, bit.ProfileID, 10) - - if bit.Timestamp != 0 { - buf = append(buf, ',') - buf = append(buf, time.Unix(0, bit.Timestamp).UTC().Format(pilosa.TimeFormat)...) - } - - buf = append(buf, '\n') - - // Write to output. - if _, err := w.Write(buf); err != nil { - return err - } - } - - // Ensure buffer is flushed before exiting. - if err := w.Flush(); err != nil { - return err - } - - return nil -} - // BackupCommand represents a command for backing up a frame. type BackupCommand struct { // Destination host and port. @@ -808,45 +686,3 @@ func (cmd *BenchCommand) runSetBit(ctx context.Context, client *pilosa.Client) e return nil } - -// readCSVRow reads a bitmap/profile pair from a CSV row. -func readCSVRow(r *csv.Reader) (bitmapID, profileID uint64, timestamp int64, err error) { - // Read CSV row. - record, err := r.Read() - if err != nil { - return 0, 0, 0, err - } - - // Ignore blank rows. - if record[0] == "" { - return 0, 0, 0, errBlank - } else if len(record) < 2 { - return 0, 0, 0, fmt.Errorf("bad column count: %d", len(record)) - } - - // Parse bitmap id. - bitmapID, err = strconv.ParseUint(record[0], 10, 64) - if err != nil { - return 0, 0, 0, fmt.Errorf("invalid bitmap id: %q", record[0]) - } - - // Parse bitmap id. - profileID, err = strconv.ParseUint(record[1], 10, 64) - if err != nil { - return 0, 0, 0, fmt.Errorf("invalid profile id: %q", record[1]) - } - - // Parse timestamp, if available. - if len(record) > 2 && record[2] != "" { - t, err := time.Parse(pilosa.TimeFormat, record[2]) - if err != nil { - return 0, 0, 0, fmt.Errorf("invalid timestamp: %q", record[2]) - } - timestamp = t.UnixNano() - } - - return bitmapID, profileID, timestamp, nil -} - -// errBlank indicates a blank row in a CSV file. -var errBlank = errors.New("blank row") diff --git a/cmd/sort.go b/cmd/sort.go new file mode 100644 index 000000000..813624ddc --- /dev/null +++ b/cmd/sort.go @@ -0,0 +1,45 @@ +package cmd + +import ( + "context" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/pilosa/pilosa/ctl" +) + +var sorter = ctl.NewSortCommand(os.Stdin, os.Stdout, os.Stderr) + +var sortCmd = &cobra.Command{ + Use: "sort ", + Short: "sort - sort import data for optimal import performance", + Long: ` +Sorts the import data at PATH into the optimal sort order for importing. + +The format of the CSV file is: + + BITMAPID,PROFILEID + +The file should contain no headers. +`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println(cmd.Flags()) + if len(args) == 0 { + fmt.Println("path required") + return + } else if len(args) > 1 { + fmt.Println("only one path supported") + return + } + sorter.Path = args[0] + if err := sorter.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + RootCmd.AddCommand(sortCmd) +} diff --git a/ctl/sort.go b/ctl/sort.go new file mode 100644 index 000000000..eac68b7ab --- /dev/null +++ b/ctl/sort.go @@ -0,0 +1,138 @@ +package ctl + +import ( + "bufio" + "context" + "encoding/csv" + "errors" + "fmt" + "io" + "os" + "sort" + "strconv" + "time" + + "github.com/pilosa/pilosa" +) + +// SortCommand represents a command for sorting import data. +type SortCommand struct { + // Filename to sort + Path string + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewSortCommand returns a new instance of SortCommand. +func NewSortCommand(stdin io.Reader, stdout, stderr io.Writer) *SortCommand { + return &SortCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// Run executes the main program execution. +func (cmd *SortCommand) Run(ctx context.Context) error { + // Open file for reading. + f, err := os.Open(cmd.Path) + if err != nil { + return err + } + defer f.Close() + + // Read rows as bits. + r := csv.NewReader(f) + r.FieldsPerRecord = -1 + a := make([]pilosa.Bit, 0, 1000000) + for { + bitmapID, profileID, timestamp, err := readCSVRow(r) + if err == io.EOF { + break + } else if err == errBlank { + continue + } else if err != nil { + return err + } + a = append(a, pilosa.Bit{BitmapID: bitmapID, ProfileID: profileID, Timestamp: timestamp}) + } + + // Sort bits by position. + sort.Sort(pilosa.BitsByPos(a)) + + // Rewrite to STDOUT. + w := bufio.NewWriter(cmd.Stdout) + buf := make([]byte, 0, 1024) + for _, bit := range a { + // Write CSV to buffer. + buf = buf[:0] + buf = strconv.AppendUint(buf, bit.BitmapID, 10) + + buf = append(buf, ',') + buf = strconv.AppendUint(buf, bit.ProfileID, 10) + + if bit.Timestamp != 0 { + buf = append(buf, ',') + buf = append(buf, time.Unix(0, bit.Timestamp).UTC().Format(pilosa.TimeFormat)...) + } + + buf = append(buf, '\n') + + // Write to output. + if _, err := w.Write(buf); err != nil { + return err + } + } + + // Ensure buffer is flushed before exiting. + if err := w.Flush(); err != nil { + return err + } + + return nil +} + +// readCSVRow reads a bitmap/profile pair from a CSV row. +func readCSVRow(r *csv.Reader) (bitmapID, profileID uint64, timestamp int64, err error) { + // Read CSV row. + record, err := r.Read() + if err != nil { + return 0, 0, 0, err + } + + // Ignore blank rows. + if record[0] == "" { + return 0, 0, 0, errBlank + } else if len(record) < 2 { + return 0, 0, 0, fmt.Errorf("bad column count: %d", len(record)) + } + + // Parse bitmap id. + bitmapID, err = strconv.ParseUint(record[0], 10, 64) + if err != nil { + return 0, 0, 0, fmt.Errorf("invalid bitmap id: %q", record[0]) + } + + // Parse bitmap id. + profileID, err = strconv.ParseUint(record[1], 10, 64) + if err != nil { + return 0, 0, 0, fmt.Errorf("invalid profile id: %q", record[1]) + } + + // Parse timestamp, if available. + if len(record) > 2 && record[2] != "" { + t, err := time.Parse(pilosa.TimeFormat, record[2]) + if err != nil { + return 0, 0, 0, fmt.Errorf("invalid timestamp: %q", record[2]) + } + timestamp = t.UnixNano() + } + + return bitmapID, profileID, timestamp, nil +} + +// errBlank indicates a blank row in a CSV file. +var errBlank = errors.New("blank row") From f20e6c193d01207ead2191ddd318d28a1d0ef155 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 14:46:45 -0600 Subject: [PATCH 06/20] move backup to subcommand --- cmd/backup.go | 42 ++++++++++++++++++++ cmd/pilosactl/main.go | 89 ------------------------------------------- ctl/backup.go | 72 ++++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 89 deletions(-) create mode 100644 cmd/backup.go create mode 100644 ctl/backup.go diff --git a/cmd/backup.go b/cmd/backup.go new file mode 100644 index 000000000..883ce7be8 --- /dev/null +++ b/cmd/backup.go @@ -0,0 +1,42 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/ctl" +) + +var backuper = ctl.NewBackupCommand(os.Stdin, os.Stdout, os.Stderr) + +var backupCmd = &cobra.Command{ + Use: "backup", + Short: "backup - backup data from pilosa", + Long: ` +Backs up the database and frame from across the cluster into a single file. +`, + Run: func(cmd *cobra.Command, args []string) { + if err := backuper.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + backupCmd.Flags().StringVarP(&backuper.Host, "host", "", "localhost:15000", "host:port of Pilosa.") + backupCmd.Flags().StringVarP(&backuper.Database, "database", "d", "", "Pilosa database to backup into.") + backupCmd.Flags().StringVarP(&backuper.Frame, "frame", "f", "", "Frame to backup into.") + backupCmd.Flags().StringVarP(&backuper.Path, "output-file", "o", "", "File to write backup to - default stdout") + + err := viper.BindPFlags(backupCmd.Flags()) + if err != nil { + log.Fatalf("Error binding backup flags: %v", err) + } + + RootCmd.AddCommand(backupCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index e3052ac12..72399e9b2 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -90,7 +90,6 @@ Usage: The commands are: - backup backs up a frame to an archive file restore restores a frame from an archive file inspect inspects fragment data files check performs a consistency check of data files @@ -116,8 +115,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "backup": - m.Cmd = NewBackupCommand(m.Stdin, m.Stdout, m.Stderr) case "restore": m.Cmd = NewRestoreCommand(m.Stdin, m.Stdout, m.Stderr) case "inspect": @@ -149,92 +146,6 @@ type Command interface { Run(context.Context) error } -// BackupCommand represents a command for backing up a frame. -type BackupCommand struct { - // Destination host and port. - Host string - - // Name of the database & frame to backup. - Database string - Frame string - - // Output file to write to. - Path string - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewBackupCommand returns a new instance of BackupCommand. -func NewBackupCommand(stdin io.Reader, stdout, stderr io.Writer) *BackupCommand { - return &BackupCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *BackupCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") - fs.StringVar(&cmd.Database, "d", "", "database") - fs.StringVar(&cmd.Frame, "f", "", "frame") - fs.StringVar(&cmd.Path, "o", "", "output file") - if err := fs.Parse(args); err != nil { - return err - } - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *BackupCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl backup -host HOST -d database -f frame -o PATH - -Backs up the database and frame from across the cluster into a single file. -`) -} - -// Run executes the main program execution. -func (cmd *BackupCommand) Run(ctx context.Context) error { - // Validate arguments. - if cmd.Path == "" { - return errors.New("output file required") - } - - // Create a client to the server. - client, err := pilosa.NewClient(cmd.Host) - if err != nil { - return err - } - - // Open output file. - f, err := os.Create(cmd.Path) - if err != nil { - return err - } - defer f.Close() - - // Begin streaming backup. - if err := client.BackupTo(ctx, f, cmd.Database, cmd.Frame); err != nil { - return err - } - - // Sync & close file to ensure durability. - if err := f.Sync(); err != nil { - return err - } else if err = f.Close(); err != nil { - return err - } - - return nil -} - // RestoreCommand represents a command for restoring a frame from a backup. type RestoreCommand struct { // Destination host and port. diff --git a/ctl/backup.go b/ctl/backup.go new file mode 100644 index 000000000..23b34cd1f --- /dev/null +++ b/ctl/backup.go @@ -0,0 +1,72 @@ +package ctl + +import ( + "context" + "errors" + "io" + "os" + + "github.com/pilosa/pilosa" +) + +// BackupCommand represents a command for backing up a frame. +type BackupCommand struct { + // Destination host and port. + Host string + + // Name of the database & frame to backup. + Database string + Frame string + + // Output file to write to. + Path string + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewBackupCommand returns a new instance of BackupCommand. +func NewBackupCommand(stdin io.Reader, stdout, stderr io.Writer) *BackupCommand { + return &BackupCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// Run executes the main program execution. +func (cmd *BackupCommand) Run(ctx context.Context) error { + // Validate arguments. + if cmd.Path == "" { + return errors.New("output file required") + } + + // Create a client to the server. + client, err := pilosa.NewClient(cmd.Host) + if err != nil { + return err + } + + // Open output file. + f, err := os.Create(cmd.Path) + if err != nil { + return err + } + defer f.Close() + + // Begin streaming backup. + if err := client.BackupTo(ctx, f, cmd.Database, cmd.Frame); err != nil { + return err + } + + // Sync & close file to ensure durability. + if err := f.Sync(); err != nil { + return err + } else if err = f.Close(); err != nil { + return err + } + + return nil +} From 6dc164da69ed49543997245b06b06edc22aee1e6 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 14:47:47 -0600 Subject: [PATCH 07/20] fix copy/paste bug in export subcommand --- cmd/export.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/export.go b/cmd/export.go index 16afd2475..a5cd0f62d 100644 --- a/cmd/export.go +++ b/cmd/export.go @@ -38,7 +38,7 @@ func init() { exportCmd.Flags().StringVarP(&exporter.Host, "host", "", "localhost:15000", "host:port of Pilosa.") exportCmd.Flags().StringVarP(&exporter.Database, "database", "d", "", "Pilosa database to export into.") exportCmd.Flags().StringVarP(&exporter.Frame, "frame", "f", "", "Frame to export into.") - exportCmd.Flags().StringVarP(&exporter.Frame, "output-file", "o", "", "File to write export to - default stdout") + exportCmd.Flags().StringVarP(&exporter.Path, "output-file", "o", "", "File to write export to - default stdout") err := viper.BindPFlags(exportCmd.Flags()) if err != nil { From 21478cb85270052e4817d9f26a1c5431757c377a Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 14:53:35 -0600 Subject: [PATCH 08/20] move restore to subcommand --- cmd/pilosactl/main.go | 89 ------------------------------------------- cmd/restore.go | 42 ++++++++++++++++++++ ctl/restore.go | 65 +++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 89 deletions(-) create mode 100644 cmd/restore.go create mode 100644 ctl/restore.go diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index 72399e9b2..ee77ba2a8 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -90,7 +90,6 @@ Usage: The commands are: - restore restores a frame from an archive file inspect inspects fragment data files check performs a consistency check of data files bench benchmarks operations @@ -115,8 +114,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "restore": - m.Cmd = NewRestoreCommand(m.Stdin, m.Stdout, m.Stderr) case "inspect": m.Cmd = NewInspectCommand(m.Stdin, m.Stdout, m.Stderr) case "check": @@ -146,92 +143,6 @@ type Command interface { Run(context.Context) error } -// RestoreCommand represents a command for restoring a frame from a backup. -type RestoreCommand struct { - // Destination host and port. - Host string - - // Name of the database & frame to backup. - Database string - Frame string - - // Import file to read from. - Path string - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewRestoreCommand returns a new instance of RestoreCommand. -func NewRestoreCommand(stdin io.Reader, stdout, stderr io.Writer) *RestoreCommand { - return &RestoreCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *RestoreCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") - fs.StringVar(&cmd.Database, "d", "", "database") - fs.StringVar(&cmd.Frame, "f", "", "frame") - if err := fs.Parse(args); err != nil { - return err - } - - // Read input path from the args. - if fs.NArg() == 0 { - return errors.New("path required") - } else if fs.NArg() > 1 { - return errors.New("too many paths specified") - } - cmd.Path = fs.Arg(0) - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *RestoreCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl restore -host HOST -d database -f frame PATH - -Restores a frame to the cluster from a backup file. -`) -} - -// Run executes the main program execution. -func (cmd *RestoreCommand) Run(ctx context.Context) error { - // Validate arguments. - if cmd.Path == "" { - return errors.New("backup file required") - } - - // Create a client to the server. - client, err := pilosa.NewClient(cmd.Host) - if err != nil { - return err - } - - // Open backup file. - f, err := os.Open(cmd.Path) - if err != nil { - return err - } - defer f.Close() - - // Restore backup file to the cluster. - if err := client.RestoreFrom(ctx, f, cmd.Database, cmd.Frame); err != nil { - return err - } - - return nil -} - // InspectCommand represents a command for inspecting fragment data files. type InspectCommand struct { // Path to data file diff --git a/cmd/restore.go b/cmd/restore.go new file mode 100644 index 000000000..420cd9c5f --- /dev/null +++ b/cmd/restore.go @@ -0,0 +1,42 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/ctl" +) + +var restorer = ctl.NewRestoreCommand(os.Stdin, os.Stdout, os.Stderr) + +var restoreCmd = &cobra.Command{ + Use: "restore", + Short: "restore - restore data to pilosa", + Long: ` +Restores a frame to the cluster from a backup file. +`, + Run: func(cmd *cobra.Command, args []string) { + if err := restorer.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + restoreCmd.Flags().StringVarP(&restorer.Host, "host", "", "localhost:15000", "host:port of Pilosa.") + restoreCmd.Flags().StringVarP(&restorer.Database, "database", "d", "", "Pilosa database to restore into.") + restoreCmd.Flags().StringVarP(&restorer.Frame, "frame", "f", "", "Frame to restore into.") + restoreCmd.Flags().StringVarP(&restorer.Path, "input-file", "i", "", "File to write restore from") + + err := viper.BindPFlags(restoreCmd.Flags()) + if err != nil { + log.Fatalf("Error binding restore flags: %v", err) + } + + RootCmd.AddCommand(restoreCmd) +} diff --git a/ctl/restore.go b/ctl/restore.go new file mode 100644 index 000000000..b9a573704 --- /dev/null +++ b/ctl/restore.go @@ -0,0 +1,65 @@ +package ctl + +import ( + "context" + "errors" + "io" + "os" + + "github.com/pilosa/pilosa" +) + +// RestoreCommand represents a command for restoring a frame from a backup. +type RestoreCommand struct { + // Destination host and port. + Host string + + // Name of the database & frame to backup. + Database string + Frame string + + // Import file to read from. + Path string + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewRestoreCommand returns a new instance of RestoreCommand. +func NewRestoreCommand(stdin io.Reader, stdout, stderr io.Writer) *RestoreCommand { + return &RestoreCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// Run executes the main program execution. +func (cmd *RestoreCommand) Run(ctx context.Context) error { + // Validate arguments. + if cmd.Path == "" { + return errors.New("backup file required") + } + + // Create a client to the server. + client, err := pilosa.NewClient(cmd.Host) + if err != nil { + return err + } + + // Open backup file. + f, err := os.Open(cmd.Path) + if err != nil { + return err + } + defer f.Close() + + // Restore backup file to the cluster. + if err := client.RestoreFrom(ctx, f, cmd.Database, cmd.Frame); err != nil { + return err + } + + return nil +} From 2c1929a063f7560c9ea95ba644c89ceeeff5768d Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 15:00:54 -0600 Subject: [PATCH 09/20] move inspect to subcommand --- cmd/inspect.go | 39 +++++++++++++ cmd/pilosactl/main.go | 114 ------------------------------------- ctl/inspect.go | 127 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+), 114 deletions(-) create mode 100644 cmd/inspect.go create mode 100644 ctl/inspect.go diff --git a/cmd/inspect.go b/cmd/inspect.go new file mode 100644 index 000000000..48bbf8308 --- /dev/null +++ b/cmd/inspect.go @@ -0,0 +1,39 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/ctl" +) + +var inspecter = ctl.NewInspectCommand(os.Stdin, os.Stdout, os.Stderr) + +var inspectCmd = &cobra.Command{ + Use: "inspect", + Short: "inspect - inspect a pilosa data file", + Long: ` +Inspects a data file and provides stats. +`, + Run: func(cmd *cobra.Command, args []string) { + if err := inspecter.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + inspectCmd.Flags().StringVarP(&inspecter.Path, "file", "i", "", "File to inspect") + + err := viper.BindPFlags(inspectCmd.Flags()) + if err != nil { + log.Fatalf("Error binding inspect flags: %v", err) + } + + RootCmd.AddCommand(inspectCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index ee77ba2a8..a04be0b02 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -12,9 +12,7 @@ import ( "path/filepath" "strings" "syscall" - "text/tabwriter" "time" - "unsafe" "github.com/pilosa/pilosa" "github.com/pilosa/pilosa/roaring" @@ -90,7 +88,6 @@ Usage: The commands are: - inspect inspects fragment data files check performs a consistency check of data files bench benchmarks operations @@ -114,8 +111,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "inspect": - m.Cmd = NewInspectCommand(m.Stdin, m.Stdout, m.Stderr) case "check": m.Cmd = NewCheckCommand(m.Stdin, m.Stdout, m.Stderr) case "bench": @@ -143,115 +138,6 @@ type Command interface { Run(context.Context) error } -// InspectCommand represents a command for inspecting fragment data files. -type InspectCommand struct { - // Path to data file - Path string - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewInspectCommand returns a new instance of InspectCommand. -func NewInspectCommand(stdin io.Reader, stdout, stderr io.Writer) *InspectCommand { - return &InspectCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *InspectCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - if err := fs.Parse(args); err != nil { - return err - } - - // Parse path. - if fs.NArg() == 0 { - return errors.New("path required") - } else if fs.NArg() > 1 { - return errors.New("only one path allowed") - } - cmd.Path = fs.Arg(0) - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *InspectCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl inspect PATH - -Inspects a data file and provides stats. - -`) -} - -// Run executes the main program execution. -func (cmd *InspectCommand) Run(ctx context.Context) error { - // Open file handle. - f, err := os.Open(cmd.Path) - if err != nil { - return err - } - defer f.Close() - - fi, err := f.Stat() - if err != nil { - return err - } - - // Memory map the file. - data, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()), syscall.PROT_READ, syscall.MAP_SHARED) - if err != nil { - return err - } - defer syscall.Munmap(data) - - // Attach the mmap file to the bitmap. - t := time.Now() - fmt.Fprintf(cmd.Stderr, "unmarshaling bitmap...") - bm := roaring.NewBitmap() - if err := bm.UnmarshalBinary(data); err != nil { - return err - } - fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) - - // Retrieve stats. - t = time.Now() - fmt.Fprintf(cmd.Stderr, "calculating stats...") - info := bm.Info() - fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) - - // Print top-level info. - fmt.Fprintf(cmd.Stdout, "== Bitmap Info ==\n") - fmt.Fprintf(cmd.Stdout, "Containers: %d\n", len(info.Containers)) - fmt.Fprintf(cmd.Stdout, "Operations: %d\n", info.OpN) - fmt.Fprintln(cmd.Stdout, "") - - // Print info for each container. - fmt.Fprintln(cmd.Stdout, "== Containers ==") - tw := tabwriter.NewWriter(cmd.Stdout, 0, 8, 0, '\t', 0) - fmt.Fprintf(tw, "%s\t%s\t% 8s \t% 8s\t%s\n", "KEY", "TYPE", "N", "ALLOC", "OFFSET") - for _, ci := range info.Containers { - fmt.Fprintf(tw, "%d\t%s\t% 8d \t% 8d \t0x%08x\n", - ci.Key, - ci.Type, - ci.N, - ci.Alloc, - uintptr(ci.Pointer)-uintptr(unsafe.Pointer(&data[0])), - ) - } - tw.Flush() - - return nil -} - // CheckCommand represents a command for performing consistency checks on data files. type CheckCommand struct { // Data file paths. diff --git a/ctl/inspect.go b/ctl/inspect.go new file mode 100644 index 000000000..1b00dbcee --- /dev/null +++ b/ctl/inspect.go @@ -0,0 +1,127 @@ +package ctl + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "io/ioutil" + "os" + "strings" + "syscall" + "text/tabwriter" + "time" + "unsafe" + + "github.com/pilosa/pilosa/roaring" +) + +// InspectCommand represents a command for inspecting fragment data files. +type InspectCommand struct { + // Path to data file + Path string + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewInspectCommand returns a new instance of InspectCommand. +func NewInspectCommand(stdin io.Reader, stdout, stderr io.Writer) *InspectCommand { + return &InspectCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// ParseFlags parses command line flags from args. +func (cmd *InspectCommand) ParseFlags(args []string) error { + fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) + fs.SetOutput(ioutil.Discard) + if err := fs.Parse(args); err != nil { + return err + } + + // Parse path. + if fs.NArg() == 0 { + return errors.New("path required") + } else if fs.NArg() > 1 { + return errors.New("only one path allowed") + } + cmd.Path = fs.Arg(0) + + return nil +} + +// Usage returns the usage message to be printed. +func (cmd *InspectCommand) Usage() string { + return strings.TrimSpace(` +usage: pilosactl inspect PATH + +Inspects a data file and provides stats. + +`) +} + +// Run executes the main program execution. +func (cmd *InspectCommand) Run(ctx context.Context) error { + // Open file handle. + f, err := os.Open(cmd.Path) + if err != nil { + return err + } + defer f.Close() + + fi, err := f.Stat() + if err != nil { + return err + } + + // Memory map the file. + data, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()), syscall.PROT_READ, syscall.MAP_SHARED) + if err != nil { + return err + } + defer syscall.Munmap(data) + + // Attach the mmap file to the bitmap. + t := time.Now() + fmt.Fprintf(cmd.Stderr, "unmarshaling bitmap...") + bm := roaring.NewBitmap() + if err := bm.UnmarshalBinary(data); err != nil { + return err + } + fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) + + // Retrieve stats. + t = time.Now() + fmt.Fprintf(cmd.Stderr, "calculating stats...") + info := bm.Info() + fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) + + // Print top-level info. + fmt.Fprintf(cmd.Stdout, "== Bitmap Info ==\n") + fmt.Fprintf(cmd.Stdout, "Containers: %d\n", len(info.Containers)) + fmt.Fprintf(cmd.Stdout, "Operations: %d\n", info.OpN) + fmt.Fprintln(cmd.Stdout, "") + + // Print info for each container. + fmt.Fprintln(cmd.Stdout, "== Containers ==") + tw := tabwriter.NewWriter(cmd.Stdout, 0, 8, 0, '\t', 0) + fmt.Fprintf(tw, "%s\t%s\t% 8s \t% 8s\t%s\n", "KEY", "TYPE", "N", "ALLOC", "OFFSET") + for _, ci := range info.Containers { + fmt.Fprintf(tw, "%d\t%s\t% 8d \t% 8d \t0x%08x\n", + ci.Key, + ci.Type, + ci.N, + ci.Alloc, + uintptr(ci.Pointer)-uintptr(unsafe.Pointer(&data[0])), + ) + } + tw.Flush() + + return nil +} From ff532f2064e5ae0c7cefc9dabefcca582ee14436 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 15:01:29 -0600 Subject: [PATCH 10/20] fix help text in restore command --- cmd/restore.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/restore.go b/cmd/restore.go index 420cd9c5f..44899e4ca 100644 --- a/cmd/restore.go +++ b/cmd/restore.go @@ -31,7 +31,7 @@ func init() { restoreCmd.Flags().StringVarP(&restorer.Host, "host", "", "localhost:15000", "host:port of Pilosa.") restoreCmd.Flags().StringVarP(&restorer.Database, "database", "d", "", "Pilosa database to restore into.") restoreCmd.Flags().StringVarP(&restorer.Frame, "frame", "f", "", "Frame to restore into.") - restoreCmd.Flags().StringVarP(&restorer.Path, "input-file", "i", "", "File to write restore from") + restoreCmd.Flags().StringVarP(&restorer.Path, "input-file", "i", "", "File to restore from.") err := viper.BindPFlags(restoreCmd.Flags()) if err != nil { From 01020d06a84ae4bf18fb308d6fddf1d114bb6e47 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 15:05:59 -0600 Subject: [PATCH 11/20] mvoe check to subcommand --- cmd/check.go | 35 ++++++++++ cmd/pilosactl/main.go | 135 --------------------------------------- ctl/check.go | 145 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 180 insertions(+), 135 deletions(-) create mode 100644 cmd/check.go create mode 100644 ctl/check.go diff --git a/cmd/check.go b/cmd/check.go new file mode 100644 index 000000000..541f33cb2 --- /dev/null +++ b/cmd/check.go @@ -0,0 +1,35 @@ +package cmd + +import ( + "context" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/pilosa/pilosa/ctl" +) + +var checker = ctl.NewCheckCommand(os.Stdin, os.Stdout, os.Stderr) + +var checkCmd = &cobra.Command{ + Use: "check [path2]...", + Short: "check - check a pilosa data file", + Long: ` +Performs a consistency check on data files. +`, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + fmt.Println("path required") + return + } + checker.Paths = args + if err := checker.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + RootCmd.AddCommand(checkCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index a04be0b02..401d1cff5 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -9,13 +9,10 @@ import ( "io/ioutil" "math/rand" "os" - "path/filepath" "strings" - "syscall" "time" "github.com/pilosa/pilosa" - "github.com/pilosa/pilosa/roaring" ) var ( @@ -88,7 +85,6 @@ Usage: The commands are: - check performs a consistency check of data files bench benchmarks operations Use the "-h" flag with any command for more information. @@ -111,8 +107,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "check": - m.Cmd = NewCheckCommand(m.Stdin, m.Stdout, m.Stderr) case "bench": m.Cmd = NewBenchCommand(m.Stdin, m.Stdout, m.Stderr) default: @@ -138,135 +132,6 @@ type Command interface { Run(context.Context) error } -// CheckCommand represents a command for performing consistency checks on data files. -type CheckCommand struct { - // Data file paths. - Paths []string - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewCheckCommand returns a new instance of CheckCommand. -func NewCheckCommand(stdin io.Reader, stdout, stderr io.Writer) *CheckCommand { - return &CheckCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *CheckCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - if err := fs.Parse(args); err != nil { - return err - } - - // Parse path. - if fs.NArg() == 0 { - return errors.New("path required") - } - cmd.Paths = fs.Args() - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *CheckCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl check PATHS... - -Performs a consistency check on data files. - -`) -} - -// Run executes the main program execution. -func (cmd *CheckCommand) Run(ctx context.Context) error { - for _, path := range cmd.Paths { - switch filepath.Ext(path) { - case "": - if err := cmd.checkBitmapFile(path); err != nil { - return err - } - - case ".cache": - if err := cmd.checkCacheFile(path); err != nil { - return err - } - - case ".snapshotting": - if err := cmd.checkSnapshotFile(path); err != nil { - return err - } - } - } - - return nil -} - -// checkBitmapFile performs a consistency check on path for a roaring bitmap file. -func (cmd *CheckCommand) checkBitmapFile(path string) error { - // Open file handle. - f, err := os.Open(path) - if err != nil { - return err - } - defer f.Close() - - fi, err := f.Stat() - if err != nil { - return err - } - - // Memory map the file. - data, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()), syscall.PROT_READ, syscall.MAP_SHARED) - if err != nil { - return err - } - defer syscall.Munmap(data) - - // Attach the mmap file to the bitmap. - bm := roaring.NewBitmap() - if err := bm.UnmarshalBinary(data); err != nil { - return err - } - - // Perform consistency check. - if err := bm.Check(); err != nil { - // Print returned errors. - switch err := err.(type) { - case roaring.ErrorList: - for i := range err { - fmt.Fprintf(cmd.Stdout, "%s: %s\n", path, err[i].Error()) - } - default: - fmt.Fprintf(cmd.Stdout, "%s: %s\n", path, err.Error()) - } - } - - // Print success message if no errors were found. - fmt.Fprintf(cmd.Stdout, "%s: ok\n", path) - - return nil -} - -// checkCacheFile performs a consistency check on path for a cache file. -func (cmd *CheckCommand) checkCacheFile(path string) error { - fmt.Fprintf(cmd.Stderr, "%s: ignoring cache file\n", path) - return nil -} - -// checkSnapshotFile performs a consistency check on path for a snapshot file. -func (cmd *CheckCommand) checkSnapshotFile(path string) error { - fmt.Fprintf(cmd.Stderr, "%s: ignoring snapshot file\n", path) - return nil -} - // BenchCommand represents a command for benchmarking database operations. type BenchCommand struct { // Destination host and port. diff --git a/ctl/check.go b/ctl/check.go new file mode 100644 index 000000000..616e189bf --- /dev/null +++ b/ctl/check.go @@ -0,0 +1,145 @@ +package ctl + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + "syscall" + + "github.com/pilosa/pilosa/roaring" +) + +// CheckCommand represents a command for performing consistency checks on data files. +type CheckCommand struct { + // Data file paths. + Paths []string + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewCheckCommand returns a new instance of CheckCommand. +func NewCheckCommand(stdin io.Reader, stdout, stderr io.Writer) *CheckCommand { + return &CheckCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// ParseFlags parses command line flags from args. +func (cmd *CheckCommand) ParseFlags(args []string) error { + fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) + fs.SetOutput(ioutil.Discard) + if err := fs.Parse(args); err != nil { + return err + } + + // Parse path. + if fs.NArg() == 0 { + return errors.New("path required") + } + cmd.Paths = fs.Args() + + return nil +} + +// Usage returns the usage message to be printed. +func (cmd *CheckCommand) Usage() string { + return strings.TrimSpace(` +usage: pilosactl check PATHS... + +Performs a consistency check on data files. + +`) +} + +// Run executes the main program execution. +func (cmd *CheckCommand) Run(ctx context.Context) error { + for _, path := range cmd.Paths { + switch filepath.Ext(path) { + case "": + if err := cmd.checkBitmapFile(path); err != nil { + return err + } + + case ".cache": + if err := cmd.checkCacheFile(path); err != nil { + return err + } + + case ".snapshotting": + if err := cmd.checkSnapshotFile(path); err != nil { + return err + } + } + } + + return nil +} + +// checkBitmapFile performs a consistency check on path for a roaring bitmap file. +func (cmd *CheckCommand) checkBitmapFile(path string) error { + // Open file handle. + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + + fi, err := f.Stat() + if err != nil { + return err + } + + // Memory map the file. + data, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()), syscall.PROT_READ, syscall.MAP_SHARED) + if err != nil { + return err + } + defer syscall.Munmap(data) + + // Attach the mmap file to the bitmap. + bm := roaring.NewBitmap() + if err := bm.UnmarshalBinary(data); err != nil { + return err + } + + // Perform consistency check. + if err := bm.Check(); err != nil { + // Print returned errors. + switch err := err.(type) { + case roaring.ErrorList: + for i := range err { + fmt.Fprintf(cmd.Stdout, "%s: %s\n", path, err[i].Error()) + } + default: + fmt.Fprintf(cmd.Stdout, "%s: %s\n", path, err.Error()) + } + } + + // Print success message if no errors were found. + fmt.Fprintf(cmd.Stdout, "%s: ok\n", path) + + return nil +} + +// checkCacheFile performs a consistency check on path for a cache file. +func (cmd *CheckCommand) checkCacheFile(path string) error { + fmt.Fprintf(cmd.Stderr, "%s: ignoring cache file\n", path) + return nil +} + +// checkSnapshotFile performs a consistency check on path for a snapshot file. +func (cmd *CheckCommand) checkSnapshotFile(path string) error { + fmt.Fprintf(cmd.Stderr, "%s: ignoring snapshot file\n", path) + return nil +} From 64f007547e88be2690bb0e4da9a5be0687ee1bd6 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 15:14:02 -0600 Subject: [PATCH 12/20] move bench to subcommand --- cmd/bench.go | 43 +++++++++++++ cmd/pilosactl/main.go | 3 - ctl/bench.go | 143 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 cmd/bench.go create mode 100644 ctl/bench.go diff --git a/cmd/bench.go b/cmd/bench.go new file mode 100644 index 000000000..9b3e85399 --- /dev/null +++ b/cmd/bench.go @@ -0,0 +1,43 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/pilosa/pilosa/ctl" +) + +var bencher = ctl.NewBenchCommand(os.Stdin, os.Stdout, os.Stderr) + +var benchCmd = &cobra.Command{ + Use: "bench", + Short: "bench - benchmark operations", + Long: ` +Executes a benchmark for a given operation against the database. +`, + Run: func(cmd *cobra.Command, args []string) { + if err := bencher.Run(context.Background()); err != nil { + fmt.Println(err) + } + }, +} + +func init() { + benchCmd.Flags().StringVarP(&bencher.Host, "host", "", "localhost:15000", "host:port of Pilosa.") + benchCmd.Flags().StringVarP(&bencher.Database, "database", "d", "", "Pilosa database to benchmark.") + benchCmd.Flags().StringVarP(&bencher.Frame, "frame", "f", "", "Frame to benchmark.") + benchCmd.Flags().StringVarP(&bencher.Op, "operation", "o", "set-bit", "Operation to perform: choose from [set-bit]") + benchCmd.Flags().IntVarP(&bencher.N, "num", "n", 0, "Number of operations to perform.") + + err := viper.BindPFlags(benchCmd.Flags()) + if err != nil { + log.Fatalf("Error binding bench flags: %v", err) + } + + RootCmd.AddCommand(benchCmd) +} diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go index 401d1cff5..417ebaead 100644 --- a/cmd/pilosactl/main.go +++ b/cmd/pilosactl/main.go @@ -85,7 +85,6 @@ Usage: The commands are: - bench benchmarks operations Use the "-h" flag with any command for more information. `) @@ -107,8 +106,6 @@ func (m *Main) ParseFlags(args []string) error { fmt.Fprintln(m.Stderr, m.Usage()) fmt.Fprintln(m.Stderr, "") return flag.ErrHelp - case "bench": - m.Cmd = NewBenchCommand(m.Stdin, m.Stdout, m.Stderr) default: return ErrUnknownCommand } diff --git a/ctl/bench.go b/ctl/bench.go new file mode 100644 index 000000000..7e789b5cd --- /dev/null +++ b/ctl/bench.go @@ -0,0 +1,143 @@ +package ctl + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "io/ioutil" + "math/rand" + "strings" + "time" + + "github.com/pilosa/pilosa" +) + +// BenchCommand represents a command for benchmarking database operations. +type BenchCommand struct { + // Destination host and port. + Host string + + // Name of the database & frame to execute against. + Database string + Frame string + + // Type of operation and number to execute. + Op string + N int + + // Standard input/output + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewBenchCommand returns a new instance of BenchCommand. +func NewBenchCommand(stdin io.Reader, stdout, stderr io.Writer) *BenchCommand { + return &BenchCommand{ + Stdin: stdin, + Stdout: stdout, + Stderr: stderr, + } +} + +// ParseFlags parses command line flags from args. +func (cmd *BenchCommand) ParseFlags(args []string) error { + fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) + fs.SetOutput(ioutil.Discard) + fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") + fs.StringVar(&cmd.Database, "d", "", "database") + fs.StringVar(&cmd.Frame, "f", "", "frame") + fs.StringVar(&cmd.Op, "op", "", "operation") + fs.IntVar(&cmd.N, "n", 0, "op count") + + if err := fs.Parse(args); err != nil { + return err + } + return nil +} + +// Usage returns the usage message to be printed. +func (cmd *BenchCommand) Usage() string { + return strings.TrimSpace(` +usage: pilosactl bench [args] + +Executes a benchmark for a given operation against the database. + +The following flags are allowed: + + -host HOSTPORT + hostname and port of running pilosa server + + -d DATABASE + database to execute operation against + + -f FRAME + frame to execute operation against + + -op OP + name of operation to execute + + -n COUNT + number of iterations to execute + +The following operations are available: + + set-bit + Sets a single random bit on the frame + +`) +} + +// Run executes the main program execution. +func (cmd *BenchCommand) Run(ctx context.Context) error { + // Create a client to the server. + client, err := pilosa.NewClient(cmd.Host) + if err != nil { + return err + } + + switch cmd.Op { + case "set-bit": + return cmd.runSetBit(ctx, client) + case "": + return errors.New("op required") + default: + return fmt.Errorf("unknown bench op: %q", cmd.Op) + } +} + +// runSetBit executes a benchmark of random SetBit() operations. +func (cmd *BenchCommand) runSetBit(ctx context.Context, client *pilosa.Client) error { + if cmd.N == 0 { + return errors.New("operation count required") + } else if cmd.Database == "" { + return pilosa.ErrDatabaseRequired + } else if cmd.Frame == "" { + return pilosa.ErrFrameRequired + } + + const maxBitmapID = 1000 + const maxProfileID = 100000 + + startTime := time.Now() + + // Execute operation continuously. + for i := 0; i < cmd.N; i++ { + bitmapID := rand.Intn(maxBitmapID) + profileID := rand.Intn(maxProfileID) + + q := fmt.Sprintf(`SetBit(id=%d, frame="%s", profileID=%d)`, bitmapID, cmd.Frame, profileID) + + if _, err := client.ExecuteQuery(ctx, cmd.Database, q, true); err != nil { + return err + } + } + + // Print results. + elapsed := time.Since(startTime) + fmt.Fprintf(cmd.Stdout, "Executed %d operations in %s (%0.3f op/sec)\n", cmd.N, elapsed, float64(cmd.N)/elapsed.Seconds()) + + return nil +} From a47f93329ea7aa55d22904df6f6875f7e2e08c49 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Fri, 3 Mar 2017 15:24:39 -0600 Subject: [PATCH 13/20] remove pilosactl and add version/build to root cmd --- cmd/pilosactl/main.go | 258 ------------------------------------- cmd/pilosactl/main_test.go | 1 - cmd/root.go | 21 ++- 3 files changed, 20 insertions(+), 260 deletions(-) delete mode 100644 cmd/pilosactl/main.go delete mode 100644 cmd/pilosactl/main_test.go diff --git a/cmd/pilosactl/main.go b/cmd/pilosactl/main.go deleted file mode 100644 index 417ebaead..000000000 --- a/cmd/pilosactl/main.go +++ /dev/null @@ -1,258 +0,0 @@ -package main - -import ( - "context" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "math/rand" - "os" - "strings" - "time" - - "github.com/pilosa/pilosa" -) - -var ( - // ErrUnknownCommand is returned when specifying an unknown command. - ErrUnknownCommand = errors.New("unknown command") - - // ErrPathRequired is returned when executing a command without a required path. - ErrPathRequired = errors.New("path required") - Version string - BuildTime string -) - -func init() { - if Version == "" { - Version = "v0.0.0" - } - if BuildTime == "" { - BuildTime = "not recorded" - } -} - -func main() { - m := NewMain() - - fmt.Fprintf(m.Stderr, "Pilosactl %s, build time %s\n", Version, BuildTime) - - // Parse command line arguments. - if err := m.ParseFlags(os.Args[1:]); err == flag.ErrHelp { - os.Exit(2) - } else if err != nil { - fmt.Fprintln(m.Stderr, err) - os.Exit(2) - } - - // Execute the program. - if err := m.Run(); err != nil { - fmt.Fprintln(m.Stderr, err) - os.Exit(1) - } -} - -// Main represents the main program execution. -type Main struct { - // Subcommand to execute. - Cmd Command - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewMain returns a new instance of Main. -func NewMain() *Main { - return &Main{ - Stdin: os.Stdin, - Stdout: os.Stdout, - Stderr: os.Stderr, - } -} - -// Usage returns the usage message to be printed. -func (m *Main) Usage() string { - return strings.TrimSpace(` -Pilosactl is a tool for interacting with a pilosa server. - -Usage: - - pilosactl command [arguments] - -The commands are: - - -Use the "-h" flag with any command for more information. -`) -} - -// Run executes the main program execution. -func (m *Main) Run() error { return m.Cmd.Run(context.Background()) } - -// ParseFlags parses command line flags from args. -func (m *Main) ParseFlags(args []string) error { - var command string - if len(args) > 0 { - command = args[0] - args = args[1:] - } - - switch command { - case "", "help", "-h": - fmt.Fprintln(m.Stderr, m.Usage()) - fmt.Fprintln(m.Stderr, "") - return flag.ErrHelp - default: - return ErrUnknownCommand - } - - // Parse command's flags. - if err := m.Cmd.ParseFlags(args); err == flag.ErrHelp { - fmt.Fprintln(m.Stderr, m.Cmd.Usage()) - fmt.Fprintln(m.Stderr, "") - return err - } else if err != nil { - return err - } - - return nil -} - -// Command represents an executable subcommand. -type Command interface { - Usage() string - ParseFlags(args []string) error - Run(context.Context) error -} - -// BenchCommand represents a command for benchmarking database operations. -type BenchCommand struct { - // Destination host and port. - Host string - - // Name of the database & frame to execute against. - Database string - Frame string - - // Type of operation and number to execute. - Op string - N int - - // Standard input/output - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// NewBenchCommand returns a new instance of BenchCommand. -func NewBenchCommand(stdin io.Reader, stdout, stderr io.Writer) *BenchCommand { - return &BenchCommand{ - Stdin: stdin, - Stdout: stdout, - Stderr: stderr, - } -} - -// ParseFlags parses command line flags from args. -func (cmd *BenchCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") - fs.StringVar(&cmd.Database, "d", "", "database") - fs.StringVar(&cmd.Frame, "f", "", "frame") - fs.StringVar(&cmd.Op, "op", "", "operation") - fs.IntVar(&cmd.N, "n", 0, "op count") - - if err := fs.Parse(args); err != nil { - return err - } - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *BenchCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl bench [args] - -Executes a benchmark for a given operation against the database. - -The following flags are allowed: - - -host HOSTPORT - hostname and port of running pilosa server - - -d DATABASE - database to execute operation against - - -f FRAME - frame to execute operation against - - -op OP - name of operation to execute - - -n COUNT - number of iterations to execute - -The following operations are available: - - set-bit - Sets a single random bit on the frame - -`) -} - -// Run executes the main program execution. -func (cmd *BenchCommand) Run(ctx context.Context) error { - // Create a client to the server. - client, err := pilosa.NewClient(cmd.Host) - if err != nil { - return err - } - - switch cmd.Op { - case "set-bit": - return cmd.runSetBit(ctx, client) - case "": - return errors.New("op required") - default: - return fmt.Errorf("unknown bench op: %q", cmd.Op) - } -} - -// runSetBit executes a benchmark of random SetBit() operations. -func (cmd *BenchCommand) runSetBit(ctx context.Context, client *pilosa.Client) error { - if cmd.N == 0 { - return errors.New("operation count required") - } else if cmd.Database == "" { - return pilosa.ErrDatabaseRequired - } else if cmd.Frame == "" { - return pilosa.ErrFrameRequired - } - - const maxBitmapID = 1000 - const maxProfileID = 100000 - - startTime := time.Now() - - // Execute operation continuously. - for i := 0; i < cmd.N; i++ { - bitmapID := rand.Intn(maxBitmapID) - profileID := rand.Intn(maxProfileID) - - q := fmt.Sprintf(`SetBit(id=%d, frame="%s", profileID=%d)`, bitmapID, cmd.Frame, profileID) - - if _, err := client.ExecuteQuery(ctx, cmd.Database, q, true); err != nil { - return err - } - } - - // Print results. - elapsed := time.Since(startTime) - fmt.Fprintf(cmd.Stdout, "Executed %d operations in %s (%0.3f op/sec)\n", cmd.N, elapsed, float64(cmd.N)/elapsed.Seconds()) - - return nil -} diff --git a/cmd/pilosactl/main_test.go b/cmd/pilosactl/main_test.go deleted file mode 100644 index 0fee6f5dc..000000000 --- a/cmd/pilosactl/main_test.go +++ /dev/null @@ -1 +0,0 @@ -package main_test diff --git a/cmd/root.go b/cmd/root.go index 91d866a18..f7517dc73 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -2,13 +2,32 @@ package cmd import "github.com/spf13/cobra" +var ( + Version string + BuildTime string +) + var RootCmd = &cobra.Command{ Use: "pilosa", Short: "pilosa - A Distributed In-memory Binary Bitmap Index", + // TODO - is documentation actually there? Long: `Pilosa is a fast index to turbocharge your database. This binary contains Pilosa itself, as well as common tools for administering pilosa, importing/exporting data, backing up, and more. Complete documentation is available -at http://pilosa.com/docs`, // TODO - is documentation actually there? +at http://pilosa.com/docs + +`, +} + +func init() { + if Version == "" { + Version = "v0.0.0" + } + if BuildTime == "" { + BuildTime = "not recorded" + } + + RootCmd.Long = RootCmd.Long + "Version: " + Version + "\nBuild Time: " + BuildTime + "\n" } From 756c44c17d0e775bc795ab91af195315eed2b083 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Mon, 6 Mar 2017 10:19:50 -0600 Subject: [PATCH 14/20] fix bugs with pilosa server -config and remove dead code --- cmd/server.go | 2 +- server/server.go | 65 +----------------------------------------------- 2 files changed, 2 insertions(+), 65 deletions(-) diff --git a/cmd/server.go b/cmd/server.go index cc8bbec49..d31806eea 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -29,7 +29,7 @@ on the configured port.`, fmt.Fprintf(serve.Stderr, "Pilosa %s, build time %s\n", server.Version, server.BuildTime) // Parse command line arguments. - if err := serve.ParseFlags(os.Args[1:]); err != nil { + if err := serve.SetupConfig(args); err != nil { fmt.Fprintln(serve.Stderr, err) os.Exit(2) } diff --git a/server/server.go b/server/server.go index bb151a37d..247d0efa9 100644 --- a/server/server.go +++ b/server/server.go @@ -2,14 +2,11 @@ package server import ( "errors" - "flag" "fmt" "io" "math/rand" "os" - "os/signal" "path/filepath" - "runtime/pprof" "strings" "time" @@ -39,57 +36,6 @@ const ( DefaultDataDir = "~/.pilosa" ) -func mainz() { - serve := NewMain() - serve.Server.Handler.Version = Version - fmt.Fprintf(serve.Stderr, "Pilosa %s, build time %s\n", Version, BuildTime) - - // Parse command line arguments. - if err := serve.ParseFlags(os.Args[1:]); err != nil { - fmt.Fprintln(serve.Stderr, err) - os.Exit(2) - } - - // Start CPU profiling. - if serve.CPUProfile != "" { - f, err := os.Create(serve.CPUProfile) - if err != nil { - fmt.Fprintf(serve.Stderr, "create cpu profile: %v", err) - os.Exit(1) - } - defer f.Close() - - fmt.Fprintln(serve.Stderr, "Starting cpu profile") - pprof.StartCPUProfile(f) - time.AfterFunc(serve.CPUTime, func() { - fmt.Fprintln(serve.Stderr, "Stopping cpu profile") - pprof.StopCPUProfile() - f.Close() - }) - } - - // Execute the program. - if err := serve.Run(); err != nil { - fmt.Fprintln(serve.Stderr, err) - fmt.Fprintln(serve.Stderr, "stopping profile") - os.Exit(1) - } - - // First SIGKILL causes server to shut down gracefully. - c := make(chan os.Signal, 2) - signal.Notify(c, os.Interrupt) - sig := <-c - fmt.Fprintf(serve.Stderr, "Received %s; gracefully shutting down...\n", sig.String()) - - // Second signal causes a hard shutdown. - go func() { <-c; os.Exit(1) }() - - if err := serve.Close(); err != nil { - fmt.Fprintln(serve.Stderr, err) - os.Exit(1) - } -} - // Main represents the main program execution. type Main struct { Server *pilosa.Server @@ -158,16 +104,7 @@ func (m *Main) Close() error { } // ParseFlags parses command line flags from args. -func (m *Main) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosa", flag.ContinueOnError) - fs.StringVar(&m.CPUProfile, "cpuprofile", "", "cpu profile") - fs.DurationVar(&m.CPUTime, "cputime", 30*time.Second, "cpu profile duration") - fs.StringVar(&m.ConfigPath, "config", "", "config path") - fs.SetOutput(m.Stderr) - if err := fs.Parse(args); err != nil { - return err - } - +func (m *Main) SetupConfig(args []string) error { // Load config, if specified. if m.ConfigPath != "" { if _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil { From c419c082da0a13ac0ed285853fe316f58f42baa0 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Mon, 6 Mar 2017 11:18:16 -0600 Subject: [PATCH 15/20] update readme to reflect subcommands and pilosactl gone --- README.md | 92 +++++-------------------------------------------------- 1 file changed, 8 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index bd6aacbe2..148a7a139 100644 --- a/README.md +++ b/README.md @@ -23,18 +23,16 @@ $ go install github.com/pilosa/pilosa/cmd/... Now run a single pilosa node with the default configuration: ```sh -pilosa +pilosa server ``` -If you would like to quickly create a multi-node pilosa cluster, see the `pilosactl create` documentation. - ## Configuration You can specify a configuration by setting the `-config` flag when running `pilosa`. ```sh -pilosa -config custom-config-file.cfg +pilosa server --config custom-config-file.cfg ``` The config file uses the [TOML](https://github.com/toml-lang/toml) configuration file format, @@ -54,6 +52,12 @@ host = "127.0.0.1:15000" host = "127.0.0.1:15001" ``` +You can generate a template config file with default values with: + +```sh +pilosa config +``` + The first two configuration options will be unique to each node in the cluster: `data-dir`: directory in which data is stored to disk @@ -242,83 +246,3 @@ $ go install --ldflags="-X main.Version=1.0.0" ``` [Glide]: http://glide.sh/ - -## Pilosactl - -Pilosactl contains a suite of tools for interacting with pilosa. Run `pilosactl` for an overview of commands, and `pilosactl -h` for specific information on that command. - -### Create - -`pilosactl create` is used to create pilosa clusters. It has a number of options for controlling how the cluster is configured, what hosts it is on, and even the ability to build the pilosa binary locally and copy it to each cluster node automatically. To start pilosa on remote hosts, you only need `ssh` access to those hosts. See `pilosactl create -h` for a full list of options. - -Examples: - -Create a 5 node cluster locally (using 5 different ports), with a replication factor of 2. -``` -pilosactl create \ - -serverN 5 \ - -replicaN 2 -``` - -Create a cluster on 3 remote hosts - all logs will come to local stderr, pilosa binary must be available on remote hosts. The ssh user on the remote hosts needs to be the same as your local user. Otherwise use the `ssh-user` option. -``` -pilosactl create \ - -hosts="node1.example.com:15000,node2.example.com:15000,node3.example.com:15000" -``` - -Create a cluster on 3 remote hosts running OSX, but build the binary locally and copy it up. Stream the stderr of each node to a separate local log file. -``` -pilosactl create \ - -hosts="mac1.example.com:15000,mac2.example.com:15000,mac3.example.com:15000" \ - -copy-binary \ - -goos=darwin \ - -goarch=amd64 \ - -log-file-prefix=clusterlogs -``` - -### Bagent - -`pilosactl bagent` is what you want if you just want to run a simple benchmark against an existing cluster. Running it with no arguments will print some help, including the set of subcommands that it may be passed. Calling a subcommand with `-h'` will print the options for that subcommand. The `agent-num` flag can be passed an integer which can change the behavior the benchmarks that are run. This is useful when multiple invocations of the same benchmark are made by the `bspawn` command - they can each (for example) set different bits even though they all have the same arguments. - -E.G. -``` -pilosactl bagent \ - -hosts="localhost:15000,localhost:15001" \ - import -h -``` - -Multiple subcommands and their arguments may be concatenated at the command line and they will be run serially. This is useful (i.e.) for importing a bunch of data, and then executing queries against it. - -This will generate and import a bunch of data, and then execute random queries against it. - -``` -pilosactl bagent \ - -hosts="localhost:15000,localhost:15001" \ - import -max-bits-per-map=10000 \ - random-query -iterations 100 -``` - -### Bspawn -`pilosactl bspawn` allows you to automate the creation of clusters and the running of complex benchmarks which span multiple benchmark agents against them. It has a number of options which are described by `pilosactl bspawn` with no arguments, and also takes a config file which describes the Benchmark itself - this file is described below. - -#### Configuration Format - -The configuration file is a json object with the top level key `benchmarks`. This contains a list of objects each of which represents a `bagent` command (the `args` key) that will be run some number of times concurrently (the `num` key), and a `name` which should describe the overall effect that command. An example is below. -```json -{ - "benchmarks": [ - { - "num": 3, - "name": "set-diags", - "args": ["diagonal-set-bits", "-iterations", "30000", "-client-type", "round_robin"] - }, - { - "num": 2, - "name": "rand-plus-zipf", - "args": ["random-set-bits", "-iterations", "20000", "zipf", "-iterations", "100"] - } - ] -} -``` - -All of the benchmarks, and agents are run concurrently. Each agent will be passed an `agent-num` which can modify the behavior in a way that is benchmark specific. See the documentation for each benchmark to see how `agent-num` changes its behavior. From f463ab9d9b19177e5c8e9bc4df32d0b68d1fbdab Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Mon, 6 Mar 2017 16:37:41 -0600 Subject: [PATCH 16/20] make inspect behave like pilosactl version --- cmd/inspect.go | 19 +++++++++---------- cmd/sort.go | 1 - 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/cmd/inspect.go b/cmd/inspect.go index 48bbf8308..56ded3bb7 100644 --- a/cmd/inspect.go +++ b/cmd/inspect.go @@ -3,11 +3,9 @@ package cmd import ( "context" "fmt" - "log" "os" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/pilosa/pilosa/ctl" ) @@ -16,11 +14,19 @@ var inspecter = ctl.NewInspectCommand(os.Stdin, os.Stdout, os.Stderr) var inspectCmd = &cobra.Command{ Use: "inspect", - Short: "inspect - inspect a pilosa data file", + Short: "get stats on pilosa data file", Long: ` Inspects a data file and provides stats. `, Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + fmt.Println("path required") + return + } else if len(args) > 1 { + fmt.Println("only one path allowed") + return + } + inspecter.Path = args[0] if err := inspecter.Run(context.Background()); err != nil { fmt.Println(err) } @@ -28,12 +34,5 @@ Inspects a data file and provides stats. } func init() { - inspectCmd.Flags().StringVarP(&inspecter.Path, "file", "i", "", "File to inspect") - - err := viper.BindPFlags(inspectCmd.Flags()) - if err != nil { - log.Fatalf("Error binding inspect flags: %v", err) - } - RootCmd.AddCommand(inspectCmd) } diff --git a/cmd/sort.go b/cmd/sort.go index 813624ddc..4df585629 100644 --- a/cmd/sort.go +++ b/cmd/sort.go @@ -25,7 +25,6 @@ The format of the CSV file is: The file should contain no headers. `, Run: func(cmd *cobra.Command, args []string) { - fmt.Println(cmd.Flags()) if len(args) == 0 { fmt.Println("path required") return From c7caea6b30dacd853d7c6482ef295e983ab1a408 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Mon, 6 Mar 2017 16:45:37 -0600 Subject: [PATCH 17/20] fix short help strings on commands --- cmd/backup.go | 2 +- cmd/bench.go | 2 +- cmd/check.go | 2 +- cmd/config.go | 2 +- cmd/export.go | 2 +- cmd/import.go | 2 +- cmd/inspect.go | 2 +- cmd/restore.go | 2 +- cmd/root.go | 2 +- cmd/server.go | 2 +- cmd/sort.go | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/cmd/backup.go b/cmd/backup.go index 883ce7be8..418f6a720 100644 --- a/cmd/backup.go +++ b/cmd/backup.go @@ -16,7 +16,7 @@ var backuper = ctl.NewBackupCommand(os.Stdin, os.Stdout, os.Stderr) var backupCmd = &cobra.Command{ Use: "backup", - Short: "backup - backup data from pilosa", + Short: "Backup data from pilosa.", Long: ` Backs up the database and frame from across the cluster into a single file. `, diff --git a/cmd/bench.go b/cmd/bench.go index 9b3e85399..3e093d68e 100644 --- a/cmd/bench.go +++ b/cmd/bench.go @@ -16,7 +16,7 @@ var bencher = ctl.NewBenchCommand(os.Stdin, os.Stdout, os.Stderr) var benchCmd = &cobra.Command{ Use: "bench", - Short: "bench - benchmark operations", + Short: "Benchmark operations.", Long: ` Executes a benchmark for a given operation against the database. `, diff --git a/cmd/check.go b/cmd/check.go index 541f33cb2..560130187 100644 --- a/cmd/check.go +++ b/cmd/check.go @@ -14,7 +14,7 @@ var checker = ctl.NewCheckCommand(os.Stdin, os.Stdout, os.Stderr) var checkCmd = &cobra.Command{ Use: "check [path2]...", - Short: "check - check a pilosa data file", + Short: "Do a consistency check on a pilosa data file.", Long: ` Performs a consistency check on data files. `, diff --git a/cmd/config.go b/cmd/config.go index 72202ffe3..5fccbfc7d 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -14,7 +14,7 @@ var conf = ctl.NewConfigCommand(os.Stdin, os.Stdout, os.Stderr) var confCmd = &cobra.Command{ Use: "config", - Short: "config - prints the default configuration", + Short: "Print the default configuration.", Long: `config prints the default configuration to stdout `, Run: func(cmd *cobra.Command, args []string) { diff --git a/cmd/export.go b/cmd/export.go index a5cd0f62d..06a76118d 100644 --- a/cmd/export.go +++ b/cmd/export.go @@ -16,7 +16,7 @@ var exporter = ctl.NewExportCommand(os.Stdin, os.Stdout, os.Stderr) var exportCmd = &cobra.Command{ Use: "export", - Short: "export - export data from pilosa", + Short: "Export data from pilosa.", Long: ` Bulk exports a fragment to a CSV file. If the OUTFILE is not specified then the output is written to STDOUT. diff --git a/cmd/import.go b/cmd/import.go index af1a7fcd5..5f878c431 100644 --- a/cmd/import.go +++ b/cmd/import.go @@ -16,7 +16,7 @@ var importer = ctl.NewImportCommand(os.Stdin, os.Stdout, os.Stderr) var importCmd = &cobra.Command{ Use: "import", - Short: "import - import data to pilosa", + Short: "Bulk load data into pilosa.", Long: `Bulk imports one or more CSV files to a host's database and frame. The bits of the CSV file are grouped by slice for the most efficient import. diff --git a/cmd/inspect.go b/cmd/inspect.go index 56ded3bb7..666c59d5c 100644 --- a/cmd/inspect.go +++ b/cmd/inspect.go @@ -14,7 +14,7 @@ var inspecter = ctl.NewInspectCommand(os.Stdin, os.Stdout, os.Stderr) var inspectCmd = &cobra.Command{ Use: "inspect", - Short: "get stats on pilosa data file", + Short: "Get stats on a pilosa data file.", Long: ` Inspects a data file and provides stats. `, diff --git a/cmd/restore.go b/cmd/restore.go index 44899e4ca..399122ff3 100644 --- a/cmd/restore.go +++ b/cmd/restore.go @@ -16,7 +16,7 @@ var restorer = ctl.NewRestoreCommand(os.Stdin, os.Stdout, os.Stderr) var restoreCmd = &cobra.Command{ Use: "restore", - Short: "restore - restore data to pilosa", + Short: "Restore data to pilosa from a backup file.", Long: ` Restores a frame to the cluster from a backup file. `, diff --git a/cmd/root.go b/cmd/root.go index f7517dc73..139214302 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -9,7 +9,7 @@ var ( var RootCmd = &cobra.Command{ Use: "pilosa", - Short: "pilosa - A Distributed In-memory Binary Bitmap Index", + Short: "Pilosa - A Distributed In-memory Binary Bitmap Index.", // TODO - is documentation actually there? Long: `Pilosa is a fast index to turbocharge your database. diff --git a/cmd/server.go b/cmd/server.go index d31806eea..6603a0989 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -18,7 +18,7 @@ var serve = server.NewMain() var serveCmd = &cobra.Command{ Use: "server", - Short: "server - run the pilosa server", + Short: "Run Pilosa.", Long: `pilosa server runs Pilosa. It will load existing data from the configured diff --git a/cmd/sort.go b/cmd/sort.go index 4df585629..f9a1d682e 100644 --- a/cmd/sort.go +++ b/cmd/sort.go @@ -14,7 +14,7 @@ var sorter = ctl.NewSortCommand(os.Stdin, os.Stdout, os.Stderr) var sortCmd = &cobra.Command{ Use: "sort ", - Short: "sort - sort import data for optimal import performance", + Short: "Sort import data for optimal import performance.", Long: ` Sorts the import data at PATH into the optimal sort order for importing. From 555a514e37526ec6624a4b1e632f927f0c96ecb7 Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Tue, 7 Mar 2017 11:30:31 -0600 Subject: [PATCH 18/20] code review tweaks --- cmd/pilosa/main.go | 2 +- cmd/server.go | 2 +- ctl/backup.go | 2 +- ctl/config.go | 2 +- ctl/export.go | 2 +- ctl/sort.go | 2 +- server/server.go | 21 +++++++++------------ server/server_test.go | 20 ++++++++++---------- 8 files changed, 25 insertions(+), 28 deletions(-) diff --git a/cmd/pilosa/main.go b/cmd/pilosa/main.go index 255aef606..c3bef0622 100644 --- a/cmd/pilosa/main.go +++ b/cmd/pilosa/main.go @@ -10,6 +10,6 @@ import ( func main() { if err := cmd.RootCmd.Execute(); err != nil { fmt.Println(err) - os.Exit(-1) + os.Exit(1) } } diff --git a/cmd/server.go b/cmd/server.go index 6603a0989..64e45eed4 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -14,7 +14,7 @@ import ( "github.com/pilosa/pilosa/server" ) -var serve = server.NewMain() +var serve = server.NewCommand() var serveCmd = &cobra.Command{ Use: "server", diff --git a/ctl/backup.go b/ctl/backup.go index 23b34cd1f..f0adf5766 100644 --- a/ctl/backup.go +++ b/ctl/backup.go @@ -36,7 +36,7 @@ func NewBackupCommand(stdin io.Reader, stdout, stderr io.Writer) *BackupCommand } } -// Run executes the main program execution. +// Run executes the backup. func (cmd *BackupCommand) Run(ctx context.Context) error { // Validate arguments. if cmd.Path == "" { diff --git a/ctl/config.go b/ctl/config.go index 516069e2d..998c17b47 100644 --- a/ctl/config.go +++ b/ctl/config.go @@ -24,7 +24,7 @@ func NewConfigCommand(stdin io.Reader, stdout, stderr io.Writer) *ConfigCommand } } -// Run executes the main program execution. +// Run prints out the default config. func (cmd *ConfigCommand) Run(ctx context.Context) error { fmt.Fprintln(cmd.Stdout, strings.TrimSpace(` data-dir = "~/.pilosa" diff --git a/ctl/export.go b/ctl/export.go index f19c7123f..4eead3239 100644 --- a/ctl/export.go +++ b/ctl/export.go @@ -36,7 +36,7 @@ func NewExportCommand(stdin io.Reader, stdout, stderr io.Writer) *ExportCommand } } -// Run executes the main program execution. +// Run executes the export. func (cmd *ExportCommand) Run(ctx context.Context) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) diff --git a/ctl/sort.go b/ctl/sort.go index eac68b7ab..66bd16372 100644 --- a/ctl/sort.go +++ b/ctl/sort.go @@ -35,7 +35,7 @@ func NewSortCommand(stdin io.Reader, stdout, stderr io.Writer) *SortCommand { } } -// Run executes the main program execution. +// Run executes the sort command. func (cmd *SortCommand) Run(ctx context.Context) error { // Open file for reading. f, err := os.Open(cmd.Path) diff --git a/server/server.go b/server/server.go index 247d0efa9..b7b8ca2f9 100644 --- a/server/server.go +++ b/server/server.go @@ -36,8 +36,8 @@ const ( DefaultDataDir = "~/.pilosa" ) -// Main represents the main program execution. -type Main struct { +// Command represents the state of the pilosa server command. +type Command struct { Server *pilosa.Server // Configuration options. @@ -55,8 +55,8 @@ type Main struct { } // NewMain returns a new instance of Main. -func NewMain() *Main { - return &Main{ +func NewCommand() *Command { + return &Command{ Server: pilosa.NewServer(), Config: pilosa.NewConfig(), @@ -66,8 +66,8 @@ func NewMain() *Main { } } -// Run executes the main program execution. -func (m *Main) Run(args ...string) error { +// Run executes the pilosa server. +func (m *Command) Run(args ...string) error { // Notify user of config file. if m.ConfigPath != "" { fmt.Fprintf(m.Stdout, "Using config: %s\n", m.ConfigPath) @@ -99,12 +99,12 @@ func (m *Main) Run(args ...string) error { } // Close shuts down the server. -func (m *Main) Close() error { +func (m *Command) Close() error { return m.Server.Close() } // ParseFlags parses command line flags from args. -func (m *Main) SetupConfig(args []string) error { +func (m *Command) SetupConfig(args []string) error { // Load config, if specified. if m.ConfigPath != "" { if _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil { @@ -120,11 +120,8 @@ func (m *Main) SetupConfig(args []string) error { // Expand home directory. prefix := "~" + string(filepath.Separator) if strings.HasPrefix(m.Config.DataDir, prefix) { - // u, err := user.Current() HomeDir := os.Getenv("HOME") - /*if err != nil { - return err - } else*/if HomeDir == "" { + if HomeDir == "" { return errors.New("data directory not specified and no home dir available") } m.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix)) diff --git a/server/server_test.go b/server/server_test.go index bb772ab45..9e907522a 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -304,7 +304,7 @@ path = "/path/to/plugins" // Main represents a test wrapper for main.Main. type Main struct { - *server.Main + *server.Command Stdin bytes.Buffer Stdout bytes.Buffer @@ -318,16 +318,16 @@ func NewMain() *Main { panic(err) } - m := &Main{Main: server.NewMain()} + m := &Main{Command: server.NewCommand()} m.Config.DataDir = path m.Config.Host = "localhost:0" - m.Main.Stdin = &m.Stdin - m.Main.Stdout = &m.Stdout - m.Main.Stderr = &m.Stderr + m.Command.Stdin = &m.Stdin + m.Command.Stdout = &m.Stdout + m.Command.Stderr = &m.Stderr if testing.Verbose() { - m.Main.Stdout = io.MultiWriter(os.Stdout, m.Main.Stdout) - m.Main.Stderr = io.MultiWriter(os.Stderr, m.Main.Stderr) + m.Command.Stdout = io.MultiWriter(os.Stdout, m.Command.Stdout) + m.Command.Stderr = io.MultiWriter(os.Stderr, m.Command.Stderr) } return m @@ -345,18 +345,18 @@ func MustRunMain() *Main { // Close closes the program and removes the underlying data directory. func (m *Main) Close() error { defer os.RemoveAll(m.Config.DataDir) - return m.Main.Close() + return m.Command.Close() } // Reopen closes the program and reopens it. func (m *Main) Reopen() error { - if err := m.Main.Close(); err != nil { + if err := m.Command.Close(); err != nil { return err } // Create new main with the same config. config := m.Config - m.Main = server.NewMain() + m.Command = server.NewCommand() m.Config = config // Run new program. From 320110f0116c94a6194cb8a8fa276fbfde6afe9e Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Tue, 7 Mar 2017 11:35:58 -0600 Subject: [PATCH 19/20] tweak comments and remove dead code --- ctl/bench.go | 53 +----------------------------------------------- ctl/check.go | 33 +----------------------------- ctl/inspect.go | 35 +------------------------------- ctl/restore.go | 2 +- server/server.go | 2 +- 5 files changed, 5 insertions(+), 120 deletions(-) diff --git a/ctl/bench.go b/ctl/bench.go index 7e789b5cd..2afe7bb27 100644 --- a/ctl/bench.go +++ b/ctl/bench.go @@ -3,12 +3,9 @@ package ctl import ( "context" "errors" - "flag" "fmt" "io" - "io/ioutil" "math/rand" - "strings" "time" "github.com/pilosa/pilosa" @@ -42,55 +39,7 @@ func NewBenchCommand(stdin io.Reader, stdout, stderr io.Writer) *BenchCommand { } } -// ParseFlags parses command line flags from args. -func (cmd *BenchCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - fs.StringVar(&cmd.Host, "host", "localhost:15000", "host:port") - fs.StringVar(&cmd.Database, "d", "", "database") - fs.StringVar(&cmd.Frame, "f", "", "frame") - fs.StringVar(&cmd.Op, "op", "", "operation") - fs.IntVar(&cmd.N, "n", 0, "op count") - - if err := fs.Parse(args); err != nil { - return err - } - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *BenchCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl bench [args] - -Executes a benchmark for a given operation against the database. - -The following flags are allowed: - - -host HOSTPORT - hostname and port of running pilosa server - - -d DATABASE - database to execute operation against - - -f FRAME - frame to execute operation against - - -op OP - name of operation to execute - - -n COUNT - number of iterations to execute - -The following operations are available: - - set-bit - Sets a single random bit on the frame - -`) -} - -// Run executes the main program execution. +// Run executes the bench command. func (cmd *BenchCommand) Run(ctx context.Context) error { // Create a client to the server. client, err := pilosa.NewClient(cmd.Host) diff --git a/ctl/check.go b/ctl/check.go index 616e189bf..0893790f2 100644 --- a/ctl/check.go +++ b/ctl/check.go @@ -2,14 +2,10 @@ package ctl import ( "context" - "errors" - "flag" "fmt" "io" - "io/ioutil" "os" "path/filepath" - "strings" "syscall" "github.com/pilosa/pilosa/roaring" @@ -35,34 +31,7 @@ func NewCheckCommand(stdin io.Reader, stdout, stderr io.Writer) *CheckCommand { } } -// ParseFlags parses command line flags from args. -func (cmd *CheckCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - if err := fs.Parse(args); err != nil { - return err - } - - // Parse path. - if fs.NArg() == 0 { - return errors.New("path required") - } - cmd.Paths = fs.Args() - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *CheckCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl check PATHS... - -Performs a consistency check on data files. - -`) -} - -// Run executes the main program execution. +// Run executes the check command. func (cmd *CheckCommand) Run(ctx context.Context) error { for _, path := range cmd.Paths { switch filepath.Ext(path) { diff --git a/ctl/inspect.go b/ctl/inspect.go index 1b00dbcee..86434b131 100644 --- a/ctl/inspect.go +++ b/ctl/inspect.go @@ -2,13 +2,9 @@ package ctl import ( "context" - "errors" - "flag" "fmt" "io" - "io/ioutil" "os" - "strings" "syscall" "text/tabwriter" "time" @@ -37,36 +33,7 @@ func NewInspectCommand(stdin io.Reader, stdout, stderr io.Writer) *InspectComman } } -// ParseFlags parses command line flags from args. -func (cmd *InspectCommand) ParseFlags(args []string) error { - fs := flag.NewFlagSet("pilosactl", flag.ContinueOnError) - fs.SetOutput(ioutil.Discard) - if err := fs.Parse(args); err != nil { - return err - } - - // Parse path. - if fs.NArg() == 0 { - return errors.New("path required") - } else if fs.NArg() > 1 { - return errors.New("only one path allowed") - } - cmd.Path = fs.Arg(0) - - return nil -} - -// Usage returns the usage message to be printed. -func (cmd *InspectCommand) Usage() string { - return strings.TrimSpace(` -usage: pilosactl inspect PATH - -Inspects a data file and provides stats. - -`) -} - -// Run executes the main program execution. +// Run executes the inspect command. func (cmd *InspectCommand) Run(ctx context.Context) error { // Open file handle. f, err := os.Open(cmd.Path) diff --git a/ctl/restore.go b/ctl/restore.go index b9a573704..a650df495 100644 --- a/ctl/restore.go +++ b/ctl/restore.go @@ -36,7 +36,7 @@ func NewRestoreCommand(stdin io.Reader, stdout, stderr io.Writer) *RestoreComman } } -// Run executes the main program execution. +// Run executes the restore command. func (cmd *RestoreCommand) Run(ctx context.Context) error { // Validate arguments. if cmd.Path == "" { diff --git a/server/server.go b/server/server.go index b7b8ca2f9..845340485 100644 --- a/server/server.go +++ b/server/server.go @@ -103,7 +103,7 @@ func (m *Command) Close() error { return m.Server.Close() } -// ParseFlags parses command line flags from args. +// SetupConfig loads the config file if specified and sets state on the Command. func (m *Command) SetupConfig(args []string) error { // Load config, if specified. if m.ConfigPath != "" { From fa9586f64f4c122cf0e2fc503a8f7dc5440d610e Mon Sep 17 00:00:00 2001 From: Matt Jaffee Date: Tue, 7 Mar 2017 13:18:51 -0600 Subject: [PATCH 20/20] remove useless print --- cmd/server.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/server.go b/cmd/server.go index 64e45eed4..efff0ac7d 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -55,7 +55,6 @@ on the configured port.`, // Execute the program. if err := serve.Run(); err != nil { fmt.Fprintln(serve.Stderr, err) - fmt.Fprintln(serve.Stderr, "stopping profile") os.Exit(1) }