Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[tools] CLI tool to simplify some tasks, and eliminate the curl commands from the docs #2097

Merged
merged 70 commits into from
Apr 15, 2020
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
70 commits
Select commit Hold shift + click to select a range
f3b7ccf
[script] remove DS_PROMETHEUS variable interpolation syntax in Docker…
xmcqueen Dec 12, 2019
062e74d
Merge remote-tracking branch 'upstream/master'
xmcqueen Jan 4, 2020
96f2d6e
start of tool for some operational tasks
xmcqueen Jan 5, 2020
d01a473
looks like yaml inputs works nicely
xmcqueen Jan 7, 2020
30fd1a5
cleaned up a lot and added many api calls
xmcqueen Jan 7, 2020
040a2b4
added placement init
xmcqueen Jan 8, 2020
8e86a94
factored
xmcqueen Jan 8, 2020
f857964
factoring
xmcqueen Jan 8, 2020
4330b01
cleanup
xmcqueen Jan 8, 2020
9038a0a
docs
xmcqueen Jan 8, 2020
e32ba1d
rename and add to Makefilf
xmcqueen Jan 8, 2020
4e8ed42
Merge remote-tracking branch 'upstream/master'
xmcqueen Jan 8, 2020
5ff5b0c
Merge branch 'tool-sample'
xmcqueen Jan 8, 2020
9714424
factor flags into main per PR comment
xmcqueen Jan 9, 2020
b2af08e
many of the PR comments are done
xmcqueen Jan 9, 2020
66c577a
more PR comments
xmcqueen Jan 9, 2020
9c73f0f
last code comments, next add some tests
xmcqueen Jan 9, 2020
a70df4d
factoring
xmcqueen Jan 9, 2020
3685e07
add yaml loader test
xmcqueen Jan 10, 2020
62a7368
checkpoint refactor to redo the cli syntax
xmcqueen Jan 10, 2020
bc86828
finished putting in new cli syntax
xmcqueen Jan 11, 2020
9e7f3fb
factoring
xmcqueen Jan 11, 2020
f9981ff
renaming and README
xmcqueen Jan 11, 2020
385ddf0
working test for arg processing
xmcqueen Jan 12, 2020
024e500
added test for namespaces command line parsing
xmcqueen Jan 12, 2020
75e49d2
add placements cli args test
xmcqueen Jan 13, 2020
0e13026
cleaning up
xmcqueen Jan 13, 2020
099d24d
address more PR comments
xmcqueen Jan 13, 2020
2ef9297
checkpoint
xmcqueen Jan 28, 2020
8a6a793
better arg handling started and test passes
xmcqueen Jan 29, 2020
e7651f5
make it more test-friendly and make the test less sucky
xmcqueen Jan 30, 2020
becd223
rename some items
xmcqueen Jan 31, 2020
0fc035f
checkpoint
xmcqueen Feb 1, 2020
e77f0ba
checkpoint
xmcqueen Feb 2, 2020
51f92dd
add an operation type to the yaml and wrap the existing pb
xmcqueen Feb 2, 2020
95f239f
add an operation type to the yaml and wrap the existing pb
xmcqueen Feb 2, 2020
383f9e8
checkpoint
xmcqueen Feb 3, 2020
d2bbeb4
checkpoint
xmcqueen Feb 3, 2020
be670f1
loader is working and tests are passing
xmcqueen Feb 3, 2020
1f8bfe5
all commands work and tests pass. next add zap then cleanup
xmcqueen Feb 4, 2020
fa9dc7a
factor
xmcqueen Feb 4, 2020
f38dda5
remove the old code
xmcqueen Feb 4, 2020
f08e1c6
deleted cruft
xmcqueen Feb 4, 2020
915a5b5
cleaning up names
xmcqueen Feb 4, 2020
f6c462e
cleaning up
xmcqueen Feb 4, 2020
8258385
add zap
xmcqueen Feb 5, 2020
47d28b1
add usage messages and zap
xmcqueen Feb 5, 2020
3467e72
readme
xmcqueen Feb 5, 2020
b3384e3
readme and go fmt
xmcqueen Feb 5, 2020
7e56aae
restore a deleted tab from the Makefile
xmcqueen Feb 5, 2020
bd3be5f
make the bottom return errors too
xmcqueen Feb 5, 2020
400bfe3
fix bug in apply yaml
xmcqueen Feb 6, 2020
79a82f0
reorg and fix peeker
xmcqueen Mar 11, 2020
40b339e
probably working again with cobra now
xmcqueen Mar 16, 2020
49bb639
tested with cobra and added some aliases
xmcqueen Mar 16, 2020
ee2e442
add delete namespace
xmcqueen Mar 16, 2020
17dffdc
move output to logger per comment
xmcqueen Mar 16, 2020
b0a787f
factor out the logger instantiation
xmcqueen Mar 16, 2020
79a1090
address pr comments
xmcqueen Mar 25, 2020
e9835db
go gmt and fix statusCode check
xmcqueen Mar 25, 2020
79a6805
fix peeker test
xmcqueen Mar 26, 2020
e0caad9
fix example yamls which didnt match the tests
xmcqueen Mar 26, 2020
02a952a
clean it up a bit
xmcqueen Mar 26, 2020
fcafd11
go fmt
xmcqueen Mar 26, 2020
0a613b2
tiny cleanup
xmcqueen Mar 26, 2020
d597f51
Merge branch 'master' into master
robskillington Apr 6, 2020
0a6e318
fixed nil data case in checkForAndHandleError error log line
xmcqueen Apr 7, 2020
63969be
Merge branch 'master' into master
robskillington Apr 14, 2020
c654e44
Address feedback
robskillington Apr 14, 2020
a11e6c1
Delete unused
robskillington Apr 14, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ TOOLS := \
verify_index_files \
carbon_load \
docs_test \
m3db_tool \

