~abp998/gwacl/subscription

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
// Copyright 2013 Canonical Ltd.  This software is licensed under the
// GNU Lesser General Public License version 3 (see the file COPYING).

package gwacl

import (
    "fmt"
    "sort"
    "strings"
)

type ListInstancesRequest struct {
    ServiceName string
}

// ListInstances returns a slice of all instances for all deployments for the
// given hosted service name.
func (api *ManagementAPI) ListInstances(request *ListInstancesRequest) ([]RoleInstance, error) {
    instances := []RoleInstance{}
    properties, err := api.GetHostedServiceProperties(request.ServiceName, true)
    if err != nil {
        return nil, err
    }
    for _, deployment := range properties.Deployments {
        instances = append(instances, deployment.RoleInstanceList...)
    }
    return instances, nil
}

// ListAllDeploymentsRequest is a parameter object for ListAllDeployments.
type ListAllDeploymentsRequest struct {
    // ServiceName restricts the listing to the given service.
    ServiceName string
}

// ListAllDeployments returns a slice containing all deployments that match
// the request.
func (api *ManagementAPI) ListAllDeployments(request *ListAllDeploymentsRequest) ([]Deployment, error) {
    properties, err := api.GetHostedServiceProperties(request.ServiceName, true)
    if err != nil {
        return nil, err
    }
    return properties.Deployments, nil
}

// ListDeploymentsRequest is a parameter object for ListDeployments.
type ListDeploymentsRequest struct {
    // ServiceName restricts the listing to the given service.
    ServiceName string
    // DeploymentNames is a set (its value type is ignored) that restricts the
    // listing to those deployments which it contains.
    DeploymentNames []string
}

// ListDeployments returns a slice containing specific deployments, insofar
// as they match the request.
func (api *ManagementAPI) ListDeployments(request *ListDeploymentsRequest) ([]Deployment, error) {
    properties, err := api.GetHostedServiceProperties(request.ServiceName, true)
    if err != nil {
        return nil, err
    }
    // Filter the deployment list according to the given names.
    filter := make(map[string]bool)
    for _, name := range request.DeploymentNames {
        filter[name] = true
    }
    deployments := []Deployment{}
    for _, deployment := range properties.Deployments {
        if _, ok := filter[deployment.Name]; ok {
            deployments = append(deployments, deployment)
        }
    }
    return deployments, nil
}

type ListSpecificHostedServicesRequest struct {
    ServiceNames []string
}

// ListSpecificHostedServices returns a slice containing specific
// HostedServiceDescriptor objects, insofar as they match the request.
func (api *ManagementAPI) ListSpecificHostedServices(request *ListSpecificHostedServicesRequest) ([]HostedServiceDescriptor, error) {
    allServices, err := api.ListHostedServices()
    if err != nil {
        return nil, err
    }
    // Filter the service list according to the given names.
    filter := make(map[string]bool)
    for _, name := range request.ServiceNames {
        filter[name] = true
    }
    services := []HostedServiceDescriptor{}
    for _, service := range allServices {
        if _, ok := filter[service.ServiceName]; ok {
            services = append(services, service)
        }
    }
    return services, nil
}

type ListPrefixedHostedServicesRequest struct {
    ServiceNamePrefix string
}

// ListPrefixedHostedServices returns a slice containing specific
// HostedServiceDescriptor objects, insofar as they match the request.
func (api *ManagementAPI) ListPrefixedHostedServices(request *ListPrefixedHostedServicesRequest) ([]HostedServiceDescriptor, error) {
    services, err := api.ListHostedServices()
    if err != nil {
        return nil, err
    }
    resServices := []HostedServiceDescriptor{}
    for _, service := range services {
        if strings.HasPrefix(service.ServiceName, request.ServiceNamePrefix) {
            resServices = append(resServices, service)
        }
    }
    services = resServices
    return services, nil
}

type DestroyDeploymentRequest struct {
    ServiceName    string
    DeploymentName string
}

// DestroyDeployment brings down all resources within a deployment - running
// instances, disks, etc. - and deletes the deployment itself.
func (api *ManagementAPI) DestroyDeployment(request *DestroyDeploymentRequest) error {
    deployment, err := api.GetDeployment(&GetDeploymentRequest{
        ServiceName:    request.ServiceName,
        DeploymentName: request.DeploymentName,
    })
    if err != nil {
        if IsNotFoundError(err) {
            return nil
        }
        return err
    }
    // 1. Get the list of the VM disks.
    diskNameMap := make(map[string]bool)
    for _, role := range deployment.RoleList {
        for _, osVHD := range role.OSVirtualHardDisk {
            diskNameMap[osVHD.DiskName] = true
        }
    }
    // 2. Delete deployment.  This will delete all the role instances inside
    // this deployment as a side effect.
    err = api.DeleteDeployment(request.ServiceName, request.DeploymentName)
    if err != nil && !IsNotFoundError(err) {
        return err
    }
    // Sort the disk names to aid testing.
    diskNames := []string{}
    for diskName := range diskNameMap {
        diskNames = append(diskNames, diskName)
    }
    sort.Strings(diskNames)
    // 3. Delete the disks.
    for _, diskName := range diskNames {
        err = api.DeleteDisk(&DeleteDiskRequest{
            DiskName:   diskName,
            DeleteBlob: true})
        if err != nil && !IsNotFoundError(err) {
            return err
        }
    }
    // Done.
    return nil
}

