forked from cpuguy83/dockerhub-webhook-listener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rancher.go
473 lines (436 loc) · 18.1 KB
/
rancher.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package listener
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
type Rancher struct {
rancherConfig
}
type rancherConfig struct {
Url string
UserKey string
SecretKey string
Service string
}
type rancherService struct {
Actions struct{} `json:"actions"`
CreateDefaults struct{} `json:"createDefaults"`
CreateTypes struct {
DNSService string `json:"dnsService"`
ExternalService string `json:"externalService"`
LoadBalancerService string `json:"loadBalancerService"`
Service string `json:"service"`
} `json:"createTypes"`
Data []struct {
AccountID string `json:"accountId"`
Actions struct {
Addservicelink string `json:"addservicelink"`
Deactivate string `json:"deactivate"`
Remove string `json:"remove"`
Removeservicelink string `json:"removeservicelink"`
Restart string `json:"restart"`
Setservicelinks string `json:"setservicelinks"`
Update string `json:"update"`
Upgrade string `json:"upgrade"`
FinishUpgrade string `json:"finishupgrade"`
} `json:"actions"`
AssignServiceIPAddress bool `json:"assignServiceIpAddress"`
CreateIndex int `json:"createIndex"`
Created string `json:"created"`
CreatedTS int `json:"createdTS"`
Description interface{} `json:"description"`
EnvironmentID string `json:"environmentId"`
ExternalID interface{} `json:"externalId"`
Fqdn interface{} `json:"fqdn"`
HealthState string `json:"healthState"`
ID string `json:"id"`
Kind string `json:"kind"`
LaunchConfig struct {
CapAdd []interface{} `json:"capAdd"`
CapDrop []interface{} `json:"capDrop"`
Count interface{} `json:"count"`
CPUSet interface{} `json:"cpuSet"`
CPUShares interface{} `json:"cpuShares"`
DataVolumes []interface{} `json:"dataVolumes"`
DataVolumesFrom []interface{} `json:"dataVolumesFrom"`
DataVolumesFromLaunchConfigs []interface{} `json:"dataVolumesFromLaunchConfigs"`
Description interface{} `json:"description"`
Devices []interface{} `json:"devices"`
DNS []interface{} `json:"dns"`
DNSSearch []interface{} `json:"dnsSearch"`
DomainName interface{} `json:"domainName"`
Environment struct {
CONFIGFILE string `json:"CONFIGFILE"`
} `json:"environment"`
Hostname interface{} `json:"hostname"`
ImageUUID string `json:"imageUuid"`
Kind string `json:"kind"`
Labels struct {
Io_rancher_container_pullImage string `json:"io.rancher.container.pull_image"`
Io_rancher_scheduler_affinity_containerLabelSoftNe string `json:"io.rancher.scheduler.affinity:container_label_soft_ne"`
} `json:"labels"`
LogConfig struct {
Config struct{} `json:"config"`
Driver string `json:"driver"`
} `json:"logConfig"`
Memory interface{} `json:"memory"`
MemoryMb interface{} `json:"memoryMb"`
MemorySwap interface{} `json:"memorySwap"`
NetworkLaunchConfig interface{} `json:"networkLaunchConfig"`
NetworkMode string `json:"networkMode"`
PidMode interface{} `json:"pidMode"`
Ports []interface{} `json:"ports"`
Privileged bool `json:"privileged"`
PublishAllPorts bool `json:"publishAllPorts"`
ReadOnly bool `json:"readOnly"`
RequestedHostID interface{} `json:"requestedHostId"`
RequestedIPAddress interface{} `json:"requestedIpAddress"`
StartOnCreate bool `json:"startOnCreate"`
StdinOpen bool `json:"stdinOpen"`
Tty bool `json:"tty"`
User interface{} `json:"user"`
Userdata interface{} `json:"userdata"`
Vcpu int `json:"vcpu"`
Version string `json:"version"`
VolumeDriver interface{} `json:"volumeDriver"`
WorkingDir interface{} `json:"workingDir"`
} `json:"launchConfig"`
Links struct {
Account string `json:"account"`
Consumedbyservices string `json:"consumedbyservices"`
Consumedservices string `json:"consumedservices"`
ContainerStats string `json:"containerStats"`
Environment string `json:"environment"`
Instances string `json:"instances"`
Self string `json:"self"`
ServiceExposeMaps string `json:"serviceExposeMaps"`
} `json:"links"`
Metadata interface{} `json:"metadata"`
Name string `json:"name"`
PublicEndpoints interface{} `json:"publicEndpoints"`
Removed interface{} `json:"removed"`
RetainIP interface{} `json:"retainIp"`
Scale int `json:"scale"`
SecondaryLaunchConfigs []interface{} `json:"secondaryLaunchConfigs"`
SelectorContainer interface{} `json:"selectorContainer"`
SelectorLink interface{} `json:"selectorLink"`
StartOnCreate bool `json:"startOnCreate"`
State string `json:"state"`
Transitioning string `json:"transitioning"`
TransitioningMessage interface{} `json:"transitioningMessage"`
TransitioningProgress interface{} `json:"transitioningProgress"`
Type string `json:"type"`
Upgrade struct {
InServiceStrategy struct {
BatchSize int `json:"batchSize"`
IntervalMillis int `json:"intervalMillis"`
LaunchConfig struct {
CapAdd []interface{} `json:"capAdd"`
CapDrop []interface{} `json:"capDrop"`
Count interface{} `json:"count"`
CPUSet interface{} `json:"cpuSet"`
CPUShares interface{} `json:"cpuShares"`
DataVolumes []interface{} `json:"dataVolumes"`
DataVolumesFrom []interface{} `json:"dataVolumesFrom"`
DataVolumesFromLaunchConfigs []interface{} `json:"dataVolumesFromLaunchConfigs"`
Description interface{} `json:"description"`
Devices []interface{} `json:"devices"`
DNS []interface{} `json:"dns"`
DNSSearch []interface{} `json:"dnsSearch"`
DomainName interface{} `json:"domainName"`
Environment struct {
CONFIGFILE string `json:"CONFIGFILE"`
} `json:"environment"`
Hostname interface{} `json:"hostname"`
ImageUUID string `json:"imageUuid"`
Kind string `json:"kind"`
Labels struct {
Io_rancher_container_pullImage string `json:"io.rancher.container.pull_image"`
Io_rancher_scheduler_affinity_containerLabelSoftNe string `json:"io.rancher.scheduler.affinity:container_label_soft_ne"`
} `json:"labels"`
LogConfig struct {
Config struct{} `json:"config"`
Driver string `json:"driver"`
} `json:"logConfig"`
Memory interface{} `json:"memory"`
MemoryMb interface{} `json:"memoryMb"`
MemorySwap interface{} `json:"memorySwap"`
NetworkLaunchConfig interface{} `json:"networkLaunchConfig"`
NetworkMode string `json:"networkMode"`
PidMode interface{} `json:"pidMode"`
Ports []interface{} `json:"ports"`
Privileged bool `json:"privileged"`
PublishAllPorts bool `json:"publishAllPorts"`
ReadOnly bool `json:"readOnly"`
RequestedHostID interface{} `json:"requestedHostId"`
RequestedIPAddress interface{} `json:"requestedIpAddress"`
StartOnCreate bool `json:"startOnCreate"`
StdinOpen bool `json:"stdinOpen"`
Tty bool `json:"tty"`
User interface{} `json:"user"`
Userdata interface{} `json:"userdata"`
Vcpu int `json:"vcpu"`
Version string `json:"version"`
VolumeDriver interface{} `json:"volumeDriver"`
WorkingDir interface{} `json:"workingDir"`
} `json:"launchConfig"`
PreviousLaunchConfig struct {
CapAdd []interface{} `json:"capAdd"`
CapDrop []interface{} `json:"capDrop"`
Count interface{} `json:"count"`
CPUSet interface{} `json:"cpuSet"`
CPUShares interface{} `json:"cpuShares"`
DataVolumes []interface{} `json:"dataVolumes"`
DataVolumesFrom []interface{} `json:"dataVolumesFrom"`
DataVolumesFromLaunchConfigs []interface{} `json:"dataVolumesFromLaunchConfigs"`
Description interface{} `json:"description"`
Devices []interface{} `json:"devices"`
DNS []interface{} `json:"dns"`
DNSSearch []interface{} `json:"dnsSearch"`
DomainName interface{} `json:"domainName"`
Environment struct {
CONFIGFILE string `json:"CONFIGFILE"`
} `json:"environment"`
Hostname interface{} `json:"hostname"`
ImageUUID string `json:"imageUuid"`
Kind string `json:"kind"`
Labels struct {
Io_rancher_container_pullImage string `json:"io.rancher.container.pull_image"`
Io_rancher_scheduler_affinity_containerLabelSoftNe string `json:"io.rancher.scheduler.affinity:container_label_soft_ne"`
} `json:"labels"`
LogConfig struct {
Config struct{} `json:"config"`
Driver string `json:"driver"`
} `json:"logConfig"`
Memory interface{} `json:"memory"`
MemoryMb interface{} `json:"memoryMb"`
MemorySwap interface{} `json:"memorySwap"`
NetworkLaunchConfig interface{} `json:"networkLaunchConfig"`
NetworkMode string `json:"networkMode"`
PidMode interface{} `json:"pidMode"`
Ports []interface{} `json:"ports"`
Privileged bool `json:"privileged"`
PublishAllPorts bool `json:"publishAllPorts"`
ReadOnly bool `json:"readOnly"`
RequestedHostID interface{} `json:"requestedHostId"`
RequestedIPAddress interface{} `json:"requestedIpAddress"`
StartOnCreate bool `json:"startOnCreate"`
StdinOpen bool `json:"stdinOpen"`
Tty bool `json:"tty"`
User interface{} `json:"user"`
Userdata interface{} `json:"userdata"`
Vcpu int `json:"vcpu"`
Version string `json:"version"`
VolumeDriver interface{} `json:"volumeDriver"`
WorkingDir interface{} `json:"workingDir"`
} `json:"previousLaunchConfig"`
PreviousSecondaryLaunchConfigs []interface{} `json:"previousSecondaryLaunchConfigs"`
SecondaryLaunchConfigs []interface{} `json:"secondaryLaunchConfigs"`
StartFirst bool `json:"startFirst"`
} `json:"inServiceStrategy"`
ToServiceStrategy interface{} `json:"toServiceStrategy"`
} `json:"upgrade"`
UUID string `json:"uuid"`
Vip interface{} `json:"vip"`
} `json:"data"`
Filters struct {
AccountID interface{} `json:"accountId"`
CreateIndex interface{} `json:"createIndex"`
Created interface{} `json:"created"`
Description interface{} `json:"description"`
EnvironmentID interface{} `json:"environmentId"`
ExternalID interface{} `json:"externalId"`
HealthState interface{} `json:"healthState"`
ID interface{} `json:"id"`
Kind interface{} `json:"kind"`
Name []struct {
Modifier string `json:"modifier"`
Value string `json:"value"`
} `json:"name"`
RemoveTime interface{} `json:"removeTime"`
Removed interface{} `json:"removed"`
SelectorContainer interface{} `json:"selectorContainer"`
SelectorLink interface{} `json:"selectorLink"`
State interface{} `json:"state"`
UUID interface{} `json:"uuid"`
Vip interface{} `json:"vip"`
} `json:"filters"`
Links struct {
Self string `json:"self"`
} `json:"links"`
Pagination struct {
First interface{} `json:"first"`
Limit int `json:"limit"`
Next interface{} `json:"next"`
Partial bool `json:"partial"`
Previous interface{} `json:"previous"`
Total interface{} `json:"total"`
} `json:"pagination"`
ResourceType string `json:"resourceType"`
Sort interface{} `json:"sort"`
SortLinks struct {
AccountID string `json:"accountId"`
CreateIndex string `json:"createIndex"`
Created string `json:"created"`
Description string `json:"description"`
EnvironmentID string `json:"environmentId"`
ExternalID string `json:"externalId"`
HealthState string `json:"healthState"`
ID string `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
RemoveTime string `json:"removeTime"`
Removed string `json:"removed"`
SelectorContainer string `json:"selectorContainer"`
SelectorLink string `json:"selectorLink"`
State string `json:"state"`
UUID string `json:"uuid"`
Vip string `json:"vip"`
} `json:"sortLinks"`
Type string `json:"type"`
}
func (r *Rancher) Call(hubMsg HubMessage) {
log.Print("### Got WebHook call. BEGIN:")
var ranchersvc = getService(r)
lc, _ := json.Marshal(ranchersvc.Data[0].LaunchConfig)
slc, _ := json.Marshal(ranchersvc.Data[0].SecondaryLaunchConfigs)
url := ranchersvc.Data[0].Actions.Upgrade
user := r.rancherConfig.UserKey
pass := r.rancherConfig.SecretKey
if url == "" {
svcstatus := ranchersvc.Data[0].State
log.Print("# Rancher not available for upgrade")
log.Print("# Current status: ", svcstatus)
if svcstatus == "upgrading" {
log.Print("### END.")
return
} else if svcstatus == "upgraded" {
log.Print("# Attempting to complete in-progress upgrade...")
finishUpgrade(r)
}
} else {
log.Print("# API URL: ", url)
}
var jsonStr = []byte(`{"inServiceStrategy":` +
`{` +
`"batchSize": 1,` +
`"intervalMillis": 2000,` +
`"startFirst": false,` +
`"launchConfig":` + string(lc) + `,` +
`"secondaryLaunchConfigs":` + string(slc) +
`}` +
`}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.SetBasicAuth(user, pass)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
log.Print("# Sent upgrade request: ", resp.StatusCode)
minute := time.Minute
pollurl := ranchersvc.Data[0].Links.Self
for i := 1; i <= 10; i++ {
pollstatus, err := getUpgradeStatus(r, pollurl)
if err != nil {
log.Print("# ERR:", err)
}
if pollstatus == false {
log.Print("# Waiting for upgrade to complete (try ", i, " of 10)...")
time.Sleep(minute)
} else {
log.Print("# Upgraded service. Finishing...")
finishUpgrade(r)
dockerHubCallback(hubMsg)
break
}
}
log.Print(`### END.`)
}
func getService(r *Rancher) rancherService {
url := r.rancherConfig.Url + "/services?name=" + r.rancherConfig.Service
user := r.rancherConfig.UserKey
pass := r.rancherConfig.SecretKey
req, err := http.NewRequest("GET", url, nil)
req.SetBasicAuth(user, pass)
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var ranchersvc rancherService
err = json.Unmarshal(body, &ranchersvc)
if err != nil {
log.Print("error unmarshaling Rancher JSON response: ", err)
}
return ranchersvc
}
func getUpgradeStatus(r *Rancher, url string) (status bool, err error) {
var ranchersvc = getService(r)
upgradestatus := ranchersvc.Data[0].State
if upgradestatus == "upgrading" {
status := false
return status, err
} else if upgradestatus == "upgraded" {
status := true
return status, err
} else {
err = fmt.Errorf("Rancher state '%v' not of supported type (upgrading or upgraded). Check Rancher for additional information.", upgradestatus)
status := false
return status, err
}
}
func finishUpgrade(r *Rancher) {
ranchersvc := getService(r)
url := ranchersvc.Data[0].Actions.FinishUpgrade
user := r.rancherConfig.UserKey
pass := r.rancherConfig.SecretKey
req, err := http.NewRequest("POST", url, nil)
req.SetBasicAuth(user, pass)
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
if resp.StatusCode == 202 {
log.Print("# Finished Upgrade.")
} else {
log.Print("# Unknown Upgrade Status: ", resp.StatusCode)
}
return
}
func dockerHubCallback(hubMsg HubMessage) {
url := hubMsg.CallbackUrl
var jsonStr = []byte(`{
"state": "success",
"description": "Rancher Deployment Successful",
"context": "Rancher Deployment",
"target_url": ""
}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
switch resp.StatusCode {
case 202:
log.Print("# Callback to Docker Hub Webhook complete: ", resp.StatusCode)
case 200:
log.Print("# Callback to Docker Hub Webhook complete: ", resp.StatusCode)
default:
log.Print("# Unacceptable Docker Hub Webhook Callback Status: ", resp.StatusCode)
}
}