.PHONY: setup
setup:
Expand Down
2 changes: 1 addition & 1 deletion docs/operational_guide/placement_configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ curl -X POST localhost:7201/api/v1/services/m3db/placement/init -d '{
"endpoint": "<NODE_3_HOST_NAME>:<NODE_3_PORT>",
"hostname": "<NODE_3_HOST_NAME>",
"port": <NODE_3_PORT>
},
}
]
}'
```
Expand Down
62 changes: 62 additions & 0 deletions src/cmd/tools/m3db_tool/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
M3DB Tool
========

This is a CLI tool to do some things that may be desirable for cluster introspection, or for operational purposes.

Where configuration data is required its provided via YAML.

You can:

* create a database per the simplified database create API
* list namespaces
* delete namespaces
* list placements
* delete placements
* add nodes
* remove nodes

NOTE: This tool can delete namespaces and placements. It can be quite hazardous if used without adequate understanding of your m3db cluster's topology, or without a decent understanding of how m3db works.

Examples
-------

# show help
m3db-tool -h
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved
# create a database
m3db-tool db -create ./database/examples/devel.yaml
# list namespaces
m3db-tool ns
# delete a namespace
m3db-tool ns -delete default
# list placements
m3db-tool pl
# point to some remote and list namespaces
m3db-tool -endpoint http://localhost:7201 ns
# list the ids of the placements
m3db-tool -endpoint http://localhost:7201 pl | jq .placement.instances[].id

Some example yaml files are provided in the examples directories. Here's one for database creation:

---
type: cluster
namespace_name: default
retention_time: 168h
num_shards: 64
replication_factor: 1
hosts:
- id: m3db_seed
isolation_group: rack-a
zone: embedded
weight: 1024
endpoint: m3db_seed:9000
hostname: m3db_seed
port: 9000


See the examples directories below.

References
==========

[https://m3db.github.io/m3/operational_guide](operational guide)
[api docs](https://www.m3db.io/openapi/)
115 changes: 115 additions & 0 deletions src/cmd/tools/m3db_tool/main/common/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package common
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved

import (
"flag"
"fmt"
"go.uber.org/zap"
"io"
"io/ioutil"
"net/http"
)

var (
EndPoint *string
)

// This is used across all the commands
func init() {
EndPoint = flag.String("endpoint", "http://localhost:7201", "The url for target m3db backend.")
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved
}

func DoGet(url string, logger *zap.SugaredLogger, getter func(reader io.Reader, logger *zap.SugaredLogger)) {

logger.Debugf("DoGet:url:%s:\n", url)

resp, err := http.Get(url)
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
logger.Fatal(err)
}

defer func() {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}()

checkForAndHandleError(url, resp, logger)

getter(resp.Body, logger)

}

func DoPost(url string, data io.Reader, logger *zap.SugaredLogger, getter func(reader io.Reader, logger *zap.SugaredLogger)) {

logger.Debugf("DoPost:url:%s:\n", url)

client := &http.Client{}
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved

req, err := http.NewRequest(http.MethodPost, url, data)
req.Header.Add("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
logger.Fatal(err)

}
defer func() {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}()

checkForAndHandleError(url, resp, logger)

getter(resp.Body, logger)

}

func DoDelete(url string, logger *zap.SugaredLogger, getter func(reader io.Reader, logger *zap.SugaredLogger)) {

logger.Debugf("DoDelete:url:%s:\n", url)

client := &http.Client{}
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved

req, err := http.NewRequest(http.MethodDelete, url, nil)
req.Header.Add("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
logger.Fatal(err)

}
defer func() {
ioutil.ReadAll(resp.Body)

resp.Body.Close()
}()

checkForAndHandleError(url, resp, logger)

getter(resp.Body, logger)

}

func DoDump(in io.Reader, log *zap.SugaredLogger) {

dat, err := ioutil.ReadAll(in)
if err != nil {
log.Fatal(err)
}

fmt.Println(string(dat))
}

func checkForAndHandleError(url string, resp *http.Response, log *zap.SugaredLogger) {

log.Debugf("resp.StatusCode:%d:\n", resp.StatusCode)

if resp.StatusCode > 299 {
dat, _ := ioutil.ReadAll(resp.Body)

if dat != nil {
fmt.Println(string(dat))
}

log.Fatalf("error from m3db:%s:url:%s:", resp.Status, url)
}
}
35 changes: 35 additions & 0 deletions src/cmd/tools/m3db_tool/main/common/yaml.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package common

import (
"bytes"
"github.com/ghodss/yaml"
"github.com/gogo/protobuf/jsonpb"
"github.com/gogo/protobuf/proto"
"go.uber.org/zap"
"io"
"io/ioutil"
)

func LoadYaml(path string, target proto.Message, log *zap.SugaredLogger) io.Reader {

log.Debugf("path:%s:\n", path)

content, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}

if err = yaml.Unmarshal(content, target); err != nil {
log.Fatalf("cannot unmarshal data:%v:from yaml file:%s:", err, path)
}

var data *bytes.Buffer
data = bytes.NewBuffer(nil)

marshaller := &jsonpb.Marshaler{}
if err = marshaller.Marshal(data, target); err != nil {
log.Fatal(err)
}

return data
}
65 changes: 65 additions & 0 deletions src/cmd/tools/m3db_tool/main/database/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package database

import (
"flag"
"fmt"
"go.uber.org/zap"
"os"

"github.com/m3db/m3/src/cmd/tools/m3db_tool/main/common"
"github.com/m3db/m3/src/cmd/tools/m3db_tool/main/flagvar"
"github.com/m3db/m3/src/query/generated/proto/admin"
)

var (
CmdFlags *flag.FlagSet
createYaml = flagvar.File{}
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved

defaultPath = "/api/v1/database"
debugQS = "debug=true"
)

func init() {
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved
CmdFlags = flag.NewFlagSet("db", flag.ExitOnError)
CmdFlags.Var(&createYaml, "create", "Path to yaml for simplified db creation with sane defaults.")
CmdFlags.Usage = func() {
fmt.Fprintf(CmdFlags.Output(), `
This is the "%s" subcommand for database scoped operations.

