Skip to content
Snippets Groups Projects
prompt.go 16.8 KiB
Newer Older
  • Learn to ignore specific revisions
  • /*
    Copyright © 2021 da/net Research Group <danet@h-da.de>
    All rights reserved.
    
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    
    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
    
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
    */
    
    package cmd
    
    import (
    
    
    	"code.fbi.h-da.de/danet/gosdn/cli/completer"
    
    	"code.fbi.h-da.de/danet/gosdn/controller/api"
    
    	"github.com/c-bata/go-prompt"
    	"github.com/google/uuid"
    
    	"github.com/openconfig/goyang/pkg/yang"
    
    	"github.com/pterm/pterm"
    
    	"github.com/pterm/pterm/putils"
    
    	"github.com/spf13/cobra"
    	"github.com/spf13/pflag"
    
    	"github.com/spf13/viper"
    
    var c *PromptCompleter
    
    var fd int
    var originalTermios *unix.Termios
    var mutContext *ContextMutable
    
    // suggestionTracker is used to keep track of the last used command in
    // combination with the resulting suggestions.
    type suggestionTracker struct {
    	lastCommand    *cobra.Command
    	lastSuggestion []prompt.Suggest
    }
    
    
    Malte Bauch's avatar
    Malte Bauch committed
    // PromptCompleter provides completion for a Network Element.
    
    type PromptCompleter struct {
    
    	YangSchemaCompleterMap map[uuid.UUID]*completer.YangSchemaCompleter
    
    	// nolint:unused
    	document *prompt.Document
    	history  []string
    
    type ContextMutable struct {
    	context.Context
    }
    
    
    // NewPromptCompleter returns a new promptCompleter.
    
    func NewPromptCompleter() *PromptCompleter {
    	return &PromptCompleter{
    
    		YangSchemaCompleterMap: make(map[uuid.UUID]*completer.YangSchemaCompleter),
    
    // Run starts the interactive completion.
    
    func (pc *PromptCompleter) Run() {
    
    	title, _ := pterm.DefaultBigText.WithLetters(
    
    		putils.LettersFromString("go"),
    		putils.LettersFromStringWithStyle("SDN", pterm.NewStyle(pterm.FgCyan)),
    		putils.LettersFromString("c"),
    
    	).Srender()
    	description := pterm.DefaultBasicText.Sprint("Control your goSDN controller like you've never done it before!")
    	pterm.DefaultCenter.Println(title)
    	pterm.DefaultCenter.Println(description)
    
    
    	p := prompt.New(
    		executeFunc,
    		pc.cstmCompleter,
    		prompt.OptionTitle("gosdnc-prompt: interactive gosdn CLI"),
    		prompt.OptionPrefix(">>> "),
    
    		prompt.OptionPrefixTextColor(prompt.Cyan),
    
    		prompt.OptionCompletionWordSeparator(completer.YangSchemaCompletionSeperator),
    		prompt.OptionShowCompletionAtStart(),
    
    		prompt.OptionCompletionOnDown(),
    		prompt.OptionHistory(pc.history),
    		prompt.OptionSuggestionBGColor(prompt.DarkGray),
    		prompt.OptionSuggestionTextColor(prompt.LightGray),
    		prompt.OptionDescriptionTextColor(prompt.DarkGray),
    		prompt.OptionDescriptionBGColor(prompt.LightGray),
    		prompt.OptionSelectedSuggestionBGColor(prompt.Cyan),
    
    		prompt.OptionSelectedSuggestionTextColor(prompt.DarkGray),
    
    		prompt.OptionSelectedDescriptionBGColor(prompt.LightGray),
    		prompt.OptionSelectedDescriptionTextColor(prompt.DarkGray),
    
    	var err error
    
    	fd, err = syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
    	if err != nil {
    		panic(err)
    	}
    
    	// get the original settings
    	originalTermios, err = termios.Tcgetattr(uintptr(fd))
    	if err != nil {
    		panic(err)
    	}
    
    
    	p.Run()
    }
    
    func executeFunc(s string) {
    	if s := strings.TrimSpace(s); s == "" {
    		return
    	}
    
    	// restore the original settings to allow ctrl-c to generate signal
    	if err := termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(originalTermios)); err != nil {
    		panic(err)
    	}
    
    	ctx, ctxCancelFn := createContextWithAuthorization()
    
    	mutContext.Context = ctx
    
    	startContextListener(mutContext, ctxCancelFn)
    
    	rootCmd.SetArgs(strings.Fields(s))
    
    	err := rootCmd.ExecuteContext(mutContext)
    
    		pterm.Error.Println("Could not execute:", err)
    
    func (pc *PromptCompleter) cstmCompleter(d prompt.Document) []prompt.Suggest {
    
    	// Start with the cobra 'rootCmd' and walk through it
    	// Reference: https://github.com/stromland/cobra-prompt
    	currCmd := rootCmd
    
    	inputSplit := strings.Fields(d.CurrentLine())
    	inputSplitFiltered, inputFlags := filterFlagSlice(inputSplit)
    	if c, _, err := currCmd.Find(inputSplitFiltered); err == nil {
    
    	return completionBasedOnCmd(pc, currCmd, inputSplit, inputSplitFiltered, inputFlags, d)
    
    func filterFlagSlice(input []string) (commandSlice []string, flagSlice []string) {
    
    	for _, in := range input {
    		if !strings.HasPrefix(in, "--") {
    
    			commandSlice = append(commandSlice, in)
    		} else {
    			flagSlice = append(flagSlice, strings.Split(in, "=")[0])
    
    	return commandSlice, flagSlice
    
    func networkElementPathCompletion(c *PromptCompleter, command *cobra.Command, d prompt.Document, inputSplit []string) []prompt.Suggest {
    
    	switch inputLen := len(inputSplit); inputLen {
    	case 3:
    
    		return c.updateSuggestionsThroughFunc(d, command, getNetworkElements)
    
    		id, err := uuid.Parse(inputSplit[inputLen-1])
    		if err != nil {
    
    			return c.updateSuggestionsThroughFunc(d, command, getNetworkElements)
    
    		if c, ok := c.YangSchemaCompleterMap[id]; ok {
    
    		schemaTree, err := getSchemaTreeForNetworkElementID(id)
    
    			return []prompt.Suggest{}
    		}
    
    		c.YangSchemaCompleterMap[id] = completer.NewYangSchemaCompleter(schemaTree["Device"], true)
    		if yc, ok := c.YangSchemaCompleterMap[id]; ok {
    
    		if d.GetWordBeforeCursor() == "" || d.GetWordAfterCursor() != "" {
    
    			id, err := uuid.Parse(inputSplit[inputLen-2])
    			if err != nil {
    
    				return c.updateSuggestionsThroughFunc(d, command, getNetworkElements)
    
    			}
    			if yc, ok := c.YangSchemaCompleterMap[id]; ok {
    				err := yc.UpdateEntry(inputSplit[inputLen-1])
    				if err != nil {
    					pterm.Error.Println(err)
    				}
    			}
    
    			return []prompt.Suggest{}
    		}
    		id, err := uuid.Parse(inputSplit[inputLen-2])
    		if err != nil {
    
    			return c.updateSuggestionsThroughFunc(d, command, getNetworkElements)
    
    		if yc, ok := c.YangSchemaCompleterMap[id]; ok {
    
    		return []prompt.Suggest{}
    	}
    	return []prompt.Suggest{}
    }
    
    
    func (pc *PromptCompleter) updateSuggestionsThroughFunc(d prompt.Document, c *cobra.Command, fn func() ([]prompt.Suggest, error)) []prompt.Suggest {
    	if pc.lastSuggestions == nil {
    
    		if err != nil {
    			return prompt.FilterHasPrefix([]prompt.Suggest{}, d.GetWordBeforeCursor(), true)
    		}
    
    		pc.lastSuggestions = &suggestionTracker{
    			lastCommand:    c,
    			lastSuggestion: newSuggestions,
    		}
    
    	return prompt.FilterHasPrefix(pc.lastSuggestions.lastSuggestion, d.GetWordBeforeCursor(), true)
    
    }
    
    func cobraCommandCompletion(currCmd *cobra.Command, d prompt.Document, inputFlags []string, loaded []prompt.Suggest) []prompt.Suggest {
    
    	if currCmd.HasAvailableFlags() {
    
    		currCmd.LocalFlags().VisitAll(
    			func(f *pflag.Flag) {
    				if !f.Hidden && !sliceContains(inputFlags, "--"+f.Name) {
    					loaded = append(loaded, prompt.Suggest{Text: "--" + f.Name, Description: f.Usage})
    				}
    			},
    		)
    
    	}
    
    	for _, cmd := range currCmd.Commands() {
    
    		loaded = append(loaded, prompt.Suggest{Text: cmd.Name(), Description: cmd.Short})
    
    
    	return prompt.FilterHasPrefix(loaded, d.GetWordBeforeCursor(), true)
    
    func completionBasedOnCmd(c *PromptCompleter, cmd *cobra.Command, inputSplit []string, inputSplitFiltered []string, inputFlags []string, d prompt.Document) []prompt.Suggest {
    
    	case pndUseCmd, pndGetCmd, pndRemoveCmd:
    
    		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
    
    			if c.lastSuggestions != nil {
    				lastCommand := c.lastSuggestions.lastCommand
    				if lastCommand != pndUseCmd && lastCommand != pndGetCmd && lastCommand != pndRemoveCmd {
    					c.lastSuggestions = nil
    				}
    			}
    			suggestions := c.updateSuggestionsThroughFunc(d, cmd, getPnds)
    
    			return cobraCommandCompletion(cmd, d, inputFlags, suggestions)
    		}
    
    		if c.lastSuggestions != nil {
    			if c.lastSuggestions.lastCommand != commitCmd {
    				c.lastSuggestions = nil
    			}
    		}
    
    		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
    
    			return c.updateSuggestionsThroughFunc(d, cmd, getPendingChanges)
    
    		if c.lastSuggestions != nil {
    			if c.lastSuggestions.lastCommand != confirmCmd {
    				c.lastSuggestions = nil
    			}
    		}
    
    		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
    
    			return c.updateSuggestionsThroughFunc(d, cmd, getCommittedChanges)
    
    	case networkElementRemoveCmd:
    
    		if c.lastSuggestions != nil {
    			if c.lastSuggestions.lastCommand != networkElementRemoveCmd {
    				c.lastSuggestions = nil
    			}
    		}
    
    		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
    
    			return c.updateSuggestionsThroughFunc(d, cmd, getNetworkElements)
    
    		if c.lastSuggestions != nil {
    			if c.lastSuggestions.lastCommand != networkElementCreateCmd {
    				c.lastSuggestions = nil
    			}
    		}
    
    		if len(inputFlags) != 0 {
    			if inputFlags[len(inputFlags)-1] == "--plugin-id" &&
    				((inputSplit[len(inputSplit)-1] == "--plugin-id" && d.GetWordBeforeCursor() == "") ||
    					(inputSplit[len(inputSplit)-2] == "--plugin-id" && d.GetWordBeforeCursor() != "")) {
    
    				return c.updateSuggestionsThroughFunc(d, cmd, getAvailablePlugins)
    
    			} else {
    				return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
    			}
    		} else {
    			return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
    		}
    
    	case networkElementPathGetCmd, networkElementPathGetIntendedCmd, networkElementPathSetCmd:
    
    		if c.lastSuggestions != nil {
    			lastCommand := c.lastSuggestions.lastCommand
    			if lastCommand != networkElementPathGetCmd && lastCommand != networkElementPathGetIntendedCmd && lastCommand != networkElementPathSetCmd {
    				c.lastSuggestions = nil
    			}
    		}
    		return networkElementPathCompletion(c, cmd, d, inputSplitFiltered)
    
    Malte Bauch's avatar
    Malte Bauch committed
    		networkElements, err := getNetworkElements()
    
    		if err != nil {
    			return []prompt.Suggest{}
    		}
    
    Malte Bauch's avatar
    Malte Bauch committed
    		return networkElements
    
    	case networkElementCmd, pndCmd, changeCmd:
    
    		return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
    
    		return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
    	}
    
    	return []prompt.Suggest{}
    }
    
    
    Malte Bauch's avatar
    Malte Bauch committed
    // getNetworkElements is a helper function which requests Network Elements from the controller
    
    // and gives feedback about the current pulling status with the help of pterm
    // the result is converted into a prompt.Suggest slice.
    
    Malte Bauch's avatar
    Malte Bauch committed
    func getNetworkElements() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching Network Elements from controller.")
    
    	// create a authorizedContext for further requests
    
    	ctx, _ := createContextWithAuthorization()
    
    	resp, err := pndAdapter.GetFlattenedNetworkElements(ctx)
    
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    
    	for _, mne := range resp.Mne {
    		s = append(s, prompt.Suggest{Text: mne.GetId(), Description: mne.GetName()})
    
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    
    func getAvailablePlugins() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching available plugins from controller.")
    
    	// create a authorizedContext for further requests
    
    	ctx, _ := createContextWithAuthorization()
    
    	resp, err := pndAdapter.GetAvailablePlugins(ctx)
    
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, plugin := range resp.GetPlugins() {
    		s = append(s, prompt.Suggest{Text: plugin.GetId(), Description: plugin.Manifest.GetName()})
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    
    Malte Bauch's avatar
    Malte Bauch committed
    // getSchemaTreeForNetworkElementID is a helper function which requests the SBI's
    // schema tree of a specific Network Element. The function gives feedback about the
    
    // current pulling status with the help of pterm.
    
    func getSchemaTreeForNetworkElementID(id uuid.UUID) (map[string]*yang.Entry, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching schema tree for Device with ID: ", id)
    
    	// create a authorizedContext for further requests
    
    	ctx, _ := createContextWithAuthorization()
    
    	networkElement, err := pndAdapter.GetFlattenedNetworkElement(ctx, id.String())
    
    	if err != nil {
    		spinner.Fail(err)
    		return nil, err
    	}
    
    
    	pluginID := networkElement.GetMne().GetPluginid()
    	pluginUUID := uuid.MustParse(pluginID)
    
    	// create a authorizedContext for further requests
    
    	ctx, _ = createContextWithAuthorization()
    
    	schemaTree, err := pndAdapter.GetPluginSchemaTree(ctx, pluginUUID)
    
    	if err != nil {
    		spinner.Fail(err)
    		return nil, err
    	}
    	spinner.Success()
    
    }
    
    // getPnds is a helper function which requests pnds from the controller and
    // gives feedback about the current pulling status with the help of pterm the
    // result is converted into a prompt.Suggest slice.
    func getPnds() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching PNDs from controller.")
    
    	// create a authorizedContext for further requests
    
    	ctx, _ := createContextWithAuthorization()
    
    	resp, err := api.GetIds(ctx, viper.GetString("controllerAPIEndpoint"))
    
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, pnd := range resp {
    		s = append(s, prompt.Suggest{Text: pnd.GetId(), Description: pnd.GetDescription()})
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    
    // getPendingChanges is a helper function which requests all the pending
    
    // changes from the controller and gives feedback about the current pulling
    // status with the help of pterm the result is converted into a prompt.Suggest
    // slice.
    
    func getPendingChanges() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching committed changes.")
    
    	// create a authorizedContext for further requests
    
    	ctx, _ := createContextWithAuthorization()
    
    	resp, err := pndAdapter.PendingChanges(ctx)
    
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, change := range resp {
    		s = append(s, prompt.Suggest{Text: change.GetId(), Description: change.State.String()})
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    // getCommittedChanges is a helper function which requests all the committed
    // changes from the controller and gives feedback about the current pulling
    // status with the help of pterm the result is converted into a prompt.Suggest
    // slice.
    func getCommittedChanges() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching pending changes.")
    
    	// create a authorizedContext for further requests
    
    	ctx, _ := createContextWithAuthorization()
    
    	resp, err := pndAdapter.CommittedChanges(ctx)
    
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, change := range resp {
    		s = append(s, prompt.Suggest{Text: change.GetId(), Description: change.State.String()})
    
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    
    }
    
    var exitCmd = &cobra.Command{
    	Use:   "exit",
    	Short: "The exit command exits the interactive prompt mode.",
    	Long:  `The exit command exits the interactive prompt mode.`,
    
    
    	Run: func(cmd *cobra.Command, args []string) {
    
    		rawModeOff := exec.Command("/bin/stty", "-raw", "echo")
    		rawModeOff.Stdin = os.Stdin
    
    		err := rawModeOff.Run()
    		if err != nil {
    			logrus.Error(err)
    			os.Exit(1)
    		}
    		os.Exit(0)
    
    	},
    }
    
    var promptCmd = &cobra.Command{
    	Use:   "prompt",
    	Short: "The prompt command runs the CLI in an interactive shell.",
    	Long: `The prompt command rund the CLI in an interactive shell and
        provides the user with autocompletion and more...`,
    
    
    	Run: func(cmd *cobra.Command, args []string) {
    
    		mutContext = &ContextMutable{Context: nil}
    
    		c = NewPromptCompleter()
    
    		c.Run()
    	},
    }
    
    func init() {
    	rootCmd.AddCommand(promptCmd)
    	rootCmd.AddCommand(exitCmd)
    }