blob: 04626ed233d2e779503add96458cceffa636e08c [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 {
300 switch resp.StatusCode {
David K. Bainbridge8352c592016-06-02 12:48:37 -0700301 case http.StatusOK: // provisioning completed
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700302 if options.Verbose {
303 log.Printf("[info] Marking node '%s' with ID '%s' as provisioned",
304 node.Hostname(), node.ID())
305 }
306 record.State = Provisioned
307 options.ProvTracker.Set(node.ID(), record)
David K. Bainbridge8352c592016-06-02 12:48:37 -0700308 case http.StatusAccepted: // in the provisioning state
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700309 // Noop, presumably alread in this state
310 default: // Consider anything else an erorr
David K. Bainbridge8352c592016-06-02 12:48:37 -0700311 log.Printf("[warn] Node '%s' with ID '%s' failed provisioning, will retry",
312 node.Hostname(), node.ID())
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700313 record.State = ProvisionError
314 options.ProvTracker.Set(node.ID(), record)
315 }
316 }
317 }
318 }
319 } else if options.Verbose {
320 log.Printf("[info] Not invoking provisioning for '%s', currned state is '%s'", node.Hostname(),
321 record.State.String())
322 }
323
324 return nil
325}
326
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700327// Done we are at the target state, nothing to do
328var Done = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
329 // As devices are normally in the "COMPLETED" state we don't want to
330 // log this fact unless we are in verbose mode. I suspect it would be
331 // nice to log it once when the device transitions from a non COMPLETE
332 // state to a complete state, but that would require keeping state.
333 if options.Verbose {
334 log.Printf("COMPLETE: %s", node.Hostname())
335 }
336
337 if options.AlwaysRename {
338 updateNodeName(client, node, options)
339 }
340
341 return nil
342}
343
344// Deploy cause a node to deploy
345var Deploy = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
346 log.Printf("DEPLOY: %s", node.Hostname())
347
348 if options.AlwaysRename {
349 updateNodeName(client, node, options)
350 }
351
352 if !options.Preview {
353 nodesObj := client.GetSubObject("nodes")
354 myNode := nodesObj.GetSubObject(node.ID())
355 // Start the node with the trusty distro. This should really be looked up or
356 // a parameter default
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700357 _, err := myNode.CallPost("start", url.Values{"distro_series": []string{"trusty"}})
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700358 if err != nil {
359 log.Printf("ERROR: DEPLOY '%s' : '%s'", node.Hostname(), err)
360 return err
361 }
362 }
363 return nil
364}
365
366// Aquire aquire a machine to a specific operator
367var Aquire = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
368 log.Printf("AQUIRE: %s", node.Hostname())
369 nodesObj := client.GetSubObject("nodes")
370
371 if options.AlwaysRename {
372 updateNodeName(client, node, options)
373 }
374
375 if !options.Preview {
376 // With a new version of MAAS we have to make sure the node is linked
377 // to the subnet vid DHCP before we move to the Aquire state. To do this
378 // We need to unlink the interface to the subnet and then relink it.
379 //
380 // Iterate through all the interfaces on the node, searching for ones
381 // that are valid and not DHCP and move them to DHCP
382 ifcsObj := client.GetSubObject("nodes").GetSubObject(node.ID()).GetSubObject("interfaces")
383 ifcsListObj, err := ifcsObj.CallGet("", url.Values{})
384 if err != nil {
385 return err
386 }
387
388 ifcsArray, err := ifcsListObj.GetArray()
389 if err != nil {
390 return err
391 }
392
393 for _, ifc := range ifcsArray {
394 ifcMap, err := ifc.GetMap()
395 if err != nil {
396 return err
397 }
398
399 // Iterate over the links assocated with the interface, looking for
400 // links with a subnect as well as a mode of "auto"
401 links, ok := ifcMap["links"]
402 if ok {
403 linkArray, err := links.GetArray()
404 if err != nil {
405 return err
406 }
407
408 for _, link := range linkArray {
409 linkMap, err := link.GetMap()
410 if err != nil {
411 return err
412 }
413 subnet, ok := linkMap["subnet"]
414 if ok {
415 subnetMap, err := subnet.GetMap()
416 if err != nil {
417 return err
418 }
419
420 val, err := linkMap["mode"].GetString()
421 if err != nil {
422 return err
423 }
424
425 if val == "auto" {
426 // Found one we like, so grab the subnet from the data and
427 // then relink this as DHCP
428 cidr, err := subnetMap["cidr"].GetString()
429 if err != nil {
430 return err
431 }
432
433 fifcID, err := ifcMap["id"].GetFloat64()
434 if err != nil {
435 return err
436 }
437 ifcID := strconv.Itoa(int(fifcID))
438
439 flID, err := linkMap["id"].GetFloat64()
440 if err != nil {
441 return err
442 }
443 lID := strconv.Itoa(int(flID))
444
445 ifcObj := ifcsObj.GetSubObject(ifcID)
446 _, err = ifcObj.CallPost("unlink_subnet", url.Values{"id": []string{lID}})
447 if err != nil {
448 return err
449 }
450 _, err = ifcObj.CallPost("link_subnet", url.Values{"mode": []string{"DHCP"}, "subnet": []string{cidr}})
451 if err != nil {
452 return err
453 }
454 }
455 }
456 }
457 }
458 }
459 _, err = nodesObj.CallPost("acquire",
460 url.Values{"name": []string{node.Hostname()}})
461 if err != nil {
462 log.Printf("ERROR: AQUIRE '%s' : '%s'", node.Hostname(), err)
463 return err
464 }
465 }
466 return nil
467}
468
469// Commission cause a node to be commissioned
470var Commission = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
471 updateNodeName(client, node, options)
472
473 // Need to understand the power state of the node. We only want to move to "Commissioning" if the node
474 // power is off. If the node power is not off, then turn it off.
475 state := node.PowerState()
476 switch state {
477 case "on":
478 // Attempt to turn the node off
479 log.Printf("POWER DOWN: %s", node.Hostname())
480 if !options.Preview {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700481 //POST /api/1.0/nodes/{system_id}/ op=stop
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700482 nodesObj := client.GetSubObject("nodes")
483 nodeObj := nodesObj.GetSubObject(node.ID())
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700484 _, err := nodeObj.CallPost("stop", url.Values{"stop_mode": []string{"soft"}})
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700485 if err != nil {
486 log.Printf("ERROR: Commission '%s' : changing power start to off : '%s'", node.Hostname(), err)
487 }
488 return err
489 }
490 break
491 case "off":
492 // We are off so move to commissioning
493 log.Printf("COMISSION: %s", node.Hostname())
494 if !options.Preview {
495 nodesObj := client.GetSubObject("nodes")
496 nodeObj := nodesObj.GetSubObject(node.ID())
497
498 updateNodeName(client, node, options)
499
500 _, err := nodeObj.CallPost("commission", url.Values{})
501 if err != nil {
502 log.Printf("ERROR: Commission '%s' : '%s'", node.Hostname(), err)
503 }
504 return err
505 }
506 break
507 default:
508 // We are in a state from which we can't move forward.
David K. Bainbridge6ea57c12016-06-06 23:29:12 -0700509 log.Printf("[warn]: %s has invalid power state '%s'", node.Hostname(), state)
510
511 // If a power helper script is set, we have an unknown power state, and
512 // we have not power type then attempt to use the helper script to discover
513 // and set the power settings
514 if options.PowerHelper != "" && node.PowerType() == "" {
515 cmd := exec.Command(options.PowerHelper,
516 append([]string{options.PowerHelperUser, options.PowerHelperHost},
517 node.MACs()...)...)
518 stdout, err := cmd.Output()
519 if err != nil {
520 log.Printf("[error] Failed while executing power helper script '%s' : %s",
521 options.PowerHelper, err)
522 return err
523 }
524 power := Power{}
525 err = json.Unmarshal(stdout, &power)
526 if err != nil {
527 log.Printf("[error] Failed to parse output of power helper script '%s' : %s",
528 options.PowerHelper, err)
529 return err
530 }
531 switch power.Name {
532 case "amt":
533 params := map[string]string{
534 "mac_address": power.MacAddress,
535 "power_pass": power.PowerPassword,
536 "power_address": power.PowerAddress,
537 }
538 node.UpdatePowerParameters(power.Name, params)
539 default:
540 log.Printf("[warn] Unsupported power type discovered '%s'", power.Name)
541 }
542 }
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700543 break
544 }
545 return nil
546}
547
548// Wait a do nothing state, while work is being done
549var Wait = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
550 log.Printf("WAIT: %s", node.Hostname())
551 return nil
552}
553
554// Fail a state from which we cannot, currently, automatically recover
555var Fail = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
556 log.Printf("FAIL: %s", node.Hostname())
557 return nil
558}
559
560// AdminState an administrative state from which we should make no automatic transition
561var AdminState = func(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
562 log.Printf("ADMIN: %s", node.Hostname())
563 return nil
564}
565
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700566func findActions(target string, current string) ([]Action, error) {
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700567 targets, ok := Transitions[target]
568 if !ok {
569 log.Printf("[warn] unable to find transitions to target state '%s'", target)
570 return nil, fmt.Errorf("Could not find transition to target state '%s'", target)
571 }
572
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700573 actions, ok := targets[current]
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700574 if !ok {
575 log.Printf("[warn] unable to find transition from current state '%s' to target state '%s'",
576 current, target)
577 return nil, fmt.Errorf("Could not find transition from current state '%s' to target state '%s'",
578 current, target)
579 }
580
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700581 return actions, nil
582}
583
584// ProcessActions
585func ProcessActions(actions []Action, client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
586 var err error
587 for _, action := range actions {
588 if err = action(client, node, options); err != nil {
David K. Bainbridge6ea57c12016-06-06 23:29:12 -0700589 log.Printf("[error] Error while processing action for node '%s' : %s",
590 node.Hostname(), err)
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700591 break
592 }
593 }
594 return err
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700595}
596
597// ProcessNode something
598func ProcessNode(client *maas.MAASObject, node MaasNode, options ProcessingOptions) error {
599 substatus, err := node.GetInteger("substatus")
600 if err != nil {
601 return err
602 }
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700603 actions, err := findActions("Deployed", MaasNodeStatus(substatus).String())
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700604 if err != nil {
605 return err
606 }
607
608 if options.Preview {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700609 ProcessActions(actions, client, node, options)
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700610 } else {
David K. Bainbridgeefa951d2016-05-26 10:54:25 -0700611 go ProcessActions(actions, client, node, options)
David K. Bainbridgeb5415042016-05-13 17:06:10 -0700612 }
613 return nil
614}
615
616func buildFilter(filter []string) ([]*regexp.Regexp, error) {
617
618 results := make([]*regexp.Regexp, len(filter))
619 for i, v := range filter {
620 r, err := regexp.Compile(v)
621 if err != nil {
622 return nil, err
623 }
624 results[i] = r
625 }
626 return results, nil
627}
628
629func matchedFilter(include []*regexp.Regexp, target string) bool {
630 for _, e := range include {
631 if e.MatchString(target) {
632 return true
633 }
634 }
635 return false
636}
637
638// ProcessAll something
639func ProcessAll(client *maas.MAASObject, nodes []MaasNode, options ProcessingOptions) []error {
640 errors := make([]error, len(nodes))
641 includeHosts, err := buildFilter(options.Filter.Hosts.Include)
642 if err != nil {
643 log.Fatalf("[error] invalid regular expression for include filter '%s' : %s", options.Filter.Hosts.Include, err)
644 }
645
646 includeZones, err := buildFilter(options.Filter.Zones.Include)
647 if err != nil {
648 log.Fatalf("[error] invalid regular expression for include filter '%v' : %s", options.Filter.Zones.Include, err)
649 }
650
651 for i, node := range nodes {
652 // For hostnames we always match on an empty filter
653 if len(includeHosts) >= 0 && matchedFilter(includeHosts, node.Hostname()) {
654
655 // For zones we don't match on an empty filter
656 if len(includeZones) >= 0 && matchedFilter(includeZones, node.Zone()) {
657 err := ProcessNode(client, node, options)
658 if err != nil {
659 errors[i] = err
660 } else {
661 errors[i] = nil
662 }
663 } else {
664 if options.Verbose {
665 log.Printf("[info] ignoring node '%s' as its zone '%s' didn't match include zone name filter '%v'",
666 node.Hostname(), node.Zone(), options.Filter.Zones.Include)
667 }
668 }
669 } else {
670 if options.Verbose {
671 log.Printf("[info] ignoring node '%s' as it didn't match include hostname filter '%v'",
672 node.Hostname(), options.Filter.Hosts.Include)
673 }
674 }
675 }
676 return errors
677}