forked from Griesbacher/nagflux
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Connector.go
196 lines (179 loc) · 5.35 KB
/
Connector.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
package influx
import (
"encoding/json"
"github.com/griesbacher/nagflux/collector"
"github.com/griesbacher/nagflux/data"
"github.com/griesbacher/nagflux/helper"
"github.com/griesbacher/nagflux/logging"
"github.com/kdar/factorlog"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
)
//Connector makes the basic connection to an influxdb.
type Connector struct {
connectionHost string
connectionArgs string
dumpFile string
workers []*Worker
maxWorkers int
jobs chan collector.Printable
quit chan bool
log *factorlog.FactorLog
version string
isAlive bool
databaseExists bool
databaseName string
httpClient http.Client
}
var regexDatabaseName = regexp.MustCompile(`.*db=(.*)`)
//ConnectorFactory Constructor which will create some workers if the connection is established.
func ConnectorFactory(jobs chan collector.Printable, connectionHost, connectionArgs, dumpFile, version string, workerAmount, maxWorkers int, createDatabaseIfNotExists bool) *Connector {
var databaseName string
for _, argument := range strings.Split(connectionArgs, "&") {
hits := regexDatabaseName.FindStringSubmatch(argument)
if len(hits) > 1 {
databaseName = hits[1]
}
}
timeout := time.Duration(5 * time.Second)
client := http.Client{Timeout: timeout}
s := &Connector{
connectionHost, connectionArgs, dumpFile, make([]*Worker, workerAmount), maxWorkers,
jobs, make(chan bool), logging.GetLogger(), version, false, false, databaseName, client,
}
gen := WorkerGenerator(jobs, connectionHost+"/write?"+connectionArgs, dumpFile, version, s, data.InfluxDB)
s.TestIfIsAlive()
if !s.isAlive {
s.log.Info("Waiting for InfluxDB server")
}
for i := 0; i < 12 && !s.isAlive; i++ {
s.TestIfIsAlive()
time.Sleep(5)
s.log.Info(".")
}
if !s.isAlive {
s.log.Panic("Influxdb not running")
}
s.TestDatabaseExists()
for i := 0; i < 5 && !s.databaseExists; i++ {
time.Sleep(time.Duration(2) * time.Second)
if createDatabaseIfNotExists {
s.CreateDatabase()
}
s.TestDatabaseExists()
}
if !s.databaseExists {
s.log.Panic("Database does not exists and was not able to created")
}
for w := 0; w < workerAmount; w++ {
s.workers[w] = gen(w)
}
go s.run()
return s
}
//AddWorker creates a new worker
func (connector *Connector) AddWorker() {
oldLength := connector.AmountWorkers()
if oldLength < connector.maxWorkers {
gen := WorkerGenerator(
connector.jobs, connector.connectionHost+"/write?"+connector.connectionArgs,
connector.dumpFile, connector.version, connector, data.InfluxDB,
)
connector.workers = append(connector.workers, gen(oldLength+2))
connector.log.Infof("Starting Worker: %d -> %d", oldLength, connector.AmountWorkers())
}
}
//RemoveWorker stops a worker
func (connector *Connector) RemoveWorker() {
oldLength := connector.AmountWorkers()
if oldLength > 1 {
lastWorkerIndex := oldLength - 1
connector.workers[lastWorkerIndex].Stop()
connector.workers = connector.workers[:lastWorkerIndex]
connector.log.Infof("Stopping Worker: %d -> %d", oldLength, connector.AmountWorkers())
}
}
//AmountWorkers current amount of workers.
func (connector Connector) AmountWorkers() int {
return len(connector.workers)
}
//IsAlive is the database system alive.
func (connector Connector) IsAlive() bool {
return connector.isAlive
}
//DatabaseExists does the database exist.
func (connector Connector) DatabaseExists() bool {
return connector.databaseExists
}
//Stop the connector and its workers.
func (connector *Connector) Stop() {
connector.quit <- true
<-connector.quit
connector.log.Debug("InfluxConnectorFactory stopped")
}
//Waits just for the end.
func (connector *Connector) run() {
for {
select {
case <-connector.quit:
for _, worker := range connector.workers {
go worker.Stop()
}
for len(connector.workers) > 0 {
for connector.workers[0].IsRunning == true {
time.Sleep(time.Duration(100) * time.Millisecond)
}
if len(connector.workers) > 1 {
connector.workers = connector.workers[1:]
} else {
connector.workers = connector.workers[:0]
}
}
connector.quit <- true
return
}
}
}
//TestIfIsAlive test active if the database system is alive.
func (connector *Connector) TestIfIsAlive() bool {
result := helper.RequestedReturnCodeIsOK(connector.httpClient, connector.connectionHost+"/ping", "GET")
connector.isAlive = result
return result
}
//TestDatabaseExists test active if the database exists.
func (connector *Connector) TestDatabaseExists() bool {
resp, err := http.Get(connector.connectionHost + "/query?q=show%20databases")
if err != nil {
return false
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var jsonResult ShowSeriesResult
json.Unmarshal(body, &jsonResult)
for _, tablename := range jsonResult.Results[0].Series[0].Values {
if connector.databaseName == tablename[0] {
connector.databaseExists = true
return true
}
}
}
connector.databaseExists = false
return false
}
//CreateDatabase creates the database.
func (connector *Connector) CreateDatabase() bool {
resp, err := http.Get(connector.connectionHost + "/query?q=create%20database%20" + connector.databaseName)
if err != nil {
return false
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if string(body) == `results":[{}]}` {
return true
}
return false
}