Skip to content

Commit

Permalink
Allow changing root command name and make separate vpp command
Browse files Browse the repository at this point in the history
Signed-off-by: Ondrej Fabry <ofabry@cisco.com>
  • Loading branch information
ondrej-fabry committed Aug 21, 2019
1 parent 8482a14 commit 2bdc8be
Show file tree
Hide file tree
Showing 18 changed files with 4,526 additions and 56 deletions.
9 changes: 9 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,7 @@ required = [
[[prune.project]]
name = "github.com/gogo/protobuf"
unused-packages = false

[[constraint]]
branch = "master"
name = "github.com/common-nighthawk/go-figure"
2 changes: 1 addition & 1 deletion cmd/agentctl/agentctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
func main() {
cli := commands.NewAgentCli()

cmd := commands.NewAgentctlCommand(cli)
cmd := commands.NewRootCommand(cli)
if err := cmd.Execute(); err != nil {
os.Exit(-1)
}
Expand Down
16 changes: 10 additions & 6 deletions cmd/agentctl/commands/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,20 @@ func NewAgentCli() *AgentCli {
}

func (cli *AgentCli) Initialize() {
Debugf("[DEBUG] Initialize - globalsFlags: %+v\n\n", globalFlags)
Debugf("Initialize - globalsFlags: %+v\n\n", global)

host := globalFlags.AgentHost
host := global.AgentHost
if host == "" {
host = "127.0.0.1"
}
httpAddr := net.JoinHostPort(host, globalFlags.HttpPort)
httpAddr := net.JoinHostPort(host, global.HttpPort)
cli.RestClient = utils.NewRestClient(httpAddr)
}

func (cli *AgentCli) KVDBClient() keyval.BytesBroker {
etcdCfg := etcd.ClientConfig{
Config: &clientv3.Config{
Endpoints: globalFlags.Endpoints,
Endpoints: global.Endpoints,
DialTimeout: time.Second * 3,
},
OpTimeout: time.Second * 10,
Expand All @@ -73,7 +73,7 @@ func (cli *AgentCli) KVDBClient() keyval.BytesBroker {
ExitWithError(err)
}

return kvdb.NewBroker(globalFlags.ServiceLabel)
return kvdb.NewBroker(global.ServiceLabel)
}

type ModelDetail struct {
Expand All @@ -96,7 +96,11 @@ type protoFields []*descriptor.FieldDescriptorProto

func (cli *AgentCli) AllModels() []ModelDetail {
var list []ModelDetail
for _, m := range models.RegisteredModels() {

registeredModels := models.RegisteredModels()
Debugf("found %d registered models", len(registeredModels))

for _, m := range registeredModels {
module := strings.Split(m.Model.Module, ".")
typ := m.Model.Type
version := m.Model.Version
Expand Down
12 changes: 6 additions & 6 deletions cmd/agentctl/commands/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,16 @@ func runConfigPut(cli *AgentCli, key, value string) {
if !strings.HasPrefix(key, servicelabel.GetAllAgentsPrefix()) {
tmp := strings.Split(key, "/")
if tmp[0] != "config" {
globalFlags.ServiceLabel = tmp[0]
global.ServiceLabel = tmp[0]
key = strings.Join(tmp[1:], "/")
}

db, err = utils.GetDbForOneAgent(globalFlags.Endpoints, globalFlags.ServiceLabel)
db, err = utils.GetDbForOneAgent(global.Endpoints, global.ServiceLabel)
if err != nil {
utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error()))
}
} else {
db, err = utils.GetDbForAllAgents(globalFlags.Endpoints)
db, err = utils.GetDbForAllAgents(global.Endpoints)
if err != nil {
utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error()))
}
Expand Down Expand Up @@ -168,16 +168,16 @@ func runConfigDel(cli *AgentCli, key string) {
if !strings.HasPrefix(key, servicelabel.GetAllAgentsPrefix()) {
tmp := strings.Split(key, "/")
if tmp[0] != "config" {
globalFlags.ServiceLabel = tmp[0]
global.ServiceLabel = tmp[0]
key = strings.Join(tmp[1:], "/")
}

db, err = utils.GetDbForOneAgent(globalFlags.Endpoints, globalFlags.ServiceLabel)
db, err = utils.GetDbForOneAgent(global.Endpoints, global.ServiceLabel)
if err != nil {
utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error()))
}
} else {
db, err = utils.GetDbForAllAgents(globalFlags.Endpoints)
db, err = utils.GetDbForAllAgents(global.Endpoints)
if err != nil {
utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error()))
}
Expand Down
8 changes: 6 additions & 2 deletions cmd/agentctl/commands/dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"net/url"
"os"

"github.com/ligato/vpp-agent/plugins/kvscheduler/api"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -50,8 +51,11 @@ func NewDumpCommand(cli *AgentCli) *cobra.Command {
}

func runDump(cli *AgentCli, model ModelDetail) {
q := fmt.Sprintf(`key-prefix=%s&view=cached`, url.QueryEscape(model.KeyPrefix))
resp, err := cli.HttpRestGET("/scheduler/dump?" + q)
dumpView := api.CachedView
q := fmt.Sprintf(`/scheduler/dump?key-prefix=%s&view=%s`,
url.QueryEscape(model.KeyPrefix), url.QueryEscape(dumpView.String()))

resp, err := cli.HttpRestGET(q)
if err != nil {
ExitWithError(err)
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/agentctl/commands/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func grpcImport(keyVals []keyVal) error {

func etcdImport(keyVals []keyVal) error {
// Connect to etcd
db, err := utils.GetDbForAllAgents(globalFlags.Endpoints)
db, err := utils.GetDbForAllAgents(global.Endpoints)
if err != nil {
return fmt.Errorf("connecting to Etcd failed: %v", err)
}
Expand Down Expand Up @@ -237,7 +237,7 @@ func parseKey(key string) (string, error) {
if !strings.HasPrefix(key, "config/") {
return "", fmt.Errorf("invalid format for key: %q", key)
}
return path.Join(servicelabel.GetAllAgentsPrefix(), globalFlags.ServiceLabel, key), nil
return path.Join(servicelabel.GetAllAgentsPrefix(), global.ServiceLabel, key), nil
}

func unmarshalKeyVal(fullKey string, data string) (proto.Message, error) {
Expand Down
61 changes: 36 additions & 25 deletions cmd/agentctl/commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ import (
"os"
"strings"

"github.com/common-nighthawk/go-figure"
"github.com/ligato/cn-infra/agent"
"github.com/ligato/cn-infra/logging"
"github.com/spf13/cobra"
)

var globalFlags struct {
// RootName defines default name used for root command
var RootName = "agentctl"

var global struct {
AgentHost string
GrpcPort string
HttpPort string
Expand All @@ -34,45 +38,52 @@ var globalFlags struct {
Debug bool
}

// NewAgentctlCommand returns new root command.
func NewAgentctlCommand(cli *AgentCli) *cobra.Command {
// NewRootCommand returns new root command.
func NewRootCommand(cli *AgentCli) *cobra.Command {
return newRootCommand(cli, RootName)
}

func newRootCommand(cli *AgentCli, name string) *cobra.Command {
cmd := &cobra.Command{
Use: "agentctl",
Short: "agentctl manages vpp-agent instances",
Version: fmt.Sprintf("%s", agent.BuildVersion),
Use: name,
Short: fmt.Sprintf("%s manages Ligato agents", name),
Long: figure.NewFigure(name, "", false).String(),
Version: fmt.Sprintf("%s (%s)", agent.BuildVersion, agent.CommitHash),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
Debugf("cmd %s: %+v", cmd.Name(), cmd.Commands())
cli.Initialize()
},
}

AddFlags(cmd)
AddCommands(cmd, cli)

Debugf("cmd.Commands: %+v", cmd.Commands())

return cmd
}

func AddFlags(cmd *cobra.Command) {
var (
serviceLabel = os.Getenv("MICROSERVICE_LABEL")
agentHost = os.Getenv("AGENT_HOST")
etcdEndpoints = strings.Split(os.Getenv("ETCD_ENDPOINTS"), ",")
)

flags := cmd.PersistentFlags()
// global flags
flags.StringVarP(&globalFlags.AgentHost, "host", "H", agentHost, "Address on which agent is reachable")
flags.StringVar(&globalFlags.GrpcPort, "grpc-port", "9111", "gRPC server port")
flags.StringVar(&globalFlags.HttpPort, "http-port", "9191", "HTTP server port")
flags.StringVarP(&globalFlags.ServiceLabel, "service-label", "l", serviceLabel, "Service label for agent instance")
flags.StringSliceVarP(&globalFlags.Endpoints, "etcd-endpoints", "e", etcdEndpoints, "Etcd endpoints to connect to")
flags.BoolVarP(&globalFlags.Debug, "debug", "D", false, "Enable debug mode")

addCommands(cmd, cli)

Debugf("cmd: %+v", cmd.Commands())

return cmd
flags.StringVarP(&global.AgentHost, "host", "H", agentHost, "Address on which agent is reachable")
flags.StringVar(&global.GrpcPort, "grpc-port", "9111", "gRPC server port")
flags.StringVar(&global.HttpPort, "http-port", "9191", "HTTP server port")
flags.StringVarP(&global.ServiceLabel, "service-label", "l", serviceLabel, "Service label for agent instance")
flags.StringSliceVarP(&global.Endpoints, "etcd-endpoints", "e", etcdEndpoints, "Etcd endpoints to connect to")
flags.BoolVarP(&global.Debug, "debug", "D", false, "Enable debug mode")
}

func addCommands(cmd *cobra.Command, cli *AgentCli) {
func AddCommands(cmd *cobra.Command, cli *AgentCli) {
cmd.AddCommand(
NewDumpCommand(cli),
NewModelCommand(cli),
NewLogCommand(cli),
NewImportCommand(cli),
NewVppcliCommand(cli),
NewVppCommand(cli),
NewModelCommand(cli),
NewConfigCommand(cli),
showCmd(),
Expand All @@ -81,10 +92,10 @@ func addCommands(cmd *cobra.Command, cli *AgentCli) {
}

func Debugf(f string, a ...interface{}) {
if globalFlags.Debug || logging.DefaultLogger.GetLevel() >= logging.DebugLevel {
if global.Debug || logging.DefaultLogger.GetLevel() >= logging.DebugLevel {
if !strings.HasSuffix(f, "\n") {
f = f + "\n"
}
fmt.Printf(f, a...)
fmt.Printf("[DEBUG] "+f, a...)
}
}
4 changes: 2 additions & 2 deletions cmd/agentctl/commands/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ func setKeyPrefix(args []string) {
}

func showFunction(cmd *cobra.Command, args []string) {
db, err := utils.GetDbForAllAgents(globalFlags.Endpoints)
db, err := utils.GetDbForAllAgents(global.Endpoints)
if err != nil {
utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error()))
}
Expand Down Expand Up @@ -334,7 +334,7 @@ func printAgentConfig(db keyval.ProtoBroker, agentLabel string, kprefix string)
}

func keyFunction(cmd *cobra.Command, args []string) {
db, err := utils.GetDbForAllAgents(globalFlags.Endpoints)
db, err := utils.GetDbForAllAgents(global.Endpoints)
if err != nil {
utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error()))
}
Expand Down
66 changes: 54 additions & 12 deletions cmd/agentctl/commands/vppcli.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,41 @@ import (
"github.com/spf13/cobra"
)

func NewVppcliCommand(cli *AgentCli) *cobra.Command {
func NewVppCommand(cli *AgentCli) *cobra.Command {
cmd := &cobra.Command{
Use: "vppcli",
Use: "vpp",
Short: "Manage VPP instance",
}
cmd.AddCommand(
newVppCliCommand(cli),
newVppInfoCommand(cli),
)
return cmd
}

func newVppCliCommand(cli *AgentCli) *cobra.Command {
cmd := &cobra.Command{
Use: "cli",
Short: "Execute VPP CLI command",
Long: `
A CLI tool to connect to vppagent and run VPP CLI command.
`,
Example: `Run a VPP CLI command:
$ agentctl vppcli show version
Example: `
To run a VPP CLI command:
$ agentctl vpp cli show version
Do same as above, but specify the HTTP address of the agent:
$ agentctl --httpaddr 172.17.0.3:9191 vppcli show version
Do same as above, but specify the HTTP address of the agent:
$ agentctl --httpaddr 172.17.0.3:9191 vpp cli show version
`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
vppcmd := strings.Join(args, " ")
return RunVppcli(cli, vppcmd)
return runVppCli(cli, vppcmd)
},
SilenceUsage: true,
}
return cmd
}

func RunVppcli(cli *AgentCli, vppcmd string) error {
fmt.Fprintf(os.Stdout, "vpp# %s\n", vppcmd)
func runVppCli(cli *AgentCli, vppcmd string) error {
fmt.Fprintf(os.Stdout, "# %s\n", vppcmd)

data := map[string]interface{}{
"vppclicommand": vppcmd,
Expand All @@ -65,3 +75,35 @@ func RunVppcli(cli *AgentCli, vppcmd string) error {
fmt.Fprintf(os.Stdout, "%s", reply)
return nil
}

func newVppInfoCommand(cli *AgentCli) *cobra.Command {
cmd := &cobra.Command{
Use: "info",
Aliases: []string{"i"},
Short: "Retrieve info about VPP",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runVppInfo(cli)
},
SilenceUsage: true,
}
return cmd
}

func runVppInfo(cli *AgentCli) error {
data := map[string]interface{}{
"vppclicommand": "show version verbose",
}
resp, err := cli.HttpRestPOST("/vpp/command", data)
if err != nil {
return fmt.Errorf("HTTP POST request failed: %v", err)
}

var reply string
if err := json.Unmarshal(resp, &reply); err != nil {
return fmt.Errorf("decoding reply failed: %v", err)
}

fmt.Fprintf(os.Stdout, "%s", reply)
return nil
}
1 change: 1 addition & 0 deletions vendor/github.com/common-nighthawk/go-figure/.travis.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 2bdc8be

Please sign in to comment.