在自己的应用里集成grafana

grafana 是一款非常优秀的可视化报表工具,有设计精良的可视化工具,今天来聊一聊如何将grafana集成到自己的应用中。

原理是:

  • grafana允许iframe访问,开启auth.proxy, java 后端鉴权后代理grafana
  • 前端通过iframe访问后端代理过的grafana

grafana配置

要集成,可以选用iframe集成方式,需要配置可以embedding

[security]
allow_embedding = true

另外,还需要考虑认证的问题,可以开启auth.proxy,通过http头传入认证信息:

[security]
allow_embedding = true

[auth.proxy]
# Defaults to false, but set to true to enable this feature
enabled = true
# HTTP Header name that will contain the username or email
header_name = Auth
# HTTP Header property, defaults to `username` but can also be `email`
header_property = username
# Set to `true` to enable auto sign up of users who do not exist in Grafana DB. Defaults to `true`.
auto_sign_up = true
# Define cache time to live in minutes
# If combined with Grafana LDAP integration it is also the sync interval
sync_ttl = 60
# Limit where auth proxy requests come from by configuring a list of IP addresses.
# This can be used to prevent users spoofing the X-WEBAUTH-USER header.
# Example `whitelist = 192.168.1.1, 192.168.1.0/24, 2001::23, 2001::0/120`
whitelist =
# Optionally define more headers to sync other user attributes
# Example `headers = Name:X-WEBAUTH-NAME Role:X-WEBAUTH-ROLE Email:X-WEBAUTH-EMAIL Groups:X-WEBAUTH-GROUPS`
headers =
# Check out docs on this for more details on the below setting
enable_login_token = false
default_theme = light


由于默认是black主题,集成到系统里效果不美观,可以设置默认主题为light。

为了方便外部认证proxy,可以设置下sub_path 和 root_url

[server]
root_url = http://SERVER_IP_OR_DOMAIN:3000/grafana
serve_from_sub_path=true

配置文件存储到/opt/grafana-storage/grafana.ini

DOCKER 启动

docker run -d -p 3000:3000 --name=grafana   -v /opt/grafana-storage:/var/lib/grafana -v /opt/grafana-storage/grafana.ini:/etc/grafana/grafana.ini   grafana/grafana-oss

java后端配置

引入httpproxy

        <dependency>
            <groupId>org.mitre.dsmiley.httpproxy</groupId>
            <artifactId>smiley-http-proxy-servlet</artifactId>
            <version>1.11</version>
        </dependency>

添加配置:

proxy:
  grafana:
    servlet_url: /grafana/*
    target_url: http://grafana_url/grafana

添加代理Servlet:

/**
 * 代理Grafana 用做管理面板
 */
public class GrafanaProxyServlet extends ProxyServlet {

    @Override
    protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
                                     HttpRequest proxyRequest) throws IOException {
        String currentUser = SecurityUtils.getCurrentUserLogin().orElse(null);
        if(currentUser == null){
            return null;
        }
		// 设置用户
        proxyRequest.setHeader("Auth", currentUser);
        return super.doExecute(servletRequest, servletResponse, proxyRequest);
    }
}

注册servlet:

@Configuration
public class ProxyServletConfiguration {
    /**
     * 读取配置文件中路由设置
     */
    @Value("${proxy.grafana.servlet_url}")
    private String servlet_url;

    /**
     * 读取配置中代理目标地址
     */
    @Value("${proxy.grafana.target_url}")
    private String target_url;

    @Bean
    public ServletRegistrationBean proxyServletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new GrafanaProxyServlet(), servlet_url);
        //设置网址以及参数
        Map<String, String> params = ImmutableMap.of("targetUri", target_url, "log", "true");
        registrationBean.setInitParameters(params);
        return registrationBean;
    }
}

前端配置

新增一个vue页面,iframe地址填写后端代理过的grafana面板。

<template>
  <div class="grafana">
    <iframe
      :src="url"
      width="100%"
      height="1000px"
      frameborder="0"></iframe>
  </div>
</template>

<script>
export default {
  data() {
    return {
      url: '/grafana/d/FN0S0R47z/qian-duan-ri-zhi-mai-dian?orgId=1&kiosk&from=now-6h&to=now'
    }
  }
}
</script>

debug的时候,可以配置webpack的proxy:

      '/grafana': {
        target: 'http://172.31.161.36:13000',
        changeOrigin: true,
        headers: {
          'Auth': 'viewer'
        },
        pathRewrite: {
        }
      },

headers 添加Auth认证头。

集成效果:

集成效果

posted @ 2021-09-06 20:42  JadePeng  阅读(6252)  评论(7编辑  收藏  举报