forked from go-goose/goose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_http.go
1380 lines (1310 loc) · 38.3 KB
/
service_http.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
// Nova double testing service - HTTP API implementation
package novaservice
import (
"crypto/rand"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"path"
"regexp"
"strconv"
"strings"
"time"
"gopkg.in/niedbalski/goose.v3/neutron"
"gopkg.in/niedbalski/goose.v3/nova"
"gopkg.in/niedbalski/goose.v3/testservices"
"gopkg.in/niedbalski/goose.v3/testservices/identityservice"
)
const authToken = "X-Auth-Token"
// errorResponse defines a single HTTP error response.
type errorResponse struct {
code int
body string
contentType string
errorText string
headers map[string]string
nova *Nova
}
var (
regexpVolumeAttachmentDevice = regexp.MustCompile("(^/dev/x{0,1}[a-z]{0,1}d{0,1})([a-z]+)[0-9]*$")
)
// verbatim real Nova responses (as errors).
var (
errUnauthorized = &errorResponse{
http.StatusUnauthorized,
`401 Unauthorized
This server could not verify that you are authorized to access the ` +
`document you requested. Either you supplied the wrong ` +
`credentials (e.g., bad password), or your browser does ` +
`not understand how to supply the credentials required.
Authentication required
`,
"text/plain; charset=UTF-8",
"unauthorized request",
nil,
nil,
}
errForbidden = &errorResponse{
http.StatusForbidden,
`{"forbidden": {"message": "Policy doesn't allow compute_extension:` +
`flavormanage to be performed.", "code": 403}}`,
"application/json; charset=UTF-8",
"forbidden flavors request",
nil,
nil,
}
errBadRequest = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "Malformed request url", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request base path or URL",
nil,
nil,
}
errBadRequest2 = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "The server could not comply with the ` +
`request since it is either malformed or otherwise incorrect.", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request URL",
nil,
nil,
}
errBadRequest3 = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "Malformed request body", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request body",
nil,
nil,
}
errBadRequestDuplicateValue = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "entity already exists", "code": 400}}`,
"application/json; charset=UTF-8",
"duplicate value",
nil,
nil,
}
errBadRequestSrvName = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "Server name is not defined", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request - missing server name",
nil,
nil,
}
errBadRequestSrvFlavor = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "Missing flavorRef attribute", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request - missing flavorRef",
nil,
nil,
}
errBadRequestSrvImage = &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "Missing imageRef attribute", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request - missing imageRef",
nil,
nil,
}
errNotFound = &errorResponse{
http.StatusNotFound,
`404 Not Found
The resource could not be found.
`,
"text/plain; charset=UTF-8",
"resource not found",
nil,
nil,
}
errNotFoundJSON = &errorResponse{
http.StatusNotFound,
`{"itemNotFound": {"message": "The resource could not be found.", "code": 404}}`,
"application/json; charset=UTF-8",
"resource not found",
nil,
nil,
}
errNotFoundJSONSG = &errorResponse{
http.StatusNotFound,
`{"itemNotFound": {"message": "Security group $ID$ not found.", "code": 404}}`,
"application/json; charset=UTF-8",
"",
nil,
nil,
}
errNotFoundJSONSGR = &errorResponse{
http.StatusNotFound,
`{"itemNotFound": {"message": "Rule ($ID$) not found.", "code": 404}}`,
"application/json; charset=UTF-8",
"security rule not found",
nil,
nil,
}
errMultipleChoices = &errorResponse{
http.StatusMultipleChoices,
`{"choices": [{"status": "CURRENT", "media-types": [{"base": ` +
`"application/xml", "type": "application/vnd.openstack.compute+` +
`xml;version=2"}, {"base": "application/json", "type": "application/` +
`vnd.openstack.compute+json;version=2"}], "id": "v2.0", "links": ` +
`[{"href": "$ENDPOINT$$URL$", "rel": "self"}]}]}`,
"application/json",
"multiple URL redirection choices",
nil,
nil,
}
errNoVersion = &errorResponse{
http.StatusOK,
`{"versions": [` +
`{"id": "v2.0", "links": [{"href": "v2", "rel": "self"}], "status": "SUPPORTED", "updated": "2011-01-21T11:33:21Z"}]}`,
"application/json",
"no version specified in URL",
nil,
nil,
}
errVersionsLinks = &errorResponse{
http.StatusOK,
`{"version": {"status": "CURRENT", "updated": "2011-01-21T11` +
`:33:21Z", "media-types": [{"base": "application/xml", "type": ` +
`"application/vnd.openstack.compute+xml;version=2"}, {"base": ` +
`"application/json", "type": "application/vnd.openstack.compute` +
`+json;version=2"}], "id": "v2.0", "links": [{"href": "$ENDPOINT$"` +
`, "rel": "self"}, {"href": "http://docs.openstack.org/api/openstack` +
`-compute/1.1/os-compute-devguide-1.1.pdf", "type": "application/pdf` +
`", "rel": "describedby"}, {"href": "http://docs.openstack.org/api/` +
`openstack-compute/1.1/wadl/os-compute-1.1.wadl", "type": ` +
`"application/vnd.sun.wadl+xml", "rel": "describedby"}]}}`,
"application/json",
"version missing from URL",
nil,
nil,
}
errNotImplemented = &errorResponse{
http.StatusNotImplemented,
"501 Not Implemented",
"text/plain; charset=UTF-8",
"not implemented",
nil,
nil,
}
errNoGroupId = &errorResponse{
errorText: "no security group id given",
}
errRateLimitExceeded = &errorResponse{
http.StatusRequestEntityTooLarge,
"",
"text/plain; charset=UTF-8",
"too many requests",
// RFC says that Retry-After should be an int, but we don't want to wait an entire second during the test suite.
map[string]string{"Retry-After": "0.001"},
nil,
}
errMaxRequestRateExceeded = &errorResponse{
http.StatusServiceUnavailable,
"",
"text/plain; charset=UTF-8",
"The maximum request receiving rate is exceeded",
// RFC says that Retry-After should be an int, but we don't want to wait an entire second during the test suite.
map[string]string{"Retry-After": "0.001"},
nil,
}
errTooManyRequests = &errorResponse{
http.StatusTooManyRequests,
"",
"text/plain; charset=UTF-8",
"too man requests",
// RFC says that Retry-After should be an int, but we don't want to wait an entire second during the test suite.
map[string]string{"Retry-After": "0.001"},
nil,
}
errForbiddenRetryAfter = &errorResponse{
http.StatusForbidden,
"",
"text/plain; charset=UTF-8",
"Forbidden, please retry",
// RFC says that Retry-After should be an int, but we don't want to wait an entire second during the test suite.
map[string]string{"Retry-After": "0.001"},
nil,
}
errNoMoreFloatingIPs = &errorResponse{
http.StatusNotFound,
"Zero floating ips available.",
"text/plain; charset=UTF-8",
"zero floating ips available",
nil,
nil,
}
errIPLimitExceeded = &errorResponse{
http.StatusRequestEntityTooLarge,
"Maximum number of floating ips exceeded.",
"text/plain; charset=UTF-8",
"maximum number of floating ips exceeded",
nil,
nil,
}
)
func (e *errorResponse) Error() string {
return e.errorText
}
// requestBody returns the body for the error response, replacing
// $ENDPOINT$, $URL$, $ID$, and $ERROR$ in e.body with the values from
// the request.
func (e *errorResponse) requestBody(r *http.Request) []byte {
url := strings.TrimLeft(r.URL.Path, "/")
body := e.body
if body != "" {
if e.nova != nil {
body = strings.Replace(body, "$ENDPOINT$", e.nova.endpointURL(true, "/"), -1)
}
body = strings.Replace(body, "$URL$", url, -1)
body = strings.Replace(body, "$ERROR$", e.Error(), -1)
if slash := strings.LastIndex(url, "/"); slash != -1 {
body = strings.Replace(body, "$ID$", url[slash+1:], -1)
}
}
return []byte(body)
}
func (e *errorResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e.contentType != "" {
w.Header().Set("Content-Type", e.contentType)
}
body := e.requestBody(r)
if e.headers != nil {
for h, v := range e.headers {
w.Header().Set(h, v)
}
}
// workaround for https://code.google.com/p/go/issues/detail?id=4454
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
if e.code != 0 {
w.WriteHeader(e.code)
}
if len(body) > 0 {
w.Write(body)
}
}
type novaHandler struct {
n *Nova
method func(n *Nova, w http.ResponseWriter, r *http.Request) error
}
func userInfo(i identityservice.IdentityService, r *http.Request) (*identityservice.UserInfo, error) {
return i.FindUser(r.Header.Get(authToken))
}
func (h *novaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
// handle invalid X-Auth-Token header
_, err := userInfo(h.n.IdentityService, r)
if err != nil {
errUnauthorized.ServeHTTP(w, r)
return
}
// handle trailing slash in the path
if strings.HasSuffix(path, "/") && path != "/" {
errNotFound.ServeHTTP(w, r)
return
}
err = h.method(h.n, w, r)
if err == nil {
return
}
var resp http.Handler
if err == testservices.RateLimitExceededError {
resp = errRateLimitExceeded
} else if err == testservices.ServiceUnavailRateLimitError {
resp = errMaxRequestRateExceeded
} else if err == testservices.TooManyRequestsError {
resp = errTooManyRequests
} else if err == testservices.ForbiddenRateLimitError {
resp = errForbiddenRetryAfter
} else if err == testservices.NoMoreFloatingIPs {
resp = errNoMoreFloatingIPs
} else if err == testservices.IPLimitExceeded {
resp = errIPLimitExceeded
} else {
resp, _ = err.(http.Handler)
if resp == nil {
code, encodedErr := errorJSONEncode(err)
resp = &errorResponse{
code,
encodedErr,
"application/json",
err.Error(),
nil,
h.n,
}
}
}
resp.ServeHTTP(w, r)
}
func writeResponse(w http.ResponseWriter, code int, body []byte) {
// workaround for https://code.google.com/p/go/issues/detail?id=4454
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(code)
w.Write(body)
}
// sendJSON sends the specified response serialized as JSON.
func sendJSON(code int, resp interface{}, w http.ResponseWriter, r *http.Request) error {
data, err := json.Marshal(resp)
if err != nil {
return err
}
writeResponse(w, code, data)
return nil
}
func (n *Nova) handler(method func(n *Nova, w http.ResponseWriter, r *http.Request) error) http.Handler {
return &novaHandler{n, method}
}
func (n *Nova) handleRoot(w http.ResponseWriter, r *http.Request) error {
if r.URL.Path == "/" {
return errNoVersion
}
return errMultipleChoices
}
func (n *Nova) HandleRoot(w http.ResponseWriter, r *http.Request) {
n.handler((*Nova).handleRoot).ServeHTTP(w, r)
}
// handleFlavors handles the flavors HTTP API.
func (n *Nova) handleFlavors(w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case "GET":
if flavorId := path.Base(r.URL.Path); flavorId != "flavors" {
flavor, err := n.flavor(flavorId)
if err != nil {
return errNotFound
}
resp := struct {
Flavor nova.FlavorDetail `json:"flavor"`
}{*flavor}
return sendJSON(http.StatusOK, resp, w, r)
}
entities := n.allFlavorsAsEntities()
if len(entities) == 0 {
entities = []nova.Entity{}
}
resp := struct {
Flavors []nova.Entity `json:"flavors"`
}{entities}
return sendJSON(http.StatusOK, resp, w, r)
case "POST":
if flavorId := path.Base(r.URL.Path); flavorId != "flavors" {
return errNotFound
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
if len(body) == 0 {
return errBadRequest2
}
return errNotImplemented
case "PUT":
if flavorId := path.Base(r.URL.Path); flavorId != "flavors" {
return errNotFoundJSON
}
return errNotFound
case "DELETE":
if flavorId := path.Base(r.URL.Path); flavorId != "flavors" {
return errForbidden
}
return errNotFound
}
return fmt.Errorf("unknown request method %q for %s", r.Method, r.URL.Path)
}
// handleFlavorsDetail handles the flavors/detail HTTP API.
func (n *Nova) handleFlavorsDetail(w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case "GET":
if flavorId := path.Base(r.URL.Path); flavorId != "detail" {
return errNotFound
}
flavors := n.allFlavors()
if len(flavors) == 0 {
flavors = []nova.FlavorDetail{}
}
resp := struct {
Flavors []nova.FlavorDetail `json:"flavors"`
}{flavors}
return sendJSON(http.StatusOK, resp, w, r)
case "POST":
return errNotFound
case "PUT":
if flavorId := path.Base(r.URL.Path); flavorId != "detail" {
return errNotFound
}
return errNotFoundJSON
case "DELETE":
if flavorId := path.Base(r.URL.Path); flavorId != "detail" {
return errNotFound
}
return errForbidden
}
return fmt.Errorf("unknown request method %q for %s", r.Method, r.URL.Path)
}
// handleServerActions handles the servers/<id>/action HTTP API.
func (n *Nova) handleServerActions(server *nova.ServerDetail, w http.ResponseWriter, r *http.Request) error {
if server == nil {
return errNotFound
}
body, err := ioutil.ReadAll(r.Body)
if err != nil || len(body) == 0 {
return errNotFound
}
var action struct {
AddSecurityGroup *struct {
Name string
}
RemoveSecurityGroup *struct {
Name string
}
AddFloatingIP *struct {
Address string
}
RemoveFloatingIP *struct {
Address string
}
}
if err := json.Unmarshal(body, &action); err != nil {
return err
}
switch {
case action.AddSecurityGroup != nil:
name := action.AddSecurityGroup.Name
group, err := n.securityGroupByName(name)
if err != nil || n.hasServerSecurityGroup(server.Id, group.Id) {
return errNotFound
}
if err := n.addServerSecurityGroup(server.Id, group.Id); err != nil {
return err
}
writeResponse(w, http.StatusAccepted, nil)
return nil
case action.RemoveSecurityGroup != nil:
name := action.RemoveSecurityGroup.Name
group, err := n.securityGroupByName(name)
if err != nil || !n.hasServerSecurityGroup(server.Id, group.Id) {
return errNotFound
}
if err := n.removeServerSecurityGroup(server.Id, group.Id); err != nil {
return err
}
writeResponse(w, http.StatusAccepted, nil)
return nil
case action.AddFloatingIP != nil:
addr := action.AddFloatingIP.Address
if n.hasServerFloatingIP(server.Id, addr) {
return errNotFound
}
fip, err := n.floatingIPByAddr(addr)
if err != nil {
return errNotFound
}
if err := n.addServerFloatingIP(server.Id, fip.Id); err != nil {
return err
}
writeResponse(w, http.StatusAccepted, nil)
return nil
case action.RemoveFloatingIP != nil:
addr := action.RemoveFloatingIP.Address
if !n.hasServerFloatingIP(server.Id, addr) {
return errNotFound
}
fip, err := n.floatingIPByAddr(addr)
if err != nil {
return errNotFound
}
if err := n.removeServerFloatingIP(server.Id, fip.Id); err != nil {
return err
}
writeResponse(w, http.StatusAccepted, nil)
return nil
}
return fmt.Errorf("unknown server action: %q", string(body))
}
// handleServerMetadata handles the servers/<id>/action HTTP API.
func (n *Nova) handleServerMetadata(server *nova.ServerDetail, w http.ResponseWriter, r *http.Request) error {
if server == nil {
return errNotFound
}
body, err := ioutil.ReadAll(r.Body)
if err != nil || len(body) == 0 {
return errNotFound
}
var req struct {
Metadata map[string]string `json:"metadata"`
}
if err := json.Unmarshal(body, &req); err != nil {
return err
}
if err := n.setServerMetadata(server.Id, req.Metadata); err != nil {
return err
}
writeResponse(w, http.StatusOK, nil)
return nil
}
// newUUID generates a random UUID conforming to RFC 4122.
func newUUID() (string, error) {
uuid := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, uuid); err != nil {
return "", err
}
uuid[8] = uuid[8]&^0xc0 | 0x80 // variant bits; see section 4.1.1.
uuid[6] = uuid[6]&^0xf0 | 0x40 // version 4; see section 4.1.3.
return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}
// noGroupError constructs a bad request response for an invalid group.
func noGroupError(groupName, tenantId string) error {
return &errorResponse{
http.StatusBadRequest,
`{"badRequest": {"message": "Security group ` + groupName + ` not found for project ` + tenantId + `.", "code": 400}}`,
"application/json; charset=UTF-8",
"bad request URL",
nil,
nil,
}
}
// handleRunServer handles creating and running a server.
func (n *Nova) handleRunServer(body []byte, w http.ResponseWriter, r *http.Request) error {
var req struct {
Server struct {
FlavorRef string
ImageRef string
Name string
Metadata map[string]string
SecurityGroups []map[string]string `json:"security_groups"`
Networks []map[string]string
AvailabilityZone string `json:"availability_zone"`
}
}
if err := json.Unmarshal(body, &req); err != nil {
return errBadRequest3
}
if req.Server.Name == "" {
return errBadRequestSrvName
}
if req.Server.ImageRef == "" {
return errBadRequestSrvImage
}
if req.Server.FlavorRef == "" {
return errBadRequestSrvFlavor
}
if az := req.Server.AvailabilityZone; az != "" {
if !n.availabilityZones[az].State.Available {
return testservices.AvailabilityZoneIsNotAvailable
}
}
n.nextServerId++
id := strconv.Itoa(n.nextServerId)
uuid, err := newUUID()
if err != nil {
return err
}
// TODO(gz) some kind of sane handling of networks
// only networks with sub-nets should be used for boot
createSecurityGroups := true
for _, net := range req.Server.Networks {
var netPortSecurity *neutron.NetworkV2
var err error
if n.useNeutronNetworking {
netPortSecurity, err = n.neutronModel.Network(net["uuid"])
if err != nil {
return errNotFoundJSON
}
if createSecurityGroups && netPortSecurity.PortSecurityEnabled != nil {
createSecurityGroups = *netPortSecurity.PortSecurityEnabled
}
} else {
_, err = n.network(net["uuid"])
if err != nil {
return errNotFoundJSON
}
}
}
// TODO: (hml) - 2017-04-26
// If the test server had state for an instance, if createSecurityGroups is
// false and req.Server.SecurityGroups > 0, during the "build" process instance
// state should be set to ERROR and a server.fault should be filled in.
// Related to neutron network.port_security_enabled.
var groups []string
if len(req.Server.SecurityGroups) > 0 && createSecurityGroups {
for _, group := range req.Server.SecurityGroups {
groupName := group["name"]
if sg, err := n.securityGroupByName(groupName); err != nil {
return noGroupError(groupName, n.TenantId)
} else {
groups = append(groups, sg.Id)
}
}
}
// TODO(dimitern) - 2013-02-11 bug=1121684
// make sure flavor/image exist (if needed)
flavor := nova.FlavorDetail{Id: req.Server.FlavorRef}
n.buildFlavorLinks(&flavor)
flavorEnt := nova.Entity{Id: flavor.Id, Links: flavor.Links}
image := nova.Entity{Id: req.Server.ImageRef}
timestr := time.Now().Format(time.RFC3339)
userInfo, _ := userInfo(n.IdentityService, r)
server := nova.ServerDetail{
Id: id,
UUID: uuid,
Name: req.Server.Name,
TenantId: n.TenantId,
UserId: userInfo.Id,
HostId: "1",
Image: image,
Flavor: flavorEnt,
Status: nova.StatusBuild,
Created: timestr,
Updated: timestr,
Addresses: make(map[string][]nova.IPAddress),
AvailabilityZone: req.Server.AvailabilityZone,
Metadata: req.Server.Metadata,
}
servers, err := n.allServers(nil)
if err != nil {
return err
}
nextServer := len(servers) + 1
n.buildServerLinks(&server)
// set some IP addresses
addr := fmt.Sprintf("127.10.0.%d", nextServer)
server.Addresses["public"] = []nova.IPAddress{{4, addr, "fixed"}, {6, "::dead:beef:f00d", "fixed"}}
addr = fmt.Sprintf("127.0.0.%d", nextServer)
server.Addresses["private"] = []nova.IPAddress{{4, addr, "fixed"}, {6, "::face::000f", "fixed"}}
if err := n.addServer(server); err != nil {
return err
}
var resp struct {
Server struct {
SecurityGroups []map[string]string `json:"security_groups"`
Id string `json:"id"`
Links []nova.Link `json:"links"`
AdminPass string `json:"adminPass"`
} `json:"server"`
}
if len(req.Server.SecurityGroups) > 0 {
for _, gid := range groups {
if err := n.addServerSecurityGroup(id, gid); err != nil {
return err
}
}
resp.Server.SecurityGroups = req.Server.SecurityGroups
} else {
if createSecurityGroups {
resp.Server.SecurityGroups = []map[string]string{{"name": "default"}}
} else {
resp.Server.SecurityGroups = []map[string]string{{}}
}
}
resp.Server.Id = id
resp.Server.Links = server.Links
resp.Server.AdminPass = "secret"
return sendJSON(http.StatusAccepted, resp, w, r)
}
// handleServers handles the servers HTTP API.
func (n *Nova) handleServers(w http.ResponseWriter, r *http.Request) error {
if strings.Contains(r.URL.Path, "os-volume_attachments") {
switch r.Method {
case "GET":
return n.handleListVolumes(w, r)
case "POST":
return n.handleAttachVolumes(w, r)
case "DELETE":
return n.handleDetachVolumes(w, r)
}
}
switch r.Method {
case "GET":
if suffix := path.Base(r.URL.Path); suffix != "servers" {
groups := false
serverId := ""
if suffix == "os-security-groups" {
// handle GET /servers/<id>/os-security-groups
serverId = path.Base(strings.Replace(r.URL.Path, "/os-security-groups", "", 1))
groups = true
} else {
serverId = suffix
}
server, err := n.server(serverId)
if err != nil {
return err
}
if groups {
srvGroups := n.allServerSecurityGroups(serverId)
if len(srvGroups) == 0 {
srvGroups = []nova.SecurityGroup{}
}
resp := struct {
Groups []nova.SecurityGroup `json:"security_groups"`
}{srvGroups}
return sendJSON(http.StatusOK, resp, w, r)
}
resp := struct {
Server nova.ServerDetail `json:"server"`
}{*server}
return sendJSON(http.StatusOK, resp, w, r)
}
f := make(filter)
if err := r.ParseForm(); err == nil && len(r.Form) > 0 {
for filterKey, filterValues := range r.Form {
for _, value := range filterValues {
f[filterKey] = value
}
}
}
entities, err := n.allServersAsEntities(f)
if err != nil {
return err
}
if len(entities) == 0 {
entities = []nova.Entity{}
}
resp := struct {
Servers []nova.Entity `json:"servers"`
}{entities}
return sendJSON(http.StatusOK, resp, w, r)
case "POST":
if suffix := path.Base(r.URL.Path); suffix != "servers" {
serverId := ""
if suffix == "action" {
// handle POST /servers/<id>/action
serverId = path.Base(strings.Replace(r.URL.Path, "/action", "", 1))
server, _ := n.server(serverId)
return n.handleServerActions(server, w, r)
} else if suffix == "metadata" {
// handle POST /servers/<id>/metadata
serverId = path.Base(strings.Replace(r.URL.Path, "/metadata", "", 1))
server, _ := n.server(serverId)
return n.handleServerMetadata(server, w, r)
} else {
serverId = suffix
}
return errNotFound
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
if len(body) == 0 {
return errBadRequest2
}
return n.handleRunServer(body, w, r)
case "PUT":
serverId := path.Base(r.URL.Path)
if serverId == "servers" {
return errNotFound
}
var req struct {
Server struct {
Name string `json:"name"`
} `json:"server"`
}
body, err := ioutil.ReadAll(r.Body)
if err != nil || len(body) == 0 {
return errBadRequest2
}
if err := json.Unmarshal(body, &req); err != nil {
return err
}
err = n.updateServerName(serverId, req.Server.Name)
if err != nil {
return err
}
server, err := n.server(serverId)
if err != nil {
return err
}
var resp struct {
Server nova.ServerDetail `json:"server"`
}
resp.Server = *server
return sendJSON(http.StatusOK, resp, w, r)
case "DELETE":
if serverId := path.Base(r.URL.Path); serverId != "servers" {
if _, err := n.server(serverId); err != nil {
return errNotFoundJSON
}
if err := n.removeServer(serverId); err != nil {
return err
}
writeResponse(w, http.StatusNoContent, nil)
return nil
}
return errNotFound
}
return fmt.Errorf("unknown request method %q for %s", r.Method, r.URL.Path)
}
// handleServersDetail handles the servers/detail HTTP API.
func (n *Nova) handleServersDetail(w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case "GET":
if serverId := path.Base(r.URL.Path); serverId != "detail" {
return errNotFound
}
f := make(filter)
if err := r.ParseForm(); err == nil && len(r.Form) > 0 {
for filterKey, filterValues := range r.Form {
for _, value := range filterValues {
f[filterKey] = value
}
}
}
servers, err := n.allServers(f)
if err != nil {
return err
}
if len(servers) == 0 {
servers = []nova.ServerDetail{}
}
resp := struct {
Servers []nova.ServerDetail `json:"servers"`
}{servers}
return sendJSON(http.StatusOK, resp, w, r)
case "POST":
return errNotFound
case "PUT":
if serverId := path.Base(r.URL.Path); serverId != "detail" {
return errNotFound
}
return errBadRequest2
case "DELETE":
if serverId := path.Base(r.URL.Path); serverId != "detail" {
return errNotFound
}
return errNotFoundJSON
}
return fmt.Errorf("unknown request method %q for %s", r.Method, r.URL.Path)
}
// processGroupId returns the group id from the given request.
// If there was no group id specified in the path, it returns errNoGroupId
func (n *Nova) processGroupId(w http.ResponseWriter, r *http.Request) (*nova.SecurityGroup, error) {
if groupId := path.Base(r.URL.Path); groupId != "os-security-groups" {
group, err := n.securityGroup(groupId)
if err != nil {
return nil, errNotFoundJSONSG
}
return group, nil
}
return nil, errNoGroupId
}
// handleSecurityGroups handles the os-security-groups HTTP API.
func (n *Nova) handleSecurityGroups(w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case "GET":
group, err := n.processGroupId(w, r)
if err == errNoGroupId {
groups := n.allSecurityGroups()
if len(groups) == 0 {
groups = []nova.SecurityGroup{}
}
resp := struct {
Groups []nova.SecurityGroup `json:"security_groups"`
}{groups}
return sendJSON(http.StatusOK, resp, w, r)
}
if err != nil {
return err
}
resp := struct {
Group nova.SecurityGroup `json:"security_group"`
}{*group}
return sendJSON(http.StatusOK, resp, w, r)
case "POST":
if groupId := path.Base(r.URL.Path); groupId != "os-security-groups" {
return errNotFound
}
body, err := ioutil.ReadAll(r.Body)
if err != nil || len(body) == 0 {
return errBadRequest2
}
var req struct {
Group struct {
Name string
Description string
} `json:"security_group"`
}
if err := json.Unmarshal(body, &req); err != nil {
return err
} else {
_, err := n.securityGroupByName(req.Group.Name)
if err == nil {
return errBadRequestDuplicateValue
}
n.nextGroupId++
nextId := strconv.Itoa(n.nextGroupId)
err = n.addSecurityGroup(nova.SecurityGroup{
Id: nextId,
Name: req.Group.Name,
Description: req.Group.Description,
TenantId: n.TenantId,
})
if err != nil {
return err
}
group, err := n.securityGroup(nextId)
if err != nil {
return err
}
var resp struct {
Group nova.SecurityGroup `json:"security_group"`
}
resp.Group = *group
return sendJSON(http.StatusOK, resp, w, r)
}
case "PUT":