-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
215 lines (194 loc) · 6.37 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
package main
import (
"fmt"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
"math/rand"
"os"
"runtime"
"strings"
"sync"
"time"
)
const (
applicationName = "prometheus_export"
letterBytes = "abcdefghijklmnopqrstuvwxyz" // map for random string
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
timeRangeOverSize = 15 // minutes used for prolong data before and after Str/Stop
)
var (
logger log.Logger // logger
Version string
Revision string
Branch string
BuildUser string
BuildDate string
src = rand.NewSource(time.Now().UnixNano()) // randomize base string
timeStart time.Time
maxRandomSize = 10 // required size of random string
//metricsMeta *MetricsMetaList
)
func RandomString() string {
sb := strings.Builder{}
sb.Grow(maxRandomSize)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := maxRandomSize-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
sb.WriteByte(letterBytes[idx])
i--
}
cache >>= letterIdxBits
remain--
}
return sb.String()
}
func main() {
promlogConfig := &promlog.Config{}
flag.AddFlags(kingpin.CommandLine, promlogConfig)
version.Branch = Branch
version.Revision = Revision
version.BuildUser = BuildUser
version.BuildDate = BuildDate
version.Version = Version
kingpin.Version(version.Print(applicationName))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
logger = promlog.New(promlogConfig)
_ = level.Info(logger).Log("msg", "Starting prometheus data export ", "version", version.Info())
timeStart = time.Now().UTC()
err := config.LoadFile(*configFile)
if *showConfig {
_ = level.Info(logger).Log("msg", "show only configuration ane exit")
if err != nil {
fmt.Print(config.print())
} else {
if config.useRange() {
fmt.Printf("%s%s", config.print(), printTimeRanges(generateRangeTable(initRangeFromTo(configFrom, configTo))))
} else {
fmt.Printf("%s%s", config.print(), printTimeRanges(generateRangeTable(initRange())))
}
}
os.Exit(0)
}
if err != nil {
_ = level.Error(logger).Log("msg", "problem with configuration", "error", err)
fmt.Printf("Program did not start due to configuration error! \r\n\tError: %s", err)
os.Exit(1)
}
// start process data
_ = level.Info(logger).Log("msg", "start collect necessary data")
v1Api, err := prepareApi(config)
if err != nil {
_ = level.Info(logger).Log("msg", "program exit, because there is problem with connect Prometheus server")
os.Exit(2)
}
start := time.Now()
var dateRange v1.Range
if config.useRange() {
dateRange = initRangeFromTo(configFrom, configTo)
} else {
dateRange = initRange()
}
timeRangeSplit := generateRangeTable(dateRange)
_ = level.Info(logger).Log("msg", fmt.Sprintf("requried time split to %d time ranges", len(timeRangeSplit)))
// process for all data
services := OrganizedServices{}
for _, source := range config.Sources {
services = processOneSources(v1Api, source, services, dateRange)
}
// process labels
if len(config.Labels) > 0 {
services = processLabels(v1Api, config.Labels, services, dateRange)
}
startReadApi(v1Api, timeRangeSplit, services)
_ = level.Info(logger).Log("msg", fmt.Sprintf("program successful ends after %s", time.Since(start).String()))
}
func processOneSources(api v1.API, sources Sources, services OrganizedServices, timeRange v1.Range) OrganizedServices {
labels, err := collectSeriesList(api, sources, timeRange)
if err != nil {
return services
}
storage := NewStorage(config.Path, sources)
_ = storage.prepareDirectory()
organized := splitToSeriesNameAndInstance(labels, storage)
storage.saveOrganized(organized, timeRange)
return append(services, organized...)
}
func processLabels(api v1.API, lbl []Labels, services OrganizedServices, timeRange v1.Range) OrganizedServices {
labels, err := collectLabelsSeriesList(api, lbl, timeRange)
if err != nil {
return services
}
storage := NewNameStorage(config.Path, "labels")
_ = storage.prepareDirectory()
organized := splitToSeriesNameAndInstance(labels, storage)
storage.saveOrganized(organized, timeRange)
return append(services, organized...)
}
func startReadApi(api v1.API, ranges []v1.Range, organized OrganizedServices) {
channel := make(chan OrganizedSeries, len(organized))
// fill data
for _, series := range organized {
channel <- series
}
_ = level.Info(logger).Log("msg", "prepared GO coroutines channel data")
var wg sync.WaitGroup
cpu := runtime.NumCPU()
if cpu > 1 {
cpu--
}
start := time.Now()
for i := 0; i < cpu; i++ {
wg.Add(1)
go processOneInstance(&wg, channel, api, ranges, i)
}
_ = level.Info(logger).Log("msg", fmt.Sprintf("wait to finish all %d routines", cpu))
wg.Wait()
_ = level.Info(logger).Log("msg", fmt.Sprintf("all coroutines finish %s", time.Since(start).String()))
}
func processOneInstance(wg *sync.WaitGroup, channel chan OrganizedSeries, api v1.API, ranges []v1.Range, cpu int) {
defer wg.Done()
for {
select {
case series := <-channel:
_ = level.Debug(logger).Log("msg", fmt.Sprintf("process data for coroutine %d", cpu), "series", series.Name)
var saveAll []SaveAllData
for _, label := range series.Set {
var saveData []SaveData
loops := 0
loopsErr := 0
loopsEmpty := 0
for _, timeRange := range ranges {
loops++
data, err := readQueryRange(api, label, timeRange)
if err != nil {
loopsErr++
continue
}
d := convertApiData(data)
if len(d) > 0 {
saveData = append(saveData, d...)
} else {
loopsEmpty++
}
}
saveAll = append(saveAll, SaveAllData{Collection: label, Data: saveData})
}
series.Storage.saveAllData(saveAll, cleanFilePathName(series.Name)+".json")
break
case <-time.Tick(1 * time.Second):
_ = level.Debug(logger).Log("msg", fmt.Sprintf("funish coroutine %d", cpu))
return
}
}
}