forked from Cepave/open-falcon-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uic.go
121 lines (100 loc) · 2.16 KB
/
uic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package api
import (
"fmt"
"github.com/Cepave/open-falcon-backend/modules/alarm/g"
log "github.com/sirupsen/logrus"
"github.com/toolkits/container/set"
"github.com/toolkits/net/httplib"
"strings"
"sync"
"time"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Phone string `json:"phone"`
IM string `json:"im"`
}
type UsersWrap struct {
Msg string `json:"msg"`
Users []*User `json:"users"`
}
type UsersCache struct {
sync.RWMutex
M map[string][]*User
}
var Users = &UsersCache{M: make(map[string][]*User)}
func (this *UsersCache) Get(team string) []*User {
this.RLock()
defer this.RUnlock()
val, exists := this.M[team]
if !exists {
return nil
}
return val
}
func (this *UsersCache) Set(team string, users []*User) {
this.Lock()
defer this.Unlock()
this.M[team] = users
}
func UsersOf(team string) []*User {
users := CurlUic(team)
if users != nil {
Users.Set(team, users)
} else {
users = Users.Get(team)
}
return users
}
func GetUsers(teams string) map[string]*User {
userMap := make(map[string]*User)
arr := strings.Split(teams, ",")
for _, team := range arr {
if team == "" {
continue
}
users := UsersOf(team)
if users == nil {
continue
}
for _, user := range users {
userMap[user.Name] = user
}
}
return userMap
}
// return phones, emails
func ParseTeams(teams string) ([]string, []string) {
if teams == "" {
return []string{}, []string{}
}
userMap := GetUsers(teams)
phoneSet := set.NewStringSet()
mailSet := set.NewStringSet()
for _, user := range userMap {
phoneSet.Add(user.Phone)
mailSet.Add(user.Email)
}
return phoneSet.ToSlice(), mailSet.ToSlice()
}
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
}