func AddOrgUser(cmd *m.AddOrgUserCommand) error { return inTransaction(func(sess *xorm.Session) error { logger := log.New("main") logger.Info(" AddOrgInvite3") // check if user exists if res, err := sess.Query("SELECT 1 from org_user WHERE org_id=? and user_id=?", cmd.OrgId, cmd.UserId); err != nil { return err } else if len(res) == 1 { return m.ErrOrgUserAlreadyAdded } if res, err := sess.Query("SELECT 1 from org WHERE id=?", cmd.OrgId); err != nil { return err } else if len(res) != 1 { return m.ErrOrgNotFound } logger1 := log.New("main") logger1.Info(" AddOrgInvite4") entity := m.OrgUser{ OrgId: cmd.OrgId, UserId: cmd.UserId, Role: cmd.Role, Created: time.Now(), Updated: time.Now(), } _, err := sess.Insert(&entity) return err }) }
func GetContextHandler() macaron.Handler { return func(c *macaron.Context) { ctx := &Context{ Context: c, SignedInUser: &m.SignedInUser{}, Session: GetSession(), IsSignedIn: false, AllowAnonymous: false, Logger: log.New("context"), } // the order in which these are tested are important // look for api key in Authorization header first // then init session and look for userId in session // then look for api key in session (special case for render calls via api) // then test if anonymous access is enabled if initContextWithRenderAuth(ctx) || initContextWithApiKey(ctx) || initContextWithBasicAuth(ctx) || initContextWithAuthProxy(ctx) || initContextWithUserSessionCookie(ctx) || initContextWithAnonymousUser(ctx) { } ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login) ctx.Data["ctx"] = ctx c.Map(ctx) } }
func AddOrgInvite(c *middleware.Context, inviteDto dtos.AddInviteForm) Response { logger := log.New("main") logger.Info(" AddOrgInvite1", c.OrgId) if !inviteDto.Role.IsValid() { return ApiError(400, "Invalid role specified", nil) } // first try get existing user userQuery := m.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail} if err := bus.Dispatch(&userQuery); err != nil { if err != m.ErrUserNotFound { return ApiError(500, "Failed to query db for existing user check", err) } } else { return inviteExistingUserToOrg(c, userQuery.Result, &inviteDto) } logger1 := log.New("main") logger1.Info(" AddOrgInvite2", c.OrgId) cmd := m.CreateTempUserCommand{} cmd.OrgId = c.OrgId cmd.Email = inviteDto.LoginOrEmail cmd.Name = inviteDto.Name cmd.Status = m.TmpUserInvitePending cmd.InvitedByUserId = c.UserId cmd.Code = util.GetRandomString(30) cmd.Role = inviteDto.Role cmd.RemoteAddr = c.Req.RemoteAddr if err := bus.Dispatch(&cmd); err != nil { return ApiError(500, "Failed to save invite to database", err) } // send invite email if !inviteDto.SkipEmails && util.IsEmail(inviteDto.LoginOrEmail) { emailCmd := m.SendEmailCommand{ To: []string{inviteDto.LoginOrEmail}, Template: "new_user_invite.html", Data: map[string]interface{}{ "Name": util.StringsFallback2(cmd.Name, cmd.Email), "OrgName": c.OrgName, "Email": c.Email, "LinkUrl": setting.ToAbsUrl("invite/" + cmd.Code), "InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login), }, } if err := bus.Dispatch(&emailCmd); err != nil { return ApiError(500, "Failed to send email invite", err) } return ApiSuccess(fmt.Sprintf("Sent invite to %s", inviteDto.LoginOrEmail)) } return ApiSuccess(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail)) }
func UpdateSubProcess(cmd *m.UpdateSubProcessCommand) error { return inTransaction2(func(sess *session) error { logger := log.New("main") logger.Info("updatedProcess3 %s") subprocess := m.SubProcess{ SubProcessId: cmd.SubProcessId, ProcessName: cmd.ProcessName, SubProcessName: cmd.SubProcessName, UpdatedBy: cmd.UpdatedBy, Updated: time.Now(), } logger.Info("updatedProcess4 %s") if _, err := sess.Where("sub_process_id= ?", subprocess.SubProcessId).Update(&subprocess); err != nil { return err } logger.Info("updatedProcess5 %s") sess.publishAfterCommit(&events.SubProcessUpdated{ Timestamp: subprocess.Created, SubProcessId: subprocess.SubProcessId, SubProcessName: subprocess.SubProcessName, ProcessName: subprocess.ProcessName, UpdatedBy: subprocess.UpdatedBy, }) return nil }) }
func UpdateOrgProcessForCurrentOrg(c *middleware.Context, cmd m.UpdateOrgProcessCommand) Response { cmd.ProcessId = c.ParamsInt64(":processId") logger := log.New("main") logger.Info("updatedProcess1 %s") return updateOrgProcessHelper(cmd) }
func (g *GrafanaServerImpl) startHttpServer() { logger = log.New("http.server") var err error m := newMacaron() api.Register(m) listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort) g.log.Info("Initializing HTTP Server", "address", listenAddr, "protocol", setting.Protocol, "subUrl", setting.AppSubUrl) switch setting.Protocol { case setting.HTTP: err = http.ListenAndServe(listenAddr, m) case setting.HTTPS: err = ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m) default: g.log.Error("Invalid protocol", "protocol", setting.Protocol) g.Shutdown(1, "Startup failed") } if err != nil { g.log.Error("Fail to start server", "error", err) g.Shutdown(1, "Startup failed") return } }
func StartServer() int { logger = log.New("server") var err error m := newMacaron() api.Register(m) listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort) logger.Info("Server Listening", "address", listenAddr, "protocol", setting.Protocol, "subUrl", 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: logger.Error("Invalid protocol", "protocol", setting.Protocol) return 1 } if err != nil { logger.Error("Fail to start server", "error", err) return 1 } return 0 }
func UpdateMachine(cmd *m.UpdateMachineCommand) error { return inTransaction2(func(sess *session) error { logger := log.New("main") logger.Info("updatedProcess3 %s") machine := m.Machine{ MachineId: cmd.MachineId, MachineName: cmd.MachineName, Description: cmd.Description, UpdatedBy: cmd.UpdatedBy, Updated: time.Now(), Vendor: cmd.Vendor, } logger.Info("updatedProcess4 %s") if _, err := sess.Where("machine_id= ?", machine.MachineId).Update(&machine); err != nil { return err } logger.Info("updatedProcess5 %s") sess.publishAfterCommit(&events.MachineUpdated{ Timestamp: machine.Created, MachineId: machine.MachineId, MachineName: machine.MachineName, Description: machine.Description, UpdatedBy: machine.UpdatedBy, Vendor: machine.Vendor, }) return nil }) }
func GetPendingAlertActionHistory(c *middleware.Context) Response { logger := log.New("main") logger.Info("GetMachine123 %s") alertId := c.ParamsInt64(":id") return GetPendingAlertActionHistoryHelper(alertId) }
func UpdateMaintenance(cmd *m.UpdateMaintenanceCommand) error { return inTransaction2(func(sess *session) error { logger := log.New("main") logger.Info("updatedProcess3 %s") maintenance := m.Maintenance{ Id: cmd.Id, Component: cmd.Component, Parameter: cmd.Parameter, Message: cmd.Message, Interval: cmd.Interval, } logger.Info("updatedProcess4 %s") if _, err := sess.Where("Id= ?", maintenance.Id).Update(&maintenance); err != nil { return err } logger.Info("updatedProcess5 %s") sess.publishAfterCommit(&events.MaintenanceUpdated{ Timestamp: time.Now(), Id: maintenance.Id, Component: maintenance.Component, Parameter: maintenance.Parameter, Message: maintenance.Message, Interval: maintenance.Interval, }) return nil }) }
func GetMaintenacneById(c *middleware.Context) Response { logger := log.New("main") logger.Info("GetMachine123 %s") Id := c.ParamsInt64(":Id") return getMaintenanceUserProfile(Id) }
// POST /api/process func AddMachineToCurrentOrg(c *middleware.Context, cmd m.AddMachineCommand) Response { logger := log.New("main") logger.Info("Add ProcessForCurrentOrg", c.OrgId) cmd.OrgId = c.OrgId return addMachineHelper(cmd) }
func NewDashAlertExtractor(dash *m.Dashboard, orgId int64) *DashAlertExtractor { return &DashAlertExtractor{ Dash: dash, OrgId: orgId, log: log.New("alerting.extractor"), } }
func GetSubProcessByName(c *middleware.Context) Response { logger := log.New("main") logger.Info("Get Sub Process1 %s") processName := c.Params(":processName") logger.Info("Get Sub Process 2 %s", processName) return getSubProcessProfile(processName) }
func GetSubProcessById(c *middleware.Context) Response { logger := log.New("main") logger.Info("GetProcess123 %s") subprocessId := c.ParamsInt64(":subProcessId") logger.Info("GetProcess123 %s", subprocessId) return getSubProcessUserProfile(subprocessId) }
// DELETE /api/orgs/:orgId/users/:userId func RemoveOrgProcess(c *middleware.Context) Response { logger := log.New("main") logger.Info("GetProcess", c.ParamsInt64(":process_id")) processId := c.ParamsInt64(":process_id") orgId := c.ParamsInt64(":orgId") return removeOrgProcessHelper(orgId, processId) }
func NewRuleReader() *DefaultRuleReader { ruleReader := &DefaultRuleReader{ log: log.New("alerting.ruleReader"), } go ruleReader.initReader() return ruleReader }
func NewApiClient(httpClient *http.Client, datasource *models.DataSource) *apiClient { return &apiClient{ DataSource: datasource, log: log.New("tsdb.mqe"), httpClient: httpClient, responseParser: NewResponseParser(), } }
func NewS3Uploader(bucket, accessKey, secretKey string) *S3Uploader { return &S3Uploader{ bucket: bucket, accessKey: accessKey, secretKey: secretKey, log: log.New("s3uploader"), } }
func NewMigrator(engine *xorm.Engine) *Migrator { mg := &Migrator{} mg.x = engine mg.Logger = log.New("migrator") mg.migrations = make([]Migration, 0) mg.dialect = NewDialect(mg.x.DriverName()) return mg }
func NewTokenClient(datasource *models.DataSource) *TokenClient { httpClient, _ := datasource.GetHttpClient() return &TokenClient{ log: log.New("tsdb.mqe.tokenclient"), Datasource: datasource, HttpClient: httpClient, } }
func NewEvalContext(alertCtx context.Context, rule *Rule) *EvalContext { return &EvalContext{ Ctx: alertCtx, StartTime: time.Now(), Rule: rule, Logs: make([]*ResultLogEntry, 0), EvalMatches: make([]*EvalMatch, 0), log: log.New("alerting.evalContext"), } }
func updateOrgProcessHelper(cmd m.UpdateOrgProcessCommand) Response { logger := log.New("main") logger.Info("updatedProcess2 %s") if err := bus.Dispatch(&cmd); err != nil { return ApiError(500, "Failed update org Process", err) } return ApiSuccess("Organization Process updated") }
func NewGrafanaServer() models.GrafanaServer { rootCtx, shutdownFn := context.WithCancel(context.Background()) childRoutines, childCtx := errgroup.WithContext(rootCtx) return &GrafanaServerImpl{ context: childCtx, shutdownFn: shutdownFn, childRoutines: childRoutines, log: log.New("server"), } }
// NewVictoropsNotifier creates an instance of VictoropsNotifier that // handles posting notifications to Victorops REST API func NewVictoropsNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find victorops url property in settings"} } return &VictoropsNotifier{ NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings), URL: url, log: log.New("alerting.notifier.victorops"), }, nil }
func NewLINENotifier(model *m.AlertNotification) (alerting.Notifier, error) { token := model.Settings.Get("token").MustString() if token == "" { return nil, alerting.ValidationError{Reason: "Could not find token in settings"} } return &LineNotifier{ NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings), Token: token, log: log.New("alerting.notifier.line"), }, nil }
func NewSlackNotifier(model *m.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} } return &SlackNotifier{ NotifierBase: NewNotifierBase(model.Name, model.Type, model.Settings), Url: url, log: log.New("alerting.notifier.slack"), }, nil }
func NewEvalContext(rule *Rule) *EvalContext { return &EvalContext{ StartTime: time.Now(), Rule: rule, Logs: make([]*ResultLogEntry, 0), EvalMatches: make([]*EvalMatch, 0), DoneChan: make(chan bool, 1), CancelChan: make(chan bool, 1), log: log.New("alerting.evalContext"), RetryCount: 0, } }
func init() { glog = log.New("tsdb.influxdb") tsdb.RegisterExecutor("influxdb", NewInfluxDBExecutor) tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } HttpClient = &http.Client{ Timeout: time.Duration(15 * time.Second), Transport: tr, } }
func NewEngine() *Engine { e := &Engine{ ticker: NewTicker(time.Now(), time.Second*0, clock.New()), execQueue: make(chan *Job, 1000), scheduler: NewScheduler(), evalHandler: NewEvalHandler(), ruleReader: NewRuleReader(), log: log.New("alerting.engine"), resultHandler: NewResultHandler(), } return e }