-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
292 lines (249 loc) · 8.12 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
var retries int
var timeout time.Duration
var maxPackages = -1
var exportedMetrics = []Metric{}
var token string
var period time.Duration
var port = 9101
type Metric map[string]interface{}
// Define a struct for you collector that contains pointers
// to prometheus descriptors for each metric you wish to expose.
// Note you can also include fields of other types if they provide utility
// but we just won't be exposing them as metrics.
type socketCollector struct {
socketMetric *prometheus.Desc
downloadMetric *prometheus.Desc
}
// You must create a constructor for you collector that
// initializes every descriptor and returns a pointer to the collector
func newSocketCollector() *socketCollector {
return &socketCollector{
socketMetric: prometheus.NewDesc("socket_score",
"Shows socket.dev packages scores",
[]string{"package", "version", "score"}, nil,
),
downloadMetric: prometheus.NewDesc("npm_download_count",
"NPM package download count for a given day",
[]string{"package"}, nil,
),
}
}
// Each and every collector must implement the Describe function.
// It essentially writes all descriptors to the prometheus desc channel.
func (collector *socketCollector) Describe(ch chan<- *prometheus.Desc) {
//Update this section with the each metric you create for a given collector
ch <- collector.socketMetric
ch <- collector.downloadMetric
}
// Collect implements required collect function for all promehteus collectors
func (collector *socketCollector) Collect(ch chan<- prometheus.Metric) {
logrus.Debug("Received HTTP request")
//Implement logic here to determine proper metric value to return to prometheus
//for each descriptor or call other functions that do so.
logrus.Debug("Sending metrics to Prometheus channel")
for _, metric := range exportedMetrics {
if metric["_type"] == "socket_score" {
s, err := strconv.ParseFloat(fmt.Sprintf("%v", metric["value"]), 64)
if err != nil {
logrus.Error(fmt.Sprintf("Error converting metric value: %s", err))
continue
}
ch <- prometheus.MustNewConstMetric(
collector.socketMetric,
prometheus.GaugeValue,
s,
fmt.Sprintf("%v", metric["name"]),
fmt.Sprintf("%v", metric["version"]),
fmt.Sprintf("%v", metric["score"]),
)
} else if metric["_type"] == "npm_download" {
s, err := strconv.ParseFloat(fmt.Sprintf("%v", metric["downloads"]), 64)
if err != nil {
logrus.Error(fmt.Sprintf("Error converting metric value: %s", err))
continue
}
ch <- prometheus.MustNewConstMetric(
collector.downloadMetric,
prometheus.GaugeValue,
s,
fmt.Sprintf("%v", metric["package"]),
)
}
}
}
func (s *SocketResponse) ToMetrics(packageName string, packageVersion string) []Metric {
metrics := []Metric{
{"score": "supplychainrisk", "value": s.Supplychainrisk.Score},
{"score": "quality", "value": s.Quality.Score},
{"score": "maintenance", "value": s.Maintenance.Score},
{"score": "vulnerability", "value": s.Vulnerability.Score},
{"score": "license", "value": s.License.Score},
{"score": "miscellaneous", "value": s.Miscellaneous.Score},
}
for _, metric := range metrics {
metric["_type"] = "socket_score"
metric["name"] = packageName
metric["version"] = packageVersion
}
return metrics
}
func (npm *NpmDownloadCountResponse) ToMetrics(packageName string) []Metric {
return []Metric{
{"package": packageName, "downloads": npm.GetDownloads(), "date": npm.End, "_type": "npm_download"},
}
}
func fetchMetrics() ([]Metric, error) {
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = retries
retryClient.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
var result = []Metric{}
retryClient.RequestLogHook = func(_ retryablehttp.Logger, req *http.Request, attempt int) {
logrus.WithFields(logrus.Fields{
"host": req.URL.Host,
"path": req.URL.Path,
"attempt": attempt,
}).Info("Sending request")
}
client := retryClient.StandardClient() // *http.Client
client.Timeout = timeout
npmResponse, err := GetCeloNPMPackages(client)
if err != nil {
logrus.Errorf("Failed to get list of celo packages, %e", err)
return nil, err
}
celoPackages := npmResponse.Objects
var socketAPI = NewSocketAPI(token)
if maxPackages > 0 {
celoPackages = celoPackages[0:maxPackages]
}
for _, object := range celoPackages {
var currentPackage = object.Package
// get socket.dev metrics for package
socketResponse, err := socketAPI.FetchSocketScores(currentPackage, client)
if err != nil {
logrus.Errorf("Failed to get socket score for package %s, %e", currentPackage.Name, err)
continue
}
socketScoreMetrics := socketResponse.ToMetrics(currentPackage.Name, currentPackage.Version)
result = append(result, socketScoreMetrics...)
// get npm download metrics for package
downloadResponse, err := GetDownloadCountForCeloNpmPackage(currentPackage, client)
if err != nil {
logrus.Errorf("Failed to get download count for package %s, %e", currentPackage.Name, err)
continue
}
packageDownloadMetrics := downloadResponse.ToMetrics(currentPackage.Name)
result = append(result, packageDownloadMetrics...)
}
return result, nil
}
func periodicLogic() {
logrus.Info("Getting metrics for socket.dev in a loop")
for {
metrics, err := fetchMetrics()
if err != nil {
logrus.Errorf("Error upon fetching metrics %e", err)
time.Sleep(1 * time.Second)
continue
}
exportedMetrics = metrics
logrus.Infof("Sleeping %f hours", period.Hours())
time.Sleep(period)
}
}
func initializeConfig() {
lvl, ok := os.LookupEnv("LOG_LEVEL")
if !ok {
lvl = "info"
}
level, err := logrus.ParseLevel(lvl)
if err != nil {
level = logrus.DebugLevel
}
logrus.SetLevel(level)
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
token, ok = os.LookupEnv("API_TOKEN")
if !ok {
logrus.Error("Could not read env. var. API_TOKEN with Socket.dev API token")
os.Exit(1)
}
periodEnvVar, ok := os.LookupEnv("PERIOD")
if !ok {
logrus.Error("Could not read env. var. PERIOD. Setting it to 24 hours.")
period, err = time.ParseDuration("24h")
} else {
period, err = time.ParseDuration(fmt.Sprintf("%sh", periodEnvVar))
if err != nil {
logrus.Error(fmt.Sprintf("Could not parse PERIOD env. var. to time.Duration: %s", err))
os.Exit(1)
}
}
retriesEnvVar, ok := os.LookupEnv("RETRIES")
if !ok {
logrus.Error("Could not read env. var. RETRIES. Setting it to 5.")
retries = 5
} else {
retries, err = strconv.Atoi(retriesEnvVar)
if err != nil {
logrus.Error(fmt.Sprintf("Could not parse RETRIES env. var. to int: %s", err))
os.Exit(1)
}
}
timeoutEnvVar, ok := os.LookupEnv("TIMEOUT")
if !ok {
logrus.Error("Could not read env. var. TIMEOUT. Setting it to 15 seconds.")
timeout = 15 * time.Second
} else {
timeoutInt, err := strconv.Atoi(timeoutEnvVar)
if err != nil {
logrus.Error(fmt.Sprintf("Could not parse TIMEOUT env. var. to int: %s", err))
os.Exit(1)
}
timeout = time.Duration(timeoutInt) * time.Second
}
maxPackagesEnvVar, ok := os.LookupEnv("MAX_PACKAGES")
if !ok {
logrus.Error("Could not read env. var. MAX_PACKAGES. Deactivating")
maxPackages = -1
} else {
maxPackagesInt, err := strconv.Atoi(maxPackagesEnvVar)
if err != nil {
logrus.Error(fmt.Sprintf("Could not parse MAX_PACKAGES env. var. to int: %s", err))
maxPackages = -1
}
maxPackages = maxPackagesInt
}
}
func main() {
initializeConfig()
socketCollector := newSocketCollector()
prometheus.MustRegister(socketCollector)
http.Handle("/metrics", promhttp.Handler())
logrus.Info("Initializing, getting metrics for socket.dev")
metrics, err := fetchMetrics()
if err != nil {
logrus.Fatalf("Error upon initializing metrics %e", err)
}
exportedMetrics = append(exportedMetrics, metrics...)
logrus.Info("Start go routine to get metrics for socket.dev")
go periodicLogic()
logrus.Infof("Listening on port %d", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}