func loadLdapConfig() { if !setting.LdapEnabled { return } log.Info("Login: Ldap enabled, reading config file: %s", setting.LdapConfigFile) _, err := toml.DecodeFile(setting.LdapConfigFile, &ldapCfg) if err != nil { log.Fatal(3, "Failed to load ldap config file: %s", err) } if len(ldapCfg.Servers) == 0 { log.Fatal(3, "ldap enabled but no ldap servers defined in config file: %s", setting.LdapConfigFile) } // set default org id for _, server := range ldapCfg.Servers { assertNotEmptyCfg(server.SearchFilter, "search_filter") assertNotEmptyCfg(server.SearchBaseDNs, "search_base_dns") for _, groupMap := range server.LdapGroups { if groupMap.OrgId == 0 { groupMap.OrgId = 1 } } } }
func NewEngine() { x, err := getEngine() if err != nil { log.Fatal(3, "Sqlstore: Fail to connect to database: %v", err) } err = SetEngine(x, true) if err != nil { log.Fatal(3, "fail to initialize orm engine: %v", err) } }
func assertNotEmptyCfg(val interface{}, propName string) { switch v := val.(type) { case string: if v == "" { log.Fatal(3, "LDAP config file is missing option: %s", propName) } case []string: if len(v) == 0 { log.Fatal(3, "LDAP config file is missing option: %s", propName) } default: fmt.Println("unknown") } }
func EnsureAdminUser() { statsQuery := m.GetSystemStatsQuery{} if err := bus.Dispatch(&statsQuery); err != nil { log.Fatal(3, "Could not determine if admin user exists: %v", err) return } if statsQuery.Result.UserCount > 0 { return } cmd := m.CreateUserCommand{} cmd.Login = setting.AdminUser cmd.Email = setting.AdminUser + "@localhost" cmd.Password = setting.AdminPassword cmd.IsAdmin = true if err := bus.Dispatch(&cmd); err != nil { log.Error(3, "Failed to create default admin user", err) return } system := m.AddSystemsCommand{} system.OrgId = cmd.Result.OrgId system.SystemsName = []string{"Cloudwiz"} if err := bus.Dispatch(&system); err != nil { log.Error(3, "Failed to create defalut system for admin", err) return } log.Info("Created default Cloudwiz system") log.Info("Created default admin user: %v", setting.AdminUser) }
func main() { buildstampInt64, _ := strconv.ParseInt(buildstamp, 10, 64) setting.BuildVersion = version setting.BuildCommit = commit setting.BuildStamp = buildstampInt64 go listenToSystemSignels() flag.Parse() writePIDFile() initRuntime() search.Init() login.Init() social.NewOAuthService() eventpublisher.Init() plugins.Init() if err := notifications.Init(); err != nil { log.Fatal(3, "Notification service failed to initialize", err) } if setting.ReportingEnabled { go metrics.StartUsageReportLoop() } cmd.StartServer() exitChan <- 0 }
func AddDatasourceFromConfig() { // Read datasource from OrgId 1 and compare with the current setting: // If same, do nothing // If different, need to update the entries in the data_source table for all the OrgIds. // Read data source from OrgId 1 (default Main.org) query := m.GetDataSourceByNameQuery{ OrgId: MAINORG_ID, Name: "opentsdb", } if err := bus.Dispatch(&query); err != nil { log.Info("Could not find data source with OrgId = 1: %v", err) } else { log.Info("Data source read from OrgId 1 (MAINORG_ID) is %s", query.Result.Url) if setting.DataSource.DataSourceUrlRoot == query.Result.Url { return } } // If initially OrgId 1 does not have data source defined in data_source table, add it. // This should only happen when the system runs at the first time. if query.Result.Url == "" { log.Info("Add default data source for OrgId = 1 from config: %v", setting.DataSource.DataSourceUrlRoot) if err := bus.Dispatch(&m.AddDataSourceCommand{ OrgId: MAINORG_ID, Name: "opentsdb", Type: m.DS_OPENTSDB, Access: m.DS_ACCESS_DIRECT, Url: setting.DataSource.DataSourceUrlRoot, IsDefault: true, }); err != nil { log.Fatal(3, "Could not add default datasource for OrgId 1 from config: %v", err) return } } else { log.Info("Update default datasource for all the Orgs") if err := bus.Dispatch(&m.UpdateDataSourceForAllOrgCommand{ Url: setting.DataSource.DataSourceUrlRoot, }); err != nil { log.Fatal(3, "Could not update default datasource for all Orgs: %v", err) return } } }
func writePIDFile() { if *pidFile == "" { return } // Ensure the required directory structure exists. err := os.MkdirAll(filepath.Dir(*pidFile), 0700) if err != nil { log.Fatal(3, "Failed to verify pid directory", err) } // Retrieve the PID and write it. pid := strconv.Itoa(os.Getpid()) if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil { log.Fatal(3, "Failed to write pidfile", err) } }
func StartServer() { var err error m := newMacaron() api.Register(m) listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort) log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl) switch setting.Protocol { case setting.HTTP: err = http.ListenAndServe(listenAddr, m) case setting.HTTPS: err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m) default: log.Fatal(4, "Invalid protocol: %s", setting.Protocol) } if err != nil { log.Fatal(4, "Fail to start server: %v", err) } }
func parseAppUrlAndSubUrl(section *ini.Section) (string, string) { appUrl := section.Key("root_url").MustString("http://localhost:3000/") if appUrl[len(appUrl)-1] != '/' { appUrl += "/" } // Check if has app suburl. url, err := url.Parse(appUrl) if err != nil { log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err) } appSubUrl := strings.TrimSuffix(url.Path, "/") return appUrl, appSubUrl }
func initRuntime() { err := setting.NewConfigContext(&setting.CommandLineArgs{ Config: *configFile, HomePath: *homePath, Args: flag.Args(), }) if err != nil { log.Fatal(3, err.Error()) } log.Info("Starting Grafana") log.Info("Version: %v, Commit: %v, Build date: %v", setting.BuildVersion, setting.BuildCommit, time.Unix(setting.BuildStamp, 0)) setting.LogConfigurationInfo() sqlstore.NewEngine() sqlstore.EnsureAdminUser() sqlstore.AddDatasourceFromConfig() }
func getCommandLineProperties(args []string) map[string]string { props := make(map[string]string) for _, arg := range args { if !strings.HasPrefix(arg, "cfg:") { continue } trimmed := strings.TrimPrefix(arg, "cfg:") parts := strings.Split(trimmed, "=") if len(parts) != 2 { log.Fatal(3, "Invalid command line argument", arg) return nil } props[parts[0]] = parts[1] } return props }
func loadConfiguration(args *CommandLineArgs) { var err error // load config defaults defaultConfigFile := path.Join(HomePath, "conf/defaults.ini") configFiles = append(configFiles, defaultConfigFile) Cfg, err = ini.Load(defaultConfigFile) Cfg.BlockMode = false if err != nil { log.Fatal(3, "Failed to parse defaults.ini, %v", err) } // command line props commandLineProps := getCommandLineProperties(args.Args) // load default overrides applyCommandLineDefaultProperties(commandLineProps) // init logging before specific config so we can log errors from here on DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath) initLogging(args) // load specified config file loadSpecifedConfigFile(args.Config) // apply environment overrides applyEnvVariableOverrides() // apply command line overrides applyCommandLineProperties(commandLineProps) // evaluate config values containing environment variables evalConfigValues() // update data path and logging config DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath) initLogging(args) }
func loadSpecifedConfigFile(configFile string) { if configFile == "" { configFile = filepath.Join(HomePath, "conf/custom.ini") // return without error if custom file does not exist if !pathExists(configFile) { return } } userConfig, err := ini.Load(configFile) userConfig.BlockMode = false if err != nil { log.Fatal(3, "Failed to parse %v, %v", configFile, err) } for _, section := range userConfig.Sections() { for _, key := range section.Keys() { if key.Value() == "" { continue } defaultSec, err := Cfg.GetSection(section.Name()) if err != nil { log.Error(3, "Unknown config section %s defined in %s", section.Name(), configFile) continue } defaultKey, err := defaultSec.GetKey(key.Name()) if err != nil { log.Error(3, "Unknown config key %s defined in section %s, in file %s", key.Name(), section.Name(), configFile) continue } defaultKey.SetValue(key.Value()) } } configFiles = append(configFiles, configFile) }
func initLogging(args *CommandLineArgs) { //close any existing log handlers. log.Close() // Get and check log mode. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",") LogsPath = makeAbsolute(Cfg.Section("paths").Key("logs").String(), HomePath) LogConfigs = make([]util.DynMap, len(LogModes)) for i, mode := range LogModes { mode = strings.TrimSpace(mode) sec, err := Cfg.GetSection("log." + mode) if err != nil { log.Fatal(4, "Unknown log mode: %s", mode) } // Log level. levelName := Cfg.Section("log."+mode).Key("level").In("Trace", []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}) level, ok := logLevels[levelName] if !ok { log.Fatal(4, "Unknown log level: %s", levelName) } // Generate log configuration. switch mode { case "console": formatting := sec.Key("formatting").MustBool(true) LogConfigs[i] = util.DynMap{ "level": level, "formatting": formatting, } case "file": logPath := sec.Key("file_name").MustString(filepath.Join(LogsPath, "grafana.log")) os.MkdirAll(filepath.Dir(logPath), os.ModePerm) LogConfigs[i] = util.DynMap{ "level": level, "filename": logPath, "rotate": sec.Key("log_rotate").MustBool(true), "maxlines": sec.Key("max_lines").MustInt(1000000), "maxsize": 1 << uint(sec.Key("max_size_shift").MustInt(28)), "daily": sec.Key("daily_rotate").MustBool(true), "maxdays": sec.Key("max_days").MustInt(7), } case "conn": LogConfigs[i] = util.DynMap{ "level": level, "reconnectOnMsg": sec.Key("reconnect_on_msg").MustBool(), "reconnect": sec.Key("reconnect").MustBool(), "net": sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}), "addr": sec.Key("addr").MustString(":7020"), } case "smtp": LogConfigs[i] = util.DynMap{ "level": level, "user": sec.Key("user").MustString("*****@*****.**"), "passwd": sec.Key("passwd").MustString("******"), "host": sec.Key("host").MustString("127.0.0.1:25"), "receivers": sec.Key("receivers").MustString("[]"), "subject": sec.Key("subject").MustString("Diagnostic message from serve"), } case "database": LogConfigs[i] = util.DynMap{ "level": level, "driver": sec.Key("driver").String(), "conn": sec.Key("conn").String(), } } cfgJsonBytes, _ := json.Marshal(LogConfigs[i]) log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, string(cfgJsonBytes)) } }