-
Notifications
You must be signed in to change notification settings - Fork 36
/
testservice.go
1875 lines (1722 loc) · 57 KB
/
testservice.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package gomaasapi
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/juju/mgo/v2/bson"
)
// TestMAASObject is a fake MAAS server MAASObject.
type TestMAASObject struct {
MAASObject
TestServer *TestServer
}
// checkError is a shorthand helper that panics if err is not nil.
func checkError(err error) {
if err != nil {
panic(err)
}
}
// NewTestMAAS returns a TestMAASObject that implements the MAASObject
// interface and thus can be used as a test object instead of the one returned
// by gomaasapi.NewMAAS().
func NewTestMAAS(version string) *TestMAASObject {
server := NewTestServer(version)
authClient, err := NewAnonymousClient(server.URL, version)
checkError(err)
maas := NewMAAS(*authClient)
return &TestMAASObject{*maas, server}
}
// Close shuts down the test server.
func (testMAASObject *TestMAASObject) Close() {
testMAASObject.TestServer.Close()
}
// A TestServer is an HTTP server listening on a system-chosen port on the
// local loopback interface, which simulates the behavior of a MAAS server.
// It is intendend for use in end-to-end HTTP tests using the gomaasapi
// library.
type TestServer struct {
*httptest.Server
serveMux *http.ServeMux
client Client
nodes map[string]MAASObject
ownedNodes map[string]bool
// mapping system_id -> list of operations performed.
nodeOperations map[string][]string
// list of operations performed at the /nodes/ level.
nodesOperations []string
// mapping system_id -> list of Values passed when performing
// operations
nodeOperationRequestValues map[string][]url.Values
// list of Values passed when performing operations at the
// /nodes/ level.
nodesOperationRequestValues []url.Values
nodeMetadata map[string]Node
files map[string]MAASObject
networks map[string]MAASObject
networksPerNode map[string][]string
ipAddressesPerNetwork map[string][]string
version string
macAddressesPerNetwork map[string]map[string]JSONObject
tagsPerNode map[string][]string
nodeDetails map[string]string
zones map[string]JSONObject
tags map[string]JSONObject
// bootImages is a map of nodegroup UUIDs to boot-image objects.
bootImages map[string][]JSONObject
// nodegroupsInterfaces is a map of nodegroup UUIDs to interface
// objects.
nodegroupsInterfaces map[string][]JSONObject
// versionJSON is the response to the /version/ endpoint listing the
// capabilities of the MAAS server.
versionJSON string
// devices is a map of device UUIDs to devices.
devices map[string]*TestDevice
subnets map[uint]TestSubnet
subnetNameToID map[string]uint
nextSubnet uint
spaces map[uint]*TestSpace
spaceNameToID map[string]uint
nextSpace uint
vlans map[int]TestVLAN
nextVLAN int
staticRoutes map[uint]*TestStaticRoute
nextStaticRoute uint
}
type TestDevice struct {
IPAddresses []string
SystemId string
MACAddresses []string
Parent string
Hostname string
// Not part of the device definition but used by the template.
APIVersion string
}
func getNodesEndpoint(version string) string {
return fmt.Sprintf("/api/%s/nodes/", version)
}
func getNodeURL(version, systemId string) string {
return fmt.Sprintf("/api/%s/nodes/%s/", version, systemId)
}
func getNodeURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/nodes/([^/]*)/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
func getDevicesEndpoint(version string) string {
return fmt.Sprintf("/api/%s/devices/", version)
}
func getDeviceURL(version, systemId string) string {
return fmt.Sprintf("/api/%s/devices/%s/", version, systemId)
}
func getDeviceURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/devices/([^/]*)/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
func getFilesEndpoint(version string) string {
return fmt.Sprintf("/api/%s/files/", version)
}
func getFileURL(version, filename string) string {
// Uses URL object so filename is correctly percent-escaped
url := url.URL{}
url.Path = fmt.Sprintf("/api/%s/files/%s/", version, filename)
return url.String()
}
func getFileURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/files/(.*)/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
func getNetworksEndpoint(version string) string {
return fmt.Sprintf("/api/%s/networks/", version)
}
func getNetworkURL(version, name string) string {
return fmt.Sprintf("/api/%s/networks/%s/", version, name)
}
func getNetworkURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/networks/(.*)/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
func getIPAddressesEndpoint(version string) string {
return fmt.Sprintf("/api/%s/ipaddresses/", version)
}
func getMACAddressURL(version, systemId, macAddress string) string {
return fmt.Sprintf("/api/%s/nodes/%s/macs/%s/", version, systemId, url.QueryEscape(macAddress))
}
func getVersionURL(version string) string {
return fmt.Sprintf("/api/%s/version/", version)
}
func getNodegroupsEndpoint(version string) string {
return fmt.Sprintf("/api/%s/nodegroups/", version)
}
func getNodegroupURL(version, uuid string) string {
return fmt.Sprintf("/api/%s/nodegroups/%s/", version, uuid)
}
func getNodegroupsInterfacesURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/nodegroups/([^/]*)/interfaces/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
func getBootimagesURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/nodegroups/([^/]*)/boot-images/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
func getZonesEndpoint(version string) string {
return fmt.Sprintf("/api/%s/zones/", version)
}
func getTagsEndpoint(version string) string {
return fmt.Sprintf("/api/%s/tags/", version)
}
func getTagURL(version, tag_name string) string {
return fmt.Sprintf("/api/%s/tags/%s/", version, tag_name)
}
func getTagURLRE(version string) *regexp.Regexp {
reString := fmt.Sprintf("^/api/%s/tags/([^/]*)/$", regexp.QuoteMeta(version))
return regexp.MustCompile(reString)
}
// Clear clears all the fake data stored and recorded by the test server
// (nodes, recorded operations, etc.).
func (server *TestServer) Clear() {
server.nodes = make(map[string]MAASObject)
server.ownedNodes = make(map[string]bool)
server.nodesOperations = make([]string, 0)
server.nodeOperations = make(map[string][]string)
server.nodesOperationRequestValues = make([]url.Values, 0)
server.nodeOperationRequestValues = make(map[string][]url.Values)
server.nodeMetadata = make(map[string]Node)
server.files = make(map[string]MAASObject)
server.networks = make(map[string]MAASObject)
server.networksPerNode = make(map[string][]string)
server.ipAddressesPerNetwork = make(map[string][]string)
server.tagsPerNode = make(map[string][]string)
server.macAddressesPerNetwork = make(map[string]map[string]JSONObject)
server.nodeDetails = make(map[string]string)
server.bootImages = make(map[string][]JSONObject)
server.nodegroupsInterfaces = make(map[string][]JSONObject)
server.zones = make(map[string]JSONObject)
server.tags = make(map[string]JSONObject)
server.versionJSON = `{"capabilities": ["networks-management","static-ipaddresses","devices-management","network-deployment-ubuntu"]}`
server.devices = make(map[string]*TestDevice)
server.subnets = make(map[uint]TestSubnet)
server.subnetNameToID = make(map[string]uint)
server.nextSubnet = 1
server.spaces = make(map[uint]*TestSpace)
server.spaceNameToID = make(map[string]uint)
server.nextSpace = 1
server.vlans = make(map[int]TestVLAN)
server.nextVLAN = 1
server.staticRoutes = make(map[uint]*TestStaticRoute)
server.nextStaticRoute = 1
}
// SetVersionJSON sets the JSON response (capabilities) returned from the
// /version/ endpoint.
func (server *TestServer) SetVersionJSON(json string) {
server.versionJSON = json
}
// NodesOperations returns the list of operations performed at the /nodes/
// level.
func (server *TestServer) NodesOperations() []string {
return server.nodesOperations
}
// NodeOperations returns the map containing the list of the operations
// performed for each node.
func (server *TestServer) NodeOperations() map[string][]string {
return server.nodeOperations
}
// NodesOperationRequestValues returns the list of url.Values extracted
// from the request used when performing operations at the /nodes/ level.
func (server *TestServer) NodesOperationRequestValues() []url.Values {
return server.nodesOperationRequestValues
}
// NodeOperationRequestValues returns the map containing the list of the
// url.Values extracted from the request used when performing operations
// on nodes.
func (server *TestServer) NodeOperationRequestValues() map[string][]url.Values {
return server.nodeOperationRequestValues
}
func parseRequestValues(request *http.Request) url.Values {
var requestValues url.Values
if request.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
if request.PostForm == nil {
if err := request.ParseForm(); err != nil {
panic(err)
}
}
requestValues = request.PostForm
}
return requestValues
}
func (server *TestServer) addNodesOperation(operation string, request *http.Request) url.Values {
requestValues := parseRequestValues(request)
server.nodesOperations = append(server.nodesOperations, operation)
server.nodesOperationRequestValues = append(server.nodesOperationRequestValues, requestValues)
return requestValues
}
func (server *TestServer) addNodeOperation(systemId, operation string, request *http.Request) url.Values {
operations, present := server.nodeOperations[systemId]
operationRequestValues, present2 := server.nodeOperationRequestValues[systemId]
if present != present2 {
panic("inconsistent state: nodeOperations and nodeOperationRequestValues don't have the same keys.")
}
requestValues := parseRequestValues(request)
if !present {
operations = []string{operation}
operationRequestValues = []url.Values{requestValues}
} else {
operations = append(operations, operation)
operationRequestValues = append(operationRequestValues, requestValues)
}
server.nodeOperations[systemId] = operations
server.nodeOperationRequestValues[systemId] = operationRequestValues
return requestValues
}
// NewNode creates a MAAS node. The provided string should be a valid json
// string representing a map and contain a string value for the key
// 'system_id'. e.g. `{"system_id": "mysystemid"}`.
// If one of these conditions is not met, NewNode panics.
func (server *TestServer) NewNode(jsonText string) MAASObject {
var attrs map[string]interface{}
err := json.Unmarshal([]byte(jsonText), &attrs)
checkError(err)
systemIdEntry, hasSystemId := attrs["system_id"]
if !hasSystemId {
panic("The given map json string does not contain a 'system_id' value.")
}
systemId := systemIdEntry.(string)
attrs[resourceURI] = getNodeURL(server.version, systemId)
if _, hasStatus := attrs["status"]; !hasStatus {
attrs["status"] = NodeStatusDeployed
}
obj := newJSONMAASObject(attrs, server.client)
server.nodes[systemId] = obj
return obj
}
// Nodes returns a map associating all the nodes' system ids with the nodes'
// objects.
func (server *TestServer) Nodes() map[string]MAASObject {
return server.nodes
}
// OwnedNodes returns a map whose keys represent the nodes that are currently
// allocated.
func (server *TestServer) OwnedNodes() map[string]bool {
return server.ownedNodes
}
// NewFile creates a file in the test MAAS server.
func (server *TestServer) NewFile(filename string, filecontent []byte) MAASObject {
attrs := make(map[string]interface{})
attrs[resourceURI] = getFileURL(server.version, filename)
base64Content := base64.StdEncoding.EncodeToString(filecontent)
attrs["content"] = base64Content
attrs["filename"] = filename
// Allocate an arbitrary URL here. It would be nice if the caller
// could do this, but that would change the API and require many
// changes.
escapedName := url.QueryEscape(filename)
attrs["anon_resource_uri"] = "/maas/1.0/files/?op=get_by_key&key=" + escapedName + "_key"
obj := newJSONMAASObject(attrs, server.client)
server.files[filename] = obj
return obj
}
func (server *TestServer) Files() map[string]MAASObject {
return server.files
}
// ChangeNode updates a node with the given key/value.
func (server *TestServer) ChangeNode(systemId, key, value string) {
node, found := server.nodes[systemId]
if !found {
panic("No node with such 'system_id'.")
}
node.GetMap()[key] = maasify(server.client, value)
}
// NewIPAddress creates a new static IP address reservation for the
// given network/subnet and ipAddress. While networks is being deprecated
// try the given name as both a netowrk and a subnet.
func (server *TestServer) NewIPAddress(ipAddress, networkOrSubnet string) {
_, foundNetwork := server.networks[networkOrSubnet]
subnetID, foundSubnet := server.subnetNameToID[networkOrSubnet]
if (foundNetwork || foundSubnet) == false {
panic("No such network or subnet: " + networkOrSubnet)
}
if foundNetwork {
ips, found := server.ipAddressesPerNetwork[networkOrSubnet]
if found {
ips = append(ips, ipAddress)
} else {
ips = []string{ipAddress}
}
server.ipAddressesPerNetwork[networkOrSubnet] = ips
} else {
subnet := server.subnets[subnetID]
netIp := net.ParseIP(ipAddress)
if netIp == nil {
panic(ipAddress + " is invalid")
}
ip := IPFromNetIP(netIp)
ip.Purpose = []string{"assigned-ip"}
subnet.InUseIPAddresses = append(subnet.InUseIPAddresses, ip)
server.subnets[subnetID] = subnet
}
}
// RemoveIPAddress removes the given existing ipAddress and returns
// whether it was actually removed.
func (server *TestServer) RemoveIPAddress(ipAddress string) bool {
for network, ips := range server.ipAddressesPerNetwork {
for i, ip := range ips {
if ip == ipAddress {
ips = append(ips[:i], ips[i+1:]...)
server.ipAddressesPerNetwork[network] = ips
return true
}
}
}
for _, device := range server.devices {
for i, addr := range device.IPAddresses {
if addr == ipAddress {
device.IPAddresses = append(device.IPAddresses[:i], device.IPAddresses[i+1:]...)
return true
}
}
}
return false
}
// IPAddresses returns the map with network names as keys and slices
// of IP addresses belonging to each network as values.
func (server *TestServer) IPAddresses() map[string][]string {
return server.ipAddressesPerNetwork
}
// NewNetwork creates a network in the test MAAS server
func (server *TestServer) NewNetwork(jsonText string) MAASObject {
var attrs map[string]interface{}
err := json.Unmarshal([]byte(jsonText), &attrs)
checkError(err)
nameEntry, hasName := attrs["name"]
_, hasIP := attrs["ip"]
_, hasNetmask := attrs["netmask"]
if !hasName || !hasIP || !hasNetmask {
panic("The given map json string does not contain a 'name', 'ip', or 'netmask' value.")
}
// TODO(gz): Sanity checking done on other fields
name := nameEntry.(string)
attrs[resourceURI] = getNetworkURL(server.version, name)
obj := newJSONMAASObject(attrs, server.client)
server.networks[name] = obj
return obj
}
// NewNodegroupInterface adds a nodegroup-interface, for the specified
// nodegroup, in the test MAAS server.
func (server *TestServer) NewNodegroupInterface(uuid, jsonText string) JSONObject {
_, ok := server.bootImages[uuid]
if !ok {
panic("no nodegroup with the given UUID")
}
var attrs map[string]interface{}
err := json.Unmarshal([]byte(jsonText), &attrs)
checkError(err)
requiredMembers := []string{"ip_range_high", "ip_range_low", "broadcast_ip", "static_ip_range_low", "static_ip_range_high", "name", "ip", "subnet_mask", "management", "interface"}
for _, member := range requiredMembers {
_, hasMember := attrs[member]
if !hasMember {
panic(fmt.Sprintf("The given map json string does not contain a required %q", member))
}
}
obj := maasify(server.client, attrs)
server.nodegroupsInterfaces[uuid] = append(server.nodegroupsInterfaces[uuid], obj)
return obj
}
func (server *TestServer) ConnectNodeToNetwork(systemId, name string) {
_, hasNode := server.nodes[systemId]
if !hasNode {
panic("no node with the given system id")
}
_, hasNetwork := server.networks[name]
if !hasNetwork {
panic("no network with the given name")
}
networkNames, _ := server.networksPerNode[systemId]
server.networksPerNode[systemId] = append(networkNames, name)
}
func (server *TestServer) ConnectNodeToNetworkWithMACAddress(systemId, networkName, macAddress string) {
node, hasNode := server.nodes[systemId]
if !hasNode {
panic("no node with the given system id")
}
if _, hasNetwork := server.networks[networkName]; !hasNetwork {
panic("no network with the given name")
}
networkNames, _ := server.networksPerNode[systemId]
server.networksPerNode[systemId] = append(networkNames, networkName)
attrs := make(map[string]interface{})
attrs[resourceURI] = getMACAddressURL(server.version, systemId, macAddress)
attrs["mac_address"] = macAddress
array := []JSONObject{}
if set, ok := node.GetMap()["macaddress_set"]; ok {
var err error
array, err = set.GetArray()
if err != nil {
panic(err)
}
}
array = append(array, maasify(server.client, attrs))
node.GetMap()["macaddress_set"] = JSONObject{value: array, client: server.client}
if _, ok := server.macAddressesPerNetwork[networkName]; !ok {
server.macAddressesPerNetwork[networkName] = map[string]JSONObject{}
}
server.macAddressesPerNetwork[networkName][systemId] = maasify(server.client, attrs)
}
// AddBootImage adds a boot-image object to the specified nodegroup.
func (server *TestServer) AddBootImage(nodegroupUUID string, jsonText string) {
var attrs map[string]interface{}
err := json.Unmarshal([]byte(jsonText), &attrs)
checkError(err)
if _, ok := attrs["architecture"]; !ok {
panic("The boot-image json string does not contain an 'architecture' value.")
}
if _, ok := attrs["release"]; !ok {
panic("The boot-image json string does not contain a 'release' value.")
}
obj := maasify(server.client, attrs)
server.bootImages[nodegroupUUID] = append(server.bootImages[nodegroupUUID], obj)
}
// AddZone adds a physical zone to the server.
func (server *TestServer) AddZone(name, description string) {
attrs := map[string]interface{}{
"name": name,
"description": description,
}
obj := maasify(server.client, attrs)
server.zones[name] = obj
}
// AddTah adds a tag to the server.
func (server *TestServer) AddTag(name, comment string) {
attrs := map[string]interface{}{
"name": name,
"comment": comment,
resourceURI: getTagURL(server.version, name),
}
obj := maasify(server.client, attrs)
server.tags[name] = obj
}
func (server *TestServer) AddDevice(device *TestDevice) {
server.devices[device.SystemId] = device
}
func (server *TestServer) Devices() map[string]*TestDevice {
return server.devices
}
// NewTestServer starts and returns a new MAAS test server. The caller should call Close when finished, to shut it down.
func NewTestServer(version string) *TestServer {
server := &TestServer{version: version}
serveMux := http.NewServeMux()
devicesURL := getDevicesEndpoint(server.version)
// Register handler for '/api/<version>/devices/*'.
serveMux.HandleFunc(devicesURL, func(w http.ResponseWriter, r *http.Request) {
devicesHandler(server, w, r)
})
nodesURL := getNodesEndpoint(server.version)
// Register handler for '/api/<version>/nodes/*'.
serveMux.HandleFunc(nodesURL, func(w http.ResponseWriter, r *http.Request) {
nodesHandler(server, w, r)
})
filesURL := getFilesEndpoint(server.version)
// Register handler for '/api/<version>/files/*'.
serveMux.HandleFunc(filesURL, func(w http.ResponseWriter, r *http.Request) {
filesHandler(server, w, r)
})
networksURL := getNetworksEndpoint(server.version)
// Register handler for '/api/<version>/networks/'.
serveMux.HandleFunc(networksURL, func(w http.ResponseWriter, r *http.Request) {
networksHandler(server, w, r)
})
ipAddressesURL := getIPAddressesEndpoint(server.version)
// Register handler for '/api/<version>/ipaddresses/'.
serveMux.HandleFunc(ipAddressesURL, func(w http.ResponseWriter, r *http.Request) {
ipAddressesHandler(server, w, r)
})
versionURL := getVersionURL(server.version)
// Register handler for '/api/<version>/version/'.
serveMux.HandleFunc(versionURL, func(w http.ResponseWriter, r *http.Request) {
versionHandler(server, w, r)
})
// Register handler for '/api/<version>/nodegroups/*'.
nodegroupsURL := getNodegroupsEndpoint(server.version)
serveMux.HandleFunc(nodegroupsURL, func(w http.ResponseWriter, r *http.Request) {
nodegroupsHandler(server, w, r)
})
// Register handler for '/api/<version>/zones/*'.
zonesURL := getZonesEndpoint(server.version)
serveMux.HandleFunc(zonesURL, func(w http.ResponseWriter, r *http.Request) {
zonesHandler(server, w, r)
})
// Register handler for '/api/<version>/zones/*'.
tagsURL := getTagsEndpoint(server.version)
serveMux.HandleFunc(tagsURL, func(w http.ResponseWriter, r *http.Request) {
tagsHandler(server, w, r)
})
subnetsURL := getSubnetsEndpoint(server.version)
serveMux.HandleFunc(subnetsURL, func(w http.ResponseWriter, r *http.Request) {
subnetsHandler(server, w, r)
})
spacesURL := getSpacesEndpoint(server.version)
serveMux.HandleFunc(spacesURL, func(w http.ResponseWriter, r *http.Request) {
spacesHandler(server, w, r)
})
staticRoutesURL := getStaticRoutesEndpoint(server.version)
serveMux.HandleFunc(staticRoutesURL, func(w http.ResponseWriter, r *http.Request) {
staticRoutesHandler(server, w, r)
})
vlansURL := getVLANsEndpoint(server.version)
serveMux.HandleFunc(vlansURL, func(w http.ResponseWriter, r *http.Request) {
vlansHandler(server, w, r)
})
var mu sync.Mutex
singleFile := func(w http.ResponseWriter, req *http.Request) {
mu.Lock()
defer mu.Unlock()
serveMux.ServeHTTP(w, req)
}
newServer := httptest.NewServer(http.HandlerFunc(singleFile))
client, err := NewAnonymousClient(newServer.URL, "1.0")
checkError(err)
server.Server = newServer
server.serveMux = serveMux
server.client = *client
server.Clear()
return server
}
// devicesHandler handles requests for '/api/<version>/devices/*'.
func devicesHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
values, err := url.ParseQuery(r.URL.RawQuery)
checkError(err)
op := values.Get("op")
deviceURLRE := getDeviceURLRE(server.version)
deviceURLMatch := deviceURLRE.FindStringSubmatch(r.URL.Path)
devicesURL := getDevicesEndpoint(server.version)
switch {
case r.URL.Path == devicesURL:
devicesTopLevelHandler(server, w, r, op)
case deviceURLMatch != nil:
// Request for a single device.
deviceHandler(server, w, r, deviceURLMatch[1], op)
default:
// Default handler: not found.
http.NotFoundHandler().ServeHTTP(w, r)
}
}
// devicesTopLevelHandler handles a request for /api/<version>/devices/
// (with no device id following as part of the path).
func devicesTopLevelHandler(server *TestServer, w http.ResponseWriter, r *http.Request, op string) {
switch {
case r.Method == "GET" && op == "list":
// Device listing operation.
deviceListingHandler(server, w, r)
case r.Method == "POST" && op == "new":
newDeviceHandler(server, w, r)
default:
w.WriteHeader(http.StatusBadRequest)
}
}
func macMatches(mac string, device *TestDevice) bool {
return contains(device.MACAddresses, mac)
}
// deviceListingHandler handles requests for '/devices/'.
func deviceListingHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
values, err := url.ParseQuery(r.URL.RawQuery)
checkError(err)
// TODO(mfoord): support filtering by hostname and id
macs, hasMac := values["mac_address"]
var matchedDevices []*TestDevice
if !hasMac {
for _, device := range server.devices {
matchedDevices = append(matchedDevices, device)
}
} else {
for _, mac := range macs {
for _, device := range server.devices {
if macMatches(mac, device) {
matchedDevices = append(matchedDevices, device)
}
}
}
}
deviceChunks := make([]string, len(matchedDevices))
for i := range matchedDevices {
deviceChunks[i] = renderDevice(matchedDevices[i])
}
json := fmt.Sprintf("[%v]", strings.Join(deviceChunks, ", "))
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, json)
}
var templateFuncs = template.FuncMap{
"quotedList": func(items []string) string {
var pieces []string
for _, item := range items {
pieces = append(pieces, fmt.Sprintf("%q", item))
}
return strings.Join(pieces, ", ")
},
"last": func(items []string) []string {
if len(items) == 0 {
return []string{}
}
return items[len(items)-1:]
},
"allButLast": func(items []string) []string {
if len(items) < 2 {
return []string{}
}
return items[0 : len(items)-1]
},
}
const (
// The json template for generating new devices.
// TODO(mfoord): set resource_uri in MAC addresses
deviceTemplate = `{
"macaddress_set": [{{range .MACAddresses | allButLast}}
{
"mac_address": "{{.}}"
},{{end}}{{range .MACAddresses | last}}
{
"mac_address": "{{.}}"
}{{end}}
],
"zone": {
"resource_uri": "/MAAS/api/{{.APIVersion}}/zones/default/",
"name": "default",
"description": ""
},
"parent": "{{.Parent}}",
"ip_addresses": [{{.IPAddresses | quotedList }}],
"hostname": "{{.Hostname}}",
"tag_names": [],
"owner": "maas-admin",
"system_id": "{{.SystemId}}",
"resource_uri": "/MAAS/api/{{.APIVersion}}/devices/{{.SystemId}}/"
}`
)
func renderDevice(device *TestDevice) string {
t := template.New("Device template")
t = t.Funcs(templateFuncs)
t, err := t.Parse(deviceTemplate)
checkError(err)
var buf bytes.Buffer
err = t.Execute(&buf, device)
checkError(err)
return buf.String()
}
func getValue(values url.Values, value string) (string, bool) {
result, hasResult := values[value]
if !hasResult || len(result) != 1 || result[0] == "" {
return "", false
}
return result[0], true
}
func getValues(values url.Values, key string) ([]string, bool) {
result, hasResult := values[key]
if !hasResult {
return nil, false
}
var output []string
for _, val := range result {
if val != "" {
output = append(output, val)
}
}
if len(output) == 0 {
return nil, false
}
return output, true
}
// newDeviceHandler creates, stores and returns new devices.
func newDeviceHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
checkError(err)
values := r.PostForm
// TODO(mfood): generate a "proper" uuid for the system Id.
uuid, err := generateNonce()
checkError(err)
systemId := fmt.Sprintf("node-%v", uuid)
// At least one MAC address must be specified.
// TODO(mfoord) we only support a single MAC in the test server.
macs, hasMacs := getValues(values, "mac_addresses")
// hostname and parent are optional.
// TODO(mfoord): we require both to be set in the test server.
hostname, hasHostname := getValue(values, "hostname")
parent, hasParent := getValue(values, "parent")
if !hasHostname || !hasMacs || !hasParent {
w.WriteHeader(http.StatusBadRequest)
return
}
device := &TestDevice{
MACAddresses: macs,
APIVersion: server.version,
Parent: parent,
Hostname: hostname,
SystemId: systemId,
}
deviceJSON := renderDevice(device)
server.devices[systemId] = device
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, deviceJSON)
return
}
// deviceHandler handles requests for '/api/<version>/devices/<system_id>/'.
func deviceHandler(server *TestServer, w http.ResponseWriter, r *http.Request, systemId string, operation string) {
device, ok := server.devices[systemId]
if !ok {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
if r.Method == "GET" {
deviceJSON := renderDevice(device)
if operation == "" {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, deviceJSON)
return
} else {
w.WriteHeader(http.StatusBadRequest)
return
}
}
if r.Method == "POST" {
if operation == "claim_sticky_ip_address" {
err := r.ParseForm()
checkError(err)
values := r.PostForm
// TODO(mfoord): support optional mac_address parameter
// TODO(mfoord): requested_address should be optional
// and we should generate one if it isn't provided.
address, hasAddress := getValue(values, "requested_address")
if !hasAddress {
w.WriteHeader(http.StatusBadRequest)
return
}
checkError(err)
device.IPAddresses = append(device.IPAddresses, address)
deviceJSON := renderDevice(device)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, deviceJSON)
return
} else {
w.WriteHeader(http.StatusBadRequest)
return
}
} else if r.Method == "DELETE" {
delete(server.devices, systemId)
w.WriteHeader(http.StatusNoContent)
return
}
// TODO(mfoord): support PUT method for updating device
http.NotFoundHandler().ServeHTTP(w, r)
}
// nodesHandler handles requests for '/api/<version>/nodes/*'.
func nodesHandler(server *TestServer, w http.ResponseWriter, r *http.Request) {
values, err := url.ParseQuery(r.URL.RawQuery)
checkError(err)
op := values.Get("op")
nodeURLRE := getNodeURLRE(server.version)
nodeURLMatch := nodeURLRE.FindStringSubmatch(r.URL.Path)
nodesURL := getNodesEndpoint(server.version)
switch {
case r.URL.Path == nodesURL:
nodesTopLevelHandler(server, w, r, op)
case nodeURLMatch != nil:
// Request for a single node.
nodeHandler(server, w, r, nodeURLMatch[1], op)
default:
// Default handler: not found.
http.NotFoundHandler().ServeHTTP(w, r)
}
}
// nodeHandler handles requests for '/api/<version>/nodes/<system_id>/'.
func nodeHandler(server *TestServer, w http.ResponseWriter, r *http.Request, systemId string, operation string) {
node, ok := server.nodes[systemId]
if !ok {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
UUID, UUIDError := node.values["system_id"].GetString()
if UUIDError == nil {
i, err := JSONObjectFromStruct(server.client, server.nodeMetadata[UUID].Interfaces)
checkError(err)
node.values["interface_set"] = i
}
if r.Method == "GET" {
if operation == "" {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, marshalNode(node))
return
} else if operation == "details" {
nodeDetailsHandler(server, w, r, systemId)
return
} else {
w.WriteHeader(http.StatusBadRequest)
return
}
}
if r.Method == "POST" {
// The only operations supported are "start", "stop" and "release".
if operation == "start" || operation == "stop" || operation == "release" {
// Record operation on node.
server.addNodeOperation(systemId, operation, r)
if operation == "release" {
delete(server.OwnedNodes(), systemId)
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, marshalNode(node))
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
if r.Method == "DELETE" {
delete(server.nodes, systemId)
w.WriteHeader(http.StatusOK)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
}
func contains(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}