コード例 #1
1
ファイル: conf.go プロジェクト: RobinUS2/indispenso
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
}
コード例 #2
0
ファイル: default.go プロジェクト: rafaelsilvag/gobgp
func setDefaultConfigValuesWithViper(v *viper.Viper, b *BgpConfigSet) error {
	if v == nil {
		v = viper.New()
	}

	if err := SetDefaultGlobalConfigValues(&b.Global); err != nil {
		return err
	}

	for idx, server := range b.BmpServers {
		if server.Config.Port == 0 {
			server.Config.Port = bmp.BMP_DEFAULT_PORT
		}
		b.BmpServers[idx] = server
	}

	if b.Zebra.Config.Url == "" {
		b.Zebra.Config.Url = "unix:/var/run/quagga/zserv.api"
	}

	list, err := extractArray(v.Get("neighbors"))
	if err != nil {
		return err
	}

	for idx, n := range b.Neighbors {
		vv := viper.New()
		if len(list) > idx {
			vv.Set("neighbor", list[idx])
		}
		if err := setDefaultNeighborConfigValuesWithViper(vv, &n, b.Global.Config.As); err != nil {
			return err
		}
		b.Neighbors[idx] = n
	}

	for idx, r := range b.RpkiServers {
		if r.Config.Port == 0 {
			b.RpkiServers[idx].Config.Port = rtr.RPKI_DEFAULT_PORT
		}
	}

	list, err = extractArray(v.Get("policy-definitions"))
	if err != nil {
		return err
	}

	for idx, p := range b.PolicyDefinitions {
		vv := viper.New()
		if len(list) > idx {
			vv.Set("policy", list[idx])
		}
		if err := setDefaultPolicyConfigValuesWithViper(vv, &p); err != nil {
			return err
		}
		b.PolicyDefinitions[idx] = p
	}

	return nil
}
コード例 #3
0
ファイル: keys_test.go プロジェクト: cyli/notary
// Non-roles and delegation keys can't be rotated with the command line
func TestRotateKeyInvalidRoles(t *testing.T) {
	setUp(t)
	invalids := []string{
		"notevenARole",
		"targets/a",
	}
	for _, role := range invalids {
		for _, serverManaged := range []bool{true, false} {
			k := &keyCommander{
				configGetter:           func() (*viper.Viper, error) { return viper.New(), nil },
				getRetriever:           func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
				rotateKeyRole:          role,
				rotateKeyServerManaged: serverManaged,
			}
			commands := []string{"gun", role}
			if serverManaged {
				commands = append(commands, "-r")
			}
			err := k.keysRotate(&cobra.Command{}, commands)
			require.Error(t, err)
			require.Contains(t, err.Error(),
				fmt.Sprintf("does not currently permit rotating the %s key", role))
		}
	}
}
コード例 #4
0
ファイル: tuf_test.go プロジェクト: jfrazelle/notary
func TestGetTrustPinningErrors(t *testing.T) {
	setUp(t)
	invalidTrustPinConfig := tempDirWithConfig(t, `{
		"trust_pinning": {
		    "certs": {
		        "repo3": [60, "abc", [1, 2, 3]]
		    }
		 }
	}`)
	defer os.RemoveAll(invalidTrustPinConfig)

	tc := &tufCommander{
		// returns a nil pointer
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetConfigFile(filepath.Join(invalidTrustPinConfig, "config.json"))
			v.ReadInConfig()
			return v, nil
		},
	}
	require.Error(t, tc.tufStatus(&cobra.Command{}, []string{"gun"}))
	tc.resetAll = true
	require.Error(t, tc.tufReset(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufDeleteGUN(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufInit(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufPublish(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufVerify(&cobra.Command{}, []string{"gun", "target", "file"}))
	require.Error(t, tc.tufLookup(&cobra.Command{}, []string{"gun", "target"}))
	require.Error(t, tc.tufList(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufAdd(&cobra.Command{}, []string{"gun", "target", "file"}))
	require.Error(t, tc.tufRemove(&cobra.Command{}, []string{"gun", "target", "file"}))
	require.Error(t, tc.tufWitness(&cobra.Command{}, []string{"gun", "targets/role"}))
	tc.sha256 = "88b76b34ab83a9e4d5abe3697950fb73f940aab1aa5b534f80cf9de9708942be"
	require.Error(t, tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test1", "100"}))
}
コード例 #5
0
ファイル: tuf_test.go プロジェクト: jfrazelle/notary
func TestStatusUnstageAndReset(t *testing.T) {
	setUp(t)
	tempBaseDir := tempDirWithConfig(t, "{}")
	defer os.RemoveAll(tempBaseDir)

	tc := &tufCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}

	// run a reset with an empty changelist and make sure it succeeds
	tc.resetAll = true
	err := tc.tufReset(&cobra.Command{}, []string{"gun"})
	require.NoError(t, err)

	// add some targets
	tc.sha256 = "88b76b34ab83a9e4d5abe3697950fb73f940aab1aa5b534f80cf9de9708942be"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test1", "100"})
	require.NoError(t, err)
	tc.sha256 = "4a7c203ce63b036a1999ea74eebd307c338368eb2b32218b722de6c5fdc7f016"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test2", "100"})
	require.NoError(t, err)
	tc.sha256 = "64bd0565907a6a55fc66fd828a71dbadd976fa875d0a3869f53d02eb8710ecb4"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test3", "100"})
	require.NoError(t, err)
	tc.sha256 = "9d9e890af64dd0f44b8a1538ff5fa0511cc31bf1ab89f3a3522a9a581a70fad8"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test4", "100"})
	require.NoError(t, err)

	out, err := runCommand(t, tempBaseDir, "status", "gun")
	require.NoError(t, err)
	require.Contains(t, out, "test1")
	require.Contains(t, out, "test2")
	require.Contains(t, out, "test3")
	require.Contains(t, out, "test4")

	_, err = runCommand(t, tempBaseDir, "reset", "gun", "-n", "-1,1,3,10")
	require.NoError(t, err)

	out, err = runCommand(t, tempBaseDir, "status", "gun")
	require.NoError(t, err)
	require.Contains(t, out, "test1")
	require.NotContains(t, out, "test2")
	require.Contains(t, out, "test3")
	require.NotContains(t, out, "test4")

	_, err = runCommand(t, tempBaseDir, "reset", "gun", "--all")
	require.NoError(t, err)

	out, err = runCommand(t, tempBaseDir, "status", "gun")
	require.NoError(t, err)
	require.NotContains(t, out, "test1")
	require.NotContains(t, out, "test2")
	require.NotContains(t, out, "test3")
	require.NotContains(t, out, "test4")

}
コード例 #6
0
ファイル: config.go プロジェクト: LiranCohen/quarid-go
func init() {
	c := viper.New()

	c.SetEnvPrefix("Q")
	c.AutomaticEnv()

	flag.StringVar(&configFile, "config", "", "")
	flag.Parse()
	c.BindPFlag("config", flag.Lookup("config"))

	if c.GetString("config") == "" {
		// Read from "default" configuration path
		c.SetConfigName("config")
		c.AddConfigPath("/etc/qurid")
		c.AddConfigPath("$HOME/.quarid")
		c.AddConfigPath(".")
	} else {
		c.SetConfigFile(c.GetString("config"))
	}

	if err := c.ReadInConfig(); err != nil {
		panic(fmt.Errorf("Unable to read any configuration file: %s\n", err))
	}

	location, err := time.LoadLocation(c.GetString("timezone"))
	if err == nil {
		c.Set("timezone", location)
	} else {
		c.Set("timezone", time.UTC)
	}

	config = c
}
コード例 #7
0
ファイル: keys_test.go プロジェクト: jfrazelle/notary
func TestExportKeysByID(t *testing.T) {
	setUp(t)
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)
	output, err := ioutil.TempFile("", "notary-test-import-")
	require.NoError(t, err)
	defer os.RemoveAll(output.Name())
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}
	k.outFile = output.Name()
	err = output.Close() // close so export can open
	require.NoError(t, err)
	k.exportKeyIDs = []string{"one", "three"}

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	fileStore, err := store.NewPrivateKeyFileStorage(tempBaseDir, notary.KeyExtension)
	require.NoError(t, err)
	err = fileStore.Set("one", bBytes)
	require.NoError(t, err)
	err = fileStore.Set("two", b2Bytes)
	require.NoError(t, err)
	err = fileStore.Set("three", cBytes)
	require.NoError(t, err)

	err = k.exportKeys(&cobra.Command{}, nil)
	require.NoError(t, err)

	outRes, err := ioutil.ReadFile(k.outFile)
	require.NoError(t, err)

	block, rest := pem.Decode(outRes)
	require.Equal(t, b.Bytes, block.Bytes)
	require.Equal(t, "one", block.Headers["path"])

	block, rest = pem.Decode(rest)
	require.Equal(t, c.Bytes, block.Bytes)
	require.Equal(t, "three", block.Headers["path"])
	require.Len(t, rest, 0)
}
コード例 #8
0
ファイル: config.go プロジェクト: r0b6/gin-microservice
func GetConfig() *viper.Viper {

	env := os.Getenv("VIPER_ENV")

	if len(env) == 0 {
		env = "development"
	}

	config := viper.New()

	config.SetConfigName(env) // name of config file (without extension)

	configPath := os.Getenv("VIPER_CONFIG")

	if len(configPath) == 0 {
		configPath = "config"
	}

	config.AddConfigPath(configPath)

	err := config.ReadInConfig() // Find and read the config file
	if err != nil {              // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s]: %s \n", configPath, err))
	}

	return config
}
コード例 #9
0
ファイル: config.go プロジェクト: lebauce/skydive
func init() {
	cfg = viper.New()
	cfg.SetDefault("agent.analyzers", "127.0.0.1:8082")
	cfg.SetDefault("agent.listen", "127.0.0.1:8081")
	cfg.SetDefault("agent.flowtable_expire", 300)
	cfg.SetDefault("agent.flowtable_update", 30)
	cfg.SetDefault("ovs.ovsdb", "127.0.0.1:6400")
	cfg.SetDefault("graph.backend", "memory")
	cfg.SetDefault("graph.gremlin", "ws://127.0.0.1:8182")
	cfg.SetDefault("sflow.bind_address", "127.0.0.1:6345")
	cfg.SetDefault("sflow.port_min", 6345)
	cfg.SetDefault("sflow.port_max", 6355)
	cfg.SetDefault("analyzer.listen", "127.0.0.1:8082")
	cfg.SetDefault("analyzer.flowtable_expire", 600)
	cfg.SetDefault("analyzer.flowtable_update", 60)
	cfg.SetDefault("storage.elasticsearch", "127.0.0.1:9200")
	cfg.SetDefault("ws_pong_timeout", 5)
	cfg.SetDefault("docker.url", "unix:///var/run/docker.sock")
	cfg.SetDefault("etcd.data_dir", "/tmp/skydive-etcd")
	cfg.SetDefault("etcd.embedded", true)
	cfg.SetDefault("etcd.port", 2379)
	cfg.SetDefault("etcd.servers", []string{"http://127.0.0.1:2379"})
	cfg.SetDefault("auth.type", "noauth")
	cfg.SetDefault("auth.keystone.tenant", "admin")
}
コード例 #10
0
ファイル: env.go プロジェクト: MondayHopscotch/genfront
func (env *Env) AddSettings(frontmatter string) (*Env, error) {
	v := viper.New()
	v.SetConfigType("yaml")
	err := v.ReadConfig(bytes.NewBufferString(frontmatter))
	env.AddPairs(v.AllSettings())
	return env, err
}
コード例 #11
0
ファイル: settings.go プロジェクト: Arimeka/static-proxy
func Build() (err error) {

	err = AppSettings.UnmarshalKey(AppSettings.GetString("env"), Config)
	if err != nil {
		return
	}

	Config.Address = AppSettings.GetString("address")
	Config.Port = AppSettings.GetString("port")

	s3Config := &S3Config{}
	err = S3Settings.UnmarshalKey(S3Settings.GetString("env"), s3Config)
	if err != nil {
		return
	}
	Config.S3Config = s3Config

	sizes := viper.New()
	sizes.SetConfigName("sizes")
	sizes.AddConfigPath("./")

	err = sizes.ReadInConfig()
	if err != nil {
		return
	}

	mapSizes := &ValidSizes{}
	err = sizes.UnmarshalKey(AppSettings.GetString("env"), mapSizes)
	if err != nil {
		return
	}
	Config.ValidSizes = mapSizes

	return
}
コード例 #12
0
ファイル: config_test.go プロジェクト: hyperledger/fabric
func TestEnvSlice(t *testing.T) {
	envVar := "ORDERER_INNER_SLICE"
	envVal := "[a, b, c]"
	os.Setenv(envVar, envVal)
	defer os.Unsetenv(envVar)
	config := viper.New()
	config.SetEnvPrefix(Prefix)
	config.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	config.SetEnvKeyReplacer(replacer)
	config.SetConfigType("yaml")

	data := "---\nInner:\n    Slice: [d,e,f]"

	err := config.ReadConfig(bytes.NewReader([]byte(data)))

	if err != nil {
		t.Fatalf("Error reading %s plugin config: %s", Prefix, err)
	}

	var uconf testSlice

	err = ExactWithDateUnmarshal(config, &uconf)
	if err != nil {
		t.Fatalf("Failed to unmarshal with: %s", err)
	}

	expected := []string{"a", "b", "c"}
	if !reflect.DeepEqual(uconf.Inner.Slice, expected) {
		t.Fatalf("Did not get back the right slice, expeced: %v got %v", expected, uconf.Inner.Slice)
	}
}
コード例 #13
0
ファイル: obc-pbft.go プロジェクト: magooster/obc-peer
func loadConfig() (config *viper.Viper) {
	config = viper.New()

	// for environment variables
	config.SetEnvPrefix(configPrefix)
	config.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	config.SetEnvKeyReplacer(replacer)

	config.SetConfigName("config")
	config.AddConfigPath("./")
	config.AddConfigPath("../consensus/obcpbft/")
	config.AddConfigPath("../../consensus/obcpbft")
	// Path to look for the config file in based on GOPATH
	gopath := os.Getenv("GOPATH")
	for _, p := range filepath.SplitList(gopath) {
		obcpbftpath := filepath.Join(p, "src/github.com/hyperledger/fabric/consensus/obcpbft")
		config.AddConfigPath(obcpbftpath)
	}

	err := config.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Error reading %s plugin config: %s", configPrefix, err))
	}
	return
}
コード例 #14
0
ファイル: helper.go プロジェクト: masterDev1985/obc-peer
// GetReplicaHash returns the crypto IDs of the current replica and the whole network
// TODO func (h *Helper) GetReplicaHash() (self []byte, network [][]byte, err error) {
// ATTN: Until the crypto package is integrated, this functions returns
// the <IP:port>s of the current replica and the whole network instead
func (h *Helper) GetReplicaHash() (self string, network []string, err error) {
	// v, _ := h.coordinator.GetValidator()
	// self = v.GetID()
	peer, err := peer.GetPeerEndpoint()
	if err != nil {
		return "", nil, err
	}
	self = peer.Address

	config := viper.New()
	config.SetConfigName("openchain")
	config.AddConfigPath("./")
	err = config.ReadInConfig()
	if err != nil {
		err = fmt.Errorf("Fatal error reading root config: %s", err)
		return self, nil, err
	}

	// encodedHashes := config.GetStringSlice("peer.validator.replicas.hashes")
	/* network = make([][]byte, len(encodedHashes))
	for i, v := range encodedHashes {
		network[i], _ = base64.StdEncoding.DecodeString(v)
	} */
	network = config.GetStringSlice("peer.validator.replicas.ips")

	return self, network, nil
}
コード例 #15
0
ファイル: viperconfig.go プロジェクト: ryanwalls/golang-seed
func init() {
	v := viper.New()
	v.SetDefault("env", "dev")
	v.BindEnv("env")
	env := v.GetString("env")
	Viper = &config{EnvironmentSpecificConfig(v, env)}
}
コード例 #16
0
ファイル: keys_test.go プロジェクト: carriercomm/notary
// The command line uses NotaryRepository's RotateKey - this is just testing
// that the correct config variables are passed for the client to request a key
// from the remote server.
func TestRotateKeyRemoteServerManagesKey(t *testing.T) {
	// Temporary directory where test files will be created
	tempBaseDir, err := ioutil.TempDir("/tmp", "notary-test-")
	defer os.RemoveAll(tempBaseDir)
	assert.NoError(t, err, "failed to create a temporary directory: %s", err)
	gun := "docker.com/notary"

	ret := passphrase.ConstantRetriever("pass")

	ts, initialKeys := setUpRepo(t, tempBaseDir, gun, ret)
	defer ts.Close()

	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			v.SetDefault("remote_server.url", ts.URL)
			return v, nil
		},
		getRetriever:           func() passphrase.Retriever { return ret },
		rotateKeyRole:          data.CanonicalSnapshotRole,
		rotateKeyServerManaged: true,
	}
	err = k.keysRotate(&cobra.Command{}, []string{gun})
	assert.NoError(t, err)

	repo, err := client.NewNotaryRepository(tempBaseDir, gun, ts.URL, nil, ret)
	assert.NoError(t, err, "error creating repo: %s", err)

	cl, err := repo.GetChangelist()
	assert.NoError(t, err, "unable to get changelist: %v", err)
	assert.Len(t, cl.List(), 1)
	// no keys have been created, since a remote key was specified
	assert.Equal(t, initialKeys, repo.CryptoService.ListAllKeys())
}
コード例 #17
0
ファイル: configuration_test.go プロジェクト: mbentley/notary
// initializes a viper object with test configuration
func configure(jsonConfig string) *viper.Viper {
	config := viper.New()
	SetupViper(config, envPrefix)
	config.SetConfigType("json")
	config.ReadConfig(bytes.NewBuffer([]byte(jsonConfig)))
	return config
}
コード例 #18
0
ファイル: config.go プロジェクト: omise/omise-go
func bindViper(cmd *cobra.Command) error {
	v := viper.New()
	collectFlags(v, cmd)
	for _, key := range v.AllKeys() {
		if envkey, ok := envMap[key]; ok {
			v.BindEnv(key, "OMISE_"+envkey)
		} else {
			v.BindEnv(key, "OMISE_"+strings.Replace(strings.ToUpper(key), "-", "_", -1))
		}
	}

	configPath := os.Getenv("HOME") + "/.omise"
	if configFile, e := os.Open(configPath); e == nil {
		defer configFile.Close()

		v.SetConfigType("json")
		if e := v.ReadConfig(configFile); e != nil {
			return e
		}
	}

	if e := v.Unmarshal(config); e != nil {
		return e
	}

	config.viper = v
	return nil
}
コード例 #19
0
ファイル: viperconfig.go プロジェクト: ryanwalls/golang-seed
// EnvironmentSpecificConfig sets the configuration to match the given env.
func EnvironmentSpecificConfig(v *viper.Viper, env string) *viper.Viper {
	if v == nil {
		v = viper.New()
		v.SetDefault("env", env)
	}
	// Read common config
	v.AddConfigPath(".")
	v.AddConfigPath("../")
	v.AddConfigPath("config/")
	v.AddConfigPath("../config/")
	v.SetConfigName("config-common")
	v.SetConfigType("yml")
	if err := v.ReadInConfig(); err != nil {
		panic(fmt.Errorf("Fatal error reading common config file: %s \n", err))
	}

	// Merge in environment specific config
	mergeInConfig(v, "config-"+env+".yml", "yml")
	// Merge in version config
	mergeInConfig(v, "version.properties", "properties")

	// Read config from consul
	// v.AddRemoteProvider("consul", "http://someconsul/endpoint", "some/path/to/config.json")
	// v.SetConfigType("yaml")
	// err = v.ReadRemoteConfig() // Find and read the config file
	// if err != nil {            // Handle errors reading the config file
	// 	panic(fmt.Errorf("Fatal error reading remote config file: %s \n", err))
	// }
	return v
}
コード例 #20
0
ファイル: manager.go プロジェクト: bom-d-van/csfw
// NewManager creates the main new configuration for all scopes: default, website and store
func NewManager() *Manager {
	s := &Manager{
		v: viper.New(),
	}
	s.v.Set(newArg(Path(PathCSBaseURL)).scopePath(), CSBaseURL)
	return s
}
コード例 #21
0
ファイル: load_package.go プロジェクト: eris-ltd/eris-pm
func LoadPackage(fileName string) (*definitions.Package, error) {
	log.Info("Loading eris-pm Package Definition File.")
	var pkg = definitions.BlankPackage()
	var epmJobs = viper.New()

	// setup file
	abs, err := filepath.Abs(fileName)
	if err != nil {
		return nil, fmt.Errorf("Sorry, the marmots were unable to find the absolute path to the eris-pm jobs file.")
	}

	path := filepath.Dir(abs)
	file := filepath.Base(abs)
	extName := filepath.Ext(file)
	bName := file[:len(file)-len(extName)]
	log.WithFields(log.Fields{
		"path": path,
		"name": bName,
	}).Debug("Loading eris-pm file")

	epmJobs.AddConfigPath(path)
	epmJobs.SetConfigName(bName)

	// load file
	if err := epmJobs.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("Sorry, the marmots were unable to load the eris-pm jobs file. Please check your path.\nERROR =>\t\t\t%v", err)
	}

	// marshall file
	if err := epmJobs.Unmarshal(pkg); err != nil {
		return nil, fmt.Errorf("Sorry, the marmots could not figure that eris-pm jobs file out.\nPlease check your epm.yaml is properly formatted.\n")
	}

	return pkg, nil
}
コード例 #22
0
ファイル: gofig_pflag.go プロジェクト: akutz/gofig
func newConfigObj() *config {
	return &config{
		v:                         viper.New(),
		flagSets:                  map[string]*pflag.FlagSet{},
		disableEnvVarSubstitution: DisableEnvVarSubstitution,
	}
}
コード例 #23
0
ファイル: service.go プロジェクト: chop-dbhi/dcc
// 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)
}
コード例 #24
0
ファイル: configuration_test.go プロジェクト: mbentley/notary
func TestParseViperWithInvalidFile(t *testing.T) {
	v := viper.New()
	SetupViper(v, envPrefix)

	err := ParseViper(v, "Chronicle_Of_Dark_Secrets.json")
	require.Error(t, err)
	require.Contains(t, err.Error(), "Could not read config")
}
コード例 #25
0
ファイル: registry.go プロジェクト: pedronasser/garf
// New creates registry instance
func New(server server.Handler) Handler {
	c := viper.New()
	r := &registry{
		config: c,
	}
	r.server = server
	return r
}
コード例 #26
0
ファイル: config.go プロジェクト: rightscale/right_st
func init() {
	Config.Viper = viper.New()
	Config.SetDefault("login", map[interface{}]interface{}{"accounts": make(map[interface{}]interface{})})
	Config.SetDefault("update", map[string]interface{}{"check": true})
	Config.SetEnvPrefix(app.Name)
	Config.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	Config.AutomaticEnv()
}
コード例 #27
0
ファイル: keys_test.go プロジェクト: carriercomm/notary
func TestChangeKeyPassphraseInvalidNumArgs(t *testing.T) {
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) { return viper.New(), nil },
		getRetriever: func() passphrase.Retriever { return passphrase.ConstantRetriever("pass") },
	}
	err := k.keyPassphraseChange(&cobra.Command{}, []string{})
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "must specify the key ID")
}
コード例 #28
0
ファイル: keys_test.go プロジェクト: carriercomm/notary
func TestChangeKeyPassphraseInvalidID(t *testing.T) {
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) { return viper.New(), nil },
		getRetriever: func() passphrase.Retriever { return passphrase.ConstantRetriever("pass") },
	}
	err := k.keyPassphraseChange(&cobra.Command{}, []string{"too_short"})
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "invalid key ID provided")
}
コード例 #29
0
ファイル: manager.go プロジェクト: optimuse/csfw
// NewManager creates the main new configuration for all scopes: default, website and store
func NewManager() *Manager {
	m := &Manager{
		v:      viper.New(),
		pubSub: newPubSub(),
	}
	m.v.Set(mustNewArg(Path(PathCSBaseURL)).scopePath(), CSBaseURL)
	go m.publish()
	return m
}
コード例 #30
0
ファイル: keys_test.go プロジェクト: cyli/notary
// The command line uses NotaryRepository's RotateKey - this is just testing
// that multiple keys can be rotated at once locally
func TestRotateKeyBothKeys(t *testing.T) {
	setUp(t)
	// Temporary directory where test files will be created
	tempBaseDir, err := ioutil.TempDir("/tmp", "notary-test-")
	defer os.RemoveAll(tempBaseDir)
	require.NoError(t, err, "failed to create a temporary directory: %s", err)
	gun := "docker.com/notary"

	ret := passphrase.ConstantRetriever("pass")

	ts, initialKeys := setUpRepo(t, tempBaseDir, gun, ret)
	defer ts.Close()

	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			v.SetDefault("remote_server.url", ts.URL)
			return v, nil
		},
		getRetriever: func() notary.PassRetriever { return ret },
	}
	require.NoError(t, k.keysRotate(&cobra.Command{}, []string{gun, data.CanonicalTargetsRole}))
	require.NoError(t, k.keysRotate(&cobra.Command{}, []string{gun, data.CanonicalSnapshotRole}))

	repo, err := client.NewNotaryRepository(tempBaseDir, gun, ts.URL, nil, ret, trustpinning.TrustPinConfig{})
	require.NoError(t, err, "error creating repo: %s", err)

	cl, err := repo.GetChangelist()
	require.NoError(t, err, "unable to get changelist: %v", err)
	require.Len(t, cl.List(), 0)

	// two new keys have been created, and the old keys should still be gone
	newKeys := repo.CryptoService.ListAllKeys()
	// there should be 3 keys - snapshot, targets, and root
	require.Len(t, newKeys, 3)

	// the old snapshot/targets keys should be gone
	for keyID, role := range initialKeys {
		r, ok := newKeys[keyID]
		switch r {
		case data.CanonicalSnapshotRole, data.CanonicalTargetsRole:
			require.False(t, ok, "original key %s still there", keyID)
		case data.CanonicalRootRole:
			require.Equal(t, role, r)
			require.True(t, ok, "old root key has changed")
		}
	}

	found := make(map[string]bool)
	for _, role := range newKeys {
		found[role] = true
	}
	require.True(t, found[data.CanonicalTargetsRole], "targets key was not created")
	require.True(t, found[data.CanonicalSnapshotRole], "snapshot key was not created")
	require.True(t, found[data.CanonicalRootRole], "root key was removed somehow")
}