type DestroyHostedServiceRequest struct {
    ServiceName string
}

// DestroyHostedService destroys all of the hosted service's contained
// deployments then deletes the hosted service itself.
func (api *ManagementAPI) DestroyHostedService(request *DestroyHostedServiceRequest) error {
    // 1. Get properties.
    properties, err := api.GetHostedServiceProperties(request.ServiceName, true)
    if err != nil {
        if IsNotFoundError(err) {
            return nil
        }
        return err
    }
    // 2. Delete deployments.
    for _, deployment := range properties.Deployments {
        err := api.DestroyDeployment(&DestroyDeploymentRequest{
            ServiceName:    request.ServiceName,
            DeploymentName: deployment.Name,
        })
        if err != nil {
            return err
        }
    }
    // 3. Delete service.
    err = api.DeleteHostedService(request.ServiceName)
    if err != nil && !IsNotFoundError(err) {
        return err
    }
    // Done.
    return nil
}

func (api *ManagementAPI) AddVirtualNetworkSite(site *VirtualNetworkSite) error {
    // Obtain the current network config, which we will then modify.
    networkConfig, err := api.GetNetworkConfiguration()
    if err != nil {
        return err
    }
    if networkConfig == nil {
        // There's no config yet.
        networkConfig = &NetworkConfiguration{XMLNS: XMLNS_NC}
    }
    if networkConfig.VirtualNetworkSites == nil {
        networkConfig.VirtualNetworkSites = &[]VirtualNetworkSite{}
    }
    // Check to see if this network already exists.
    for _, existingSite := range *networkConfig.VirtualNetworkSites {
        if existingSite.Name == site.Name {
            // Network already defined.
            return fmt.Errorf("could not add virtual network: %q already exists", site.Name)
        }
    }
    // Add the network to the configuration.
    virtualNetworkSites := append(*networkConfig.VirtualNetworkSites, *site)
    networkConfig.VirtualNetworkSites = &virtualNetworkSites
    // Put it back up to Azure. There's a race here...
    return api.SetNetworkConfiguration(networkConfig)
}

func (api *ManagementAPI) RemoveVirtualNetworkSite(siteName string) error {
    // Obtain the current network config, which we will then modify.
    networkConfig, err := api.GetNetworkConfiguration()
    if err != nil {
        return err
    }
    if networkConfig == nil || networkConfig.VirtualNetworkSites == nil {
        // There's no config, nothing to do.
        return nil
    }
    // Remove all references to the specified virtual network site name.
    virtualNetworkSites := []VirtualNetworkSite{}
    for _, existingSite := range *networkConfig.VirtualNetworkSites {
        if existingSite.Name != siteName {
            virtualNetworkSites = append(virtualNetworkSites, existingSite)
        }
    }
    if len(virtualNetworkSites) < len(*networkConfig.VirtualNetworkSites) {
        // Put it back up to Azure. There's a race here...
        networkConfig.VirtualNetworkSites = &virtualNetworkSites
        return api.SetNetworkConfiguration(networkConfig)
    }
    return nil
}

type ListRoleEndpointsRequest struct {
    ServiceName    string
    DeploymentName string
    RoleName       string
}

// ListRoleEndpoints lists the open endpoints for the named service/deployment/role name.
func (api *ManagementAPI) ListRoleEndpoints(request *ListRoleEndpointsRequest) ([]InputEndpoint, error) {
    var err error
    vmRole, err := api.GetRole(&GetRoleRequest{
        ServiceName:    request.ServiceName,
        DeploymentName: request.DeploymentName,
        RoleName:       request.RoleName})

    if err != nil {
        return nil, err
    }

    for i, configSet := range vmRole.ConfigurationSets {
        if configSet.ConfigurationSetType == CONFIG_SET_NETWORK {
            endpointsP := vmRole.ConfigurationSets[i].InputEndpoints
            if endpointsP != nil {
                return *endpointsP, nil
            }
        }
    }
    return []InputEndpoint{}, nil
}

type AddRoleEndpointsRequest struct {
    ServiceName    string
    DeploymentName string
    RoleName       string
    InputEndpoints []InputEndpoint
}

