func checkLogin(m *MainController) bool { // Skip the login check in debug mode. if g.Config().Debug { return true } sig := m.Ctx.GetCookie("sig") isLoggedIn := CheckLoginStatusByCookie(sig) if !isLoggedIn { RedirectUrl := g.Config().RedirectUrl m.Redirect(RedirectUrl, 302) return false } return true }
func LinkToSMS(content string) (string, error) { links := g.Config().Api.Links uri := fmt.Sprintf("%s/store", links) req := httplib.Post(uri).SetTimeout(3*time.Second, 10*time.Second) req.Body([]byte(content)) return req.String() }
func ParseUserSms(event *model.Event, action *api.Action) { userMap := api.GetUsers(action.Uic) content := GenerateSmsContent(event) metric := event.Metric() status := event.Status priority := event.Priority() queue := g.Config().Redis.UserSmsQueue rc := g.RedisConnPool.Get() defer rc.Close() for _, user := range userMap { dto := SmsDto{ Priority: priority, Metric: metric, Content: content, Phone: user.Phone, Status: status, } bs, err := json.Marshal(dto) if err != nil { log.Println("json marshal SmsDto fail:", err) continue } _, err = rc.Do("LPUSH", queue, string(bs)) if err != nil { log.Println("LPUSH redis", queue, "fail:", err, "dto:", string(bs)) } } }
func (this *MainController) Index() { if checkLogin(this) == false { return } defer func() { this.Data["Now"] = time.Now().Unix() this.TplName = "index.html" this.Data["FalconPortal"] = g.Config().Shortcut.FalconPortal this.Data["FalconDashboard"] = g.Config().Shortcut.FalconDashboard this.Data["GrafanaDashboard"] = g.Config().Shortcut.GrafanaDashboard this.Data["FalconAlarm"] = g.Config().Shortcut.FalconAlarm this.Data["FalconUIC"] = g.Config().Shortcut.FalconUIC }() this.Data["Events"] = g.Events.CloneToOrderedEvents() }
func popAllServerchanDto() []*ServerchanDto { ret := []*ServerchanDto{} queue := g.Config().Redis.UserServerchanQueue rc := g.RedisConnPool.Get() defer rc.Close() for { reply, err := redis.String(rc.Do("RPOP", queue)) if err != nil { if err != redis.ErrNil { log.Println("get ServerchanDto fail", err) } break } if reply == "" || reply == "nil" { continue } var serverchanDto ServerchanDto err = json.Unmarshal([]byte(reply), &serverchanDto) if err != nil { log.Printf("json unmarshal ServerchanDto: %s fail: %v", reply, err) continue } ret = append(ret, &serverchanDto) } return ret }
func (this *MainController) ConfigReload() { remoteAddr := this.Ctx.Input.Context.Request.RemoteAddr if strings.HasPrefix(remoteAddr, "127.0.0.1") { g.ParseConfig(g.ConfigFile) this.Data["json"] = g.Config() this.ServeJSON() } else { this.Ctx.WriteString("no privilege") } }
func Start() { if !g.Config().Http.Enabled { return } addr := g.Config().Http.Listen if addr == "" { return } if g.Config().Debug { beego.BConfig.RunMode = "dev" } else { beego.BConfig.RunMode = "prod" } beego.Run(addr) log.Println("http listening", addr) }
func InitDatabase() { // set default database config := g.Config() orm.RegisterDataBase("default", "mysql", config.Uic.Addr, config.Uic.Idle, config.Uic.Max) orm.RegisterDataBase("falcon_portal", "mysql", config.FalconPortal.Addr, config.FalconPortal.Idle, config.FalconPortal.Max) // register model orm.RegisterModel(new(uic.User), new(uic.Session), new(event.Events), new(event.EventCases)) if config.Debug { orm.Debug = true } }
func InitDatabase() { // set default database config := g.Config() orm.RegisterDataBase("default", "mysql", config.Uic.Addr, config.Uic.Idle, config.Uic.Max) // register model orm.RegisterModel(new(User), new(Session)) if config.Debug == true { orm.Debug = true } }
func WriteServerchanModel(serverchan *model.Serverchan) { if serverchan == nil { return } bs, err := json.Marshal(serverchan) if err != nil { log.Println(err) return } LPUSH(g.Config().Queue.Serverchan, string(bs)) }
func WriteQQModel(qq *model.QQ) { if qq == nil { return } bs, err := json.Marshal(qq) if err != nil { log.Println(err) return } LPUSH(g.Config().Queue.QQ, string(bs)) }
func WriteSmsModel(sms *model.Sms) { if sms == nil { return } bs, err := json.Marshal(sms) if err != nil { log.Println(err) return } LPUSH(g.Config().Queue.Sms, string(bs)) }
func InitLogger() { config := g.Config() if logger == nil { logrus.SetFormatter(&logrus.JSONFormatter{}) logrus.SetOutput(os.Stderr) if config.Debug { logrus.SetLevel(logrus.DebugLevel) } else { logrus.SetLevel(logrus.WarnLevel) } logger = logrus.WithFields(logrus.Fields{}) } }
func WriteMailModel(mail *model.Mail) { if mail == nil { return } bs, err := json.Marshal(mail) if err != nil { log.Println(err) return } LPUSH(g.Config().Queue.Mail, string(bs)) }
func combineSms() { dtos := popAllSmsDto() count := len(dtos) if count == 0 { return } dtoMap := make(map[string][]*SmsDto) for i := 0; i < count; i++ { key := fmt.Sprintf("%d%s%s%s", dtos[i].Priority, dtos[i].Status, dtos[i].Phone, dtos[i].Metric) if _, ok := dtoMap[key]; ok { dtoMap[key] = append(dtoMap[key], dtos[i]) } else { dtoMap[key] = []*SmsDto{dtos[i]} } } for _, arr := range dtoMap { size := len(arr) if size == 1 { redi.WriteSms([]string{arr[0].Phone}, arr[0].Content) continue } // 把多个sms内容写入数据库,只给用户提供一个链接 contentArr := make([]string, size) for i := 0; i < size; i++ { contentArr[i] = arr[i].Content } content := strings.Join(contentArr, ",,") first := arr[0].Content t := strings.Split(first, "][") eg := "" if len(t) >= 3 { eg = t[2] } path, err := api.LinkToSMS(content) sms := "" if err != nil || path == "" { sms = fmt.Sprintf("[P%d][%s] %d %s. e.g. %s detail in email", arr[0].Priority, arr[0].Status, size, arr[0].Metric, eg) log.Println("get link fail", err) } else { links := g.Config().Api.Links sms = fmt.Sprintf("[P%d][%s] %d %s e.g. %s %s/%s ", arr[0].Priority, arr[0].Status, size, arr[0].Metric, eg, links, path) } redi.WriteSms([]string{arr[0].Phone}, sms) } }
func ReadLowEvent() { queues := g.Config().Redis.LowQueues if len(queues) == 0 { return } for { event, err := popEvent(queues) if err != nil { time.Sleep(time.Second) continue } consume(event, false) } }
func CurlUic(team string) []*User { if team == "" { return []*User{} } uri := fmt.Sprintf("%s/team/users", g.Config().Api.Uic) req := httplib.Get(uri).SetTimeout(2*time.Second, 10*time.Second) req.Param("name", team) req.Param("token", g.Config().UicToken) var usersWrap UsersWrap err := req.ToJson(&usersWrap) if err != nil { log.Printf("curl %s fail: %v", uri, err) return nil } if usersWrap.Msg != "" { log.Printf("curl %s return msg: %v", uri, usersWrap.Msg) return nil } return usersWrap.Users }
func (this *MainController) Index() { if false == g.Config().Debug { sig := this.Ctx.GetCookie("sig") isLoggedIn := CheckLoginStatusByCookie(sig) if !isLoggedIn { RedirectUrl := g.Config().RedirectUrl this.Redirect(RedirectUrl, 302) } } events := g.Events.Clone() defer func() { this.Data["Now"] = time.Now().Unix() this.TplNames = "index.html" this.Data["FalconPortal"] = g.Config().Shortcut.FalconPortal this.Data["FalconDashboard"] = g.Config().Shortcut.FalconDashboard this.Data["GrafanaDashboard"] = g.Config().Shortcut.GrafanaDashboard this.Data["FalconAlarm"] = g.Config().Shortcut.FalconAlarm this.Data["FalconUIC"] = g.Config().Shortcut.FalconUIC }() if len(events) == 0 { this.Data["Events"] = []*g.EventDto{} return } count := len(events) if count == 0 { this.Data["Events"] = []*g.EventDto{} return } // 按照持续时间排序 beforeOrder := make([]*g.EventDto, count) i := 0 for _, event := range events { beforeOrder[i] = event i++ } sort.Sort(g.OrderedEvents(beforeOrder)) this.Data["Events"] = beforeOrder }
func CurlAction(id int) *Action { if id <= 0 { return nil } uri := fmt.Sprintf("%s/api/action/%d", g.Config().Api.Portal, id) req := httplib.Get(uri).SetTimeout(5*time.Second, 30*time.Second) var actionWrap ActionWrap err := req.ToJson(&actionWrap) if err != nil { log.Printf("curl %s fail: %v", uri, err) return nil } if actionWrap.Msg != "" { log.Printf("curl %s return msg: %v", uri, actionWrap.Msg) return nil } return actionWrap.Data }
func popEvent(queues []string) (*model.Event, error) { count := len(queues) params := make([]interface{}, count+1) for i := 0; i < count; i++ { params[i] = queues[i] } // set timeout 0 params[count] = 0 rc := g.RedisConnPool.Get() defer rc.Close() reply, err := redis.Strings(rc.Do("BRPOP", params...)) if err != nil { log.Printf("get alarm event from redis fail: %v", err) return nil, err } var event model.Event err = json.Unmarshal([]byte(reply[1]), &event) if err != nil { log.Printf("parse alarm event fail: %v", err) return nil, err } if g.Config().Debug { log.Println("======>>>>") log.Println(event.String()) } // save in memory. display in dashboard g.Events.Put(&event) return &event, nil }