Description:

This subcommand allows the creation of a new database from a yaml specification.

Usage of %s:

`, CmdFlags.Name(), CmdFlags.Name())
CmdFlags.PrintDefaults()
}
}

func Cmd(log *zap.SugaredLogger) {

if err := CmdFlags.Parse(flag.Args()[1:]); err != nil {
CmdFlags.Usage()
os.Exit(1)
}

xmcqueen marked this conversation as resolved.
Show resolved Hide resolved
if CmdFlags.NFlag() > 1 {
fmt.Fprintf(os.Stderr, "Please specify only one action. There were too many cli arguments provided.\n")
CmdFlags.Usage()
os.Exit(1)
}

if len(createYaml.Value) < 1 {
CmdFlags.Usage()
os.Exit(1)
}

data := common.LoadYaml(createYaml.Value, &admin.DatabaseCreateRequest{}, log)

url := fmt.Sprintf("%s%s/create", *common.EndPoint, defaultPath)

common.DoPost(url, data, log, common.DoDump)

return
}
26 changes: 26 additions & 0 deletions src/cmd/tools/m3db_tool/main/database/examples/create.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
type: cluster
namespace_name: 1week_namespace
retention_time: 168h
num_shards: 1024
replication_factor: 3
hosts:
- id: m3db001
isolationGroup: us-east1-a
zone: embedded
weight: 100
address: 10.142.0.1
port: 9000
- id: m3db002
isolationGroup: us-east1-b
zone: embedded
weight: 100
address: 10.142.0.2
port: 9000
- id: m3db003
isolationGroup: us-east1-c
zone: embedded
weight: 100
address: 10.142.0.3
port: 9000

15 changes: 15 additions & 0 deletions src/cmd/tools/m3db_tool/main/database/examples/devel.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
type: cluster
namespace_name: default
retention_time: 168h
num_shards: 64
replication_factor: 1
hosts:
- id: m3db_seed
isolation_group: rack-a
zone: embedded
weight: 1024
endpoint: m3db_seed:9000
hostname: m3db_seed
port: 9000

52 changes: 52 additions & 0 deletions src/cmd/tools/m3db_tool/main/flagvar/file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package flagvar
xmcqueen marked this conversation as resolved.
Show resolved Hide resolved

import (
"os"
"strings"
)

// File is a `flag.Value` for file path arguments.
// By default, any errors from os.Stat are returned.
// Alternatively, the value of the `Validate` field is used as a validator when specified.
type File struct {
Validate func(os.FileInfo, error) error

Value string
}

// Set is flag.Value.Set
func (fv *File) Set(v string) error {
info, err := os.Stat(v)
fv.Value = v
if fv.Validate != nil {
return fv.Validate(info, err)
}
return err
}

func (fv *File) String() string {
return fv.Value
}

// Files is a `flag.Value` for file path arguments.
// By default, any errors from os.Stat are returned.
// Alternatively, the value of the `Validate` field is used as a validator when specified.
type Files struct {
Validate func(os.FileInfo, error) error

Values []string
}

// Set is flag.Value.Set
func (fv *Files) Set(v string) error {
info, err := os.Stat(v)
fv.Values = append(fv.Values, v)
if fv.Validate != nil {
return fv.Validate(info, err)
}
return err
}

func (fv *Files) String() string {
return strings.Join(fv.Values, ",")
}
Loading