client

package
v0.0.0-...-b4bb62b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2024 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CLIService service.Type = "cli"
)

Variables

View Source
var (
	// AuthenticationOpts Authentication options
	AuthenticationOpts http.AuthenticationOpts
	// CrudClient holds an API CRUD client
	CrudClient *http.CrudClient
	// Host holds the hostname
	Host string
	// HubAddress holds the hub address
	HubAddress string
)
View Source
var (

	// ShellAssets holds the extra assets for the JavaScript engine
	ShellAssets assets.Assets

	// ErrContinue parser error continue input
	ErrContinue = errors.New("<continue input>")
	// ErrQuit parser error quit session
	ErrQuit = errors.New("<quit session>")
)
View Source
var AlertCmd = &cobra.Command{
	Use:          "alert",
	Short:        "Manage alerts",
	Long:         "Manage alerts",
	SilenceUsage: false,
}

AlertCmd skydive alert root command

View Source
var AlertCreate = &cobra.Command{
	Use:   "create",
	Short: "Create alert",
	Long:  "Create alert",
	Run: func(cmd *cobra.Command, args []string) {
		alert := types.NewAlert()
		alert.Name = alertName
		alert.Description = alertDescription
		alert.Expression = alertExpression
		alert.Trigger = alertTrigger
		alert.Action = alertAction

		if err := CrudClient.Create("alert", &alert, nil); err != nil {
			exitOnError(err)
		}
		printJSON(&alert)
	},
}

AlertCreate skydive alert creates command

View Source
var AlertDelete = &cobra.Command{
	Use:   "delete [alert]",
	Short: "Delete alert",
	Long:  "Delete alert",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		for _, id := range args {
			if err := CrudClient.Delete("alert", id); err != nil {
				logging.GetLogger().Error(err)
			}
		}
	},
}

AlertDelete skydive alert delete command

View Source
var AlertGet = &cobra.Command{
	Use:   "get [alert]",
	Short: "Display alert",
	Long:  "Display alert",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var alert types.Alert
		if err := CrudClient.Get("alert", args[0], &alert); err != nil {
			exitOnError(err)
		}
		printJSON(&alert)
	},
}

AlertGet skydive alert get command

View Source
var AlertList = &cobra.Command{
	Use:   "list",
	Short: "List alerts",
	Long:  "List alerts",
	Run: func(cmd *cobra.Command, args []string) {
		var alerts map[string]types.Alert
		if err := CrudClient.List("alert", &alerts); err != nil {
			exitOnError(err)
		}
		printJSON(alerts)
	},
}

AlertList skydive alert list command

View Source
var AlertUpdate = &cobra.Command{
	Use:   "update [alert]",
	Short: "Update alert",
	Long:  "Update alert",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var patch gapi.JSONPatch
		if alertName != "" {
			patch = append(patch, gapi.NewPatchOperation("add", "/Name", alertName))
		}
		if alertDescription != "" {
			patch = append(patch, gapi.NewPatchOperation("add", "/Description", alertDescription))
		}
		if alertTrigger != "" {
			patch = append(patch, gapi.NewPatchOperation("add", "/Trigger", alertTrigger))
		}
		if alertExpression != "" {
			patch = append(patch, gapi.NewPatchOperation("add", "/Expression", alertExpression))
		}
		if alertAction != "" {
			patch = append(patch, gapi.NewPatchOperation("add", "/Action", alertAction))
		}

		var result interface{}
		for _, id := range args {
			if _, err := CrudClient.Update("alert", id, &patch, &result); err != nil {
				exitOnError(err)
			}
		}

		printJSON(result)
	},
}

AlertUpdate skydive alert delete command

