...
1 package metrics
2
3 import (
4 "fmt"
5 "sync"
6
7 "github.com/gin-gonic/gin"
8 "github.com/prometheus/client_golang/prometheus"
9 "github.com/prometheus/client_golang/prometheus/promauto"
10 "github.com/prometheus/client_golang/prometheus/promhttp"
11 )
12
13 type Key struct {
14 Group string
15 Version string
16 Kind string
17 }
18
19 func init() {
20 gin.SetMode(gin.ReleaseMode)
21 gin.DisableConsoleColor()
22 }
23
24 var Mutex sync.Mutex
25 var (
26
27
28
29 CtlfishResourceCreations = promauto.NewCounterVec(
30 prometheus.CounterOpts{
31 Namespace: "ctlfish",
32 Name: "resource_creations",
33 Help: "Resources Created by ctlfish",
34 }, []string{"Group", "Version", "Kind"})
35
36 CtlfishResourceUpdates = promauto.NewCounterVec(
37 prometheus.CounterOpts{
38 Namespace: "ctlfish",
39 Name: "resource_updates",
40 Help: "Resources Updated by ctlfish",
41 }, []string{"Group", "Version", "Kind"})
42
43 CtlfishResourceDeletions = promauto.NewCounterVec(
44 prometheus.CounterOpts{
45 Namespace: "ctlfish",
46 Name: "resource_deletions",
47 Help: "Resources Deleted by ctlfish",
48 }, []string{"Group", "Version", "Kind"})
49 )
50
51 type ServerConfig struct {
52 Port int
53 }
54
55 type LogMessageObject struct {
56 Level string `json:"level"`
57 Timestamp int64 `json:"ts"`
58 Msg string `json:"msg"`
59
60
61 RequestBody []byte
62 UserAgent string
63 RemoteAddr string
64 Method string
65 URL string
66
67
68 Status int
69 Latency string
70 }
71
72 type Server struct {
73 Router *gin.Engine
74
75 Config ServerConfig
76 }
77
78 var MetricsEndpoints = []string{"/metrics", "/ctlfish/metrics"}
79
80
81 func NewServer(cfg ServerConfig) (*Server, error) {
82 if cfg.Port <= 0 || cfg.Port > 65535 {
83 return nil, fmt.Errorf("Invalid port number %q", cfg.Port)
84 }
85
86 s := &Server{
87 Config: cfg,
88 }
89
90
91 s.Router = gin.New()
92
93
94 metricsHandlerFunc := gin.WrapH(promhttp.Handler())
95 for _, mep := range MetricsEndpoints {
96 s.Router.GET(mep, metricsHandlerFunc)
97 }
98
99 return s, nil
100 }
101
102
103 func (s *Server) Run() {
104 addr := fmt.Sprintf(":%d", s.Config.Port)
105 err := s.Router.Run(addr)
106 if err != nil {
107 fmt.Print("Error when Running the router")
108 }
109 }
110
View as plain text