-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
181 lines (149 loc) · 4.62 KB
/
main.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package main
import (
"encoding/json"
"flag"
"os"
"path/filepath"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/yaml.v2"
"github.com/cloudworkz/grafana-permission-sync/pkg/watcher"
"github.com/gin-gonic/gin"
)
var (
config *Config // current
newConfig *Config // new config to use next
log *zap.SugaredLogger
configPath string
dryRunNoPlanNoExec = len(os.Getenv("GRAFANA_PERMISSION_SYNC_NO_PLAN_NO_EXEC")) > 0
dryRunNoExec = len(os.Getenv("GRAFANA_PERMISSION_SYNC_NO_EXEC")) > 0
)
func main() {
// 1. Setup, load config, ...
logRaw, _ := zap.NewProduction()
log = logRaw.Sugar()
flag.StringVar(&configPath, "configPath", "./config.yaml", "alternative path to the config file")
flag.Parse()
// Load config
config = tryLoadConfig(configPath)
if config == nil {
log.Fatal("can't start, error loading config. initial config must be valid (hot reloaded config may be invalid, in which case the old/previous config will be kept)")
}
// Configure hot-reload
setupConfigHotReload(configPath)
// 2. Start sync
setupSync()
go startSync()
// 3. Start HTTP server
startWebServer()
}
func startWebServer() {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
rawLog := log.Desugar()
r.Use(gin.LoggerWithConfig(gin.LoggerConfig{
Formatter: func(param gin.LogFormatterParams) string {
// don't log liveness checks
if strings.HasPrefix(param.Path, "/admin/") {
return ""
}
fields := []zapcore.Field{
zap.String("clientIP", param.ClientIP),
zap.String("method", param.Method),
zap.String("path", param.Path),
zap.String("protocol", param.Request.Proto),
zap.Int("statusCode", param.StatusCode),
zap.Duration("latency", param.Latency),
zap.String("userAgent", param.Request.UserAgent()),
}
if param.ErrorMessage != "" {
fields = append(fields, zap.String("error", param.ErrorMessage))
}
rawLog.Info("handling http request", fields...)
return "" // prevent unstructured logging
},
}))
r.Use(gin.Recovery())
r.GET("/admin/ready", func(c *gin.Context) {
if createdPlans > 0 {
renderYAML(c, 200, gin.H{"status": "ready"})
} else {
renderYAML(c, 503, gin.H{"status": "starting"})
}
})
r.GET("/admin/alive", func(c *gin.Context) {
renderYAML(c, 200, gin.H{"status": "ready"})
})
r.GET("/admin/groups/:email", func(c *gin.Context) {
email := c.Param("email")
recurse := c.Query("recurse") == "true"
members, err := groupTree.ListGroupMembersForDisplay(email, recurse)
if err != nil {
renderJSON(c, 500, gin.H{"error": err.Error()})
return
}
renderJSON(c, 200, members)
})
r.GET("/admin/users/:email", func(c *gin.Context) {
email := c.Param("email")
groups, err := groupTree.ListUserGroupsForDisplay(email)
if err != nil {
renderJSON(c, 500, gin.H{"error": err.Error()})
return
}
renderJSON(c, 200, groups)
// todo:
// 1. resulting in permissions: x, y, z, ...
// 2. and the user would not be in organizations: a, b, c, ...
})
err := r.Run(":3000")
if err != nil {
log.Fatalw("error in router.Run", "error", err)
}
}
func renderYAML(c *gin.Context, code int, obj interface{}) {
bytes, err := yaml.Marshal(obj)
if err != nil {
c.String(500, "error: "+err.Error())
}
c.Data(code, "text/plain; charset=utf-8", bytes)
}
func renderJSON(c *gin.Context, code int, obj interface{}) {
bytes, err := json.MarshalIndent(obj, "", " ")
if err != nil {
c.String(500, "error: "+err.Error())
}
c.Data(code, "text/plain; charset=utf-8", bytes)
}
func setupConfigHotReload(configPath string) {
configPathAbs, err := filepath.Abs(configPath)
if err != nil {
log.Fatal("cannot build absolute path", "path", configPath, "error", err)
}
watcher, err := watcher.WatchPath(configPath)
if err != nil {
log.Errorw("can't start config file watcher. config hot-reloading will be disabled!", "error", err)
}
watcher.OnError = func(err error) {
log.Errorw("error in config watcher", "error", err)
}
watcher.OnChange = func(filePath string) {
filePathAbs, err := filepath.Abs(filePath)
if err != nil {
log.Fatal("cannot build absolute path", "path", filePath, "error", err)
}
if filePathAbs != configPathAbs {
log.Warnw("config file watcher notified us about a file we don't want to know about", "fileWeWantToWatch", configPath, "fileReportedByWatcher", filePath)
return
}
// Try to reload the config, and if it is valid, set it
c := tryLoadConfig(configPath)
if c == nil {
log.Error("Config file changed, but loading failed. Will continue with already loaded config and ignore new config.")
return
}
newConfig = c
log.Info("new config loaded successfully, swapping on next idle phase")
}
}