View Source
var ClientCmd = &cobra.Command{
	Use:          "client",
	Short:        "Skydive client",
	Long:         "Skydive client",
	SilenceUsage: true,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		var err error
		hubService, err = service.AddressFromString(HubAddress)
		if err != nil {
			exitOnError(err)
		}

		if certfile != "" && keyfile != "" {
			tlsConfig, err = gtls.SetupTLSClientConfig(certfile, keyfile)
			if err != nil {
				exitOnError(err)
			}

			tlsConfig.InsecureSkipVerify = skipVerify

			if cafile != "" {
				tlsConfig.RootCAs, err = gtls.SetupTLSLoadCA(cafile)
				if err != nil {
					exitOnError(err)
				}
			}
		}

		url, _ := http.MakeURL("http", hubService.Addr, hubService.Port, "/api/", tlsConfig != nil)
		restClient := http.NewRestClient(url, &AuthenticationOpts, tlsConfig)
		CrudClient = http.NewCrudClient(restClient)
	},
}

ClientCmd describes the skydive client root command

View Source
var EdgeCmd = &cobra.Command{
	Use:          "edge",
	Short:        "edge",
	Long:         "edge",
	SilenceUsage: false,
}

EdgeCmd skydive edge rule root command

View Source
var EdgeCreate = &cobra.Command{
	Use:          "create",
	Short:        "create",
	Long:         "create",
	SilenceUsage: false,

	Run: func(cmd *cobra.Command, args []string) {
		m, err := graph.DefToMetadata(edgeMetadata, graph.Metadata{})
		if err != nil {
			exitOnError(err)
		}

		if edgeType != "" {
			m["RelationType"] = edgeType
		}

		var parentNode, childNode graph.Node
		if err := CrudClient.Get("node", parentNodeID, &parentNode); err != nil {
			exitOnError(fmt.Errorf("Could not find parent node: %s", err))
		}

		if err := CrudClient.Get("node", childNodeID, &childNode); err != nil {
			exitOnError(fmt.Errorf("Could not find child node: %s", err))
		}

		origin := graph.Origin(Host, CLIService)
		edge := &types.Edge{Edge: graph.CreateEdge(graph.GenID(), &parentNode, &childNode, m, graph.Time(time.Now()), Host, origin)}

		if err = CrudClient.Create("edge", edge, nil); err != nil {
			exitOnError(err)
		}

		printJSON(edge)
	},
}

EdgeCreate skydive edge create command

View Source
var EdgeDelete = &cobra.Command{
	Use:   "delete [edge]",
	Short: "Delete edge",
	Long:  "Delete edge",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var ids []string
		if gremlinFlag {
			queryHelper := client.NewGremlinQueryHelper(CrudClient.RestClient)

			for _, gremlinQuery := range args {
				edges, err := queryHelper.GetEdges(gremlinQuery)
				if err != nil {
					exitOnError(err)
				}

				for _, edge := range edges {
					ids = append(ids, string(edge.ID))
				}
			}
		} else {
			ids = args
		}

		for _, arg := range ids {
			if err := CrudClient.Delete("edge", arg); err != nil {
				logging.GetLogger().Error(err)
			}
		}
	},
}

EdgeDelete edge delete command

View Source
var EdgeGet = &cobra.Command{
	Use:   "get [edge]",
	Short: "Display edge",
	Long:  "Display edge",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var edge types.Edge
		if err := CrudClient.Get("edge", args[0], &edge); err != nil {
			exitOnError(err)
		}
		printJSON(&edge)
	},
}

EdgeGet edge get command

View Source
var EdgeList = &cobra.Command{
	Use:   "list",
	Short: "List edges",
	Long:  "List edges",
	Run: func(cmd *cobra.Command, args []string) {
		var edges map[string]types.Edge
		if err := CrudClient.List("edge", &edges); err != nil {
			exitOnError(err)
		}
		printJSON(edges)
	},
}

EdgeList edge list command

