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 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 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", key.Name(), section.Name(), configFile) continue } defaultKey.SetValue(key.Value()) } } configFiles = append(configFiles, configFile) }
func main() { buildstampInt64, _ := strconv.ParseInt(buildstamp, 10, 64) setting.BuildVersion = version setting.BuildCommit = commit setting.BuildStamp = buildstampInt64 go func() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) <-c os.Exit(0) }() flag.Parse() writePIDFile() initRuntime() search.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() log.Close() }
func initLogging(args *CommandLineArgs) { // 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": LogConfigs[i] = util.DynMap{"level": level} 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)) } }