blob: 30d3f069ab6f10cf6042d5489bf5544f50e15368 [file] [log] [blame]
David K. Bainbridgeb5415042016-05-13 17:06:10 -07001package main
2
3import (
David K. Bainbridgeefa951d2016-05-26 10:54:25 -07004 "bytes"
5 "encoding/json"
David K. Bainbridgeb5415042016-05-13 17:06:10 -07006 "fmt"
7 "log"
David K. Bainbridgeefa951d2016-05-26 10:54:25 -07008 "net/http"
David K. Bainbridgeb5415042016-05-13 17:06:10 -07009 "net/url"
David K. Bainbridgeefa951d2016-05-26 10:54:25 -070010 "os/exec"
David K. Bainbridgeb5415042016-05-13 17:06:10 -070011 "regexp"
12 "strconv"
13 "strings"
David K. Bainbridgeefa951d2016-05-26 10:54:25 -070014 "time"
David K. Bainbridgeb5415042016-05-13 17:06:10 -070015
16 maas "github.com/juju/gomaasapi"
17)
18
19// Action how to get from there to here
20type Action func(*maas.MAASObject, MaasNode, ProcessingOptions) error
21
22// Transition the map from where i want to be from where i might be
23type Transition struct {
24 Target string
25 Current string
26 Using Action
27}
28
David K. Bainbridge6ea57c12016-06-06 23:29:12 -070029type Power struct {
30 Name string `json:"name"`
31 MacAddress string `json:"mac_address"`
32 PowerPassword string `json:"power_password"`
33 PowerAddress string `json:"power_address"`
34}
35
David K. Bainbridgeb5415042016-05-13 17:06:10 -070036// ProcessingOptions used to determine on what hosts to operate
37type ProcessingOptions struct {
38 Filter struct {
39 Zones struct {
40 Include []string
41 Exclude []string
42 }
43 Hosts struct {
44 Include []string
45 Exclude []string
46 }
47 }
David K. Bainbridge6ea57c12016-06-06 23:29:12 -070048 Mappings map[string]interface{}
49 Verbose bool
50 Preview bool
51 AlwaysRename bool
52 ProvTracker Tracker
53 ProvisionURL string
54 ProvisionTTL time.Duration
55 PowerHelper string
56 PowerHelperUser string
57 PowerHelperHost string
David K. Bainbridgeb5415042016-05-13 17:06:10 -070058}
59
60// Transitions the actual map
61//
62// Currently this is a hand compiled / optimized "next step" table. This should
63// really be generated from the state machine chart input. Once this has been
64// accomplished you should be able to determine the action to take given your
65// target state and your current state.
David K. Bainbridgeefa951d2016-05-26 10:54:25 -070066var Transitions = map[string]map[string][]Action{
David K. Bainbridgeb5415042016-05-13 17:06:10 -070067 "Deployed": {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -070068 "New": []Action{Reset, Commission},
69 "Deployed": []Action{Provision, Done},
70 "Ready": []Action{Reset, Aquire},
71 "Allocated": []Action{Reset, Deploy},
72 "Retired": []Action{Reset, AdminState},
73 "Reserved": []Action{Reset, AdminState},
74 "Releasing": []Action{Reset, Wait},
75 "DiskErasing": []Action{Reset, Wait},
76 "Deploying": []Action{Reset, Wait},
77 "Commissioning": []Action{Reset, Wait},
78 "Missing": []Action{Reset, Fail},
79 "FailedReleasing": []Action{Reset, Fail},
80 "FailedDiskErasing": []Action{Reset, Fail},
81 "FailedDeployment": []Action{Reset, Fail},
82 "Broken": []Action{Reset, Fail},
83 "FailedCommissioning": []Action{Reset, Fail},
David K. Bainbridgeb5415042016-05-13 17:06:10 -070084 },
85}
86
87const (
88 // defaultStateMachine Would be nice to drive from a graph language
89 defaultStateMachine string = `
David K. Bainbridged9b966f2016-05-31 13:30:05 -070090 (New)->(Commissioning)
David K. Bainbridgeb5415042016-05-13 17:06:10 -070091 (Commissioning)->(FailedCommissioning)
92 (FailedCommissioning)->(New)
93 (Commissioning)->(Ready)
94 (Ready)->(Deploying)
95 (Ready)->(Allocated)
96 (Allocated)->(Deploying)
97 (Deploying)->(Deployed)
98 (Deploying)->(FailedDeployment)
99 (FailedDeployment)->(Broken)
100 (Deployed)->(Releasing)
101 (Releasing)->(FailedReleasing)
102 (FailedReleasing)->(Broken)
103 (Releasing)->(DiskErasing)
104 (DiskErasing)->(FailedEraseDisk)
105 (FailedEraseDisk)->(Broken)
106 (Releasing)->(Ready)
107 (DiskErasing)->(Ready)
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700108 (Broken)->(Ready)
David K. Bainbridged9b966f2016-05-31 13:30:05 -0700109 (Deployed)->(Provisioning)
110 (Provisioning)->|a|
111 |a|->(Execute Script)->|b|
112 |a|->(HTTP PUT)
113 (HTTP PUT)->(HTTP GET)
114 (HTTP GET)->(HTTP GET)
115 (HTTP GET)->|b|
116 |b|->(Provisioned)
117 |b|->(ProvisionError)
118 (ProvisionError)->(Provisioning)`
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700119)
120
121// updateName - changes the name of the MAAS node based on the configuration file
122func updateNodeName(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
123 macs := node.MACs()
124
125 // Get current node name and strip off domain name
126 current := node.Hostname()
127 if i := strings.IndexRune(current, '.'); i != -1 {
128 current = current[:i]
129 }
130 for _, mac := range macs {
131 if entry, ok := options.Mappings[mac]; ok {
132 if name, ok := entry.(map[string]interface{})["hostname"]; ok && current != name.(string) {
133 nodesObj := client.GetSubObject("nodes")
134 nodeObj := nodesObj.GetSubObject(node.ID())
135 log.Printf("RENAME '%s' to '%s'\n", node.Hostname(), name.(string))
136
137 if !options.Preview {
138 nodeObj.Update(url.Values{"hostname": []string{name.(string)}})
139 }
140 }
141 }
142 }
143 return nil
144}
145
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700146// Reset we are at the target state, nothing to do
147var Reset = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
148 if options.Verbose {
149 log.Printf("RESET: %s", node.Hostname())
150 }
151
152 if options.AlwaysRename {
153 updateNodeName(client, node, options)
154 }
155
156 options.ProvTracker.Clear(node.ID())
157
158 return nil
159}
160
161// Provision we are at the target state, nothing to do
162var Provision = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
163 if options.Verbose {
164 log.Printf("CHECK PROVISION: %s", node.Hostname())
165 }
166
167 if options.AlwaysRename {
168 updateNodeName(client, node, options)
169 }
170
171 record, err := options.ProvTracker.Get(node.ID())
172 if options.Verbose {
173 log.Printf("[info] Current state of node '%s' is '%s'", node.Hostname(), record.State.String())
174 }
175 if err != nil {
176 log.Printf("[warn] unable to retrieve provisioning state of node '%s' : %s", node.Hostname(), err)
177 } else if record.State == Unprovisioned || record.State == ProvisionError {
178 var err error = nil
179 var callout *url.URL
180 log.Printf("PROVISION '%s'", node.Hostname())
181 if len(options.ProvisionURL) > 0 {
182 if options.Verbose {
183 log.Printf("[info] Provisioning callout to '%s'", options.ProvisionURL)
184 }
185 callout, err = url.Parse(options.ProvisionURL)
186 if err != nil {
187 log.Printf("[error] Failed to parse provisioning URL '%s' : %s", options.ProvisionURL, err)
188 } else {
189 ips := node.IPs()
190 ip := ""
191 if len(ips) > 0 {
192 ip = ips[0]
193 }
David K. Bainbridged9b966f2016-05-31 13:30:05 -0700194 macs := node.MACs()
195 mac := ""
196 if len(macs) > 0 {
197 mac = macs[0]
198 }
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700199 switch callout.Scheme {
200 // If the scheme is a file, then we will execute the refereced file
201 case "", "file":
202 if options.Verbose {
203 log.Printf("[info] executing local script file '%s'", callout.Path)
204 }
205 record.State = Provisioning
206 record.Timestamp = time.Now().Unix()
207 options.ProvTracker.Set(node.ID(), record)
David K. Bainbridged9b966f2016-05-31 13:30:05 -0700208 err = exec.Command(callout.Path, node.ID(), node.Hostname(), ip, mac).Run()
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700209 if err != nil {
210 log.Printf("[error] Failed to execute '%s' : %s", options.ProvisionURL, err)
211 } else {
212 if options.Verbose {
213 log.Printf("[info] Marking node '%s' with ID '%s' as provisioned",
214 node.Hostname(), node.ID())
215 }
216 record.State = Provisioned
217 options.ProvTracker.Set(node.ID(), record)
218 }
219
220 default:
221 if options.Verbose {
222 log.Printf("[info] POSTing to '%s'", options.ProvisionURL)
223 }
224 data := map[string]string{
225 "id": node.ID(),
226 "name": node.Hostname(),
227 "ip": ip,
David K. Bainbridged9b966f2016-05-31 13:30:05 -0700228 "mac": mac,
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700229 }
230 hc := http.Client{}
231 var b []byte
232 b, err = json.Marshal(data)
233 if err != nil {
234 log.Printf("[error] Unable to marshal node data : %s", err)
235 } else {
236 var req *http.Request
237 var resp *http.Response
238 if options.Verbose {
239 log.Printf("[debug] POSTing data '%s'", string(b))
240 }
241 req, err = http.NewRequest("POST", options.ProvisionURL, bytes.NewReader(b))
242 if err != nil {
243 log.Printf("[error] Unable to construct POST request to provisioner : %s",
244 err)
245 } else {
246 req.Header.Add("Content-Type", "application/json")
247 resp, err = hc.Do(req)
248 if err != nil {
249 log.Printf("[error] Unable to process POST request : %s",
250 err)
251 } else {
252 defer resp.Body.Close()
David K. Bainbridge8352c592016-06-02 12:48:37 -0700253 if resp.StatusCode == http.StatusAccepted {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700254 record.State = Provisioning
255 } else {
256 record.State = ProvisionError
257 }
David K. Bainbridge8352c592016-06-02 12:48:37 -0700258 record.Timestamp = time.Now().Unix()
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700259 options.ProvTracker.Set(node.ID(), record)
260 }
261 }
262 }
263 }
264 }
265 }
266
267 if err != nil {
268 if options.Verbose {
269 log.Printf("[warn] Not marking node '%s' with ID '%s' as provisioned, because of error '%s'",
270 node.Hostname(), node.ID(), err)
271 record.State = ProvisionError
272 options.ProvTracker.Set(node.ID(), record)
273 }
274 }
275 } else if record.State == Provisioning && time.Since(time.Unix(record.Timestamp, 0)) > options.ProvisionTTL {
276 log.Printf("[error] Provisioning of node '%s' has passed provisioning TTL of '%v'",
277 node.Hostname(), options.ProvisionTTL)
278 record.State = ProvisionError
279 options.ProvTracker.Set(node.ID(), record)
280 } else if record.State == Provisioning {
281 callout, err := url.Parse(options.ProvisionURL)
282 if err != nil {
283 log.Printf("[error] Unable to parse provisioning URL '%s' : %s", options.ProvisionURL, err)
284 } else if callout.Scheme != "file" {
285 var req *http.Request
286 var resp *http.Response
287 if options.Verbose {
288 log.Printf("[info] Fetching provisioning state for node '%s'", node.Hostname())
289 }
290 req, err = http.NewRequest("GET", options.ProvisionURL+"/"+node.ID(), nil)
291 if err != nil {
292 log.Printf("[error] Unable to construct GET request to provisioner : %s", err)
293 } else {
294 hc := http.Client{}
295 resp, err = hc.Do(req)
296 if err != nil {
297 log.Printf("[error] Failed to quest provision state for node '%s' : %s",
298 node.Hostname(), err)
299 } else {
David K. Bainbridge2f456b82016-06-14 22:32:51 -0700300 defer resp.Body.Close()
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700301 switch resp.StatusCode {
David K. Bainbridge2f456b82016-06-14 22:32:51 -0700302 case http.StatusOK: // provisioning completed or failed
303 decoder := json.NewDecoder(resp.Body)
304 var raw interface{}
305 err = decoder.Decode(&raw)
306 if err != nil {
307 log.Printf("[error] Unable to unmarshal response from provisioner for '%s': %s",
308 node.Hostname(), err)
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700309 }
David K. Bainbridge2f456b82016-06-14 22:32:51 -0700310 status := raw.(map[string]interface{})
311 switch int(status["status"].(float64)) {
312 case 0, 1: // PENDING, RUNNING ... should never really get here
313 // noop, already in this state
314 case 2: // COMPLETE
315 if options.Verbose {
316 log.Printf("[info] Marking node '%s' with ID '%s' as provisioned",
317 node.Hostname(), node.ID())
318 }
319 record.State = Provisioned
320 options.ProvTracker.Set(node.ID(), record)
321 case 3: // FAILED
322 if options.Verbose {
323 log.Printf("[info] Marking node '%s' with ID '%s' as failed provisioning",
324 node.Hostname(), node.ID())
325 }
326 record.State = ProvisionError
327 options.ProvTracker.Set(node.ID(), record)
328 default:
329 log.Printf("[error] unknown status state for node '%s' : %d",
330 node.Hostname(), int(status["status"].(float64)))
331 }
David K. Bainbridge8352c592016-06-02 12:48:37 -0700332 case http.StatusAccepted: // in the provisioning state
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700333 // Noop, presumably alread in this state
334 default: // Consider anything else an erorr
David K. Bainbridge8352c592016-06-02 12:48:37 -0700335 log.Printf("[warn] Node '%s' with ID '%s' failed provisioning, will retry",
336 node.Hostname(), node.ID())
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700337 record.State = ProvisionError
338 options.ProvTracker.Set(node.ID(), record)
339 }
340 }
341 }
342 }
343 } else if options.Verbose {
David K. Bainbridge218fdd62016-06-15 10:31:38 -0700344 log.Printf("[info] Not invoking provisioning for '%s', current state is '%s'", node.Hostname(),
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700345 record.State.String())
346 }
347
348 return nil
349}
350
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700351// Done we are at the target state, nothing to do
352var Done = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
353 // As devices are normally in the "COMPLETED" state we don't want to
354 // log this fact unless we are in verbose mode. I suspect it would be
355 // nice to log it once when the device transitions from a non COMPLETE
356 // state to a complete state, but that would require keeping state.
357 if options.Verbose {
358 log.Printf("COMPLETE: %s", node.Hostname())
359 }
360
361 if options.AlwaysRename {
362 updateNodeName(client, node, options)
363 }
364
365 return nil
366}
367
368// Deploy cause a node to deploy
369var Deploy = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
370 log.Printf("DEPLOY: %s", node.Hostname())
371
372 if options.AlwaysRename {
373 updateNodeName(client, node, options)
374 }
375
376 if !options.Preview {
377 nodesObj := client.GetSubObject("nodes")
378 myNode := nodesObj.GetSubObject(node.ID())
379 // Start the node with the trusty distro. This should really be looked up or
380 // a parameter default
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700381 _, err := myNode.CallPost("start", url.Values{"distro_series": []string{"trusty"}})
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700382 if err != nil {
383 log.Printf("ERROR: DEPLOY '%s' : '%s'", node.Hostname(), err)
384 return err
385 }
386 }
387 return nil
388}
389
390// Aquire aquire a machine to a specific operator
391var Aquire = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
392 log.Printf("AQUIRE: %s", node.Hostname())
393 nodesObj := client.GetSubObject("nodes")
394
395 if options.AlwaysRename {
396 updateNodeName(client, node, options)
397 }
398
399 if !options.Preview {
400 // With a new version of MAAS we have to make sure the node is linked
401 // to the subnet vid DHCP before we move to the Aquire state. To do this
402 // We need to unlink the interface to the subnet and then relink it.
403 //
404 // Iterate through all the interfaces on the node, searching for ones
405 // that are valid and not DHCP and move them to DHCP
406 ifcsObj := client.GetSubObject("nodes").GetSubObject(node.ID()).GetSubObject("interfaces")
407 ifcsListObj, err := ifcsObj.CallGet("", url.Values{})
408 if err != nil {
409 return err
410 }
411
412 ifcsArray, err := ifcsListObj.GetArray()
413 if err != nil {
414 return err
415 }
416
417 for _, ifc := range ifcsArray {
418 ifcMap, err := ifc.GetMap()
419 if err != nil {
420 return err
421 }
422
423 // Iterate over the links assocated with the interface, looking for
424 // links with a subnect as well as a mode of "auto"
425 links, ok := ifcMap["links"]
426 if ok {
427 linkArray, err := links.GetArray()
428 if err != nil {
429 return err
430 }
431
432 for _, link := range linkArray {
433 linkMap, err := link.GetMap()
434 if err != nil {
435 return err
436 }
437 subnet, ok := linkMap["subnet"]
438 if ok {
439 subnetMap, err := subnet.GetMap()
440 if err != nil {
441 return err
442 }
443
444 val, err := linkMap["mode"].GetString()
445 if err != nil {
446 return err
447 }
448
449 if val == "auto" {
450 // Found one we like, so grab the subnet from the data and
451 // then relink this as DHCP
452 cidr, err := subnetMap["cidr"].GetString()
453 if err != nil {
454 return err
455 }
456
457 fifcID, err := ifcMap["id"].GetFloat64()
458 if err != nil {
459 return err
460 }
461 ifcID := strconv.Itoa(int(fifcID))
462
463 flID, err := linkMap["id"].GetFloat64()
464 if err != nil {
465 return err
466 }
467 lID := strconv.Itoa(int(flID))
468
469 ifcObj := ifcsObj.GetSubObject(ifcID)
470 _, err = ifcObj.CallPost("unlink_subnet", url.Values{"id": []string{lID}})
471 if err != nil {
472 return err
473 }
474 _, err = ifcObj.CallPost("link_subnet", url.Values{"mode": []string{"DHCP"}, "subnet": []string{cidr}})
475 if err != nil {
476 return err
477 }
478 }
479 }
480 }
481 }
482 }
483 _, err = nodesObj.CallPost("acquire",
484 url.Values{"name": []string{node.Hostname()}})
485 if err != nil {
486 log.Printf("ERROR: AQUIRE '%s' : '%s'", node.Hostname(), err)
487 return err
488 }
489 }
490 return nil
491}
492
493// Commission cause a node to be commissioned
494var Commission = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
495 updateNodeName(client, node, options)
496
497 // Need to understand the power state of the node. We only want to move to "Commissioning" if the node
498 // power is off. If the node power is not off, then turn it off.
499 state := node.PowerState()
500 switch state {
501 case "on":
502 // Attempt to turn the node off
503 log.Printf("POWER DOWN: %s", node.Hostname())
504 if !options.Preview {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700505 //POST /api/1.0/nodes/{system_id}/ op=stop
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700506 nodesObj := client.GetSubObject("nodes")
507 nodeObj := nodesObj.GetSubObject(node.ID())
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700508 _, err := nodeObj.CallPost("stop", url.Values{"stop_mode": []string{"soft"}})
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700509 if err != nil {
510 log.Printf("ERROR: Commission '%s' : changing power start to off : '%s'", node.Hostname(), err)
511 }
512 return err
513 }
514 break
515 case "off":
516 // We are off so move to commissioning
517 log.Printf("COMISSION: %s", node.Hostname())
518 if !options.Preview {
519 nodesObj := client.GetSubObject("nodes")
520 nodeObj := nodesObj.GetSubObject(node.ID())
521
522 updateNodeName(client, node, options)
523
524 _, err := nodeObj.CallPost("commission", url.Values{})
525 if err != nil {
526 log.Printf("ERROR: Commission '%s' : '%s'", node.Hostname(), err)
527 }
528 return err
529 }
530 break
531 default:
532 // We are in a state from which we can't move forward.
David K. Bainbridge6ea57c12016-06-06 23:29:12 -0700533 log.Printf("[warn]: %s has invalid power state '%s'", node.Hostname(), state)
534
535 // If a power helper script is set, we have an unknown power state, and
536 // we have not power type then attempt to use the helper script to discover
537 // and set the power settings
538 if options.PowerHelper != "" && node.PowerType() == "" {
539 cmd := exec.Command(options.PowerHelper,
540 append([]string{options.PowerHelperUser, options.PowerHelperHost},
541 node.MACs()...)...)
542 stdout, err := cmd.Output()
543 if err != nil {
544 log.Printf("[error] Failed while executing power helper script '%s' : %s",
545 options.PowerHelper, err)
546 return err
547 }
548 power := Power{}
549 err = json.Unmarshal(stdout, &power)
550 if err != nil {
551 log.Printf("[error] Failed to parse output of power helper script '%s' : %s",
552 options.PowerHelper, err)
553 return err
554 }
555 switch power.Name {
556 case "amt":
557 params := map[string]string{
558 "mac_address": power.MacAddress,
559 "power_pass": power.PowerPassword,
560 "power_address": power.PowerAddress,
561 }
562 node.UpdatePowerParameters(power.Name, params)
563 default:
564 log.Printf("[warn] Unsupported power type discovered '%s'", power.Name)
565 }
566 }
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700567 break
568 }
569 return nil
570}
571
572// Wait a do nothing state, while work is being done
573var Wait = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
574 log.Printf("WAIT: %s", node.Hostname())
575 return nil
576}
577
578// Fail a state from which we cannot, currently, automatically recover
579var Fail = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
580 log.Printf("FAIL: %s", node.Hostname())
581 return nil
582}
583
584// AdminState an administrative state from which we should make no automatic transition
585var AdminState = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
586 log.Printf("ADMIN: %s", node.Hostname())
587 return nil
588}
589
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700590func findActions(target string, current string) ([]Action, error) {
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700591 targets, ok := Transitions[target]
592 if !ok {
593 log.Printf("[warn] unable to find transitions to target state '%s'", target)
594 return nil, fmt.Errorf("Could not find transition to target state '%s'", target)
595 }
596
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700597 actions, ok := targets[current]
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700598 if !ok {
599 log.Printf("[warn] unable to find transition from current state '%s' to target state '%s'",
600 current, target)
601 return nil, fmt.Errorf("Could not find transition from current state '%s' to target state '%s'",
602 current, target)
603 }
604
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700605 return actions, nil
606}
607
608// ProcessActions
609func ProcessActions(actions []Action, client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
610 var err error
611 for _, action := range actions {
612 if err = action(client, node, options); err != nil {
David K. Bainbridge6ea57c12016-06-06 23:29:12 -0700613 log.Printf("[error] Error while processing action for node '%s' : %s",
614 node.Hostname(), err)
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700615 break
616 }
617 }
618 return err
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700619}
620
621// ProcessNode something
622func ProcessNode(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
623 substatus, err := node.GetInteger("substatus")
624 if err != nil {
625 return err
626 }
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700627 actions, err := findActions("Deployed", MaasNodeStatus(substatus).String())
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700628 if err != nil {
629 return err
630 }
631
632 if options.Preview {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700633 ProcessActions(actions, client, node, options)
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700634 } else {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700635 go ProcessActions(actions, client, node, options)
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700636 }
637 return nil
638}
639
640func buildFilter(filter []string) ([]*regexp.Regexp, error) {
641
642 results := make([]*regexp.Regexp, len(filter))
643 for i, v := range filter {
644 r, err := regexp.Compile(v)
645 if err != nil {
646 return nil, err
647 }
648 results[i] = r
649 }
650 return results, nil
651}
652
653func matchedFilter(include []*regexp.Regexp, target string) bool {
654 for _, e := range include {
655 if e.MatchString(target) {
656 return true
657 }
658 }
659 return false
660}
661
662// ProcessAll something
663func ProcessAll(client *maas.MAASObject, nodes []MaasNode, options ProcessingOptions) []error {
664 errors := make([]error, len(nodes))
665 includeHosts, err := buildFilter(options.Filter.Hosts.Include)
666 if err != nil {
667 log.Fatalf("[error] invalid regular expression for include filter '%s' : %s", options.Filter.Hosts.Include, err)
668 }
669
670 includeZones, err := buildFilter(options.Filter.Zones.Include)
671 if err != nil {
672 log.Fatalf("[error] invalid regular expression for include filter '%v' : %s", options.Filter.Zones.Include, err)
673 }
674
675 for i, node := range nodes {
676 // For hostnames we always match on an empty filter
677 if len(includeHosts) >= 0 && matchedFilter(includeHosts, node.Hostname()) {
678
679 // For zones we don't match on an empty filter
680 if len(includeZones) >= 0 && matchedFilter(includeZones, node.Zone()) {
681 err := ProcessNode(client, node, options)
682 if err != nil {
683 errors[i] = err
684 } else {
685 errors[i] = nil
686 }
687 } else {
688 if options.Verbose {
689 log.Printf("[info] ignoring node '%s' as its zone '%s' didn't match include zone name filter '%v'",
690 node.Hostname(), node.Zone(), options.Filter.Zones.Include)
691 }
692 }
693 } else {
694 if options.Verbose {
695 log.Printf("[info] ignoring node '%s' as it didn't match include hostname filter '%v'",
696 node.Hostname(), options.Filter.Hosts.Include)
697 }
698 }
699 }
700 return errors
701}