Esempio n. 1
1
func loadConfig() {
	stormpath.InitLog()

	viper.SetConfigType("yaml")
	viper.AutomaticEnv()

	//Load bundled default config
	defaultConfig, err := Asset("config/web.stormpath.yaml")
	if err != nil {
		stormpath.Logger.Panicf("[ERROR] Couldn't load default bundle configuration: %s", err)
	}

	viper.ReadConfig(bytes.NewBuffer(defaultConfig))

	//Merge users custom configuration
	viper.SetConfigFile("stormpath.yaml")
	viper.AddConfigPath("~/.stormpath/")
	viper.AddConfigPath(".")
	err = viper.MergeInConfig()
	if err != nil {
		stormpath.Logger.Println("[WARN] User didn't provide custom configuration")
	}

	Config.Produces = viper.GetStringSlice("stormpath.web.produces")
	Config.BasePath = viper.GetString("stormpath.web.basePath")

	loadSocialConfig()
	loadCookiesConfig()
	loadEndpointsConfig()
	loadOAuth2Config()
}
Esempio n. 2
0
func setupMiddleware() []http.Handler {
	return []http.Handler{
		adaptors.HandlerFromNegroni(cors.New(cors.Options{
			AllowedOrigins:   viper.GetStringSlice("cors.allowed_origins"),
			AllowedMethods:   viper.GetStringSlice("cors.allowed_methods"),
			AllowCredentials: viper.GetBool("cors.allow_credentials"),
		})),
		adaptors.HandlerFromNegroni(negroni.HandlerFunc(secure.New(secure.Options{
			AllowedHosts:            []string{},
			SSLRedirect:             false,
			SSLTemporaryRedirect:    false,
			SSLHost:                 "",
			SSLProxyHeaders:         map[string]string{},
			STSSeconds:              0,
			STSIncludeSubdomains:    false,
			STSPreload:              false,
			ForceSTSHeader:          false,
			FrameDeny:               false,
			CustomFrameOptionsValue: "",
			ContentTypeNosniff:      false,
			BrowserXssFilter:        false,
			ContentSecurityPolicy:   "",
			IsDevelopment:           viper.GetString("environment") == "development",
		}).HandlerFuncWithNext)),
	}
}
Esempio n. 3
0
func main() {
	pflag.Parse()

	viper.SetConfigName("config")
	viper.AddConfigPath(".")

	if debug {
		logrus.SetLevel(logrus.DebugLevel)
	}

	if err := viper.ReadInConfig(); err != nil {
		logrus.Fatal(err)
	}

	nick := viper.GetString("twitch.nick")
	pass := viper.GetString("twitch.pass")
	channels := viper.GetStringSlice("twitch.join")
	dbFilename := viper.GetString("database.filename")
	superusers := viper.GetStringSlice("permissions.superusers")

	bot := bot.NewBot(nick, pass, channels, dbFilename, superusers)
	if err := bot.Start(); err != nil {
		logrus.Fatal(err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c
	fmt.Print("\r\r\b")

	if err := bot.Stop(); err != nil {
		logrus.Fatal(err)
	}
}
Esempio n. 4
0
// GetStringSlice returns a config value as a string slice.
func (c *LiveConfig) GetStringSlice(ns, key string) []string {
	if ns == NSRoot {
		return viper.GetStringSlice(key)
	}

	nskey := fmt.Sprintf("%s-%s", ns, key)
	return viper.GetStringSlice(nskey)
}
Esempio n. 5
0
func Show(cmd *cobra.Command, identities []string) {
	if len(identities) == 0 {
		fmt.Printf("Please provide at least one identity to show")
		return
	}

	s := state.NewState(viper.GetStringSlice("etc.hosts"))

	fmt.Printf("Found %d identities\n", len(identities))

	for _, id := range identities {
		identity, err := s.LoadIdentity(id)
		if err != nil {
			fmt.Printf("Failed to load identity %s: %s", id, err)
		}
		if identity == nil {
			fmt.Printf("Invalid identity %s", id)
			continue
		}

		fmt.Print("\n")
		fmt.Printf("Id: %s\n", identity.Id)
		fmt.Printf("Is Valid: %t\n", identity.IsValid())
		fmt.Printf("Is Signed: %t\n", identity.IsSigned())
		fmt.Printf("Has key: %t\n", identity.Key != nil)
		fmt.Printf("Fingerprint: % x\n", identity.Fingerprint())
		fmt.Printf("Serial Number: %d\n", identity.Certificate.SerialNumber)
		fmt.Printf("Created: %s\n", identity.Certificate.NotBefore)
		fmt.Printf("Expires: %s\n", identity.Certificate.NotAfter)
	}
}
Esempio n. 6
0
func isNonProcessablePath(filePath string) bool {
	base := filepath.Base(filePath)
	if base[0] == '.' {
		return true
	}

	if base[0] == '#' {
		return true
	}

	if base[len(base)-1] == '~' {
		return true
	}

	ignoreFiles := viper.GetStringSlice("IgnoreFiles")
	if len(ignoreFiles) > 0 {
		for _, ignorePattern := range ignoreFiles {
			match, err := regexp.MatchString(ignorePattern, filePath)
			if err != nil {
				helpers.DistinctErrorLog.Printf("Invalid regexp '%s' in ignoreFiles: %s", ignorePattern, err)
				return false
			} else if match {
				return true
			}
		}
	}
	return false
}
Esempio n. 7
0
func main() {
	flag.Parse() // Scan the arguments list
	InitializeConfig()
	graphite := fmt.Sprintf("%s%s%s", viper.GetString("graphite.host"), ":", viper.GetString("graphite.port"))
	prefix := fmt.Sprintf("%s", viper.GetString("graphite.prefix"))

	if *versionFlag {
		fmt.Println("cnm2g: Cn=monitor to Graphite")
		fmt.Println("Version:", APP_VERSION)
		fmt.Println("Config File >>>", viper.ConfigFileUsed())
		fmt.Println("Graphite >>>", graphite)
		fmt.Println("Prefix >>>", prefix)
		return
	}
	ldapmap := viper.GetStringMap("ldap")
	dnmap := viper.GetStringMap("dn")
	for ldap, _ := range ldapmap {
		ldapuri := viper.GetString(fmt.Sprintf("ldap.%s.uri", ldap))
		ldapuser := viper.GetString(fmt.Sprintf("ldap.%s.user", ldap))
		ldappass := viper.GetString(fmt.Sprintf("ldap.%s.pass", ldap))
		for dn, _ := range dnmap {
			prefixldap := fmt.Sprintf("%s.%s.%s", prefix, ldap, dn)
			data := viper.GetStringSlice(fmt.Sprintf("dn.%s.data", dn))
			basedn := viper.GetString(fmt.Sprintf("dn.%s.dn", dn))
			ldapresult := FetchData(ldapuri, ldapuser, ldappass, basedn, "(objectclass=*)", data)
			if DEBUG {
				ShowData(graphite, prefixldap, ldapresult)
			} else {
				SentData(graphite, prefixldap, ldapresult)
			}
		}
	}
}
Esempio n. 8
0
func ReadConfig(agent *AgentCommand) *Config {
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		logrus.Infof("No valid config found: %s \n Applying default values.", err)
	}

	tags := viper.GetStringMapString("tags")
	server := viper.GetBool("server")
	nodeName := viper.GetString("node_name")

	if server {
		tags["dkron_server"] = "true"
	}
	tags["dkron_version"] = agent.Version

	InitLogger(viper.GetString("log_level"), nodeName)

	return &Config{
		NodeName:        nodeName,
		BindAddr:        viper.GetString("bind_addr"),
		AdvertiseAddr:   viper.GetString("advertise_addr"),
		HTTPAddr:        viper.GetString("http_addr"),
		Discover:        viper.GetString("discover"),
		Backend:         viper.GetString("backend"),
		BackendMachines: viper.GetStringSlice("backend_machine"),
		Server:          server,
		Profile:         viper.GetString("profile"),
		StartJoin:       viper.GetStringSlice("join"),
		Tags:            tags,
		Keyspace:        viper.GetString("keyspace"),
		EncryptKey:      viper.GetString("encrypt"),
		UIDir:           viper.GetString("ui_dir"),
		RPCPort:         viper.GetInt("rpc_port"),

		MailHost:     viper.GetString("mail_host"),
		MailPort:     uint16(viper.GetInt("mail_port")),
		MailUsername: viper.GetString("mail_username"),
		MailPassword: viper.GetString("mail_password"),
		MailFrom:     viper.GetString("mail_from"),
		MailPayload:  viper.GetString("mail_payload"),

		WebhookURL:     viper.GetString("webhook_url"),
		WebhookPayload: viper.GetString("webhook_payload"),
		WebhookHeaders: viper.GetStringSlice("webhook_headers"),
	}
}
Esempio n. 9
0
func runCrossbuild() {
	defer shell.ErrExit()
	shell.Tee = os.Stdout

	if viper.GetBool("verbose") {
		shell.Trace = true
	}

	var (
		goVersion        = viper.GetString("go")
		repoPath         = viper.GetString("repository.path")
		mainPlatforms    = viper.GetStringSlice("crossbuild.platforms.main")
		ARMPlatforms     = viper.GetStringSlice("crossbuild.platforms.arm")
		powerPCPlatforms = viper.GetStringSlice("crossbuild.platforms.powerpc")
		MIPSPlatforms    = viper.GetStringSlice("crossbuild.platforms.mips")

		dockerMainBuilderImage    = fmt.Sprintf("%s:%s-main", dockerBuilderImageName, goVersion)
		dockerARMBuilderImage     = fmt.Sprintf("%s:%s-arm", dockerBuilderImageName, goVersion)
		dockerPowerPCBuilderImage = fmt.Sprintf("%s:%s-powerpc", dockerBuilderImageName, goVersion)
		dockerMIPSBuilderImage    = fmt.Sprintf("%s:%s-mips", dockerBuilderImageName, goVersion)
	)

	if mainPlatformsParam := strings.Join(mainPlatforms[:], " "); mainPlatformsParam != "" {
		fmt.Println("> running the main builder docker image")
		sh("docker run --rm -t -v $PWD:/app",
			dockerMainBuilderImage, "-i", repoPath, "-p", q(mainPlatformsParam))
	}

	if ARMPlatformsParam := strings.Join(ARMPlatforms[:], " "); ARMPlatformsParam != "" {
		fmt.Println("> running the ARM builder docker image")
		sh("docker run --rm -t -v $PWD:/app",
			dockerARMBuilderImage, "-i", repoPath, "-p", q(ARMPlatformsParam))
	}

	if powerPCPlatformsParam := strings.Join(powerPCPlatforms[:], " "); powerPCPlatformsParam != "" {
		fmt.Println("> running the PowerPC builder docker image")
		sh("docker run --rm -t -v $PWD:/app",
			dockerPowerPCBuilderImage, "-i", repoPath, "-p", q(powerPCPlatformsParam))
	}

	if MIPSPlatformsParam := strings.Join(MIPSPlatforms[:], " "); MIPSPlatformsParam != "" {
		fmt.Println("> running the MIPS builder docker image")
		sh("docker run --rm -t -v $PWD:/app",
			dockerMIPSBuilderImage, "-i", repoPath, "-p", q(MIPSPlatformsParam))
	}
}
Esempio n. 10
0
func CreateDB() *BloomDatabase {
	return &BloomDatabase{
		viper.GetString("sqlConnStr"),
		viper.GetStringSlice("searchHosts"),
		nil,
		nil,
	}
}
Esempio n. 11
0
func getConfiguredFormFieldNames(formName string) []string {
	configuredFields := viper.GetStringMapString("stormpath.web." + formName + ".form.fields")
	fieldOrder := viper.GetStringSlice("stormpath.web." + formName + ".form.fieldOrder")

	for fieldName := range configuredFields {
		if !contains(fieldOrder, fieldName) {
			fieldOrder = append(fieldOrder, fieldName)
		}
	}
	return fieldOrder
}
Esempio n. 12
0
func initEnviron() {
	if hostedZone == "" {
		hostedZone = viper.GetString("hosted_zone")
	}
	if checkID == "" {
		checkID = viper.GetString("check_id")
	}
	if len(domains) == 0 {
		domains = viper.GetStringSlice("domain")
	}
}
Esempio n. 13
0
func (s *StaticDiscovery) Configure(namespace string) {
	if s.Namespace != "" {
		//TODO: use logging
		fmt.Errorf("%s already inited: %s", StaticFactoryKey, s.Namespace)
		return
	}
	s.Namespace = namespace
	instances := viper.GetStringSlice(util.GetStaticRegistryKey(s))
	fmt.Printf("instances %+v\n", instances)
	s.Instances = instances
}
Esempio n. 14
0
File: config.go Progetto: ovh/tatcli
func (ui *tatui) loadConfig() {
	internal.ReadConfig()
	filters := viper.GetStringSlice("filters")

	// no range to keep order
	for index := 0; index < len(filters); index++ {
		filter := filters[index]
		tuples := strings.Split(filter, " ")
		if len(tuples) <= 2 {
			continue
		}
		topic := tuples[1]
		if _, ok := ui.currentFilterMessages[topic]; !ok {
			ui.currentFilterMessages[topic] = make(map[int]*tat.MessageCriteria)
			ui.currentFilterMessagesText[topic] = make(map[int]string)
		}
		c, criteriaText := ui.prepareFilterMessages(strings.Join(tuples[2:], " "), tuples[0], topic)
		ui.currentFilterMessages[topic][len(ui.currentFilterMessages[topic])] = c
		ui.currentFilterMessagesText[topic][len(ui.currentFilterMessagesText[topic])] = criteriaText
	}

	commands := viper.GetStringSlice("commands")
	// no range to keep order
	for index := 0; index < len(commands); index++ {
		commandsOnTopic := commands[index]
		tuples := strings.Split(strings.TrimSpace(commandsOnTopic), " ")
		if len(tuples) <= 1 {
			continue
		}
		topic := tuples[0]
		ui.uiTopicCommands[topic] = commandsOnTopic[len(topic):]
	}

	var conf config.TemplateJSONType
	err := viper.Unmarshal(&conf)
	if err != nil {
		internal.Exit("unable to decode confif file, err: %v", err)
	}

	ui.hooks = conf.Hooks
}
Esempio n. 15
0
func runTarball(binariesLocation string) {
	defer shell.ErrExit()
	shell.Tee = os.Stdout

	if viper.GetBool("verbose") {
		shell.Trace = true
	}

	info := NewProjectInfo()

	var (
		prefix = viper.GetString("tarball.prefix")
		tmpDir = ".release"
		goos   = envOr("GOOS", goos)
		goarch = envOr("GOARCH", goarch)
		name   = fmt.Sprintf("%s-%s.%s-%s", info.Name, info.Version, goos, goarch)

		binaries []Binary
		ext      string
	)

	if goos == "windows" {
		ext = ".exe"
	}

	dir := filepath.Join(tmpDir, name)

	if err := os.MkdirAll(dir, 0777); err != nil {
		fatalMsg(err, "Failed to create directory")
	}
	defer sh("rm -rf", tmpDir)

	projectFiles := viper.GetStringSlice("tarball.files")
	for _, file := range projectFiles {
		sh("cp -a", file, dir)
	}

	err := viper.UnmarshalKey("build.binaries", &binaries)
	fatalMsg(err, "Failed to Unmashal binaries :")

	for _, binary := range binaries {
		binaryName := fmt.Sprintf("%s%s", binary.Name, ext)
		sh("cp -a", shell.Path(binariesLocation, binaryName), dir)
	}

	if !fileExists(prefix) {
		os.Mkdir(prefix, 0777)
	}

	tar := fmt.Sprintf("%s.tar.gz", name)
	fmt.Println(" >  ", tar)
	sh("tar zcf", shell.Path(prefix, tar), "-C", tmpDir, name)
}
Esempio n. 16
0
func TestViperGetStringOrFail(t *testing.T) {
	assert := assert.New(t)
	viper.SetConfigFile("../.ayi.example.yml")
	err := viper.ReadInConfig()
	assert.Nil(err)
	s, err := ViperGetStringOrFail("scripts.mie")
	assert.Equal("echo mie", s)
	_, err = ViperGetStringOrFail("scripts.qian")
	assert.NotNil(err)
	ss := viper.GetStringSlice("scripts.qian")
	assert.Equal(2, len(ss))
}
Esempio n. 17
0
func Sign(cmd *cobra.Command, identities []string) {
	if len(identities) == 0 {
		fmt.Printf("Please provide at least one identity to sign")
		return
	}

	s := state.NewState(viper.GetStringSlice("etc.hosts"))

	authority, err := s.LoadAuthority()
	if err != nil {
		fmt.Printf("Failed to load authority: %s", err)
	}

	for _, id := range identities {
		identity, err := s.LoadIdentity(id)
		if err != nil {
			fmt.Printf("Failed to load identity %s: %s", id, err)
		}
		if identity == nil {
			fmt.Printf("Invalid identity: %s", id)
			continue
		}

		if identity.Request == nil {
			fmt.Printf("The identity, %s, does not have a request attached to it", id)
			continue
		}

		if identity.Certificate != nil {
			fmt.Printf("The identity, %s, already has a certificate attached to it.", id)
			continue
		}

		cert, err := authority.Sign(identity.Request)
		if err != nil {
			fmt.Printf("Failed to sign the request for %s: %s", id, err)
		}

		if err = s.StoreAuthoritySerial(authority); err != nil {
			fmt.Printf("Failed to store the authority serial number for %s: %s", id, err)
		}

		identity.Certificate = cert
		if err = s.StoreIdentity(identity); err != nil {
			fmt.Printf("Failed to store identity after signing request for %s: %s", id, err)
		}

		s.RemoveIdentityFromPending(identity)

		fmt.Printf("Signed %s", id)
	}
}
Esempio n. 18
0
func getDockerHostConfig() *docker.HostConfig {
	if hostConfig != nil {
		return hostConfig
	}
	dockerKey := func(key string) string {
		return "vm.docker.hostConfig." + key
	}
	getInt64 := func(key string) int64 {
		defer func() {
			if err := recover(); err != nil {
				dockerLogger.Warningf("load vm.docker.hostConfig.%s failed, error: %v", key, err)
			}
		}()
		n := viper.GetInt(dockerKey(key))
		return int64(n)
	}

	var logConfig docker.LogConfig
	err := viper.UnmarshalKey(dockerKey("LogConfig"), &logConfig)
	if err != nil {
		dockerLogger.Warningf("load docker HostConfig.LogConfig failed, error: %s", err.Error())
	}
	networkMode := viper.GetString(dockerKey("NetworkMode"))
	if networkMode == "" {
		networkMode = "host"
	}
	dockerLogger.Debugf("docker container hostconfig NetworkMode: %s", networkMode)

	hostConfig = &docker.HostConfig{
		CapAdd:  viper.GetStringSlice(dockerKey("CapAdd")),
		CapDrop: viper.GetStringSlice(dockerKey("CapDrop")),

		DNS:         viper.GetStringSlice(dockerKey("Dns")),
		DNSSearch:   viper.GetStringSlice(dockerKey("DnsSearch")),
		ExtraHosts:  viper.GetStringSlice(dockerKey("ExtraHosts")),
		NetworkMode: networkMode,
		IpcMode:     viper.GetString(dockerKey("IpcMode")),
		PidMode:     viper.GetString(dockerKey("PidMode")),
		UTSMode:     viper.GetString(dockerKey("UTSMode")),
		LogConfig:   logConfig,

		ReadonlyRootfs:   viper.GetBool(dockerKey("ReadonlyRootfs")),
		SecurityOpt:      viper.GetStringSlice(dockerKey("SecurityOpt")),
		CgroupParent:     viper.GetString(dockerKey("CgroupParent")),
		Memory:           getInt64("Memory"),
		MemorySwap:       getInt64("MemorySwap"),
		MemorySwappiness: getInt64("MemorySwappiness"),
		OOMKillDisable:   viper.GetBool(dockerKey("OomKillDisable")),
		CPUShares:        getInt64("CpuShares"),
		CPUSet:           viper.GetString(dockerKey("Cpuset")),
		CPUSetCPUs:       viper.GetString(dockerKey("CpusetCPUs")),
		CPUSetMEMs:       viper.GetString(dockerKey("CpusetMEMs")),
		CPUQuota:         getInt64("CpuQuota"),
		CPUPeriod:        getInt64("CpuPeriod"),
		BlkioWeight:      getInt64("BlkioWeight"),
	}

	return hostConfig
}
Esempio n. 19
0
func Pending(cmd *cobra.Command, args []string) {
	s := state.NewState(viper.GetStringSlice("etc.hosts"))

	fmt.Println("Pending identities:")

	identities, err := s.GetPendingIdentities()
	if err != nil {
		fmt.Printf("Failed to get pending identities: %s", err)
	}

	for _, identity := range identities {
		fmt.Println(identity)
	}
}
Esempio n. 20
0
File: eca.go Progetto: C0rWin/fabric
// populateAffiliationGroup populates the affiliation groups table.
//
func (eca *ECA) populateAffiliationGroup(name, parent, key string, level int) {
	eca.registerAffiliationGroup(name, parent)
	newKey := key + "." + name

	if level == 0 {
		affiliationGroups := viper.GetStringSlice(newKey)
		for ci := range affiliationGroups {
			eca.registerAffiliationGroup(affiliationGroups[ci], name)
		}
	} else {
		affiliationGroups := viper.GetStringMapString(newKey)
		for childName := range affiliationGroups {
			eca.populateAffiliationGroup(childName, name, newKey, level-1)
		}
	}
}
Esempio n. 21
0
func Remove(cmd *cobra.Command, identities []string) {
	var (
		answer string
	)

	if len(identities) == 0 {
		fmt.Printf("Please provide at least one identity to remove")
		return
	}

	s := state.NewState(viper.GetStringSlice("etc.hosts"))

	for _, id := range identities {
		identity, err := s.LoadIdentity(id)
		if err != nil {
			fmt.Printf("Failed to load identity %s: %s", id, err)
		}
		if identity == nil {
			fmt.Printf("Invalid identity: %s", id)
			continue
		}

		answer = ""
		for !Script && answer != "y" {
			fmt.Printf("Removing %s.  Continue? [y/N]: ", id)
			if _, err = fmt.Scanln(&answer); err != nil {
				fmt.Printf("Failed to read input: %s", err)
			}
			answer = strings.ToLower(answer)
			if answer == "n" {
				return
			}
		}

		if err = s.RemoveIdentity(identity); err != nil {
			fmt.Printf("Failed to remove identity: %s", err)
		}

		fmt.Printf("Removed %s\n", id)
	}
}
Esempio n. 22
0
func isNonProcessablePath(filePath string) bool {
	base := filepath.Base(filePath)
	if strings.HasPrefix(base, ".") ||
		strings.HasPrefix(base, "#") ||
		strings.HasSuffix(base, "~") {
		return true
	}
	ignoreFiles := viper.GetStringSlice("IgnoreFiles")
	if len(ignoreFiles) > 0 {
		for _, ignorePattern := range ignoreFiles {
			match, err := regexp.MatchString(ignorePattern, filePath)
			if err != nil {
				helpers.DistinctErrorLog.Printf("Invalid regexp '%s' in ignoreFiles: %s", ignorePattern, err)
				return false
			} else if match {
				return true
			}
		}
	}
	return false
}
Esempio n. 23
0
func CheckVars(client string, message string, meetingid string, userid string) bool {

	valid := (len(message) != 0)
	clientallowed := false

	// Check if the sent client name is allowed to write to logs
	for _, element := range viper.GetStringSlice("AllowedClients") {
		clientallowed = clientallowed || (element == client)
	}

	if !clientallowed {
		return false
	}

	values := [4]string{client, message, meetingid, userid}

	for _, element := range values {
		valid = valid && utf8.ValidString(element)
	}

	return valid
}
Esempio n. 24
0
func init() {
	viper.SetConfigName("caaas")        // name of config file (without extension)
	viper.AddConfigPath("/etc/caaas/")  // path to look for the config file in
	viper.AddConfigPath("$HOME/.caaas") // call multiple times to add many search paths
	viper.AddConfigPath(".")            // optionally look for config in the working directory
	err := viper.ReadInConfig()         // Find and read the config file
	if err != nil {                     // Handle errors reading the config file
		glog.Fatal("Can not read config file", err)
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	httpConfig := &HostConfig{viper.GetString("http.host"), viper.GetString("http.port")}
	authConfig := &Auth{viper.GetString("auth.username"), viper.GetString("auth.password")}
	imageConfig := &ImageConfig{
		StoreWidth:     viper.GetInt("image.storeWidth"),
		StoreHeight:    viper.GetInt("image.storeHeight"),
		DefaultWidth:   viper.GetInt("image.defaultWidth"),
		DefaultHeight:  viper.GetInt("image.defaultHeight"),
		StoreQuality:   viper.GetInt("image.storeQuality"),
		ReadQuality:    viper.GetInt("image.readQuality"),
		CacheDir:       viper.GetString("image.cacheDir"),
		CacheDirLength: viper.GetInt("image.cacheDirLength"),
		UseGoRoutine:   viper.GetBool("image.useGoRoutine"),
		ProcessPar:     viper.GetInt("image.processPar"),
	}
	dbConfig := &DbConfig{viper.GetStringSlice("db.hosts"),
		viper.GetString("db.dbName"), viper.GetInt("db.numConns"), viper.GetInt("db.timeout")}

	Config = &Configuration{
		Http:  httpConfig,
		Auth:  authConfig,
		Db:    dbConfig,
		Image: imageConfig,
	}

	// semaphore for max number of image processor run in parallel
	ImageChannel = make(chan int, Config.Image.ProcessPar)
}
Esempio n. 25
0
func isTarget(file string) bool {
	name := ""
	parts := filepath.SplitList(file)
	if len(parts) > 0 {
		name = parts[len(parts)-1]
	}

	if name == "signature" {
		return false
	}

	if match, err := filepath.Match("*.pkpass", name); err == nil && match {
		return false
	}

	for _, pattern := range viper.GetStringSlice("core.ignorepatterns") {
		if match, err := filepath.Match(pattern, name); err == nil && match {
			return false
		}
	}

	return true
}
Esempio n. 26
0
File: runner.go Progetto: dyweb/Ayi
// LookUpCommands looks for single or array of commands in built-in and scripts blocks
// TODO: test
func LookUpCommands(cmdName string) ([]string, error) {
	commands := make([]string, 1)
	// FIXME: cannot use map[string]bool as type map[string]interface {}
	// TODO: maybe because bool is a primitive type?
	// if HasKey(BuiltInCommands, cmdName) {
	// 	commands = viper.GetStringSlice(cmdName)
	// }
	_, isBuiltIn := BuiltInCommands[cmdName]

	// FIXED: https://github.com/dyweb/Ayi/issues/54
	// TODO: need more test to test the behavior of command
	fullName := cmdName
	if !isBuiltIn {
		fullName = "scripts." + cmdName
	}

	// first try single string
	command, err := util.ViperGetStringOrFail(fullName)
	// TODO: maybe we should allow empty command
	if err == nil && command != "" {
		log.Debugf("command is %s", command)
		commands[0] = command
		return commands, nil
	}

	log.Debug("single string command not found, try array")

	commands = viper.GetStringSlice(fullName)
	if len(commands) == 0 {
		if isBuiltIn {
			return commands, errors.Errorf("%s configuration not found", cmdName)
		}
		return commands, errors.Errorf("command %s not found in scripts block", cmdName)

	}
	return commands, nil
}
Esempio n. 27
0
func getCurrentIp() (bool, string) {
	log := logging.MustGetLogger("log")
	urlList := viper.GetStringSlice("servertogetip.urlList")

	ip := ""
	findIt := false

	for _, url := range urlList {
		log.Debug("Finding ip with this url: %s", url)
		client := http.Client{Timeout: 30 * time.Second}

		resp, err := client.Get(url)
		if err != nil {
			log.Warning("Unable to connect on \"%s\":", url, err)
			continue
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Warning("Unable to read data page:", err)
			continue
		}

		ip = strings.Trim(string(body), "\n")
		log.Debug("IP is \"%s\" and find on \"%s\"", ip, url)
		if ip != "" {
			findIt = true
			break
		}
	}

	log.Debug("IP is finding: %v", findIt)
	log.Debug("IP is: %s", ip)

	return findIt, ip
}
Esempio n. 28
-1
// IsAdmin checks whether a particular Mumble user is a MumbleDJ admin.
// Returns true if the user is an admin, and false otherwise.
func (dj *MumbleDJ) IsAdmin(user *gumble.User) bool {
	for _, admin := range viper.GetStringSlice("admins.names") {
		if user.Name == admin {
			return true
		}
	}
	return false
}
Esempio n. 29
-1
func assertRegistry(t *testing.T, registry Registry) []string {
	registry.Register(util.Instance{Id: "1", Host: "127.0.0.1", Port: 8080})
	registry.Register(util.Instance{Id: "2", Host: "localhost", Port: 9080})

	servers := viper.GetStringSlice(util.GetStaticRegistryKey(registry))

	require.NotNil(t, servers, "servers was nil")
	require.Equal(t, 2, len(servers), "wrong # of servers")

	return servers
}
Esempio n. 30
-1
func (s *StaticServerList) Configure(namespace string) {
	if s.Namespace != "" {
		//TODO: use logging
		fmt.Errorf("%s already inited: %s", StaticFactoryKey, s.Namespace)
		return
	}
	s.Namespace = namespace
	serverConfigs := viper.GetStringSlice(s.GetServerKey())
	fmt.Printf("serverConfigs %+v\n", serverConfigs)
	s.Servers = serverConfigs
}