从github上可以直接下载grafana的开源代码。打开后如果有飘红,可以试一下go mod download。然后来看代码。
pkg包中为主要后端部分的代码。
其中,pkg/cmd/grafana-server/main.go为入口文件;pkg/services包中为具体的逻辑处理;pkg/api中为所有的接口处理;pkg/api/api.go中为接口和方法间的映射。
granfana 启动的时候,会通过 grafana 的 registry 机制自动注册 http server。HTTPServer实现了registry中定义的Service interface,所以启动granfana的时候,会调用 HTTPServer 的Init 方法。Init方法主要初始化HTTPServer struct定义的log以及cache组件。 HTTPServer 实现了registry中定义的BackgroundService方法,所以启动granfana的时候,会调用HTTPServer 的Run方法。Run方法会创建Macaron实例,注册路由,监听http端口,并且处理shutdown逻辑。至此,http server启动完毕。
pkg/middleware/middleware.go中为所有请求进行逻辑处理前的权限校验。可以看到,主要有这几种校验方式:
switch {
case initContextWithRenderAuth(ctx, renderService):
case initContextWithApiKey(ctx):
case initContextWithBasicAuth(ctx, orgId):
case initContextWithAuthProxy(remoteCache, ctx, orgId):
case initContextWithToken(ats, ctx, orgId):
case initContextWithAnonymousUser(ctx):
}
initContextWithToken为使用token的校验。这里我们希望使用公司平台的token也能通过校验。(二次开发:)因此创建一个类似方法,case initContextWithSkiffAuth(sas, ctx, orgId):
插入。initContextWithSkiffAuth
方法如下:
func initContextWithSkiffAuth(skiffAuthService models.AuthService, ctx *models.ReqContext, orgId int64) bool {
//检查配置开关是否开启,即使用这个方法进行校验是否有效,如未开启,直接返回false。
//创建pkg/services/auth/skiff_auth.go文件,调用的方法具体见下。
if !skiffAuthService.IsEnabled() {
return false
}
//获取到请求头中cookie中包含的token,公司定义这里key为“qz_t”的value值为token。
skiffToken := ctx.GetCookie("qz_t")
if ski