zoukankan      html  css  js  c++  java
  • prometheus.(7).基于exporter模块源代码示例

    基于exporter模块源代码示例

    作者声明:本博客内容是作者在学习以及搭建过程中积累的内容,内容采自网络中各位老师的优秀博客以及视频,并根据作者本人的理解加以修改(由于工作以及学习中东拼西凑,如何造成无法提供原链接,在此抱歉!!!)

    作者再次声明:作者只是一个很抠脚的IT工作者,希望可以跟那些提供原创的老师们学习

    原文:大米运维

    一. 编写⼀个exporter的流程

    官网有介绍 编写exporter的详细内容我们这里给大家做⼀个简单的归纳首先 不同于pushgateway, exporter是⼀个独立运行的采集程序

    其中的功能需要有这三个部分

    1)自身是HTTP 服务器,可以响应 从外发过来的 HTTP GET 请求

    2)自身需要运行在后台,并可以定期触发 抓取本地的监控数据

    3)返回给prometheus_server 的内容是需要符合prometheus规定的metrics类型(Key-Value)

    1. key-value -> prometheus(TS) 需要接受 values( float int ) 不可以 return string * 否则会是空值

    二.基于go开发exporter的源代码及讲解

    package main
    import (
      "fmt"
      _ "net/http/pprof"
        "sync"
    //  "github.com/hpcloud/tail"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/common/log"
    "github.com/prometheus/common/version"
    //  //"net"
      "net/http"
    //  "net/url"
    //   "errors"
      "flag"
      "os"
      "os/exec"
      "io/ioutil"
    //  "regexp"
    //  "strconv"
    //  "strings"
        "time"
    )
    const (
      namespace = "my_exporter"
      )
    type Exporter struct {
    cmd               string
    mutex             sync.RWMutex
    up,freeRam,TotalRam   prometheus.Gauge
    Debug                 bool
    upstreamResponseTimes  *prometheus.HistogramVec
    }
    func (e *Exporter) scrape() {
    log.Infoln("--------")
    e.up.Set(1)
        }
    func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
      e.upstreamResponseTimes.Describe(ch)
    }
    func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
    e.mutex.Lock() // To protect metrics from concurrent collects
      defer e.mutex.Unlock()
      e.scrape()
      e.upstreamResponseTimes.Collect(ch)
      e.up.Collect(ch)
    }
    func NewExporter(cmd string, timeout time.Duration) (*Exporter, 
    error) {
      return &Exporter{
        cmd: cmd,
        up: prometheus.NewGauge(prometheus.GaugeOpts{
          Namespace: namespace,
          Name:      "up",
          Help:      "Was the last scrape of nginx exporter successful.",
        }),
        upstreamResponseTimes: prometheus.NewHistogramVec(
          prometheus.HistogramOpts{
            Namespace: namespace,
            Name:      "http_upstream_request_times",
            Help:      "Response times from backends/upstreams",
          },
          []string{"method", "endpoint", "response_code", 
    "client_type"},
        ),
      }, nil
    }
    func run() {
      cmd := exec.Command("/bin/sh", "-c", `free -m `)
      stdout , err := cmd.StdoutPipe()
      if err != nil {
        panic(err.Error())
      }
      if err != nil {
        fmt.Println("Stdoutpipe error", err.Error())
      }
        stderr , err := cmd.StderrPipe()
      if err != nil {
        fmt.Println("Stderrpipe error", err.Error())
      }
      if err := cmd.Start(); err != nil {
        fmt.Println("error start", err )
      }
      bytesErr, err := ioutil.ReadAll(stderr)
        if err != nil {
            fmt.Println("ReadAll stderr: ", err.Error())
            return
        }
        if len(bytesErr) != 0 {
            fmt.Printf("stderr is not nil: %s", bytesErr)
            return
        }
        bytes, err := ioutil.ReadAll(stdout)
        if err != nil {
            fmt.Println("ReadAll stdout: ", err.Error())
            return
        }
        if err := cmd.Wait(); err != nil {
            fmt.Println("Wait: ", err.Error())
            return
        }
        fmt.Printf("stdout: %s", string(bytes))
    }
    func main() {
      var (
          listenAddress = flag.String("web.listen-address", ":9101", 
    "Address to listen on for web interface and telemetry.")
          metricsPath   = flag.String("web.telemetry-path", "/metrics", 
    "Path under which to expose metrics.")
          cmd           = flag.String("free", "", "command to run")
          nginxTimeout  = flag.Duration("nginx.timeout", 
    5*time.Second, "Timeout for trying to get stats from HA.")
        showVersion   = flag.Bool("version", false, "Print version 
    information.")
    //    debug         = flag.Bool("debug", false, "Print debug 
    information.")
      )
      flag.Parse()
      if *showVersion {
        fmt.Println(os.Stdout, version.Print("shannon_exporter"))
        os.Exit(0)
      }
      log.Infoln("Starting shannon_exporter", version.Info())
      log.Infoln("Build context", version.BuildContext())
      run()
      exporter, _ := NewExporter(*cmd, *nginxTimeout)
      prometheus.MustRegister(exporter)
      prometheus.MustRegister(version.NewCollector("nginx_exporte
    r"))
      http.Handle(*metricsPath, prometheus.Handler())
      http.HandleFunc("/", func(w http.ResponseWriter, r 
    *http.Request) {
        w.Write([]byte(`<html>
          <head><title>Haproxy Exporter</title></head>
          <body>
          <h1>Haproxy Exporter</h1>
          <p><a href='` + *metricsPath + `'>Metrics</a></p>
          </body>
          </html>`))
      })
      log.Fatal(http.ListenAndServe(*listenAddress, nil))
      }
    

    //前面的 scrape describeCollect 是struct类型的成员函数,这⼏个函数并没有直接在这个go里被调用,而是MustRegister注册进去了它们。

    // http.Handle里的prometheus.Handler 将上⼀部2个Mustregister的注册 关联进⼊http.handle. 也就进⼀步注册进入了httpserver-listerner

    // http.lister是组赛程序,只有启动后被curl的时候 才会执行。并且由于之前经过2步的注册,跟exporter的成员函数简历了关联(其实是指针关联) 所以,每次被curl的时候所有上面的成员函数都会被调用//例如上⾯的up.set(1) 就是只有被curl的时候才会被调用,成员函数是作为生成metrics的入口

    注: 本Go exporter 源代码 是半年前写的了 其中⼀些地方可能需要进⼀步修改才可以正常使用(本人go开发能力也比较菜 - _ -)

    三.个人建议

    通过上面的对⼀个exporter源代码的讲解,我们也看得出来编写⼀个 exporter 远比写⼀个pushgateway脚本要复杂的多

    个人呢建议:除非是工作中真的有需要(例如:社区的exporters都不能满足需求,且对于监控客户端的规范化比较严格) 且

    对自己的编程能力有自信,那么可以自行开发new exporter

    exporter-prometheus 5s GET => exporter Handler-> handler-lister 开发的过程中 要特别注意 各种文件句柄等等资源的 完整回

    收。因为⼀个非常被频繁调用的后台程序中 ⼀旦循环中出现资源泄漏那么后果是很严重的(之前其实就遇到过⼀次 资源没有正确回收 导致每⼀次promethue_server访问过来 都造成僵尸进程 最终服务器被拖垮的窘境 …囧 当然了 如果是 开发高手的话 相信我的担心也就多余啦~~)所以 如果企业中 运维开发的实力不够过硬,我还是尽量建议大家 使用现成的社区exporters, 配合自行开发pushgateway脚本 。

  • 相关阅读:
    BZOJ3209: 花神的数论题
    BZOJ3207: 花神的嘲讽计划Ⅰ
    BZOJ3155: Preprefix sum
    BZOJ2465: [中山市选2009]小球
    BZOJ2243: [SDOI2011]染色
    BZOJ1192: [HNOI2006]鬼谷子的钱袋
    hdu1542(线段树——矩形面积并)
    hdu4578(线段树)
    hdu4614(线段树+二分)
    hdu3974(线段树+dfs)
  • 原文地址:https://www.cnblogs.com/orange-lsc/p/12825585.html
Copyright © 2011-2022 走看看