Exemple #1
1
func newConfig() *Conf {
	c := new(Conf)
	c.ldapViper = viper.New()
	c.ldapConfig = &LdapConfig{}
	c.notificationConfigs = []NotificationServiceConfig{}

	viper.SetConfigName("indispenso")
	viper.SetEnvPrefix("ind")

	// Defaults
	viper.SetDefault("Token", "")
	viper.SetDefault("Hostname", getDefaultHostName())
	viper.SetDefault("UseAutoTag", true)
	viper.SetDefault("ServerEnabled", false)
	viper.SetDefault("Home", defaultHomePath)
	viper.SetDefault("Debug", false)
	viper.SetDefault("ServerPort", 897)
	viper.SetDefault("EndpointURI", "")
	viper.SetDefault("SslCertFile", "cert.pem")
	viper.SetDefault("SslPrivateKeyFile", "key.pem")
	viper.SetDefault("AutoGenerateCert", true)
	viper.SetDefault("ClientPort", 898)
	viper.SetDefault("EnableLdap", false)
	viper.SetDefault("LdapConfigFile", "")

	//Flags
	c.confFlags = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)

	configFile := c.confFlags.StringP("config", "c", "", "Config file location default is /etc/indispenso/indispenso.{json,toml,yaml,yml,properties,props,prop}")
	c.confFlags.BoolP("serverEnabled", "s", false, "Define if server module should be started or not")
	c.confFlags.BoolP("debug", "d", false, "Enable debug mode")
	c.confFlags.StringP("home", "p", defaultHomePath, "Home directory where all config files are located")
	c.confFlags.StringP("endpointUri", "e", "", "URI of server interface, used by client")
	c.confFlags.StringP("token", "t", "", "Secret token")
	c.confFlags.StringP("hostname", "i", getDefaultHostName(), "Hostname that is use to identify itself")
	c.confFlags.BoolP("enableLdap", "l", false, "Enable LDAP authentication")
	c.confFlags.BoolP("help", "h", false, "Print help message")

	c.confFlags.Parse(os.Args[1:])
	if len(*configFile) > 2 {
		viper.SetConfigFile(*configFile)
	} else {
		legacyConfigFile := "/etc/indispenso/indispenso.conf"
		if _, err := os.Stat(legacyConfigFile); err == nil {
			viper.SetConfigFile(legacyConfigFile)
			viper.SetConfigType("yaml")
		}
	}
	viper.BindPFlags(c.confFlags)
	viper.AutomaticEnv()

	viper.ReadInConfig()

	c.setupHome(nil, viper.GetString("Home"))
	c.setupHome(c.ldapViper, viper.GetString("Home"))

	c.SetupNotificationConfig("slack", &SlackNotifyConfig{})
	c.Update()
	return c
}
Exemple #2
0
// For use in testing
func (c *Command) ResetFlags() {
	c.flagErrorBuf = new(bytes.Buffer)
	c.flagErrorBuf.Reset()
	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	c.flags.SetOutput(c.flagErrorBuf)
	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	c.pflags.SetOutput(c.flagErrorBuf)
}
Exemple #3
0
func TestBindPFlags(t *testing.T) {
	flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)

	var testValues = map[string]*string{
		"host":     nil,
		"port":     nil,
		"endpoint": nil,
	}

	var mutatedTestValues = map[string]string{
		"host":     "localhost",
		"port":     "6060",
		"endpoint": "/public",
	}

	for name, _ := range testValues {
		testValues[name] = flagSet.String(name, "", "test")
	}

	err := BindPFlags(flagSet)
	if err != nil {
		t.Fatalf("error binding flag set, %v", err)
	}

	flagSet.VisitAll(func(flag *pflag.Flag) {
		flag.Value.Set(mutatedTestValues[flag.Name])
		flag.Changed = true
	})

	for name, expected := range mutatedTestValues {
		assert.Equal(t, Get(name), expected)
	}

}
Exemple #4
0
func TestDynInt64_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	DynInt64(set, "some_int_1", 13371337, "Use it or lose it").WithValidator(ValidateDynInt64Range(0, 2000))

	assert.NoError(t, set.Set("some_int_1", "300"), "no error from validator when in range")
	assert.Error(t, set.Set("some_int_1", "2001"), "error from validator when value out of range")
}
Exemple #5
0
func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error {
	return func(c *cobra.Command) error {
		t := template.New("custom")

		t.Funcs(template.FuncMap{
			"trim":                strings.TrimSpace,
			"trimRight":           func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
			"gt":                  cobra.Gt,
			"eq":                  cobra.Eq,
			"rpad":                rpad,
			"flagsNotIntersected": flagsNotIntersected,
			"flagsUsages":         flagsUsages,
			"cmdGroups":           templater.cmdGroups,
			"rootCmd":             templater.rootCmdName,
			"isRootCmd":           templater.isRootCmd,
			"optionsCmdFor":       templater.optionsCmdFor,
			"exposed": func(c *cobra.Command) *flag.FlagSet {
				exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
				if len(exposedFlags) > 0 {
					for _, name := range exposedFlags {
						if flag := c.Flags().Lookup(name); flag != nil {
							exposed.AddFlag(flag)
						}
					}
				}
				return exposed
			},
		})

		template.Must(t.Parse(templater.UsageTemplate))
		return t.Execute(c.Out(), c)
	}
}
Exemple #6
0
func parseFlagsAndArgs() ([]string, error) {
	// We need to override the default behavior to exit program on parsing error
	// and to not immediately write errors encountered to Stdout
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	flag.CommandLine.SetOutput(&flagParsingOut)
	flag.Usage = func() {
		fmt.Fprintf(&flagParsingOut, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.BoolVarP(&verboseFlag, "verbose", "v", false, "Verbose mode")
	flag.BoolVarP(&helpFlag, "help", "h", false, "help")
	err := flag.CommandLine.Parse(os.Args[1:])
	if verboseFlag {
		log.Level = logrus.DebugLevel
	}
	args := flag.Args()
	log.Debugf("args are %v", args)
	if len(args) < 1 {
		return []string{"", ""}, err
	}
	if len(args) < 2 {
		return []string{args[0], ""}, err
	}

	return args, err
}
func TestKubectlCompatibility(t *testing.T) {
	f := clientcmd.New(pflag.NewFlagSet("name", pflag.ContinueOnError))

	oc := NewCommandCLI("oc", "oc", &bytes.Buffer{}, ioutil.Discard, ioutil.Discard)
	kubectl := kcmd.NewKubectlCommand(f.Factory, nil, ioutil.Discard, ioutil.Discard)

kubectlLoop:
	for _, kubecmd := range kubectl.Commands() {
		for _, occmd := range oc.Commands() {
			if kubecmd.Name() == occmd.Name() {
				if MissingCommands.Has(kubecmd.Name()) {
					t.Errorf("%s was supposed to be missing", kubecmd.Name())
					continue
				}
				if WhitelistedCommands.Has(kubecmd.Name()) {
					t.Errorf("%s was supposed to be whitelisted", kubecmd.Name())
					continue
				}
				continue kubectlLoop
			}
		}
		if MissingCommands.Has(kubecmd.Name()) || WhitelistedCommands.Has(kubecmd.Name()) {
			continue
		}

		t.Errorf("missing %q in oc", kubecmd.Name())
	}

}
Exemple #8
0
// All Flags which were inherited from parents commands
func (c *Command) InheritedFlags() *flag.FlagSet {
	c.mergePersistentFlags()

	inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	local := c.LocalFlags()

	var rmerge func(x *Command)

	rmerge = func(x *Command) {
		if x.HasPersistentFlags() {
			x.PersistentFlags().VisitAll(func(f *flag.Flag) {
				if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
					inherited.AddFlag(f)
				}
			})
		}
		if x.HasParent() {
			rmerge(x.parent)
		}
	}

	if c.HasParent() {
		rmerge(c.parent)
	}

	return inherited
}
Exemple #9
0
func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap {
	return template.FuncMap{
		"trim":                strings.TrimSpace,
		"trimRight":           func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
		"trimLeft":            func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) },
		"gt":                  cobra.Gt,
		"eq":                  cobra.Eq,
		"rpad":                rpad,
		"appendIfNotPresent":  appendIfNotPresent,
		"flagsNotIntersected": flagsNotIntersected,
		"visibleFlags":        visibleFlags,
		"flagsUsages":         flagsUsages,
		"cmdGroups":           templater.cmdGroups,
		"cmdGroupsString":     templater.cmdGroupsString,
		"rootCmd":             templater.rootCmdName,
		"isRootCmd":           templater.isRootCmd,
		"optionsCmdFor":       templater.optionsCmdFor,
		"usageLine":           templater.usageLine,
		"exposed": func(c *cobra.Command) *flag.FlagSet {
			exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
			if len(exposedFlags) > 0 {
				for _, name := range exposedFlags {
					if flag := c.Flags().Lookup(name); flag != nil {
						exposed.AddFlag(flag)
					}
				}
			}
			return exposed
		},
	}
}
Exemple #10
0
func parseFlags(config cfg.Config, args []string) {
	var (
		printHelp bool
		moniker   string
		nodeLaddr string
		seeds     string
		fastSync  bool
		rpcLaddr  string
		logLevel  string
	)

	// Declare flags
	var flags = flag.NewFlagSet("main", flag.ExitOnError)
	flags.BoolVar(&printHelp, "help", false, "Print this help message.")
	flags.StringVar(&moniker, "moniker", config.GetString("moniker"), "Node Name")
	flags.StringVar(&nodeLaddr, "node_laddr", config.GetString("node_laddr"), "Node listen address. (0.0.0.0:0 means any interface, any port)")
	flags.StringVar(&seeds, "seeds", config.GetString("seeds"), "Comma delimited seed nodes")
	flags.BoolVar(&fastSync, "fast_sync", config.GetBool("fast_sync"), "Fast blockchain syncing")
	flags.StringVar(&rpcLaddr, "rpc_laddr", config.GetString("rpc_laddr"), "RPC listen address. Port required")
	flags.StringVar(&logLevel, "log_level", config.GetString("log_level"), "Log level")
	flags.Parse(args)
	if printHelp {
		flags.PrintDefaults()
		os.Exit(0)
	}

	// Merge parsed flag values onto app.
	config.Set("moniker", moniker)
	config.Set("node_laddr", nodeLaddr)
	config.Set("seeds", seeds)
	config.Set("fast_sync", fastSync)
	config.Set("rpc_laddr", rpcLaddr)
	config.Set("log_level", logLevel)
}
Exemple #11
0
func main() {
	fset := pflag.NewFlagSet("gtc", pflag.ExitOnError)
	fset.BoolVarP(&Help, "help", "h", false, "show help message")
	fset.BoolVarP(&Verbose, "verbose", "v", true, "verbose output")
	fset.BoolVar(&Silence, "silence", true, "silence log output")
	args := os.Args
	if len(args) >= 2 {
		switch args[1] {
		case "test":
			Test(args[1:])
			return
		}
	}

	fset.Parse(os.Args)

	show, err := fset.GetBool("help")
	if err != nil {
		log.Fatal(err)
	}

	if show {
		fmt.Println(Usage)
		os.Exit(84)
	}
	if Silence {
		args = arrRemove(args, "--silence")
	}
	code, err := Scan(Input)
	if err != nil {
		log.Fatal(err)
	}
	os.Exit(code)
}
Exemple #12
0
func TestChecksumFlagSet_Differs(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	flagz.DynDuration(set, "some_duration_1", 5*time.Second, "Use it or lose it")
	flagz.DynInt64(set, "some_int_1", 13371337, "Use it or lose it")
	set.String("static_string_1", "foobar", "meh")

	preInitChecksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("pre init checksum:  %x", preInitChecksum)

	set.Parse([]string{"--some_duration_1", "3s", "--static_string_1", "goodbar"})
	postInitChecksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post init checksum: %x", postInitChecksum)
	assert.NotEqual(t, preInitChecksum, postInitChecksum, "checksum must be different init changed 2 flags")

	require.NoError(t, set.Set("some_int_1", "1337"))
	postSet1Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set1 checksum: %x", postSet1Checksum)
	assert.NotEqual(t, postInitChecksum, postSet1Checksum, "checksum must be different after a internal flag change")

	require.NoError(t, set.Set("some_duration_1", "4s"))
	postSet2Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set2 checksum: %x", postSet2Checksum)
	assert.NotEqual(t, postSet1Checksum, postSet2Checksum, "checksum must be different after a internal flag change")

	require.NoError(t, set.Set("some_duration_1", "3s"))
	postSet3Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set3 checksum: %x", postSet3Checksum)
	assert.EqualValues(t, postSet1Checksum, postSet3Checksum, "flipping back duration flag to state at set1 should make it equal")
}
func TestFeatureGateFlag(t *testing.T) {
	tests := []struct {
		arg        string
		allAlpha   bool
		parseError error
	}{
		{fmt.Sprintf("--%s=fooBarBaz=maybeidk", flagName), false, fmt.Errorf("unrecognized key: fooBarBaz")},
		{fmt.Sprintf("--%s=", flagName), false, nil},
		{fmt.Sprintf("--%s=allAlpha=false", flagName), false, nil},
		{fmt.Sprintf("--%s=allAlpha=true", flagName), true, nil},
		{fmt.Sprintf("--%s=allAlpha=banana", flagName), false, fmt.Errorf("invalid value of allAlpha")},
	}
	for i, test := range tests {
		fs := pflag.NewFlagSet("testfeaturegateflag", pflag.ContinueOnError)
		f := &featureGate{}
		f.AddFlag(fs)

		err := fs.Parse([]string{test.arg})
		if test.parseError != nil {
			if !strings.Contains(err.Error(), test.parseError.Error()) {
				t.Errorf("%d: Parse() Expected %v, Got %v", i, test.parseError, err)
			}
		} else if err != nil {
			t.Errorf("%d: Parse() Expected nil, Got %v", i, err)
		}
		if alpha := f.AllAlpha(); alpha != test.allAlpha {
			t.Errorf("%d: AlphaEnabled() expected %v, Got %v", i, test.allAlpha, alpha)
		}
	}
}
Exemple #14
0
func NewConfig() (*Config, error) {
	flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	c := Config{}
	flags.StringVarP(&c.URL, "url", "u", "", "the url")
	viper.BindPFlag("url", flags.Lookup("url"))

	// This doesn't need to be in the Config struct, because we're just using it to override viper.
	file := flags.StringP("file", "f", "", "name of the config file")

	// Parse the command line args into the flag set, ignoring the command name.
	flags.Parse(os.Args[1:])

	if *file != "" {
		viper.SetConfigFile(*file)
	}

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	if err := viper.Unmarshal(&c); err != nil {
		return nil, err
	}

	return &c, nil
}
func (c *Command) mergePersistentFlags() {
	var rmerge func(x *Command)

	// Save the set of local flags
	if c.lflags == nil {
		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
		if c.flagErrorBuf == nil {
			c.flagErrorBuf = new(bytes.Buffer)
		}
		c.lflags.SetOutput(c.flagErrorBuf)
		addtolocal := func(f *flag.Flag) {
			c.lflags.AddFlag(f)
		}
		c.Flags().VisitAll(addtolocal)
		c.PersistentFlags().VisitAll(addtolocal)
	}
	rmerge = func(x *Command) {
		if x.HasPersistentFlags() {
			x.PersistentFlags().VisitAll(func(f *flag.Flag) {
				if c.Flags().Lookup(f.Name) == nil {
					c.Flags().AddFlag(f)
				}
			})
		}
		if x.HasParent() {
			rmerge(x.parent)
		}
	}

	rmerge(c)
}
Exemple #16
0
func TestDynStringSet_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	DynStringSet(set, "some_stringslice_1", []string{"foo", "bar"}, "Use it or lose it").WithValidator(ValidateDynStringSetMinElements(2))

	assert.NoError(t, set.Set("some_stringslice_1", "car,far"), "no error from validator when in range")
	assert.Error(t, set.Set("some_stringslice_1", "car"), "error from validator when value out of range")
}
Exemple #17
0
func TestDynFloat64_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	DynFloat64(set, "some_float_1", 13.37, "Use it or lose it").WithValidator(ValidateDynFloat64Range(10.0, 14.0))

	assert.NoError(t, set.Set("some_float_1", "13.41"), "no error from validator when in range")
	assert.Error(t, set.Set("some_float_1", "14.001"), "error from validator when value out of range")
}
Exemple #18
0
func TestNewViperCreateFlags(t *testing.T) {
	for index, record := range testData {
		config := NewConfig()
		config.SetConfigType("yaml")

		if record.Config != "" {
			if err := config.ReadConfig(strings.NewReader(record.Config + "\n")); err != nil {
				t.Errorf("test %d: Invalid config: %v", index, err)
				continue
			}
		}

		f := pflag.NewFlagSet("test", pflag.ExitOnError)
		registerCreateFlags(f)
		config.configFromPFlags(f)

		if record.PflagArgs != nil {
			if err := f.Parse(record.PflagArgs); err != nil {
				t.Errorf("test %d: Failed to parse args: %v", err)
				continue
			}
		}

		obj := config.newViperCreateFlags()
		actual := record.Getter(&obj)
		if !assertEquals(record.Expected, actual) {
			t.Errorf("test %d: %s\n\tExpected '%s', got '%s'", index, record.Description, record.Expected, actual)
		}
	}
}
Exemple #19
0
// launchExecutorServer returns a chan that closes upon kubelet-executor death. since the kubelet-
// executor doesn't support failover right now, the right thing to do is to fail completely since all
// pods will be lost upon restart and we want mesos to recover the resources from them.
func (ms *MinionServer) launchExecutorServer(containerID string) <-chan struct{} {
	allArgs := os.Args[1:]

	// filter out minion flags, leaving those for the executor
	executorFlags := pflag.NewFlagSet("executor", pflag.ContinueOnError)
	executorFlags.SetOutput(ioutil.Discard)
	ms.AddExecutorFlags(executorFlags)
	executorArgs, _ := filterArgsByFlagSet(allArgs, executorFlags)

	// disable resource-container; mesos slave doesn't like sub-containers yet
	executorArgs = append(executorArgs, "--kubelet-cgroups=")
	if ms.cgroupRoot != "" {
		executorArgs = append(executorArgs, "--cgroup-root="+ms.cgroupRoot)
	}

	// forward containerID so that the executor may pass it along to containers that it launches
	var ctidOpt tasks.Option
	ctidOpt = func(t *tasks.Task) tasks.Option {
		oldenv := t.Env[:]
		t.Env = append(t.Env, "MESOS_EXECUTOR_CONTAINER_UUID="+containerID)
		return func(t2 *tasks.Task) tasks.Option {
			t2.Env = oldenv
			return ctidOpt
		}
	}

	// run executor and quit minion server when this exits cleanly
	execDied := make(chan struct{})
	ms.launchHyperkubeServer(hyperkube.CommandExecutor, executorArgs, executorLogFilename, tasks.NoRespawn(execDied), ctidOpt)
	return execDied
}
Exemple #20
0
// Flags returns a flagset for this server
func (s *Server) Flags() *pflag.FlagSet {
	if s.flags == nil {
		s.flags = pflag.NewFlagSet(s.Name(), pflag.ContinueOnError)
		s.flags.SetOutput(ioutil.Discard)
	}
	return s.flags
}
Exemple #21
0
func parseEnvArgs(args []string) (Command, error) {
	flag := pflag.NewFlagSet("env", pflag.ContinueOnError)
	err := flag.Parse(args)
	if err != nil {
		return nil, err
	}

	if flag.NArg() < 1 {
		return nil, ErrNotEnoughArguments
	}

	if flag.NArg() > 1 {
		return nil, ErrTooManyArguments
	}

	shell, err := detectShell()
	if err == ErrUnknownShell {
		shell = "sh"
	}

	usageHint := true
	fi, err := os.Stdout.Stat()
	if err == nil {
		if fi.Mode()&os.ModeCharDevice == 0 {
			usageHint = false
		}
	}

	e := &Env{}
	e.VaultName = flag.Arg(0)
	e.Shell = shell
	e.UsageHint = usageHint
	return e, nil
}
Exemple #22
0
// launchExecutorServer returns a chan that closes upon kubelet-executor death. since the kubelet-
// executor doesn't support failover right now, the right thing to do is to fail completely since all
// pods will be lost upon restart and we want mesos to recover the resources from them.
func (ms *MinionServer) launchExecutorServer() <-chan struct{} {
	allArgs := os.Args[1:]

	// filter out minion flags, leaving those for the executor
	executorFlags := pflag.NewFlagSet("executor", pflag.ContinueOnError)
	executorFlags.SetOutput(ioutil.Discard)
	ms.AddExecutorFlags(executorFlags)
	executorArgs, _ := filterArgsByFlagSet(allArgs, executorFlags)

	executorArgs = append(executorArgs, "--resource-container="+path.Join("/", ms.mesosCgroup, "kubelet"))
	if ms.cgroupRoot != "" {
		executorArgs = append(executorArgs, "--cgroup-root="+ms.cgroupRoot)
	}

	// run executor and quit minion server when this exits cleanly
	execDied := make(chan struct{})
	decorator := func(t *tasks.Task) *tasks.Task {
		t.Finished = func(_ bool) bool {
			// this func implements the task.finished spec, so when the executor exits
			// we return false to indicate that it should not be restarted. we also
			// close execDied to signal interested listeners.
			close(execDied)
			return false
		}
		// since we only expect to die once, and there is no restart; don't delay any longer than needed
		t.RestartDelay = 0
		return t
	}
	ms.launchHyperkubeServer(hyperkube.CommandExecutor, executorArgs, executorLogFilename, decorator)
	return execDied
}
Exemple #23
0
func parseShellArgs(args []string) (Command, error) {
	flag := pflag.NewFlagSet("shell", pflag.ContinueOnError)
	err := flag.Parse(args)
	if err != nil {
		return nil, err
	}

	currentVaultedEnv := os.Getenv("VAULTED_ENV")
	if currentVaultedEnv != "" {
		return nil, fmt.Errorf("Refusing to spawn a new shell when already in environment '%s'.", currentVaultedEnv)
	}

	if flag.NArg() < 1 {
		return nil, ErrNotEnoughArguments
	}

	if flag.NArg() > 1 {
		return nil, ErrTooManyArguments
	}

	s := &Spawn{}
	s.VaultName = flag.Arg(0)
	s.Command = interactiveShellCommand()
	return s, nil
}
Exemple #24
0
// Initializes the internal state for a new service.
func (s *Service) init() {
	if s.Logger == nil {
		s.Logger = newLogger(os.Stderr)
	}

	if s.Handler == nil {
		s.Handler = &HandlerFunc{handle: s.Handle}
	}

	// Initialize a UUID if not set.
	if s.UUID == uuid.Nil {
		s.UUID = uuid.NewV4()
	}

	// A pre-defined flagset may be supplied.
	if s.Flags == nil {
		flags := pflag.NewFlagSet(s.Name, pflag.ExitOnError)

		// Initialize the base set of options. All other configuration should
		// be specified and driven by the contents of the `config`.
		flags.String("host", "127.0.0.1", "Host of the service.")
		flags.Int("port", 5000, "Port of the service.")
		flags.Bool("debug", false, "Toggle debug mode.")
		flags.String("consul", "", "Host of Consul agent.")
		flags.String("config", "", "Path to the service config.")

		s.Flags = flags
	}

	// Bind the CLI arguments for the service.
	cli := viper.New()
	cli.SetDefault("host", "127.0.0.1")
	cli.SetDefault("port", 5000)

	s.cli = cli

	cli.BindPFlag("host", s.Flags.Lookup("host"))
	cli.BindPFlag("port", s.Flags.Lookup("port"))
	cli.BindPFlag("debug", s.Flags.Lookup("debug"))
	cli.BindPFlag("consul", s.Flags.Lookup("consul"))
	cli.BindPFlag("config", s.Flags.Lookup("config"))

	mux := newServeMux()
	s.Mux = mux

	// Bind the root endpoint with info about the service.
	mux.Get("/", func(cxt *echo.Context) error {
		return cxt.JSON(http.StatusOK, s.Info())
	})

	// Top-level context.
	cxt, cancel := context.WithCancel(context.Background())

	s.cxt = cxt
	s.cancel = cancel

	// Configuration.
	s.Config = newConfig(cxt, s.Name)
}
Exemple #25
0
func TestDynStringSet_SetAndGet(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	dynFlag := DynStringSet(set, "some_stringslice_1", []string{"foo", "bar"}, "Use it or lose it")
	assert.Equal(t, map[string]struct{}{"foo": struct{}{}, "bar": struct{}{}}, dynFlag.Get(), "value must be default after create")
	err := set.Set("some_stringslice_1", "car,bar")
	assert.NoError(t, err, "setting value must succeed")
	assert.Equal(t, map[string]struct{}{"car": struct{}{}, "bar": struct{}{}}, dynFlag.Get(), "value must be set after update")
}
Exemple #26
0
func TestDynString_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	regex := regexp.MustCompile("^[a-z]{2,8}$")
	DynString(set, "some_string_1", "something", "Use it or lose it").WithValidator(ValidateDynStringMatchesRegex(regex))

	assert.NoError(t, set.Set("some_string_1", "else"), "no error from validator when in range")
	assert.Error(t, set.Set("some_string_1", "else1"), "error from validator when value out of range")
}
Exemple #27
0
func TestDynInt64_SetAndGet(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	dynFlag := DynInt64(set, "some_int_1", 13371337, "Use it or lose it")
	assert.Equal(t, int64(13371337), dynFlag.Get(), "value must be default after create")
	err := set.Set("some_int_1", "77007700")
	assert.NoError(t, err, "setting value must succeed")
	assert.Equal(t, int64(77007700), dynFlag.Get(), "value must be set after update")
}
Exemple #28
0
func TestDynDuration_SetAndGet(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	dynFlag := DynDuration(set, "some_duration_1", 5*time.Second, "Use it or lose it")
	assert.Equal(t, 5*time.Second, dynFlag.Get(), "value must be default after create")
	err := set.Set("some_duration_1", "10h")
	assert.NoError(t, err, "setting value must succeed")
	assert.Equal(t, 10*time.Hour, dynFlag.Get(), "value must be set after update")
}
Exemple #29
0
func Benchmark_Duration_Dyn_Get(b *testing.B) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	value := DynDuration(set, "some_duration_1", 5*time.Second, "Use it or lose it")
	set.Set("some_duration_1", "10s")
	for i := 0; i < b.N; i++ {
		value.Get().Nanoseconds()
	}
}
Exemple #30
0
func Benchmark_Duration_Normal_get(b *testing.B) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	valPtr := set.Duration("some_duration_1", 5*time.Second, "Use it or lose it")
	set.Set("some_duration_1", "10s")
	for i := 0; i < b.N; i++ {
		(*valPtr).Nanoseconds()
	}
}