/
controller.go
364 lines (316 loc) · 10.5 KB
/
controller.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
//
// Copyright (c) 2018 Juniper Networks, Inc. All Rights Reserved.
//
// Licensed 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 controller_rest
import (
"errors"
"fmt"
"regexp"
"strings"
contrail "github.com/Juniper/contrail-go-api"
"github.com/Juniper/contrail-go-api/config"
"github.com/Juniper/contrail-go-api/types"
"github.com/Juniper/contrail-windows-docker-driver/common"
log "github.com/sirupsen/logrus"
)
type Info struct {
}
type ControllerAdapter struct {
ApiClient contrail.ApiClient
}
func newControllerAdapter(apiClient contrail.ApiClient) *ControllerAdapter {
client := &ControllerAdapter{ApiClient: apiClient}
return client
}
func (c *ControllerAdapter) NewProject(domain, tenant string) (*types.Project, error) {
project := new(types.Project)
project.SetFQName("domain", []string{domain, tenant})
if err := c.ApiClient.Create(project); err != nil {
return nil, err
}
return project, nil
}
func (c *ControllerAdapter) CreateNetworkWithSubnet(tenantName, networkName, subnetCIDR string) (*types.VirtualNetwork, error) {
net, err := c.GetNetwork(tenantName, networkName)
if err == nil {
showDetails := true
details, err := config.NetworkShow(c.ApiClient, net.GetUuid(), showDetails)
if err != nil {
return nil, err
}
for _, existingCIDR := range details.Subnets {
if subnetCIDR == existingCIDR {
return net, nil
}
}
return nil, errors.New("such network already has a different subnet")
}
projectFQName := fmt.Sprintf("%s:%s", common.DomainName, tenantName)
project, err := c.ApiClient.FindByName("project", projectFQName)
if err != nil {
return nil, err
}
netUUID, err := config.CreateNetworkWithSubnet(c.ApiClient, project.GetUuid(), networkName, subnetCIDR)
if err != nil {
return nil, err
}
net, err = types.VirtualNetworkByUuid(c.ApiClient, netUUID)
if err != nil {
return nil, err
}
return net, nil
}
func (c *ControllerAdapter) GetNetwork(tenantName, networkName string) (*types.VirtualNetwork,
error) {
name := fmt.Sprintf("%s:%s:%s", common.DomainName, tenantName, networkName)
net, err := types.VirtualNetworkByName(c.ApiClient, name)
if err != nil {
log.Errorf("Failed to get virtual network %s by name: %v", name, err)
return nil, err
}
return net, nil
}
// GetIpamSubnet returns IPAM subnet of specified virtual network with specified CIDR.
// If virtual network has only one subnet, CIDR is ignored.
func (c *ControllerAdapter) GetIpamSubnet(net *types.VirtualNetwork, CIDR string) (
*types.IpamSubnetType, error) {
if strings.HasPrefix(CIDR, "0.0.0.0") {
// this means that the user didn't provide a subnet
CIDR = ""
}
ipamReferences, err := net.GetNetworkIpamRefs()
if err != nil {
log.Errorf("Failed to get ipam references: %v", err)
return nil, err
}
var allIpamSubnets []types.IpamSubnetType
for _, ref := range ipamReferences {
attribute := ref.Attr
ipamSubnets := attribute.(types.VnSubnetsType).IpamSubnets
for _, ipamSubnet := range ipamSubnets {
allIpamSubnets = append(allIpamSubnets, ipamSubnet)
}
}
if len(allIpamSubnets) == 0 {
err = errors.New("No Ipam subnets found")
log.Error(err)
return nil, err
}
if CIDR == "" {
if len(allIpamSubnets) > 1 {
err = errors.New("Didn't specify subnet CIDR and there are multiple Contrail subnets")
log.Error(err)
return nil, err
}
// return the one and only subnet
return &allIpamSubnets[0], nil
}
// there are multiple subnets to choose from
for _, ipam := range allIpamSubnets {
thisCIDR := fmt.Sprintf("%s/%v", ipam.Subnet.IpPrefix,
ipam.Subnet.IpPrefixLen)
if thisCIDR == CIDR {
return &ipam, nil
}
}
err = errors.New("Subnet with specified CIDR not found")
log.Error(err)
return nil, err
}
func (c *ControllerAdapter) GetDefaultGatewayIp(subnet *types.IpamSubnetType) (string, error) {
gw := subnet.DefaultGateway
if gw == "" {
err := errors.New("Default GW is empty")
log.Error(err)
return "", err
}
return gw, nil
}
func (c *ControllerAdapter) GetOrCreateInstance(vif *types.VirtualMachineInterface, containerId string) (
*types.VirtualMachine, error) {
instance, err := c.GetInstance(containerId)
if err == nil {
return instance, nil
} else if !c.is404(err) {
log.Errorf("Failed to get instance: %v", err)
return nil, err
}
instance = new(types.VirtualMachine)
instance.SetName(containerId)
err = c.ApiClient.Create(instance)
if err != nil {
log.Errorf("Failed to create instance: %v", err)
return nil, err
}
createdInstance, err := types.VirtualMachineByName(c.ApiClient, containerId)
if err != nil {
log.Errorf("Failed to retreive instance %s by name: %v", containerId, err)
return nil, err
}
log.Infoln("Created instance: ", createdInstance.GetFQName())
err = vif.AddVirtualMachine(createdInstance)
if err != nil {
log.Errorf("Failed to add instance to vif")
return nil, err
}
err = c.ApiClient.Update(vif)
if err != nil {
log.Errorf("Failed to update vif")
return nil, err
}
return createdInstance, nil
}
func (c *ControllerAdapter) GetInstance(containerId string) (
*types.VirtualMachine, error) {
return types.VirtualMachineByName(c.ApiClient, containerId)
}
func (c *ControllerAdapter) GetExistingInterface(net *types.VirtualNetwork, tenantName,
containerId string) (*types.VirtualMachineInterface, error) {
fqName := fmt.Sprintf("%s:%s:%s", common.DomainName, tenantName, containerId)
iface, err := types.VirtualMachineInterfaceByName(c.ApiClient, fqName)
if err != nil {
return nil, err
}
if iface != nil {
return iface, nil
}
log.Errorf("Failed to get interface which does not exist")
return nil, errors.New("Interface does not exist")
}
func (c *ControllerAdapter) GetOrCreateInterface(net *types.VirtualNetwork, tenantName,
containerId string) (*types.VirtualMachineInterface, error) {
fqName := fmt.Sprintf("%s:%s:%s", common.DomainName, tenantName, containerId)
iface, err := types.VirtualMachineInterfaceByName(c.ApiClient, fqName)
if err == nil && iface != nil {
return iface, nil
}
iface = new(types.VirtualMachineInterface)
iface.SetFQName("project", []string{common.DomainName, tenantName, containerId})
err = iface.AddVirtualNetwork(net)
if err != nil {
log.Errorf("Failed to add network to interface: %v", err)
return nil, err
}
iface.SetPortSecurityEnabled(true)
err = c.assignDefaultSecurityGroup(iface, tenantName)
if err != nil {
log.Errorf("Failed to add security group to interface: %v", err)
return nil, err
}
err = c.ApiClient.Create(iface)
if err != nil {
log.Errorf("Failed to create interface: %v", err)
return nil, err
}
createdIface, err := types.VirtualMachineInterfaceByName(c.ApiClient, fqName)
if err != nil {
log.Errorf("Failed to retrieve vmi %s by name: %v", fqName, err)
return nil, err
}
log.Infoln("Created instance: ", createdIface.GetFQName())
return createdIface, nil
}
func (c *ControllerAdapter) assignDefaultSecurityGroup(iface *types.VirtualMachineInterface, tenantName string) error {
secGroupFqName := fmt.Sprintf("%s:%s:default", common.DomainName, tenantName)
secGroup, err := types.SecurityGroupByName(c.ApiClient, secGroupFqName)
if err != nil || secGroup == nil {
return fmt.Errorf("Failed to retrieve security group %s by name: %v", secGroupFqName, err)
}
return iface.AddSecurityGroup(secGroup)
}
func (c *ControllerAdapter) GetInterfaceMac(iface *types.VirtualMachineInterface) (string, error) {
macs := iface.GetVirtualMachineInterfaceMacAddresses()
if len(macs.MacAddress) == 0 {
err := errors.New("Empty MAC list")
log.Error(err)
return "", err
}
return macs.MacAddress[0], nil
}
func (c *ControllerAdapter) GetOrCreateInstanceIp(net *types.VirtualNetwork,
iface *types.VirtualMachineInterface, subnetUuid string) (*types.InstanceIp, error) {
instIp, err := types.InstanceIpByName(c.ApiClient, iface.GetName())
if err == nil && instIp != nil {
return instIp, nil
}
instIp = &types.InstanceIp{}
instIp.SetName(iface.GetName())
instIp.SetSubnetUuid(subnetUuid)
err = instIp.AddVirtualNetwork(net)
if err != nil {
log.Errorf("Failed to add network to instanceIP object: %v", err)
return nil, err
}
err = instIp.AddVirtualMachineInterface(iface)
if err != nil {
log.Errorf("Failed to add vmi to instanceIP object: %v", err)
return nil, err
}
err = c.ApiClient.Create(instIp)
if err != nil {
log.Errorf("Failed to instanceIP: %v", err)
return nil, err
}
allocatedIP, err := types.InstanceIpByUuid(c.ApiClient, instIp.GetUuid())
if err != nil {
log.Errorf("Failed to retreive instanceIP object %s by name: %v", instIp.GetUuid(), err)
return nil, err
}
return allocatedIP, nil
}
func (c *ControllerAdapter) DeleteElementRecursive(parent contrail.IObject) error {
log.Debugln("Deleting", parent.GetType(), parent.GetUuid())
for err := c.ApiClient.Delete(parent); err != nil; err = c.ApiClient.Delete(parent) {
// TODO: when fixing this method, consider using c.is404() method.
if strings.Contains(err.Error(), "404 Resource") {
log.Errorln("Failed to delete Contrail resource", err.Error())
break
} else if strings.Contains(err.Error(), "409 Conflict") {
msg := err.Error()
// example error message when object has children:
// `409 Conflict: Delete when children still present:
// ['http://10.7.0.54:8082/virtual-network/23e300f4-ab1a-4d97-a1d9-9ed69b601e17']`
// This regex finds all strings like:
// `virtual-network/23e300f4-ab1a-4d97-a1d9-9ed69b601e17`
var re *regexp.Regexp
re, err = regexp.Compile(
"([a-z-]*\\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})")
if err != nil {
return err
}
found := re.FindAll([]byte(msg), -1)
for _, f := range found {
split := strings.Split(string(f), "/")
typename := split[0]
UUID := split[1]
var child contrail.IObject
child, err = c.ApiClient.FindByUuid(typename, UUID)
if err != nil {
return err
}
if child == nil {
return errors.New("Child object is nil")
}
err = c.DeleteElementRecursive(child)
if err != nil {
return err
}
}
}
}
return nil
}
func (c *ControllerAdapter) is404(err error) bool {
return strings.HasPrefix(err.Error(), "404")
}