View Source
var EdgeUpdate = &cobra.Command{
	Use:   "update [edge]",
	Short: "Update edge",
	Long:  "Update edge",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		patch, err := createMetadataJSONPatch(edgeAddMetadata, edgeRemoveMetadata)
		if err != nil {
			exitOnError(err)
		}

		var result interface{}
		for _, id := range args {
			if _, err := CrudClient.Update("edge", id, patch, &result); err != nil {
				exitOnError(err)
			}
		}

		if result == nil {
			fmt.Println("Not modified")
		} else {
			printJSON(result)
		}
	},
}

EdgeUpdate node delete command

View Source
var NodeCmd = &cobra.Command{
	Use:          "node",
	Short:        "node",
	Long:         "node",
	SilenceUsage: false,
}

NodeCmd skydive node rule root command

View Source
var NodeCreate = &cobra.Command{
	Use:          "create",
	Short:        "create",
	Long:         "create",
	SilenceUsage: false,

	Run: func(cmd *cobra.Command, args []string) {
		m, err := graph.DefToMetadata(nodeMetadata, graph.Metadata{})
		if err != nil {
			exitOnError(err)
		}

		if nodeName != "" {
			m["Name"] = nodeName
		}

		if nodeType != "" {
			m["Type"] = nodeType
		}

		origin := graph.Origin(Host, CLIService)
		node := &types.Node{graph.CreateNode(graph.GenID(), m, graph.Time(time.Now()), Host, origin)}

		if err = CrudClient.Create("node", node, nil); err != nil {
			exitOnError(err)
		}

		printJSON(node)
	},
}

NodeCreate skydive node create command

View Source
var NodeDelete = &cobra.Command{
	Use:   "delete [node]",
	Short: "Delete node",
	Long:  "Delete node",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var ids []string
		if gremlinFlag {
			queryHelper := client.NewGremlinQueryHelper(CrudClient.RestClient)

			for _, gremlinQuery := range args {
				nodes, err := queryHelper.GetNodes(gremlinQuery)
				if err != nil {
					exitOnError(err)
				}

				for _, node := range nodes {
					ids = append(ids, string(node.ID))
				}
			}
		} else {
			ids = args
		}

		for _, arg := range ids {
			if err := CrudClient.Delete("node", arg); err != nil {
				logging.GetLogger().Error(err)
			}
		}
	},
}

NodeDelete node delete command

View Source
var NodeGet = &cobra.Command{
	Use:   "get [node]",
	Short: "Display node",
	Long:  "Display node",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var node types.Node
		if err := CrudClient.Get("node", args[0], &node); err != nil {
			exitOnError(err)
		}
		printJSON(&node)
	},
}

NodeGet node get command

View Source
var NodeList = &cobra.Command{
	Use:   "list",
	Short: "List nodes",
	Long:  "List nodes",
	Run: func(cmd *cobra.Command, args []string) {
		var nodes map[string]types.Node
		if err := CrudClient.List("node", &nodes); err != nil {
			exitOnError(err)
		}
		printJSON(nodes)
	},
}

NodeList node list command

View Source
var NodeUpdate = &cobra.Command{
	Use:   "update [node]",
	Short: "Update node",
	Long:  "Update node",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		patch, err := createMetadataJSONPatch(nodeAddMetadata, nodeRemoveMetadata)
		if err != nil {
			exitOnError(err)
		}

		var result interface{}
		for _, id := range args {
			if _, err := CrudClient.Update("node", id, patch, &result); err != nil {
				exitOnError(err)
			}
		}

		if result == nil {
			fmt.Println("Not modified")
		} else {
			printJSON(result)
		}
	},
}

NodeUpdate node delete command

