Пример #1
0
Файл: cfg.go Проект: postfix/pit
// Init Loads a INI file onto memory, first try to liad the config file from
// the etc/ directory on the current path, and if the file can't be found, try
// to load it from the /etc/ directory
// The name of the file to be used has to be the specified "appName_env.ini"
func Init(appName, env string) (err error) {
	// Trying to read the config file form the /etc directory on a first
	// instance
	if cfg, err = configparser.Read(fmt.Sprintf("etc/%s_%s.ini", appName, env)); err != nil {
		cfg, err = configparser.Read(fmt.Sprintf("/etc/%s_%s.ini", appName, env))
	}

	return
}
Пример #2
0
func TestReadConfig(t *testing.T) {
	config, err := configparser.Read("fastforward.conf")
	if err != nil {
		t.Error(err)
	}
	log.Printf("full configuration:\n%s", config)
}
Пример #3
0
func main() {
	// Read the configuration from hook.conf
	config, err := configparser.Read("hook.conf")
	if err != nil {
		log.Fatalln(err)
	}
	section, err := config.Section("host")
	if err != nil {
		log.Fatalln(err)
	}
	urlStr := section.ValueOf("url")

	// Create a JSON node tree
	rootNode := jpath.NewNode()
	rootNode.Set("text", `---
##### Build Break - Project X - December 12, 2015 - 15:32 GMT +0
| Component  | Tests Run   | Tests Failed                                   |
|:-----------|:------------|:-----------------------------------------------|
| Server     | 948         | :ghost: 0                           |
| Web Client | 123         | :warning: [2 (see details)](http://linktologs) |
| iOS Client | 78          | :poop: [3 (see details)](http://linktologs) |
---`)
	rootNode.Set("username", "HookBot9000")

	// Send the message to the Mattermost host
	if status, err := mattersend.Send(urlStr, rootNode); err != nil || status != "200 OK" {
		log.Fatalln("FAIL", err, status)
	}
	fmt.Println("SUCCESS")
}
Пример #4
0
func main() {
	flag.Usage = usage
	debug := flag.Bool("d", false, "debug")
	conffile := flag.String("c", "config.ini", "config file")
	flag.Parse()

	if *debug {
		xmpp.Debug = true
	}

	config, err := configparser.Read(*conffile)
	if err != nil {
		log.Fatal(*conffile, err)
	}
	section, err := config.Section("global")
	if err != nil {
		log.Fatal(err)
	}

	jid := xmpp.JID(section.ValueOf("jid"))
	pass := section.ValueOf("pass")

	status := make(chan xmpp.Status, 10)
	go func() {
		for s := range status {
			log.Printf("connection status %s", statuses[s])
		}

	}()
	jid = xmpp.JID(fmt.Sprintf("%s/%s", jid.Bare(), "bot"))
	c, err := xmpp.NewClient(&jid, pass, tls.Config{InsecureSkipVerify: true}, nil, xmpp.Presence{}, status)

	if err != nil {
		log.Fatalf("NewClient(%v): %v", jid, err)
	}
	defer c.Close()
	for {
		select {
		case s := <-status:
			log.Printf("connection status %s", statuses[s])
			if s.Fatal() {
				return
			}
		case st, ok := <-c.Recv:
			if !ok {
				return
			}
			if m, ok := st.(*xmpp.Message); ok {
				log.Printf("msg from %s", m.From.Bare())
				process(m, c)
			}
			if p, ok := st.(*xmpp.Presence); ok {
				log.Printf("presence from %s", p.From.Bare())
			}
			if iq, ok := st.(*xmpp.Iq); ok {
				log.Printf("iq from %s", iq.From.Bare())
			}
		}
	}
}
Пример #5
0
// Read configuration file
func ReadConfig() {
	config, err := configparser.Read("/opt/pg/libnetwork/config.ini")
	if err != nil {
		log.Fatal(err)
	}

	// get PLUMgrid config
	pg_section, pg_err := config.Section("PLUMgrid")
	if pg_err != nil {
		log.Fatal(pg_err)
	} else {
		vip = pg_section.ValueOf("virtual_ip")
		username = pg_section.ValueOf("pg_username")
		password = pg_section.ValueOf("pg_password")
		default_vd = pg_section.ValueOf("default_domain")
	}

	// get Libnetwork config
	lib_section, lib_err := config.Section("Libnetwork")
	if lib_err != nil {
		log.Fatal(lib_err)
	} else {
		scope = lib_section.ValueOf("scope")
	}
}
Пример #6
0
// getBinlogPath read and parse the my.cnf config file and returns the path to the binlog file and datadir.
func (m *MySQLBinlogGrowth) getBinlogPath() (binLog string, dataDir string) {
	// read my.cnf config file
	config, err := configparser.Read(m.myCnfPath)
	if err != nil {
		m.log.Error(err)
		return
	}

	section, err := config.Section("mysqld")
	if err != nil {
		m.log.Error("mysqld section missing in ", m.myCnfPath)
		return
	}

	binLog = section.ValueOf("log-bin")
	if binLog == "" {
		m.log.Error("log-bin value missing from ", m.myCnfPath)
		return
	}

	dataDir = section.ValueOf("datadir")
	if dataDir == "" {
		m.log.Error("datadir value missing from ", m.myCnfPath)
		return
	}

	// If the log-bin value is a relative path then it's based on datadir
	if !path.IsAbs(binLog) {
		binLog = path.Join(dataDir, binLog)
	}
	return
}
Пример #7
0
func readStorageAggregations(file string) ([]*StorageAggregation, error) {
	config, err := cfg.Read(file)
	if err != nil {
		return nil, err
	}

	sections, err := config.AllSections()
	if err != nil {
		return nil, err
	}

	var ret []*StorageAggregation
	for _, s := range sections {
		var saggr StorageAggregation
		// this is mildly stupid, but I don't feel like forking
		// configparser just for this
		saggr.name =
			strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
		if saggr.name == "" {
			continue
		}
		saggr.pattern, err = regexp.Compile(s.ValueOf("pattern"))
		if err != nil {
			logger.Logf("failed to parse pattern '%s'for [%s]: %s",
				s.ValueOf("pattern"), saggr.name, err.Error())
			continue
		}
		saggr.xFilesFactor, err = strconv.ParseFloat(s.ValueOf("xFilesFactor"), 64)
		if err != nil {
			logger.Logf("failed to parse xFilesFactor '%s' in %s: %s",
				s.ValueOf("xFilesFactor"), saggr.name, err.Error())
			continue
		}

		saggr.aggregationMethodStr = s.ValueOf("aggregationMethod")
		switch saggr.aggregationMethodStr {
		case "average", "avg":
			saggr.aggregationMethod = whisper.Average
		case "sum":
			saggr.aggregationMethod = whisper.Sum
		case "last":
			saggr.aggregationMethod = whisper.Last
		case "max":
			saggr.aggregationMethod = whisper.Max
		case "min":
			saggr.aggregationMethod = whisper.Min
		default:
			logger.Logf("unknown aggregation method '%s'",
				s.ValueOf("aggregationMethod"))
			continue
		}

		logger.Debugf("adding aggregation [%s] pattern = %s aggregationMethod = %s xFilesFactor = %f",
			saggr.name, s.ValueOf("pattern"),
			saggr.aggregationMethodStr, saggr.xFilesFactor)
		ret = append(ret, &saggr)
	}

	return ret, nil
}
Пример #8
0
// ReadWhisperSchemas reads and parses a storage-schemas.conf file and returns a sorted
// schemas structure
// see https://graphite.readthedocs.io/en/0.9.9/config-carbon.html#storage-schemas-conf
func ReadWhisperSchemas(file string) (WhisperSchemas, error) {
	config, err := configparser.Read(file)
	if err != nil {
		return nil, err
	}

	sections, err := config.AllSections()
	if err != nil {
		return nil, err
	}

	var schemas WhisperSchemas

	for i, sec := range sections {
		schema := Schema{}
		schema.Name =
			strings.Trim(strings.SplitN(sec.String(), "\n", 2)[0], " []")
		if schema.Name == "" || strings.HasPrefix(schema.Name, "#") {
			continue
		}

		patternStr := sec.ValueOf("pattern")
		if patternStr == "" {
			return nil, fmt.Errorf("[persister] Empty pattern for [%s]", schema.Name)
		}
		schema.Pattern, err = regexp.Compile(patternStr)
		if err != nil {
			return nil, fmt.Errorf("[persister] Failed to parse pattern %q for [%s]: %s",
				sec.ValueOf("pattern"), schema.Name, err.Error())
		}
		schema.RetentionStr = sec.ValueOf("retentions")
		schema.Retentions, err = ParseRetentionDefs(schema.RetentionStr)

		if err != nil {
			return nil, fmt.Errorf("[persister] Failed to parse retentions %q for [%s]: %s",
				sec.ValueOf("retentions"), schema.Name, err.Error())
		}

		priorityStr := sec.ValueOf("priority")

		p := int64(0)
		if priorityStr != "" {
			p, err = strconv.ParseInt(priorityStr, 10, 0)
			if err != nil {
				return nil, fmt.Errorf("[persister] Failed to parse priority %q for [%s]: %s", priorityStr, schema.Name, err)
			}
		}
		schema.Priority = int64(p)<<32 - int64(i) // to sort records with same priority by position in file

		schemas = append(schemas, schema)
	}

	sort.Sort(schemas)
	return schemas, nil
}
Пример #9
0
func (c *config) Update() {
	var err error

	c.RootPath, err = osext.ExecutableFolder()
	checkErr(err)
	if strings.Contains(c.RootPath, "go-build") {
		c.RootPath = "."
	}

	config, err := configparser.Read(FromRootDir("config.ini"))
	checkErr(err)

	mainConfig, err := config.Section("Main")
	checkErr(err)

	c.DefaultProfile, err = strconv.Atoi(mainConfig.ValueOf("defaultProfile"))
	if err != nil {
		panic("Error parse config parametr 'defaultProfile'")
	}
	c.AdminMail = mainConfig.ValueOf("adminMail")
	c.GonderMail = mainConfig.ValueOf("gonderMail")

	dbConfig, err := config.Section("Database")
	checkErr(err)
	c.dbType = dbConfig.ValueOf("type")
	c.dbString = dbConfig.ValueOf("string")

	mailerConfig, err := config.Section("Mailer")
	checkErr(err)
	if mailerConfig.ValueOf("send") == "yes" {
		c.RealSend = true
	} else {
		c.RealSend = false
	}
	if mailerConfig.ValueOf("dnscache") == "yes" {
		c.DnsCache = true
	} else {
		c.DnsCache = false
	}
	c.MaxCampaingns, err = strconv.Atoi(mailerConfig.ValueOf("maxcampaign"))
	if err != nil {
		panic("Error parse config parametr 'maxcampaign'")
	}

	statisticConfig, err := config.Section("Statistic")
	checkErr(err)
	apiConfig, err := config.Section("API")
	checkErr(err)
	c.Url = "http://" + mainConfig.ValueOf("host")
	c.StatPort = statisticConfig.ValueOf("port")
	c.ApiPort = apiConfig.ValueOf("port")

	c.Version = "0.7.4"
}
Пример #10
0
// init - Establish database connection
func init() {
	//database = db.GetConnection("/home/visolve/go-orm/config.ini")
	conf, _ := configparser.Read("/home/visolve/go-orm/config.ini")
	db_config, _ := conf.Section("couch")
	var db couch.Database
	if db_config.ValueOf("user") == "" {
		db, _ = couch.NewDatabase(db_config.ValueOf("ipaddress"), db_config.ValueOf("port"), db_config.ValueOf("dbname"))
	} else {
		db, _ = couch.NewDatabaseByURL("http://" + db_config.ValueOf("user") + ":" + db_config.ValueOf("password") + "@" + db_config.ValueOf("ipaddress") + ":" + db_config.ValueOf("port") + "/" + db_config.ValueOf("dbname"))
	}
	cdatabase = abstract.Database(CouchDb{db})
}
Пример #11
0
func TestOption(t *testing.T) {
	config, err := configparser.Read("fastforward.conf")
	if err != nil {
		t.Error(err)
	}
	section, err := config.Section("DEFAULT")
	if err != nil {
		t.Error(err)
	}
	options := section.Options()
	log.Printf("option names:\n%s", options["provisioning_driver"])
	assert.Equal(t, "playback", options["provisioning_driver"])
}
Пример #12
0
// Load config values from file
func LoadConfig(filename string) {
	LoadDefaults()
	log.Printf("\nLoading Configuration from %v\n", filename)
	config, err := configparser.Read(filename)
	fmt.Print(config)
	if err != nil {
		log.Fatal(err)
	}
	dbSection, err := config.Section("Database")
	if err != nil {
		log.Fatal(err)
	}
	logSection, err := config.Section("Logging")
	if err != nil {
		log.Fatal(err)
	}
	authSection, err := config.Section("Auth")
	if err != nil {
		log.Fatal(err)
	}
	registrySection, err := config.Section("ServiceRegistry")
	if err != nil {
		log.Fatal(err)
	}
	//Optional sections
	frontendSection, err := config.Section("Frontend")
	userSection, err := config.Section("Users")
	searchSection, err := config.Section("Search")
	notifSection, err := config.Section("Notifications")
	if frontendSection != nil {
		SetFrontendConfig(frontendSection)
	}
	if searchSection != nil {
		SetSearchConfig(searchSection)
	}
	if userSection != nil {
		setUsersConfig(userSection)
	}
	if notifSection != nil {
		setNotificationConfig(notifSection)
	}
	setDbConfig(dbSection)
	setLogConfig(logSection)
	setAuthConfig(authSection)
	setRegistryConfig(registrySection)
}
Пример #13
0
func TestSection(t *testing.T) {
	config, err := configparser.Read("fastforward.conf")
	if err != nil {
		t.Error(err)
	}
	section, err := config.Section("DEFAULT")
	if err != nil {
		t.Error(err)
	}
	log.Printf("the default section:\n%s", section)

	section, err = config.Section("PLAYBACK")
	if err != nil {
		t.Error(err)
	}
	log.Printf("the playback section:\n%s", section)

}
Пример #14
0
// Loads Plugin Data from the plugins ini file
func LoadPluginData(filename string) {
	readSinglePluginData := func(pluginSection *configparser.Section) *PluginData {
		theData := NewPluginData()
		for key, value := range pluginSection.Options() {
			switch key {
			case "name":
				theData.Name = value
			case "author":
				theData.Author = value
			case "version":
				theData.Version = value
			case "pluginDir":
				theData.PluginDir = value
			case "mainScript":
				theData.MainScript = value
			case "stylesheet":
				theData.Stylesheet = value
			case "enabled":
				if value == "true" {
					theData.Enabled = true
				} else {
					theData.Enabled = false
				}
			}
		}
		return theData
	}
	config, err := configparser.Read(filename)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(config)
	pluginSections, err := config.Find(".plugin$")
	if err != nil {
		log.Fatal(err)
	}
	for _, section := range pluginSections {
		theData := readSinglePluginData(section)
		if theData.Enabled {
			enabledPlugins[theData.Name] = *theData
		}
	}
}
Пример #15
0
// GetConnection - Return DB connection object based on config file.
func GetConnection(path string) abstract.Database {
	var collection *mgo.Collection
	conf, _ := configparser.Read(path)
	checkError(conf, "Invalid configuration file")
	driver_config, _ := conf.Section("nosql.db")

	var db_config *configparser.Section
	if strings.Contains(strings.ToLower(driver_config.ValueOf("name")), "mongo") {
		db_config, _ = conf.Section("mongo")
		driver_config.SetValueFor("name", "mongo")
	} else if strings.Contains(strings.ToLower(driver_config.ValueOf("name")), "couch") {
		db_config, _ = conf.Section("couch")
		driver_config.SetValueFor("name", "couch")
	}
	switch strings.ToUpper(driver_config.ValueOf("name")) {
	case "COUCH":
		var db couch.Database
		if db_config.ValueOf("user") == "" {
			db, _ = couch.NewDatabase(db_config.ValueOf("ipaddress"), db_config.ValueOf("port"), db_config.ValueOf("dbname"))
		} else {
			db, _ = couch.NewDatabaseByURL("http://" + db_config.ValueOf("user") + ":" + db_config.ValueOf("password") + "@" + db_config.ValueOf("ipaddress") + ":" + db_config.ValueOf("port") + "/" + db_config.ValueOf("dbname"))
		}
		return abstract.Database(supported_db.CouchDb{db})
	case "MONGO":
		var mongoSession *mgo.Session
		var err error
		if db_config.ValueOf("user") == "" {
			mongoSession, err = mgo.Dial(db_config.ValueOf("ipaddress") + ":" + db_config.ValueOf("port"))
		} else {
			mongoSession, err = mgo.Dial(db_config.ValueOf("user") + ":" + db_config.ValueOf("password") + "@" + db_config.ValueOf("ipaddress") + ":" + db_config.ValueOf("port") + "/" + db_config.ValueOf("dbname"))
		}
		checkError(mongoSession, err)
		db := mongoSession.DB(db_config.ValueOf("dbname"))
		collection = db.C(db_config.ValueOf("collectionname"))
		return abstract.Database(supported_db.MongoDb{collection})
	default:
		panic("Supports only Couch or MongoDb")
	}
	return nil
}
Пример #16
0
func (b *Battery) update() error {
	file := fmt.Sprintf(BatteryPath, b.Identifier)

	config, err := cfg.Read(file)
	if err != nil {
		return err
	}

	c, err := config.Section("global")
	if err != nil {
		return err
	}

	b.Present = c.ValueOf("POWER_SUPPLY_PRESENT") == "1"
	b.Status = c.ValueOf("POWER_SUPPLY_STATUS")

	fullCharge, _ := strconv.ParseFloat(c.ValueOf("POWER_SUPPLY_ENERGY_FULL"), 32)
	currentCharge, _ := strconv.ParseFloat(c.ValueOf("POWER_SUPPLY_ENERGY_NOW"), 32)
	powerUse, _ := strconv.ParseFloat(c.ValueOf("POWER_SUPPLY_POWER_NOW"), 32)

	currentPerc, _ := strconv.Atoi(c.ValueOf("POWER_SUPPLY_CAPACITY"))

	b.Level = currentPerc

	if powerUse == 0 {
		b.Remaining = 0 * time.Hour
	} else {
		switch b.Status {
		case "Charging":
			b.Remaining = time.Duration(60*60*(fullCharge-currentCharge)/powerUse) * time.Second
		case "Discharging":
			b.Remaining = time.Duration(60*60*(currentCharge/powerUse)) * time.Second
		case "Full":
			b.Remaining = 0 * time.Hour
		}
	}

	return nil
}
Пример #17
0
// LoadConf loads the FastForward configuration and return the Conf pointer.
func (c *Conf) LoadConf() *Conf {
	path := "/etc/fastforward/fastforward.conf"
	conf, err := configparser.Read(path)
	if err != nil {
		log.Fatal(err)
	}
	DefaultSection, err := conf.Section("DEFAULT")
	checkErr(err)

	PlaybackSection, err := conf.Section("PLAYBACK")
	checkErr(err)

	FFconf := &Conf{
		// Keys are the configuration file field, Values are the value of field.
		DEFAULT: map[string]string{"provisioning_driver": DefaultSection.Options()["provisioning_driver"],
			"orchestration_driver": DefaultSection.Options()["orchestration_driver"],
			"monitoring_driver":    DefaultSection.Options()["monitoring_driver"]},
		PLAYBACK: map[string]string{"use_ansible": PlaybackSection.Options()["use_ansible"],
			"ansible_cfg": PlaybackSection.Options()["ansible_cfg"],
			"private_key": PlaybackSection.Options()["private_key"]},
	}
	return FFconf
}
Пример #18
0
func readStorageSchemas(file string) ([]*StorageSchema, error) {
	config, err := cfg.Read(file)
	if err != nil {
		return nil, err
	}

	sections, err := config.AllSections()
	if err != nil {
		return nil, err
	}

	var ret []*StorageSchema
	for _, s := range sections {
		var sschema StorageSchema
		// this is mildly stupid, but I don't feel like forking
		// configparser just for this
		sschema.name =
			strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
		if sschema.name == "" {
			continue
		}
		sschema.pattern, err = regexp.Compile(s.ValueOf("pattern"))
		if err != nil {
			logger.Logf("failed to parse pattern '%s'for [%s]: %s",
				s.ValueOf("pattern"), sschema.name, err.Error())
			continue
		}
		sschema.retentionStr = s.ValueOf("retentions")
		sschema.retentions, err = whisper.ParseRetentionDefs(sschema.retentionStr)
		logger.Debugf("adding schema [%s] pattern = %s retentions = %s",
			sschema.name, s.ValueOf("pattern"), sschema.retentionStr)

		ret = append(ret, &sschema)
	}

	return ret, nil
}
Пример #19
0
// Read and modify a configuration file
func Example() {
	config, err := configparser.Read("/etc/config.ini")
	if err != nil {
		log.Fatal(err)
	}
	// Print the full configuration
	fmt.Println(config)

	// get a section
	section, err := config.Section("MYSQLD DEFAULT")
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("TotalSendBufferMemory=%s\n", section.ValueOf("TotalSendBufferMemory"))

		// set new value
		var oldValue = section.SetValueFor("TotalSendBufferMemory", "256M")
		fmt.Printf("TotalSendBufferMemory=%s, old value=%s\n", section.ValueOf("TotalSendBufferMemory"), oldValue)

		// delete option
		oldValue = section.Delete("DefaultOperationRedoProblemAction")
		fmt.Println("Deleted DefaultOperationRedoProblemAction: " + oldValue)

		// add new options
		section.Add("innodb_buffer_pool_size", "64G")
		section.Add("innodb_buffer_pool_instances", "8")
	}

	// add a new section and options
	section = config.NewSection("NDBD MGM")
	section.Add("NodeId", "2")
	section.Add("HostName", "10.10.10.10")
	section.Add("PortNumber", "1186")
	section.Add("ArbitrationRank", "1")

	// find all sections ending with .webservers
	sections, err := config.Find(".webservers$")
	if err != nil {
		log.Fatal(err)
	}
	for _, section := range sections {
		fmt.Print(section)
	}
	// or
	config.PrintSection("dc1.webservers")

	sections, err = config.Delete("NDB_MGMD DEFAULT")
	if err != nil {
		log.Fatal(err)
	}
	// deleted sections
	for _, section := range sections {
		fmt.Print(section)
	}

	options := section.Options()
	fmt.Println(options["HostName"])

	// save the new config. the original will be renamed to /etc/config.ini.bak
	err = configparser.Save(config, "/etc/config.ini")
	if err != nil {
		log.Fatal(err)
	}
}
// ReadWhisperSchemas ...
func ReadWhisperSchemas(file string) (*WhisperSchemas, error) {
	config, err := configparser.Read(file)
	if err != nil {
		return nil, err
	}

	sections, err := config.AllSections()
	if err != nil {
		return nil, err
	}

	result := NewWhisperSchemas()

	for index, s := range sections {
		item := &whisperSchemaItem{}
		// this is mildly stupid, but I don't feel like forking
		// configparser just for this
		item.name =
			strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
		if item.name == "" || strings.HasPrefix(item.name, "#") {
			continue
		}

		patternStr := s.ValueOf("pattern")
		if patternStr == "" {
			return nil, fmt.Errorf("[persister] Empty pattern '%s' for [%s]", item.name)
		}
		item.pattern, err = regexp.Compile(patternStr)
		if err != nil {
			return nil, fmt.Errorf("[persister] Failed to parse pattern '%s' for [%s]: %s",
				s.ValueOf("pattern"), item.name, err.Error())
		}
		item.retentionStr = s.ValueOf("retentions")
		item.retentions, err = ParseRetentionDefs(item.retentionStr)

		if err != nil {
			return nil, fmt.Errorf("[persister] Failed to parse retentions '%s' for [%s]: %s",
				s.ValueOf("retentions"), item.name, err.Error())
		}

		priorityStr := s.ValueOf("priority")

		var p int64
		if priorityStr == "" {
			p = 0
		} else {
			p, err = strconv.ParseInt(priorityStr, 10, 0)
			if err != nil {
				return nil, fmt.Errorf("[persister] wrong priority in schema: %s", err)
			}
		}
		item.priority = int64(p)<<32 - int64(index) // for sort records with same priority
		// item.priority = (s.ValueOf("priority"))
		logrus.Debugf("[persister] Adding schema [%s] pattern = %s retentions = %s",
			item.name, s.ValueOf("pattern"), item.retentionStr)

		result.Data = append(result.Data, item)
	}

	sort.Sort(whisperSchemaItemByPriority(result.Data))

	return result, nil
}
Пример #21
0
// ReadWhisperAggregation ...
func ReadWhisperAggregation(file string) (*WhisperAggregation, error) {
	config, err := configparser.Read(file)
	if err != nil {
		return nil, err
	}
	// pp.Println(config)
	sections, err := config.AllSections()
	if err != nil {
		return nil, err
	}

	result := NewWhisperAggregation()

	for _, s := range sections {
		item := &whisperAggregationItem{}
		// this is mildly stupid, but I don't feel like forking
		// configparser just for this
		item.name =
			strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
		if item.name == "" || strings.HasPrefix(item.name, "#") {
			continue
		}

		item.pattern, err = regexp.Compile(s.ValueOf("pattern"))
		if err != nil {
			logrus.Errorf("[persister] Failed to parse pattern '%s'for [%s]: %s",
				s.ValueOf("pattern"), item.name, err.Error())
			return nil, err
		}

		item.xFilesFactor, err = strconv.ParseFloat(s.ValueOf("xFilesFactor"), 64)
		if err != nil {
			logrus.Errorf("failed to parse xFilesFactor '%s' in %s: %s",
				s.ValueOf("xFilesFactor"), item.name, err.Error())
			continue
		}

		item.aggregationMethodStr = s.ValueOf("aggregationMethod")
		switch item.aggregationMethodStr {
		case "average", "avg":
			item.aggregationMethod = whisper.Average
		case "sum":
			item.aggregationMethod = whisper.Sum
		case "last":
			item.aggregationMethod = whisper.Last
		case "max":
			item.aggregationMethod = whisper.Max
		case "min":
			item.aggregationMethod = whisper.Min
		default:
			logrus.Errorf("unknown aggregation method '%s'",
				s.ValueOf("aggregationMethod"))
			continue
		}

		logrus.Debugf("[persister] Adding aggregation [%s] pattern = %s aggregationMethod = %s xFilesFactor = %f",
			item.name, s.ValueOf("pattern"),
			item.aggregationMethodStr, item.xFilesFactor)

		result.Data = append(result.Data, item)
	}

	return result, nil
}
Пример #22
0
func main() {

	f, err := os.OpenFile("dclog.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777)
	defer f.Close()
	log.SetOutput(f)
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	dir, err := utils.GetCurrentDir()
	if err != nil {
		log.Fatal(err)
	}
	config, err := configparser.Read(dir + "/config.ini")
	if err != nil {
		log.Fatal(err)
	}
	configIni, err := config.Section("main")

	txType := "NewHolidays"
	txTime := "1426283713"
	blockData := make(map[string]string)

	var txSlice []string
	// hash
	txSlice = append(txSlice, "22cb812e53e22ee539af4a1d39b4596d")
	// type
	txSlice = append(txSlice, strconv.Itoa(int(TypeInt(txType))))
	// time
	txSlice = append(txSlice, txTime)
	// user_id
	txSlice = append(txSlice, strconv.FormatInt(1, 10))
	//start
	txSlice = append(txSlice, strconv.FormatInt(100000, 10))
	//end
	txSlice = append(txSlice, strconv.FormatInt(4545, 10))
	// sign
	txSlice = append(txSlice, "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")

	blockData["block_id"] = strconv.FormatInt(185510, 10)
	blockData["time"] = txTime
	blockData["user_id"] = strconv.FormatInt(1, 10)

	//fmt.Println(txSlice)

	parser := new(dcparser.Parser)
	parser.DCDB = utils.NewDbConnect(configIni)
	parser.TxSlice = txSlice
	parser.BlockData = blockData

	/*for i:=0; i<10000; i++ {

		x := func() {
			stmt, err := parser.DCDB.Prepare(`INSERT INTO main_lock(lock_time,script_name) VALUES($1,$2)`)
			defer stmt.Close()
			if err!=nil {
				fmt.Println(err)
			}
			_, err = stmt.Exec(11111, "testblock_generator")
			if err!=nil {
				fmt.Println(err)
			}
		}
		x()
		//stmt, _ := parser.DCDB.Prepare(`INSERT INTO main_lock(lock_time,script_name) VALUES($1,$2)`)
		//fmt.Println(err)
		//defer stmt.Close()
		//_, _ = stmt.Exec(11111, "testblock_generator")
		//fmt.Println(err)
		//_, _ = parser.DCDB.Query("INSERT INTO main_lock(lock_time,script_name) VALUES($1,$2)", 11111, "testblock_generator")
		x2 := func() {
			row, err := parser.DCDB.Query("DELETE FROM main_lock WHERE script_name='testblock_generator'")
			defer row.Close()
			if err!=nil {
				fmt.Println(err)
			}
		}
		x2()
		//parser.DCDB.DbLock()
		//parser.DCDB.DbUnlock()
		//fmt.Println(i)
	}*/
	fmt.Println()

	err = dcparser.MakeTest(parser, txType, hashesStart)
	if err != nil {
		fmt.Println("err", err)
	}
	//go daemons.Testblock_is_ready()

	//parser.Db.HashTableData("holidays", "", "")
	//HashTableData(parser.Db.DB,"holidays", "", "")
	//hashes, err := parser.Db.AllHashes()
	utils.CheckErr(err)
	//fmt.Println(hashes)
	fmt.Println()
	/*
	   	var ptr reflect.Value
	   	var value reflect.Value
	   	//var finalMethod reflect.Value

	   	i := Test{Start: "start"}

	   	value = reflect.ValueOf(i)

	   	// if we start with a pointer, we need to get value pointed to
	   	// if we start with a value, we need to get a pointer to that value
	   	if value.Type().Kind() == reflect.Ptr {
	   		ptr = value
	   		value = ptr.Elem()
	   	} else {
	   		ptr = reflect.New(reflect.TypeOf(i))
	   		temp := ptr.Elem()
	   		temp.Set(value)
	   	}
	   	fmt.Println(value)
	   /*
	   	// check for method on value
	   	method := value.MethodByName("Finish")
	   	fmt.Println(method)
	   	// check for method on pointer
	   	method = ptr.MethodByName("Finish")
	   	fmt.Println(method)*/

}
Пример #23
0
func main() {

	i, _ := net.InterfaceAddrs()
	fmt.Println(i)

	runtime.GOMAXPROCS(runtime.NumCPU())

	log.Println("Read config file")
	config, err := configparser.Read("./config.ini")
	checkErr(err)

	dbConfig, err := config.Section("Database")
	checkErr(err)

	hostConfig, err := config.Section("Host")
	checkErr(err)

	log.Println("Connect to database")
	db, err := sql.Open(dbConfig.ValueOf("type"), dbConfig.ValueOf("string"))
	checkErr(err)
	defer db.Close()
	checkErr(db.Ping())

	mailer.Db = db
	panel.Db = db

	if hostConfig.ValueOf("port") == "80" {
		mailer.HostName = "http://" + hostConfig.ValueOf("name")
	} else {
		mailer.HostName = "http://" + hostConfig.ValueOf("name") + ":" + hostConfig.ValueOf("port")
	}

	if len(os.Args) == 2 {

		if os.Args[1] == "start" {
			p := exec.Command(os.Args[0], "start", "panel")
			p.Start()
			fmt.Println("Panel [PID]", p.Process.Pid)

			sd := exec.Command(os.Args[0], "start", "sender")
			sd.Start()
			fmt.Println("Sender [PID]", sd.Process.Pid)

			st := exec.Command(os.Args[0], "start", "stat")
			st.Start()
			fmt.Println("Statistic [PID]", st.Process.Pid)

			os.Exit(0)
		}

		if os.Args[1] == "stop" {
			c := exec.Command("killall", os.Args[0])
			c.Start()
			fmt.Println("Stop all services")

			os.Exit(0)
		}
	}

	if len(os.Args) == 3 {

		if os.Args[1] == "start" {

			if os.Args[2] == "panel" {

				log.Println("Start panel http server")
				panel.Run()

				for {
				}
			}

			if os.Args[2] == "sender" {

				log.Println("Start database mailer")
				mailer.Sender()

				for {
				}
			}

			if os.Args[2] == "stat" {

				log.Println("Start statistics http server")
				mailer.Stat(hostConfig.ValueOf("port"))

				for {
				}
			}

		}

	}

	if len(os.Args) == 1 {
		log.Println("Start panel http server")
		go panel.Run()

		log.Println("Start database mailer")
		go mailer.Sender()

		log.Println("Start statistics http server")
		go mailer.Stat(hostConfig.ValueOf("port"))

		log.Println("Press Enter for stop")
		var input string
		fmt.Scanln(&input)
	}

}