forked from apache/cloudstack-go
/
generate.go
1888 lines (1761 loc) · 54.4 KB
/
generate.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
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"sort"
"strings"
"unicode"
)
const pkg = "cloudstack"
// detailsRequireKeyValue is a prefilled map with a list of details
// that need to be encoded using an explicit key and a value entry.
var detailsRequireKeyValue = map[string]bool{
"addGuestOs": true,
"addImageStore": true,
"addResourceDetail": true,
"createSecondaryStagingStore": true,
"updateCloudToUseObjectStore": true,
"updateGuestOs": true,
"updateZone": true,
}
var mapRequireList = map[string]map[string]bool{
"deployVirtualMachine": map[string]bool{
"dhcpoptionsnetworklist": true,
"iptonetworklist": true,
"nicnetworklist": true,
},
"updateVirtualMachine": map[string]bool{
"dhcpoptionsnetworklist": true,
},
"migrateVirtualMachineWithVolume": map[string]bool{
"migrateto": true,
},
}
// nestedResponse is a prefilled map with the list of endpoints
// that responses fields are nested in a parent object. The map value
// gives the object field name.
var nestedResponse = map[string]string{
"getUploadParamsForTemplate": "getuploadparams",
"getUploadParamsForVolume": "getuploadparams",
}
// longToStringConvertedParams is a prefilled map with the list of
// response fields that migrated from long to string within
// the current major baseline. This fields will be parsed from
// json as string and then fallback on long.
var longToStringConvertedParams = map[string]bool{
"managementserverid": true,
}
// We prefill this one value to make sure it is not
// created twice, as this is also a top level type.
var typeNames = map[string]bool{"Nic": true}
type apiInfo map[string][]string
type allServices struct {
services services
}
type apiInfoNotFoundError struct {
api string
}
func (e *apiInfoNotFoundError) Error() string {
return fmt.Sprintf("Could not find API details for: %s", e.api)
}
type generateError struct {
service *service
error error
}
func (e *generateError) Error() string {
return fmt.Sprintf("API %s failed to generate code: %v", e.service.name, e.error)
}
type goimportError struct {
output string
}
func (e *goimportError) Error() string {
return fmt.Sprintf("GoImport failed to format:\n%v", e.output)
}
type service struct {
name string
apis []*API
p func(format string, args ...interface{}) // print raw
pn func(format string, args ...interface{}) // print with indent and newline
}
type services []*service
// Add functions for the Sort interface
func (s services) Len() int {
return len(s)
}
func (s services) Less(i, j int) bool {
return s[i].name < s[j].name
}
func (s services) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// APIParams represents a list of API params
type APIParams []*APIParam
// Len implements the Sort interface
func (s APIParams) Len() int {
return len(s)
}
// Less implements the Sort interface
func (s APIParams) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
// Swap implements the Sort interface
func (s APIParams) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// API represents an API endpoint we can call
type API struct {
Name string `json:"name"`
Description string `json:"description"`
Isasync bool `json:"isasync"`
Params APIParams `json:"params"`
Response APIResponses `json:"response"`
}
// APIParam represents a single API parameter
type APIParam struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Required bool `json:"required"`
}
// APIResponse represents a API response
type APIResponse struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Response APIResponses `json:"response"`
}
// APIResponses represents a list of API responses
type APIResponses []*APIResponse
// Len implements the Sort interface
func (s APIResponses) Len() int {
return len(s)
}
// Less implements the Sort interface
func (s APIResponses) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
// Swap implements the Sort interface
func (s APIResponses) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
listApis := flag.String("api", "listApis.json", "path to the saved JSON output of listApis")
flag.Parse()
as, errors, err := getAllServices(*listApis)
if err != nil {
log.Fatal(err)
}
if err = as.WriteGeneralCode(); err != nil {
log.Fatal(err)
}
for _, s := range as.services {
if err = s.WriteGeneratedCode(); err != nil {
errors = append(errors, &generateError{s, err})
}
}
outdir, err := sourceDir()
if err != nil {
log.Fatal(err)
}
out, err := exec.Command("goimports", "-w", outdir).CombinedOutput()
if err != nil {
errors = append(errors, &goimportError{string(out)})
}
if len(errors) > 0 {
log.Printf("%d API(s) failed to generate:", len(errors))
for _, ce := range errors {
log.Print(ce.Error())
}
os.Exit(1)
}
}
func (as *allServices) WriteGeneralCode() error {
outdir, err := sourceDir()
if err != nil {
log.Fatalf("Failed to get source dir: %s", err)
}
code, err := as.GeneralCode()
if err != nil {
return err
}
file := path.Join(outdir, "cloudstack.go")
return ioutil.WriteFile(file, code, 0644)
}
func (as *allServices) GeneralCode() ([]byte, error) {
// Buffer the output in memory, for gofmt'ing later in the defer.
var buf bytes.Buffer
p := func(format string, args ...interface{}) {
_, err := fmt.Fprintf(&buf, format, args...)
if err != nil {
panic(err)
}
}
pn := func(format string, args ...interface{}) {
p(format+"\n", args...)
}
pn("//")
pn("// Licensed to the Apache Software Foundation (ASF) under one")
pn("// or more contributor license agreements. See the NOTICE file")
pn("// distributed with this work for additional information")
pn("// regarding copyright ownership. The ASF licenses this file")
pn("// to you under the Apache License, Version 2.0 (the")
pn("// \"License\"); you may not use this file except in compliance")
pn("// with the License. You may obtain a copy of the License at")
pn("//")
pn("// http://www.apache.org/licenses/LICENSE-2.0")
pn("//")
pn("// Unless required by applicable law or agreed to in writing,")
pn("// software distributed under the License is distributed on an")
pn("// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY")
pn("// KIND, either express or implied. See the License for the")
pn("// specific language governing permissions and limitations")
pn("// under the License.")
pn("//")
pn("")
pn("package %s", pkg)
pn("")
pn("// UnlimitedResourceID is a special ID to define an unlimited resource")
pn("const UnlimitedResourceID = \"-1\"")
pn("")
pn("var idRegex = regexp.MustCompile(`^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-1)$`)")
pn("")
pn("// IsID return true if the passed ID is either a UUID or a UnlimitedResourceID")
pn("func IsID(id string) bool {")
pn(" return idRegex.MatchString(id)")
pn("}")
pn("")
pn("// ClientOption can be passed to new client functions to set custom options")
pn("type ClientOption func(*CloudStackClient)")
pn("")
pn("// OptionFunc can be passed to the courtesy helper functions to set additional parameters")
pn("type OptionFunc func(*CloudStackClient, interface{}) error")
pn("")
pn("type CSError struct {")
pn(" ErrorCode int `json:\"errorcode\"`")
pn(" CSErrorCode int `json:\"cserrorcode\"`")
pn(" ErrorText string `json:\"errortext\"`")
pn("}")
pn("")
pn("func (e *CSError) Error() error {")
pn(" return fmt.Errorf(\"CloudStack API error %%d (CSExceptionErrorCode: %%d): %%s\", e.ErrorCode, e.CSErrorCode, e.ErrorText)")
pn("}")
pn("")
pn("type UUID string")
pn("")
pn("func (c UUID) MarshalJSON() ([]byte, error) {")
pn(" return json.Marshal(string(c))")
pn("}")
pn("")
pn("func (c *UUID) UnmarshalJSON(data []byte) error {")
pn(" value := strings.Trim(string(data), \"\\\"\")")
pn(" if strings.HasPrefix(string(data), \"\\\"\") {")
pn(" *c = UUID(value)")
pn(" return nil")
pn(" }")
pn(" _, err := strconv.ParseInt(value, 10, 64)")
pn(" if err != nil {")
pn(" return err")
pn(" }")
pn(" *c = UUID(value)")
pn(" return nil")
pn("}")
pn("type CloudStackClient struct {")
pn(" HTTPGETOnly bool // If `true` only use HTTP GET calls")
pn("")
pn(" client *http.Client // The http client for communicating")
pn(" baseURL string // The base URL of the API")
pn(" apiKey string // Api key")
pn(" secret string // Secret key")
pn(" async bool // Wait for async calls to finish")
pn(" options []OptionFunc // A list of option functions to apply to all API calls")
pn(" timeout int64 // Max waiting timeout in seconds for async jobs to finish; defaults to 300 seconds")
pn("")
for _, s := range as.services {
pn(" %s %sIface", strings.TrimSuffix(s.name, "Service"), s.name)
}
pn("}")
pn("")
pn("// Creates a new client for communicating with CloudStack")
pn("func newClient(apiurl string, apikey string, secret string, async bool, verifyssl bool, options ...ClientOption) *CloudStackClient {")
pn(" jar, _ := cookiejar.New(nil)")
pn(" cs := &CloudStackClient{")
pn(" client: &http.Client{")
pn(" Jar: jar,")
pn(" Transport: &http.Transport{")
pn(" Proxy: http.ProxyFromEnvironment,")
pn(" DialContext: (&net.Dialer{")
pn(" Timeout: 30 * time.Second,")
pn(" KeepAlive: 30 * time.Second,")
pn(" DualStack: true,")
pn(" }).DialContext,")
pn(" MaxIdleConns: 100,")
pn(" IdleConnTimeout: 90 * time.Second,")
pn(" TLSClientConfig: &tls.Config{InsecureSkipVerify: !verifyssl},")
pn(" TLSHandshakeTimeout: 10 * time.Second,")
pn(" ExpectContinueTimeout: 1 * time.Second,")
pn(" },")
pn(" Timeout: time.Duration(60 * time.Second),")
pn(" },")
pn(" baseURL: apiurl,")
pn(" apiKey: apikey,")
pn(" secret: secret,")
pn(" async: async,")
pn(" options: []OptionFunc{},")
pn(" timeout: 300,")
pn(" }")
pn("")
pn(" for _, fn := range options {")
pn(" fn(cs)")
pn(" }")
pn("")
for _, s := range as.services {
pn(" cs.%s = New%s(cs)", strings.TrimSuffix(s.name, "Service"), s.name)
}
pn("")
pn(" return cs")
pn("}")
pn("")
pn("// Creates a new mock client for communicating with CloudStack")
pn("func newMockClient(ctrl *gomock.Controller) *CloudStackClient {")
pn(" cs := &CloudStackClient{}")
pn("")
for _, s := range as.services {
pn(" cs.%s = NewMock%sIface(ctrl)", strings.TrimSuffix(s.name, "Service"), s.name)
}
pn("")
pn(" return cs")
pn("}")
pn("")
pn("// Default non-async client. So for async calls you need to implement and check the async job result yourself. When using")
pn("// HTTPS with a self-signed certificate to connect to your CloudStack API, you would probably want to set 'verifyssl' to")
pn("// false so the call ignores the SSL errors/warnings.")
pn("func NewClient(apiurl string, apikey string, secret string, verifyssl bool, options ...ClientOption) *CloudStackClient {")
pn(" cs := newClient(apiurl, apikey, secret, false, verifyssl, options...)")
pn(" return cs")
pn("}")
pn("")
pn("// For sync API calls this client behaves exactly the same as a standard client call, but for async API calls")
pn("// this client will wait until the async job is finished or until the configured AsyncTimeout is reached. When the async")
pn("// job finishes successfully it will return actual object received from the API and nil, but when the timout is")
pn("// reached it will return the initial object containing the async job ID for the running job and a warning.")
pn("func NewAsyncClient(apiurl string, apikey string, secret string, verifyssl bool, options ...ClientOption) *CloudStackClient {")
pn(" cs := newClient(apiurl, apikey, secret, true, verifyssl, options...)")
pn(" return cs")
pn("}")
pn("")
pn("// Creates a new mock client for communicating with CloudStack")
pn("func NewMockClient(ctrl *gomock.Controller) *CloudStackClient {")
pn(" cs := newMockClient(ctrl)")
pn(" return cs")
pn("}")
pn("")
pn("// When using the async client an api call will wait for the async call to finish before returning. The default is to poll for 300 seconds")
pn("// seconds, to check if the async job is finished.")
pn("func (cs *CloudStackClient) AsyncTimeout(timeoutInSeconds int64) {")
pn(" cs.timeout = timeoutInSeconds")
pn("}")
pn("")
pn("// Sets timeout when using sync api calls. Default is 60 seconds")
pn("func (cs *CloudStackClient) Timeout(timeout time.Duration) {")
pn(" cs.client.Timeout = timeout")
pn("}")
pn("")
pn("// Set any default options that would be added to all API calls that support it.")
pn("func (cs *CloudStackClient) DefaultOptions(options ...OptionFunc) {")
pn(" if options != nil {")
pn(" cs.options = options")
pn(" } else {")
pn(" cs.options = []OptionFunc{}")
pn(" }")
pn("}")
pn("")
pn("var AsyncTimeoutErr = errors.New(\"Timeout while waiting for async job to finish\")")
pn("")
pn("// A helper function that you can use to get the result of a running async job. If the job is not finished within the configured")
pn("// timeout, the async job returns a AsyncTimeoutErr.")
pn("func (cs *CloudStackClient) GetAsyncJobResult(jobid string, timeout int64) (json.RawMessage, error) {")
pn(" var timer time.Duration")
pn(" currentTime := time.Now().Unix()")
pn("")
pn(" for {")
pn(" p := cs.Asyncjob.NewQueryAsyncJobResultParams(jobid)")
pn(" r, err := cs.Asyncjob.QueryAsyncJobResult(p)")
pn(" if err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" // Status 1 means the job is finished successfully")
pn(" if r.Jobstatus == 1 {")
pn(" return r.Jobresult, nil")
pn(" }")
pn("")
pn(" // When the status is 2, the job has failed")
pn(" if r.Jobstatus == 2 {")
pn(" if r.Jobresulttype == \"text\" {")
pn(" return nil, fmt.Errorf(string(r.Jobresult))")
pn(" } else {")
pn(" return nil, fmt.Errorf(\"Undefined error: %%s\", string(r.Jobresult))")
pn(" }")
pn(" }")
pn("")
pn(" if time.Now().Unix()-currentTime > timeout {")
pn(" return nil, AsyncTimeoutErr")
pn(" }")
pn("")
pn(" // Add an (extremely simple) exponential backoff like feature to prevent")
pn(" // flooding the CloudStack API")
pn(" if timer < 15 {")
pn(" timer++")
pn(" }")
pn("")
pn(" time.Sleep(timer * time.Second)")
pn(" }")
pn("}")
pn("")
pn("// Execute the request against a CS API. Will return the raw JSON data returned by the API and nil if")
pn("// no error occured. If the API returns an error the result will be nil and the HTTP error code and CS")
pn("// error details. If a processing (code) error occurs the result will be nil and the generated error")
pn("func (cs *CloudStackClient) newRequest(api string, params url.Values) (json.RawMessage, error) {")
pn(" params.Set(\"apiKey\", cs.apiKey)")
pn(" params.Set(\"command\", api)")
pn(" params.Set(\"response\", \"json\")")
pn("")
pn(" // Generate signature for API call")
pn(" // * Serialize parameters, URL encoding only values and sort them by key, done by encodeValues")
pn(" // * Convert the entire argument string to lowercase")
pn(" // * Replace all instances of '+' to '%%20'")
pn(" // * Calculate HMAC SHA1 of argument string with CloudStack secret")
pn(" // * URL encode the string and convert to base64")
pn(" s := encodeValues(params)")
pn(" s2 := strings.ToLower(s)")
pn(" s3 := strings.Replace(s2, \"+\", \"%%20\", -1)")
pn(" mac := hmac.New(sha1.New, []byte(cs.secret))")
pn(" mac.Write([]byte(s3))")
pn(" signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))")
pn("")
pn(" var err error")
pn(" var resp *http.Response")
pn(" if !cs.HTTPGETOnly && (api == \"deployVirtualMachine\" || api == \"login\" || api == \"updateVirtualMachine\") {")
pn(" // The deployVirtualMachine API should be called using a POST call")
pn(" // so we don't have to worry about the userdata size")
pn("")
pn(" // Add the unescaped signature to the POST params")
pn(" params.Set(\"signature\", signature)")
pn("")
pn(" // Make a POST call")
pn(" resp, err = cs.client.PostForm(cs.baseURL, params)")
pn(" } else {")
pn(" // Create the final URL before we issue the request")
pn(" url := cs.baseURL + \"?\" + s + \"&signature=\" + url.QueryEscape(signature)")
pn("")
pn(" // Make a GET call")
pn(" resp, err = cs.client.Get(url)")
pn(" }")
pn(" if err != nil {")
pn(" return nil, err")
pn(" }")
pn(" defer resp.Body.Close()")
pn("")
pn(" b, err := ioutil.ReadAll(resp.Body)")
pn(" if err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" // Need to get the raw value to make the result play nice")
pn(" b, err = getRawValue(b)")
pn(" if err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" if resp.StatusCode != 200 {")
pn(" var e CSError")
pn(" if err := json.Unmarshal(b, &e); err != nil {")
pn(" return nil, err")
pn(" }")
pn(" return nil, e.Error()")
pn(" }")
pn(" return b, nil")
pn("}")
pn("")
pn("// Custom version of net/url Encode that only URL escapes values")
pn("// Unmodified portions here remain under BSD license of The Go Authors: https://go.googlesource.com/go/+/master/LICENSE")
pn("func encodeValues(v url.Values) string {")
pn(" if v == nil {")
pn(" return \"\"")
pn(" }")
pn(" var buf bytes.Buffer")
pn(" keys := make([]string, 0, len(v))")
pn(" for k := range v {")
pn(" keys = append(keys, k)")
pn(" }")
pn(" sort.Strings(keys)")
pn(" for _, k := range keys {")
pn(" vs := v[k]")
pn(" prefix := k + \"=\"")
pn(" for _, v := range vs {")
pn(" if buf.Len() > 0 {")
pn(" buf.WriteByte('&')")
pn(" }")
pn(" buf.WriteString(prefix)")
pn(" buf.WriteString(url.QueryEscape(v))")
pn(" }")
pn(" }")
pn(" return buf.String()")
pn("}")
pn("")
pn("// Generic function to get the first raw value from a response as json.RawMessage")
pn("func getRawValue(b json.RawMessage) (json.RawMessage, error) {")
pn(" var m map[string]json.RawMessage")
pn(" if err := json.Unmarshal(b, &m); err != nil {")
pn(" return nil, err")
pn(" }")
pn(" for _, v := range m {")
pn(" return v, nil")
pn(" }")
pn(" return nil, fmt.Errorf(\"Unable to extract the raw value from:\\n\\n%%s\\n\\n\", string(b))")
pn("}")
pn("")
pn("// getSortedKeysFromMap returns the keys from m in increasing order.")
pn("func getSortedKeysFromMap(m map[string]string) (keys []string) {")
pn(" for k := range m {")
pn(" keys = append(keys, k)")
pn(" }")
pn(" sort.Strings(keys)")
pn(" return keys")
pn("}")
pn("")
pn("// WithAsyncTimeout takes a custom timeout to be used by the CloudStackClient")
pn("func WithAsyncTimeout(timeout int64) ClientOption {")
pn(" return func(cs *CloudStackClient) {")
pn(" if timeout != 0 {")
pn(" cs.timeout = timeout")
pn(" }")
pn(" }")
pn("}")
pn("")
pn("// DomainIDSetter is an interface that every type that can set a domain ID must implement")
pn("type DomainIDSetter interface {")
pn(" SetDomainid(string)")
pn("}")
pn("")
pn("// WithDomain takes either a domain name or ID and sets the `domainid` parameter")
pn("func WithDomain(domain string) OptionFunc {")
pn(" return func(cs *CloudStackClient, p interface{}) error {")
pn(" ps, ok := p.(DomainIDSetter)")
pn("")
pn(" if !ok || domain == \"\" {")
pn(" return nil")
pn(" }")
pn("")
pn(" if !IsID(domain) {")
pn(" id, _, err := cs.Domain.GetDomainID(domain)")
pn(" if err != nil {")
pn(" return err")
pn(" }")
pn(" domain = id")
pn(" }")
pn("")
pn(" ps.SetDomainid(domain)")
pn("")
pn(" return nil")
pn(" }")
pn("}")
pn("")
pn("// WithHTTPClient takes a custom HTTP client to be used by the CloudStackClient")
pn("func WithHTTPClient(client *http.Client) ClientOption {")
pn(" return func(cs *CloudStackClient) {")
pn(" if client != nil {")
pn(" if client.Jar == nil {")
pn(" client.Jar = cs.client.Jar")
pn(" }")
pn(" cs.client = client")
pn(" }")
pn(" }")
pn("}")
pn("")
pn("// ListallSetter is an interface that every type that can set listall must implement")
pn("type ListallSetter interface {")
pn(" SetListall(bool)")
pn("}")
pn("")
pn("// WithListall takes either a project name or ID and sets the `listall` parameter")
pn("func WithListall(listall bool) OptionFunc {")
pn(" return func(cs *CloudStackClient, p interface{}) error {")
pn(" ps, ok := p.(ListallSetter)")
pn("")
pn(" if !ok {")
pn(" return nil")
pn(" }")
pn("")
pn(" ps.SetListall(listall)")
pn("")
pn(" return nil")
pn(" }")
pn("}")
pn("// ProjectIDSetter is an interface that every type that can set a project ID must implement")
pn("type ProjectIDSetter interface {")
pn(" SetProjectid(string)")
pn("}")
pn("")
pn("// WithProject takes either a project name or ID and sets the `projectid` parameter")
pn("func WithProject(project string) OptionFunc {")
pn(" return func(cs *CloudStackClient, p interface{}) error {")
pn(" ps, ok := p.(ProjectIDSetter)")
pn("")
pn(" if !ok || project == \"\" {")
pn(" return nil")
pn(" }")
pn("")
pn(" if !IsID(project) {")
pn(" id, _, err := cs.Project.GetProjectID(project)")
pn(" if err != nil {")
pn(" return err")
pn(" }")
pn(" project = id")
pn(" }")
pn("")
pn(" ps.SetProjectid(project)")
pn("")
pn(" return nil")
pn(" }")
pn("}")
pn("")
pn("// VPCIDSetter is an interface that every type that can set a vpc ID must implement")
pn("type VPCIDSetter interface {")
pn(" SetVpcid(string)")
pn("}")
pn("")
pn("// WithVPCID takes a vpc ID and sets the `vpcid` parameter")
pn("func WithVPCID(id string) OptionFunc {")
pn(" return func(cs *CloudStackClient, p interface{}) error {")
pn(" vs, ok := p.(VPCIDSetter)")
pn("")
pn(" if !ok || id == \"\" {")
pn(" return nil")
pn(" }")
pn("")
pn(" vs.SetVpcid(id)")
pn("")
pn(" return nil")
pn(" }")
pn("}")
pn("")
pn("// ZoneIDSetter is an interface that every type that can set a zone ID must implement")
pn("type ZoneIDSetter interface {")
pn(" SetZoneid(string)")
pn("}")
pn("")
pn("// WithZone takes either a zone name or ID and sets the `zoneid` parameter")
pn("func WithZone(zone string) OptionFunc {")
pn(" return func(cs *CloudStackClient, p interface{}) error {")
pn(" zs, ok := p.(ZoneIDSetter)")
pn("")
pn(" if !ok || zone == \"\" {")
pn(" return nil")
pn(" }")
pn("")
pn(" if !IsID(zone) {")
pn(" id, _, err := cs.Zone.GetZoneID(zone)")
pn(" if err != nil {")
pn(" return err")
pn(" }")
pn(" zone = id")
pn(" }")
pn("")
pn(" zs.SetZoneid(zone)")
pn("")
pn(" return nil")
pn(" }")
pn("}")
pn("")
for _, s := range as.services {
pn("type %s struct {", s.name)
pn(" cs *CloudStackClient")
pn("}")
pn("")
pn("func New%s(cs *CloudStackClient) %sIface {", s.name, s.name)
pn(" return &%s{cs: cs}", s.name)
pn("}")
pn("")
}
clean, err := format.Source(buf.Bytes())
if err != nil {
return buf.Bytes(), err
}
return clean, err
}
func (s *service) WriteGeneratedCode() error {
outdir, err := sourceDir()
if err != nil {
log.Fatalf("Failed to get source dir: %s", err)
}
code, err := s.GenerateCode()
if err != nil {
return err
}
file := path.Join(outdir, s.name+".go")
return ioutil.WriteFile(file, code, 0644)
}
func (s *service) GenerateCode() ([]byte, error) {
// Buffer the output in memory, for gofmt'ing later in the defer.
var buf bytes.Buffer
s.p = func(format string, args ...interface{}) {
_, err := fmt.Fprintf(&buf, format, args...)
if err != nil {
panic(err)
}
}
s.pn = func(format string, args ...interface{}) {
s.p(format+"\n", args...)
}
pn := s.pn
pn("//")
pn("// Licensed to the Apache Software Foundation (ASF) under one")
pn("// or more contributor license agreements. See the NOTICE file")
pn("// distributed with this work for additional information")
pn("// regarding copyright ownership. The ASF licenses this file")
pn("// to you under the Apache License, Version 2.0 (the")
pn("// \"License\"); you may not use this file except in compliance")
pn("// with the License. You may obtain a copy of the License at")
pn("//")
pn("// http://www.apache.org/licenses/LICENSE-2.0")
pn("//")
pn("// Unless required by applicable law or agreed to in writing,")
pn("// software distributed under the License is distributed on an")
pn("// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY")
pn("// KIND, either express or implied. See the License for the")
pn("// specific language governing permissions and limitations")
pn("// under the License.")
pn("//")
pn("")
pn("package %s", pkg)
pn("")
if s.name == "FirewallService" {
pn("// Helper function for maintaining backwards compatibility")
pn("func convertFirewallServiceResponse(b []byte) ([]byte, error) {")
pn(" var raw map[string]interface{}")
pn(" if err := json.Unmarshal(b, &raw); err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" if _, ok := raw[\"firewallrule\"]; ok {")
pn(" return convertFirewallServiceListResponse(b)")
pn(" }")
pn("")
pn(" for _, k := range []string{\"endport\", \"startport\"} {")
pn(" if sVal, ok := raw[k].(string); ok {")
pn(" iVal, err := strconv.Atoi(sVal)")
pn(" if err != nil {")
pn(" return nil, err")
pn(" }")
pn(" raw[k] = iVal")
pn(" }")
pn(" }")
pn("")
pn(" return json.Marshal(raw)")
pn("}")
pn("")
pn("// Helper function for maintaining backwards compatibility")
pn("func convertFirewallServiceListResponse(b []byte) ([]byte, error) {")
pn(" var rawList struct {")
pn(" Count int `json:\"count\"`")
pn(" FirewallRules []map[string]interface{} `json:\"firewallrule\"`")
pn(" }")
pn("")
pn(" if err := json.Unmarshal(b, &rawList); err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" for _, r := range rawList.FirewallRules {")
pn(" for _, k := range []string{\"endport\", \"startport\"} {")
pn(" if sVal, ok := r[k].(string); ok {")
pn(" iVal, err := strconv.Atoi(sVal)")
pn(" if err != nil {")
pn(" return nil, err")
pn(" }")
pn(" r[k] = iVal")
pn(" }")
pn(" }")
pn(" }")
pn("")
pn(" return json.Marshal(rawList)")
pn("}")
pn("")
}
if s.name == "SecurityGroupService" {
pn("// Helper function for maintaining backwards compatibility")
pn("func convertAuthorizeSecurityGroupIngressResponse(b []byte) ([]byte, error) {")
pn(" var raw struct {")
pn(" Ingressrule []interface{} `json:\"ingressrule\"`")
pn(" }")
pn(" if err := json.Unmarshal(b, &raw); err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" if len(raw.Ingressrule) != 1 {")
pn(" return b, nil")
pn(" }")
pn("")
pn(" return json.Marshal(raw.Ingressrule[0])")
pn("}")
pn("")
pn("// Helper function for maintaining backwards compatibility")
pn("func convertAuthorizeSecurityGroupEgressResponse(b []byte) ([]byte, error) {")
pn(" var raw struct {")
pn(" Egressrule []interface{} `json:\"egressrule\"`")
pn(" }")
pn(" if err := json.Unmarshal(b, &raw); err != nil {")
pn(" return nil, err")
pn(" }")
pn("")
pn(" if len(raw.Egressrule) != 1 {")
pn(" return b, nil")
pn(" }")
pn("")
pn(" return json.Marshal(raw.Egressrule[0])")
pn("}")
pn("")
}
if s.name == "CustomService" {
pn("type CustomServiceParams struct {")
pn(" p map[string]interface{}")
pn("}")
pn("")
pn("func (p *CustomServiceParams) toURLValues() url.Values {")
pn(" u := url.Values{}")
pn(" if p.p == nil {")
pn(" return u")
pn(" }")
pn("")
pn(" for k, v := range p.p {")
pn(" switch t := v.(type) {")
pn(" case bool:")
pn(" u.Set(k, strconv.FormatBool(t))")
pn(" case int:")
pn(" u.Set(k, strconv.Itoa(t))")
pn(" case int64:")
pn(" vv := strconv.FormatInt(t, 10)")
pn(" u.Set(k, vv)")
pn(" case string:")
pn(" u.Set(k, t)")
pn(" case []string:")
pn(" u.Set(k, strings.Join(t, \", \"))")
pn(" case map[string]string:")
pn(" i := 0")
pn(" for kk, vv := range t {")
pn(" u.Set(fmt.Sprintf(\"%%s[%%d].%%s\", k, i, kk), vv)")
pn(" i++")
pn(" }")
pn(" }")
pn(" }")
pn("")
pn(" return u")
pn("}")
pn("")
pn("func (p *CustomServiceParams) SetParam(param string, v interface{}) {")
pn(" if p.p == nil {")
pn(" p.p = make(map[string]interface{})")
pn(" }")
pn(" p.p[param] = v")
pn("}")
pn("func (p *CustomServiceParams) GetParam(param string) (interface{}, bool) {")
pn(" if p.p == nil {")
pn(" p.p = make(map[string]interface{})")
pn(" }")
pn(" value, ok := p.p[param].(interface{})")
pn(" return value, ok")
pn("}")
pn("")
pn("func (s *CustomService) CustomRequest(api string, p *CustomServiceParams, result interface{}) error {")
pn(" resp, err := s.cs.newRequest(api, p.toURLValues())")
pn(" if err != nil {")
pn(" return err")
pn(" }")
pn("")
pn(" return json.Unmarshal(resp, result)")
pn("}")
}
s.generateInterfaceType()
for _, a := range s.apis {
s.generateParamType(a)
s.generateToURLValuesFunc(a)
s.generateParamGettersAndSettersFunc(a)
s.generateNewParamTypeFunc(a)
s.generateHelperFuncs(a)
s.generateNewAPICallFunc(a)
s.generateResponseType(a)
}
clean, err := format.Source(buf.Bytes())
if err != nil {
buf.WriteTo(os.Stdout)
return buf.Bytes(), err
}
return clean, nil
}
func (s *service) generateParamType(a *API) {
pn := s.pn
pn("type %s struct {", capitalize(a.Name+"Params"))
pn(" p map[string]interface{}")
pn("}\n")
}
func (s *service) generateInterfaceType() {
p, pn := s.p, s.pn
pn("type %sIface interface {", capitalize(s.name))
for _, api := range s.apis {
n := capitalize(api.Name)
tn := capitalize(api.Name + "Params")
// API Calls
pn(" %s(p *%s) (*%s, error)", n, n+"Params", strings.TrimPrefix(n, "Configure")+"Response")
// NewParam funcs
p("New%s(", tn)
for _, ap := range api.Params {
if ap.Required {
// rp = append(rp, ap)
p("%s %s, ", s.parseParamName(ap.Name), mapType(api.Name, ap.Name, ap.Type))