View Source
var QueryCmd = &cobra.Command{
	Use:   "query [gremlin]",
	Short: "Issue Gremlin queries",
	Long:  "Issue Gremlin queries",
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 || args[0] == "" {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		gremlinQuery := args[0]
		queryHelper := api.NewGremlinQueryHelper(CrudClient.RestClient)

		switch outputFormat {
		case "json":
			data, err := queryHelper.Query(gremlinQuery)
			if err != nil {
				exitOnError(err)
			}

			var out bytes.Buffer
			json.Indent(&out, data, "", "\t")
			out.WriteTo(os.Stdout)
		case "dot":
			header := make(http.Header)
			header.Set("Accept", "text/vnd.graphviz")
			resp, err := queryHelper.Request(gremlinQuery, header)
			if err != nil {
				exitOnError(err)
			}
			defer resp.Body.Close()

			if resp.StatusCode != http.StatusOK {
				data, _ := ioutil.ReadAll(resp.Body)
				exitOnError(fmt.Errorf("%s: %s", resp.Status, string(data)))
			}
			bufio.NewReader(resp.Body).WriteTo(os.Stdout)
		case "pcap":
			header := make(http.Header)
			header.Set("Accept", "application/vnd.tcpdump.pcap")
			resp, err := queryHelper.Request(gremlinQuery, header)
			if err != nil {
				exitOnError(err)
			}
			defer resp.Body.Close()

			if resp.StatusCode != http.StatusOK {
				data, _ := ioutil.ReadAll(resp.Body)
				exitOnError(fmt.Errorf("%s: %s", resp.Status, string(data)))
			}

			bufio.NewReader(resp.Body).WriteTo(os.Stdout)
		default:
			logging.GetLogger().Errorf("Invalid output format %s", outputFormat)
			os.Exit(1)
		}
	},
}

QueryCmd skydive topology query command

View Source
var ShellCmd = &cobra.Command{
	Use:          "shell",
	Short:        "Gremlin shell",
	Long:         "Gremlin shell",
	SilenceUsage: false,
	Run: func(cmd *cobra.Command, args []string) {
		s, err := NewSession()
		if err != nil {
			logging.GetLogger().Errorf("Error while creating session: %s", err)
			os.Exit(1)
		}
		defer s.Close()

		if shellScript != "" {
			result := s.runtime.RunScript(shellScript)
			if result.IsDefined() {
				logging.GetLogger().Errorf("Error while executing script %s: %s", shellScript, result.String())
			}
		}

		s.prompt()

		if err := s.saveHistory(); err != nil {
			logging.GetLogger().Errorf("Error while saving history: %s", err)
		}
	},
}

ShellCmd skydive shell root command

View Source
var TopologyCmd = &cobra.Command{
	Use:          "topology",
	Short:        "Request on topology",
	Long:         "Request on topology",
	SilenceUsage: false,
}

TopologyCmd skydive topology root command

View Source
var TopologyExport = &cobra.Command{
	Use:   "export",
	Short: "export topology",
	Long:  "export topology",
	Run: func(cmd *cobra.Command, args []string) {
		QueryCmd.Run(cmd, []string{"G"})
	},
}

TopologyExport skydive topology export command

View Source
var TopologyImport = &cobra.Command{
	Use:   "import",
	Short: "import topology",
	Long:  "import topology",
	Run: func(cmd *cobra.Command, args []string) {
		url, err := shttp.MakeURL("ws", hubService.Addr, hubService.Port, publisherEndpoint, tlsConfig != nil)
		if err != nil {
			exitOnError(err)
		}
		opts := websocket.ClientOpts{AuthOpts: &AuthenticationOpts, Headers: http.Header{}, TLSConfig: tlsConfig}
		opts.Headers.Add("X-Persistence-Policy", string(endpoints.Persistent))
		client := websocket.NewClient(Host, service.Type("CLI"), url, opts)

		if err := client.Connect(context.Background()); err != nil {
			exitOnError(err)
		}

		go client.Run()
		defer func() {
			client.Flush()
			client.StopAndWait()
		}()

		content, err := ioutil.ReadFile(filename)
		if err != nil {
			exitOnError(err)
		}

		els := []*graph.Elements{}
		if err := json.Unmarshal(content, &els); err != nil {
			exitOnError(err)
		}

		if len(els) != 1 {
			exitOnError(errors.New("Invalid graph format"))
		}

		for _, node := range els[0].Nodes {
			msg := messages.NewStructMessage(messages.NodeAddedMsgType, node)
			if err := client.SendMessage(msg); err != nil {
				exitOnError(fmt.Errorf("Failed to send message: %s", err))
			}
		}

		for _, edge := range els[0].Edges {
			msg := messages.NewStructMessage(messages.EdgeAddedMsgType, edge)
			if err := client.SendMessage(msg); err != nil {
				exitOnError(fmt.Errorf("Failed to send message: %s", err))
			}
		}
	},
}

