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 } log.Info("Created default admin user: %v", setting.AdminUser) }
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() }
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 main() { v := flag.Bool("v", false, "prints current version and exits") flag.Parse() if *v { fmt.Printf("Version %s (commit: %s)\n", version, commit) os.Exit(0) } 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 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(), } case "syslog": LogConfigs[i] = util.DynMap{ "level": level, "network": sec.Key("network").MustString(""), "address": sec.Key("address").MustString(""), "facility": sec.Key("facility").MustString("local7"), "tag": sec.Key("tag").MustString(""), } } cfgJsonBytes, _ := json.Marshal(LogConfigs[i]) log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, string(cfgJsonBytes)) } }