forked from DinoChiesa/go-apigee-edge
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathproxies.go
524 lines (451 loc) · 16.1 KB
/
proxies.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
package apigee
import (
"archive/zip"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
)
const proxiesPath = "apis"
// ProxiesService is an interface for interfacing with the Apigee Edge Admin API
// dealing with apiproxies.
type ProxiesService interface {
List() ([]string, *Response, error)
Get(string) (*Proxy, *Response, error)
Import(string, string) (*ProxyRevision, *Response, error)
Update(string, string, string) (*ProxyRevisionUpdate, *Response, error)
Delete(string) (*DeletedProxyInfo, *Response, error)
DeleteRevision(string, Revision) (*ProxyRevision, *Response, error)
Deploy(string, string, Revision, int, bool) (*ProxyRevisionDeployment, *Response, error)
ReDeploy(string, string, Revision, int, bool) (*ProxyRevisionDeployments, *Response, error)
Undeploy(string, string, Revision) (*ProxyRevisionDeployment, *Response, error)
Export(string, Revision) (string, *Response, error)
GetDeployments(string) (*ProxyDeployment, *Response, error)
}
type ProxiesServiceOp struct {
client *EdgeClient
}
var _ ProxiesService = &ProxiesServiceOp{}
// Proxy contains information about an API Proxy within an Edge organization.
type Proxy struct {
Revisions []Revision `json:"revision,omitempty"`
Name string `json:"name,omitempty"`
MetaData ProxyMetadata `json:"metaData,omitempty"`
}
// ProxyMetadata contains information related to the creation and last modified
// time and actor for an API Proxy within an organization.
type ProxyMetadata struct {
LastModifiedBy string `json:"lastModifiedBy,omitempty"`
CreatedBy string `json:"createdBy,omitempty"`
LastModifiedAt Timestamp `json:"lastModifiedAt,omitempty"`
CreatedAt Timestamp `json:"createdAt,omitempty"`
}
// ProxyRevision holds information about a revision of an API Proxy.
type ProxyRevision struct {
CreatedBy string `json:"createdBy,omitempty"`
CreatedAt Timestamp `json:"createdAt,omitempty"`
Description string `json:"description,omitempty"`
ContextInfo string `json:"contextInfo,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Name string `json:"name,omitempty"`
LastModifiedBy string `json:"lastModifiedBy,omitempty"`
LastModifiedAt Timestamp `json:"lastModifiedAt,omitempty"`
Revision Revision `json:"revision,omitempty"`
TargetEndpoints []string `json:"targetEndpoints,omitempty"`
TargetServers []string `json:"targetServers,omitempty"`
Resources []string `json:"resources,omitempty"`
ProxyEndpoints []string `json:"proxyEndpoints,omitempty"`
Policies []string `json:"policies,omitempty"`
Type string `json:"type,omitempty"`
}
// ProxyRevisionUpdate only returns the updated revision.
type ProxyRevisionUpdate struct {
Revision Revision `json:"revision,omitempty"`
}
// ProxyRevisionDeployment holds information about the deployment state of a
// single revision of an API Proxy.
type ProxyRevisionDeployment struct {
Name string `json:"aPIProxy,omitempty"`
Revision Revision `json:"revision,omitempty"`
Environment string `json:"environment,omitempty"`
Organization string `json:"organization,omitempty"`
State string `json:"state,omitempty"`
Servers []EdgeServer `json:"server,omitempty"`
}
// ProxyRevisionDeployment holds information about the deployment state of a
// single revision of an API Proxy.
type ProxyRevisionDeployments struct {
Name string `json:"aPIProxy,omitempty"`
Environments []ProxyRevisionDeployment `json:"environment,omitempty"`
Organization string `json:"organization,omitempty"`
}
// When inquiring the deployment status of an API PRoxy revision, even implicitly
// as when performing a Deploy or Undeploy, the response includes the deployment
// status for each particular Edge Server in the environment. This struct
// deserializes that information. It will normally not be useful at all. In rare
// cases, it may be useful in helping to diagnose problems. For example, if there
// is a problem with a deployment change, as when a Message Processor is
// experiencing a problem and cannot undeploy, or more commonly, cannot deploy an
// API Proxy, this struct will hold relevant information.
type EdgeServer struct {
Status string `json:"status,omitempty"`
Uuid string `json:"uUID,omitempty"`
Type []string `json:"type,omitempty"`
}
// ProxyDeployment holds information about the deployment state of a
// all revisions of an API Proxy.
type ProxyDeployment struct {
Environments []EnvironmentDeployment `json:"environment,omitempty"`
Name string `json:"name,omitempty"`
Organization string `json:"organization,omitempty"`
}
type EnvironmentDeployment struct {
Name string `json:"name,omitempty"`
Revision []RevisionDeployment `json:"revision,omitempty"`
}
type RevisionDeployment struct {
Number Revision `json:"name,omitempty"`
State string `json:"state,omitempty"`
Servers []EdgeServer `json:"server,omitempty"`
}
// When Delete returns successfully, it returns a payload that contains very little useful
// information. This struct deserializes that information.
type DeletedProxyInfo struct {
Name string `json:"name,omitempty"`
}
// type proxiesRoot struct {
// Proxies []Proxy `json:"proxies"`
// }
// List retrieves the list of apiproxy names for the organization referred by the EdgeClient.
func (s *ProxiesServiceOp) List() ([]string, *Response, error) {
req, e := s.client.NewRequest("GET", proxiesPath, nil, "")
if e != nil {
return nil, nil, e
}
namelist := make([]string, 0)
resp, e := s.client.Do(req, &namelist)
if e != nil {
return nil, resp, e
}
return namelist, resp, e
}
// Get retrieves the information about an API Proxy in an organization, information including
// the list of available revisions, and the created and last modified dates and actors.
func (s *ProxiesServiceOp) Get(proxy string) (*Proxy, *Response, error) {
path := path.Join(proxiesPath, proxy)
req, e := s.client.NewRequest("GET", path, nil, "")
if e != nil {
return nil, nil, e
}
returnedProxy := Proxy{}
resp, e := s.client.Do(req, &returnedProxy)
if e != nil {
return nil, resp, e
}
return &returnedProxy, resp, e
}
func smartFilter(path string) bool {
if strings.HasSuffix(path, "~") {
return false
}
if strings.HasSuffix(path, "#") && strings.HasPrefix(path, "#") {
return false
}
return true
}
func zipDirectory(source string, target string, filter func(string) bool) error {
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
info, err := os.Stat(source)
if err != nil {
return nil
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if filter == nil || filter(path) {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}
// This archive will be unzipped by a Java process. When ZIP64 extensions
// are used, Java insists on having Deflate as the compression method (0x08)
// even for directories.
header.Method = zip.Deflate
if info.IsDir() {
header.Name += "/"
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
}
return err
})
return err
}
// Import an API proxy into an organization, creating a new API Proxy revision.
// The proxyName can be passed as "nil" in which case the name is derived from the source.
// The source can be either a filesystem directory containing an exploded apiproxy bundle, OR
// the path of a zip file containing an API Proxy bundle. Returns the API proxy revision information.
// This method does not deploy the imported proxy. See the Deploy method.
func (s *ProxiesServiceOp) Import(proxyName string, source string) (*ProxyRevision, *Response, error) {
zipfileName, err := getZip(proxyName, "Import", source)
if err != nil {
return nil, nil, err
}
ioreader, err := os.Open(*zipfileName)
if err != nil {
return nil, nil, err
}
defer ioreader.Close()
// append the query params
origURL, err := url.Parse(proxiesPath)
if err != nil {
return nil, nil, err
}
q := origURL.Query()
q.Add("action", "import")
q.Add("name", proxyName)
origURL.RawQuery = q.Encode()
path := origURL.String()
req, e := s.client.NewRequest("POST", path, ioreader, "")
if e != nil {
return nil, nil, e
}
returnedProxyRevision := ProxyRevision{}
resp, e := s.client.Do(req, &returnedProxyRevision)
if e != nil {
return nil, resp, e
}
return &returnedProxyRevision, resp, e
}
// Update an API proxy revision that already exists.
// The source can be either a filesystem directory containing an exploded apiproxy bundle, OR
// the path of a zip file containing an API Proxy bundle. Returns the API proxy revision.
func (s *ProxiesServiceOp) Update(proxyName string, rev string, source string) (*ProxyRevisionUpdate, *Response, error) {
zipfileName, err := getZip(proxyName, "Update", source)
if err != nil {
return nil, nil, err
}
ioreader, err := os.Open(*zipfileName)
if err != nil {
return nil, nil, err
}
defer ioreader.Close()
path := path.Join(proxiesPath, proxyName, "revisions", rev)
req, e := s.client.NewRequest("POST", path, ioreader, "")
if e != nil {
return nil, nil, e
}
returnedProxyRevision := ProxyRevisionUpdate{}
resp, e := s.client.Do(req, &returnedProxyRevision)
if e != nil {
return nil, resp, e
}
return &returnedProxyRevision, resp, e
}
// Checks a source directory and creates a ZIP file.
func getZip(proxyName string, method string, source string) (*string, error) {
info, err := os.Stat(source)
if err != nil {
return nil, err
}
zipfileName := source
log.Printf("[INFO] *** %s *** isDir: %#v\n", method, info.IsDir())
if info.IsDir() {
// create a temporary zip file
if proxyName == "" {
proxyName = filepath.Base(source)
}
log.Printf("[INFO] *** %s *** proxyName: %#v\n", method, proxyName)
tempDir, e := ioutil.TempDir("", "go-apigee-edge-")
if e != nil {
log.Printf("[ERROR] *** %s *** error: %#v\n", method, e)
return nil, errors.New(fmt.Sprintf("while creating temp dir, error: %#v", e))
}
log.Printf("[INFO] *** %s *** tempDir: %#v\n", method, tempDir)
log.Printf("[INFO] *** %s *** sourceDir: %#v\n", method, source)
zipfileName = path.Join(tempDir, "apiproxy.zip")
e = zipDirectory(path.Join(source, "apiproxy"), zipfileName, smartFilter)
if e != nil {
return nil, errors.New(fmt.Sprintf("while creating temp dir, error: %#v", e))
}
log.Printf("[INFO] *** zipped %s into %s\n\n", source, zipfileName)
}
if !strings.HasSuffix(zipfileName, ".zip") {
return nil, errors.New("source must be a zipfile")
}
info, err = os.Stat(zipfileName)
if err != nil {
return nil, err
}
return &zipfileName, nil
}
// Export a revision of an API proxy within an organization, to a filesystem file.
func (s *ProxiesServiceOp) Export(proxyName string, rev Revision) (string, *Response, error) {
// curl -u USER:PASSWORD \
// http://MGMTSERVER/v1/o/ORGNAME/apis/APINAME/revisions/REVNUMBER?format=bundle > bundle.zip
path := path.Join(proxiesPath, proxyName, "revisions", fmt.Sprintf("%d", rev))
// append the required query param
origURL, err := url.Parse(path)
if err != nil {
return "", nil, err
}
q := origURL.Query()
q.Add("format", "bundle")
origURL.RawQuery = q.Encode()
path = origURL.String()
req, e := s.client.NewRequest("GET", path, nil, "")
if e != nil {
return "", nil, e
}
req.Header.Del("Accept")
t := time.Now()
filename := fmt.Sprintf("proxyName-r%d-%d%02d%02d-%02d%02d%02d.zip",
rev, t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
out, e := os.Create(filename)
if e != nil {
return "", nil, e
}
resp, e := s.client.Do(req, out)
if e != nil {
return "", resp, e
}
out.Close()
return filename, resp, e
}
// DeleteRevision deletes a specific revision of an API Proxy from an organization.
// The revision must exist, and must not be currently deployed.
func (s *ProxiesServiceOp) DeleteRevision(proxyName string, rev Revision) (*ProxyRevision, *Response, error) {
path := path.Join(proxiesPath, proxyName, "revisions", fmt.Sprintf("%d", rev))
req, e := s.client.NewRequest("DELETE", path, nil, "")
if e != nil {
return nil, nil, e
}
proxyRev := ProxyRevision{}
resp, e := s.client.Do(req, &proxyRev)
if e != nil {
return nil, resp, e
}
return &proxyRev, resp, e
}
// Undeploy a specific revision of an API Proxy from a particular environment within an Edge organization.
func (s *ProxiesServiceOp) Undeploy(proxyName, env string, rev Revision) (*ProxyRevisionDeployment, *Response, error) {
path := path.Join(proxiesPath, proxyName, "revisions", fmt.Sprintf("%d", rev), "deployments")
// append the query params
origURL, err := url.Parse(path)
if err != nil {
return nil, nil, err
}
q := origURL.Query()
q.Add("action", "undeploy")
q.Add("env", env)
origURL.RawQuery = q.Encode()
path = origURL.String()
req, e := s.client.NewRequest("POST", path, nil, "")
if e != nil {
return nil, nil, e
}
deployment := ProxyRevisionDeployment{}
resp, e := s.client.Do(req, &deployment)
if e != nil {
return nil, resp, e
}
return &deployment, resp, e
}
// Deploy a revision of an API proxy to a specific environment within an organization.
func (s *ProxiesServiceOp) Deploy(proxyName, env string, rev Revision, delay int, override bool) (*ProxyRevisionDeployment, *Response, error) {
req, e := prepareDeployRequest(proxyName, env, proxiesPath, rev, delay, override, s.client)
deployment := ProxyRevisionDeployment{}
resp, e := s.client.Do(req, &deployment)
return &deployment, resp, e
}
//isn't is nice that the return data structure changes on the second revision deployment?! NO!
func (s *ProxiesServiceOp) ReDeploy(proxyName, env string, rev Revision, delay int, override bool) (*ProxyRevisionDeployments, *Response, error) {
req, e := prepareDeployRequest(proxyName, env, proxiesPath, rev, delay, override, s.client)
deployment := ProxyRevisionDeployments{}
resp, e := s.client.Do(req, &deployment)
return &deployment, resp, e
}
func prepareDeployRequest(name, env, resourcePath string, rev Revision, delay int, override bool, c *EdgeClient) (*http.Request, error) {
path := path.Join("environments", env, resourcePath, name, "revisions", fmt.Sprintf("%d", rev), "deployments")
// append the query params
origURL, err := url.Parse(path)
if err != nil {
return nil, err
}
q := origURL.Query()
q.Add("override", strconv.FormatBool(override))
q.Add("delay", fmt.Sprintf("%d", delay))
origURL.RawQuery = q.Encode()
path = origURL.String()
req, e := c.NewRequest("POST", path, nil, "application/x-www-form-urlencoded")
if e != nil {
return nil, e
}
return req, e
}
// Delete an API Proxy and all its revisions from an organization. This method
// will fail if any of the revisions of the named API Proxy are currently deployed
// in any environment.
func (s *ProxiesServiceOp) Delete(proxyName string) (*DeletedProxyInfo, *Response, error) {
path := path.Join(proxiesPath, proxyName)
req, e := s.client.NewRequest("DELETE", path, nil, "")
if e != nil {
return nil, nil, e
}
proxy := DeletedProxyInfo{}
resp, e := s.client.Do(req, &proxy)
if e != nil {
return nil, resp, e
}
return &proxy, resp, e
}
// GetDeployments retrieves the information about deployments of an API Proxy in
// an organization, including the environment names and revision numbers.
func (s *ProxiesServiceOp) GetDeployments(proxy string) (*ProxyDeployment, *Response, error) {
path := path.Join(proxiesPath, proxy, "deployments")
req, e := s.client.NewRequest("GET", path, nil, "")
if e != nil {
return nil, nil, e
}
deployments := ProxyDeployment{}
resp, e := s.client.Do(req, &deployments)
if e != nil {
return nil, resp, e
}
return &deployments, resp, e
}