-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
222 lines (180 loc) · 5.73 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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
var addr = flag.String("listen-address", "0.0.0.0:9601", "The address to listen on for HTTP requests.")
var interval = flag.Int("interval", 3600, "Interval (in seconds) for request balance.")
var retryInterval = flag.Int("retry-interval", 10, "Interval (in seconds) for load balance when errors.")
var retryLimit = flag.Int("retry-limit", 10, "Count of tries when error.")
var (
credentials = CredentialsConfig{}
balanceGauge *prometheus.GaugeVec
hasError = false
retryCount = 0
)
type BalanceResponse struct {
Balance string `json:"balance"`
ErrorCode int `json:"error_code"`
Error string `json:"error"`
}
type CredentialsConfig struct {
Login string
Password string
}
func init() {
balanceGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Subsystem: "balance",
Name: "smsc",
Help: "Balance in smsc account",
},
[]string{"service"},
)
prometheus.MustRegister(balanceGauge)
flag.Parse()
}
func main() {
log.Println("Starting Smsc balance exporter", version.Info())
log.Println("Build context", version.BuildContext())
if err := readConfig(); err != nil {
log.Fatalln("Configuration error:", err.Error())
}
if err := loadBalance(); err != nil {
log.Fatalln(err.Error())
}
go startBalanceUpdater()
srv := &http.Server{
Addr: *addr,
WriteTimeout: time.Second * 2,
ReadTimeout: time.Second * 2,
IdleTimeout: time.Second * 60,
Handler: nil,
}
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html")
})
go func() {
log.Fatal(srv.ListenAndServe())
}()
log.Printf("Smsc balance exporter has been started at address %s\n", *addr)
log.Printf("Exporter will update balance every %d seconds\n", *interval)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
<-c
log.Println("Smsc balance exporter shutdown")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
err := srv.Shutdown(ctx)
if err != nil {
log.Fatal(err)
}
os.Exit(0)
}
func readConfig() error {
if login, ok := os.LookupEnv("SMSC_LOGIN"); ok {
credentials.Login = login
} else {
return errors.New("environment \"SMSC_LOGIN\" is not set")
}
if password, ok := os.LookupEnv("SMSC_PASSWORD"); ok {
credentials.Password = password
} else {
return errors.New("environment \"SMSC_PASSWORD\" is not set")
}
return nil
}
func startBalanceUpdater() {
for {
if hasError {
log.Printf("Request will retry after %d seconds\n", *retryInterval)
time.Sleep(time.Second * time.Duration(*retryInterval))
} else {
time.Sleep(time.Second * time.Duration(*interval))
}
if err := loadBalance(); err != nil {
log.Println(err.Error())
hasError = true
retryCount++
if retryCount >= *retryLimit {
log.Printf("Retry limit %d has been exceeded\n", *retryLimit)
hasError = false
retryCount = 0
}
} else {
hasError = false
retryCount = 0
}
}
}
func hideCredentials(format string, args ...interface{}) string {
var message = fmt.Sprintf(format, args...)
message = strings.Replace(message, credentials.Login, "<smsc-login>", -1)
message = strings.Replace(message, credentials.Password, "<smsc-password>", -1)
return message
}
func loadBalance() error {
body, err := loadBody()
if err != nil {
return err
}
balanceResponse := BalanceResponse{}
if err := json.Unmarshal(body, &balanceResponse); err != nil {
return errors.New(hideCredentials("Response parse error: %s", err.Error()))
}
if balanceResponse.ErrorCode > 0 {
return errors.New(hideCredentials("Response error: %s", balanceResponse.Error))
}
if b, err := strconv.ParseFloat(balanceResponse.Balance, 2); err != nil {
return errors.New(hideCredentials("Cannot parse balance: %s", err.Error()))
} else {
balanceGauge.With(prometheus.Labels{"service": credentials.Login}).Set(b)
}
return nil
}
func loadBody() ([]byte, error) {
client := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, "https://smsc.ru/sys/balance.php", nil)
q := req.URL.Query()
q.Add("login", credentials.Login)
q.Add("psw", credentials.Password)
q.Add("fmt", "3")
req.URL.RawQuery = q.Encode()
if err != nil {
return []byte{}, errors.New(hideCredentials("Cannot create request: %s", err.Error()))
}
res, err := client.Do(req)
if err != nil {
return []byte{}, errors.New(hideCredentials("Request error: %s", err.Error()))
}
defer func() {
err := res.Body.Close()
if err != nil {
log.Println(hideCredentials("Cannot close response body: %s", err.Error()))
}
}()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return []byte{}, errors.New(hideCredentials("Error read response body: %s", err.Error()))
}
return body, nil
}