TopologyImport skydive topology import command

View Source
var TopologyRequest = &cobra.Command{
	Use:   "query",
	Short: "query topology [deprecated: use 'client query' instead]",
	Long:  "query topology [deprecated: use 'client query' instead]",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Fprintln(os.Stderr, "The 'client topology query' command is deprecated. Please use 'client query' instead")
		QueryCmd.Run(cmd, []string{gremlinQuery})
	},
}

TopologyRequest skydive topology query command

View Source
var WorkflowCall = &cobra.Command{
	Use:          "call workflow",
	Short:        "Call workflow",
	Long:         "Call workflow",
	SilenceUsage: false,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) < 1 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		var workflowCall types.WorkflowCall
		var result interface{}
		params := make([]interface{}, len(args)-1)
		for i, arg := range args[1:] {
			params[i] = arg
		}

		workflowCall.Params = params

		s, err := json.Marshal(workflowCall)
		if err != nil {
			exitOnError(err)
		}

		contentReader := bytes.NewReader(s)
		resp, err := CrudClient.Request("POST", "workflow/"+args[0]+"/call", contentReader, nil)
		if err != nil {
			exitOnError(err)
		}
		defer resp.Body.Close()

		decoder := json.NewDecoder(resp.Body)
		if err := decoder.Decode(&result); err != nil {
			exitOnError(err)
		}

		printJSON(result)
	},
}

WorkflowCall describes the "workflow call" command

View Source
var WorkflowCmd = &cobra.Command{
	Use:          "workflow",
	Short:        "Manage workflows",
	Long:         "Manage workflows",
	SilenceUsage: false,
}

WorkflowCmd describe the "workflow" root command

View Source
var WorkflowCreate = &cobra.Command{
	Use:          "create",
	Short:        "create workflow",
	Long:         "create workflow",
	SilenceUsage: false,
	Run: func(cmd *cobra.Command, args []string) {
		workflow, err := loadWorklow(workflowPath)
		if err != nil {
			exitOnError(err)
		}

		if err := CrudClient.Create("workflow", &workflow, nil); err != nil {
			exitOnError(err)
		}
		printJSON(workflow)
	},
}

WorkflowCreate describes the "workflow create" command

View Source
var WorkflowDelete = &cobra.Command{
	Use:          "delete",
	Short:        "delete workflow",
	Long:         "delete workflow",
	SilenceUsage: false,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			cmd.Usage()
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		for _, id := range args {
			if err := CrudClient.Delete("workflow", id); err != nil {
				logging.GetLogger().Error(err)
			}
		}
	},
}

WorkflowDelete describes the "workflow delete" command

View Source
var WorkflowList = &cobra.Command{
	Use:          "list",
	Short:        "List workflows",
	Long:         "List workflows",
	SilenceUsage: false,
	Run: func(cmd *cobra.Command, args []string) {
		var workflows map[string]types.Workflow
		if err := CrudClient.List("workflow", &workflows); err != nil {
			exitOnError(err)
		}
		printJSON(workflows)
	},
}

WorkflowList describes the "workflow list" command

Functions

This section is empty.

Types

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session describes a shell session

func NewSession

func NewSession() (*Session, error)

NewSession creates a new shell session

func (*Session) Close

func (s *Session) Close() error

Close the session

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL