-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glrdomon.go
238 lines (185 loc) · 4.3 KB
/
glrdomon.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
package main
import (
"context"
"encoding/json"
"flag"
"io/ioutil"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/digitalocean/godo"
"github.com/dustin/go-humanize"
"golang.org/x/oauth2"
)
type config struct {
LogDest string `json:"log-dest"`
APIKey string `json:"api-key"`
Threshold int `json:"threshold"`
DeleteStale bool `json:"delete-stale"`
}
type tokenSource struct {
AccessToken string
}
var (
configPath string
logger *log.Logger
apiKey string
threshold int
deleteStale bool
wg sync.WaitGroup
client *godo.Client
)
func initConfig() {
flag.StringVar(&configPath, "config", "./config.json", "Path to configuration file")
flag.Parse()
if !validatePath(&configPath) {
usage()
}
configFile, err := ioutil.ReadFile(configPath)
if err != nil {
usage()
}
cfg := config{}
if err = json.Unmarshal(configFile, &cfg); err != nil {
usage()
}
apiKey = cfg.APIKey
threshold = cfg.Threshold
deleteStale = cfg.DeleteStale
setUpLogger(cfg.LogDest)
logger.Printf("Starting GitLab Runner monitoring with config %s", configPath)
if deleteStale {
logger.Println("Stale droplets WILL BE DELETED automatically")
} else {
logger.Println("Stale droplets will be logged, but not deleted")
}
}
func main() {
initConfig()
authenticate()
checkAPI()
wg.Wait()
logger.Println("Execution complete!")
}
func authenticate() {
tokenSource := &tokenSource{
AccessToken: apiKey,
}
oauthClient := oauth2.NewClient(context.Background(), tokenSource)
client = godo.NewClient(oauthClient)
}
// oAuth token
func (t *tokenSource) Token() (*oauth2.Token, error) {
token := &oauth2.Token{
AccessToken: t.AccessToken,
}
return token, nil
}
func checkAPI() {
ctx := context.TODO()
droplets, err := listDroplets(ctx, client)
if err != nil {
logger.Println("Warning! Failed to retrieve droplet list.")
logger.Print(err)
return
}
for _, droplet := range droplets {
wg.Add(1)
go checkDroplet(droplet)
}
}
func listDroplets(ctx context.Context, client *godo.Client) ([]godo.Droplet, error) {
list := []godo.Droplet{}
opt := &godo.ListOptions{}
for {
droplets, resp, err := client.Droplets.List(ctx, opt)
if err != nil {
return nil, err
}
for _, d := range droplets {
list = append(list, d)
}
if resp.Links == nil || resp.Links.IsLastPage() {
break
}
page, err := resp.Links.CurrentPage()
if err != nil {
return nil, err
}
opt.Page = page + 1
}
return list, nil
}
func checkDroplet(droplet godo.Droplet) {
defer wg.Done()
if !checkDropletAge(droplet) {
return
}
deleted := deleteDroplet(droplet)
if deleteStale {
if deleted {
logger.Printf("Removed droplet %s (%d)", droplet.Name, droplet.ID)
} else {
logger.Printf("Failed to delete droplet %s (%d)", droplet.Name, droplet.ID)
}
}
}
func checkDropletAge(droplet godo.Droplet) bool {
thr := time.Now().Add(time.Duration(-threshold) * time.Second)
created, err := time.Parse(time.RFC3339, droplet.Created)
if err != nil {
logger.Printf("Could not parse created-timestamp for droplet %s (%d)", droplet.Name, droplet.ID)
return false
}
stale := thr.After(created)
if stale {
logger.Printf("Stale droplet => ID: %d; name: \"%s\"; created: %s, %s (%d)", droplet.ID, droplet.Name, humanize.Time(created), droplet.Created, created.Unix())
}
return stale
}
func deleteDroplet(droplet godo.Droplet) bool {
if !deleteStale {
return false
}
logger.Printf("Deleting droplet %s (%d)", droplet.Name, droplet.ID)
ctx := context.TODO()
_, err := client.Droplets.Delete(ctx, droplet.ID)
return err == nil
}
func setUpLogger(logDest string) {
logOpts := log.Ldate | log.Ltime | log.LUTC | log.Lshortfile
if logDest == "os.Stdout" {
logger = log.New(os.Stdout, "DEBUG: ", logOpts)
} else {
path, err := filepath.Abs(logDest)
if err != nil {
logger.Fatal(err)
}
logFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}
logger = log.New(logFile, "", logOpts)
}
}
func validatePath(path *string) bool {
if len(*path) <= 1 {
return false
}
var err error
*path, err = filepath.Abs(*path)
if err != nil {
logger.Printf("Error: %s", err.Error())
return false
}
if _, err = os.Stat(*path); os.IsNotExist(err) {
return false
}
return true
}
func usage() {
flag.Usage()
os.Exit(3)
}