// AddRoleEndpoints appends the supplied endpoints to the existing endpoints
// for the named service/deployment/role name.  Note that the Azure API
// leaves this open to a race condition between fetching and updating the role.
func (api *ManagementAPI) AddRoleEndpoints(request *AddRoleEndpointsRequest) error {
    var err error
    vmRole, err := api.GetRole(&GetRoleRequest{
        ServiceName:    request.ServiceName,
        DeploymentName: request.DeploymentName,
        RoleName:       request.RoleName})

    if err != nil {
        return err
    }

    for i, configSet := range vmRole.ConfigurationSets {
        // TODO: Is NetworkConfiguration always present?
        if configSet.ConfigurationSetType == CONFIG_SET_NETWORK {
            endpointsP := vmRole.ConfigurationSets[i].InputEndpoints
            if endpointsP == nil {
                // No endpoints set at all, initialise it to be empty.
                vmRole.ConfigurationSets[i].InputEndpoints = &[]InputEndpoint{}
            }
            // Append to existing endpoints.
            // TODO: Check clashing endpoint. LocalPort/Name/Port unique?
            endpoints := append(
                *vmRole.ConfigurationSets[i].InputEndpoints,
                request.InputEndpoints...)
            vmRole.ConfigurationSets[i].InputEndpoints = &endpoints

            break // Only one NetworkConfiguration so exit loop now.
        }
    }

    // Enjoy this race condition.
    err = api.UpdateRole(&UpdateRoleRequest{
        ServiceName:      request.ServiceName,
        DeploymentName:   request.DeploymentName,
        RoleName:         request.RoleName,
        PersistentVMRole: vmRole})
    if err != nil {
        return err
    }
    return nil
}

// CompareInputEndpoints attempts to compare two InputEndpoint objects in a
// way that's congruent with how Windows's Azure considers them. The name is
// always ignored, as is LoadBalancerProbe. When LoadBalancedEndpointSetName
// is set (not the empty string), all the fields - LocalPort, Port, Protocol,
// VIP and LoadBalancedEndpointSetName - are used for the comparison. When
// LoadBalancedEndpointSetName is the empty string, all except LocalPort -
// effectively Port, Protocol and VIP - are used for comparison.
func CompareInputEndpoints(a, b *InputEndpoint) bool {
    if a.LoadBalancedEndpointSetName == "" {
        return a.Port == b.Port && a.Protocol == b.Protocol && a.VIP == b.VIP
    } else {
        return (a.LoadBalancedEndpointSetName == b.LoadBalancedEndpointSetName &&
            a.LocalPort == b.LocalPort && a.Port == b.Port &&
            a.Protocol == b.Protocol && a.VIP == b.VIP)
    }
}

type RemoveRoleEndpointsRequest struct {
    ServiceName    string
    DeploymentName string
    RoleName       string
    InputEndpoints []InputEndpoint
}

// RemoveRoleEndpoints attempts to remove the given endpoints from the
// specified role. It uses `CompareInputEndpoints` to determine when there's a
// match between the given endpoint and one already configured.
func (api *ManagementAPI) RemoveRoleEndpoints(request *RemoveRoleEndpointsRequest) error {
    filterRequest := filterRoleEndpointsRequest{
        ServiceName:    request.ServiceName,
        DeploymentName: request.DeploymentName,
        RoleName:       request.RoleName,
        Filter: func(a *InputEndpoint) bool {
            for _, b := range request.InputEndpoints {
                if CompareInputEndpoints(a, &b) {
                    return false
                }
            }
            return true
        },
    }
    return api.filterRoleEndpoints(&filterRequest)
}

// Returns true to keep the endpoint defined in the role's configuration,
// false to remove it. It is also welcome to mutate endpoints; they are passed
// by reference.
type inputEndpointFilter func(*InputEndpoint) bool

type filterRoleEndpointsRequest struct {
    ServiceName    string
    DeploymentName string
    RoleName       string
    Filter         inputEndpointFilter
}

// filterRoleEndpoints is a general role endpoint filtering function. It is
// private because it is only a support function for RemoveRoleEndpoints, and
// is not tested directly.
func (api *ManagementAPI) filterRoleEndpoints(request *filterRoleEndpointsRequest) error {
    role, err := api.GetRole(&GetRoleRequest{
        ServiceName:    request.ServiceName,
        DeploymentName: request.DeploymentName,
        RoleName:       request.RoleName,
    })
    if err != nil {
        return err
    }
    for index, configSet := range role.ConfigurationSets {
        if configSet.ConfigurationSetType == CONFIG_SET_NETWORK {
            if configSet.InputEndpoints != nil {
                endpoints := []InputEndpoint{}
                for _, existingEndpoint := range *configSet.InputEndpoints {
                    if request.Filter(&existingEndpoint) {
                        endpoints = append(endpoints, existingEndpoint)
                    }
                }
                if len(endpoints) == 0 {
                    configSet.InputEndpoints = nil
                } else {
                    configSet.InputEndpoints = &endpoints
                }
            }
        }
        // Update the role; implicit copying is a nuisance.
        role.ConfigurationSets[index] = configSet
    }
    return api.UpdateRole(&UpdateRoleRequest{
        ServiceName:      request.ServiceName,
        DeploymentName:   request.DeploymentName,
        RoleName:         request.RoleName,
        PersistentVMRole: role,
    })
}