blob: 3682fd3a13dac028f1caebc2e6ab3010382074f5 [file] [log] [blame]
Scott Bakerb63ea792016-08-11 10:24:48 -07001import os
2import base64
3import socket
Scott Bakerb63ea792016-08-11 10:24:48 -07004from xos.config import Config
5from xos.settings import RESTAPI_HOSTNAME, RESTAPI_PORT
Scott Baker8b75e852016-08-16 15:04:59 -07006from synchronizers.openstack.openstacksyncstep import OpenStackSyncStep
Scott Bakeraf599eb2017-03-21 12:43:26 -07007from synchronizers.new_base.ansible_helper import *
8from synchronizers.new_base.syncstep import *
Scott Bakerb63ea792016-08-11 10:24:48 -07009from xos.logger import observer_logger as logger
Scott Bakeraf599eb2017-03-21 12:43:26 -070010from synchronizers.new_base.modelaccessor import *
Scott Bakerb63ea792016-08-11 10:24:48 -070011
12def escape(s):
13 s = s.replace('\n',r'\n').replace('"',r'\"')
14 return s
15
16class SyncInstances(OpenStackSyncStep):
17 provides=[Instance]
18 requested_interval=0
19 observes=Instance
20 playbook='sync_instances.yaml'
21
22 def fetch_pending(self, deletion=False):
23 objs = super(SyncInstances, self).fetch_pending(deletion)
24 objs = [x for x in objs if x.isolation=="vm"]
25 return objs
26
27 def get_userdata(self, instance, pubkeys):
28 userdata = '#cloud-config\n\nopencloud:\n slicename: "%s"\n hostname: "%s"\n restapi_hostname: "%s"\n restapi_port: "%s"\n' % (instance.slice.name, instance.node.name, RESTAPI_HOSTNAME, str(RESTAPI_PORT))
29 userdata += 'ssh_authorized_keys:\n'
30 for key in pubkeys:
31 userdata += ' - %s\n' % key
32 return userdata
33
Andy Bavier4435bf02017-02-01 16:17:09 -050034 def get_nic_for_first_slot(self, nics):
35 # Try to find a NIC with "public" visibility
36 for nic in nics[:]:
37 network=nic.get("network", None)
38 if network:
39 tem = network.template
40 if (tem.visibility == "public"):
41 return nic
Scott Bakerb63ea792016-08-11 10:24:48 -070042
Andy Bavier4435bf02017-02-01 16:17:09 -050043 # Otherwise try to find a private network
Scott Bakerb63ea792016-08-11 10:24:48 -070044 for nic in nics[:]:
45 network=nic.get("network", None)
46 if network:
47 tem = network.template
48 if (tem.visibility == "private") and (tem.translation=="none") and ("management" not in tem.name):
Andy Bavier4435bf02017-02-01 16:17:09 -050049 return nic
50
51 raise Exception("Could not find a NIC for first slot")
52
53 def sort_nics(self, nics):
54 result = []
55
56 # Enforce VTN's network order requirement for vSG. The access network must be
57 # inserted into the first slot. The management network must be inserted
58 # into the second slot.
59 #
60 # Some VMs may connect to multiple networks that advertise gateways. In this case, the
61 # default gateway is enforced on eth0. So give priority to "public" networks when
62 # choosing a network for the first slot.
63
64 nic = self.get_nic_for_first_slot(nics)
65 result.append(nic)
66 nics.remove(nic)
Scott Bakerb63ea792016-08-11 10:24:48 -070067
68 # move the management network to the second spot
Scott Bakeread6af42016-10-11 16:40:40 -070069 for nic in nics[:]:
Scott Bakerb63ea792016-08-11 10:24:48 -070070 network=nic.get("network", None)
71 if network:
72 tem = network.template
73 if (tem.visibility == "private") and (tem.translation=="none") and ("management" in tem.name):
74#MCORD
75# if len(result)!=1:
76# raise Exception("Management network needs to be inserted in slot 1, but there are %d private nics" % len(result))
77 result.append(nic)
78 nics.remove(nic)
79
80 # add everything else. For VTN there probably shouldn't be any more.
81 result.extend(nics)
82
83 return result
84
85 def map_sync_inputs(self, instance):
Scott Bakere13170a2017-01-26 09:57:37 -080086
87 # sanity check - make sure model_policy for slice has run
88 if ((not instance.slice.policed) or (instance.slice.policed < instance.slice.updated)):
89 raise DeferredException("Instance %s waiting on Slice %s to execute model policies" % (instance, slice.name))
90
91 # sanity check - make sure model_policy for all slice networks have run
92 for network in instance.slice.ownedNetworks.all():
93 if ((not network.policed) or (network.policed < network.updated)):
94 raise DeferredException("Instance %s waiting on Network %s to execute model policies" % (instance, network.name))
95
Scott Bakerb63ea792016-08-11 10:24:48 -070096 inputs = {}
97 metadata_update = {}
98 if (instance.numberCores):
99 metadata_update["cpu_cores"] = str(instance.numberCores)
100
101 for tag in instance.slice.tags.all():
102 if tag.name.startswith("sysctl-"):
103 metadata_update[tag.name] = tag.value
104
Scott Bakeraf599eb2017-03-21 12:43:26 -0700105 slice_memberships = SlicePrivilege.objects.filter(slice_id=instance.slice.id)
Scott Bakerb63ea792016-08-11 10:24:48 -0700106 pubkeys = set([sm.user.public_key for sm in slice_memberships if sm.user.public_key])
107 if instance.creator.public_key:
108 pubkeys.add(instance.creator.public_key)
109
110 if instance.slice.creator.public_key:
111 pubkeys.add(instance.slice.creator.public_key)
112
113 if instance.slice.service and instance.slice.service.public_key:
114 pubkeys.add(instance.slice.service.public_key)
115
116 nics=[]
117
118 # handle ports the were created by the user
119 port_ids=[]
Scott Bakeraf599eb2017-03-21 12:43:26 -0700120 for port in Port.objects.filter(instance_id=instance.id):
Scott Bakerb63ea792016-08-11 10:24:48 -0700121 if not port.port_id:
122 raise DeferredException("Instance %s waiting on port %s" % (instance, port))
123 nics.append({"kind": "port", "value": port.port_id, "network": port.network})
124
125 # we want to exclude from 'nics' any network that already has a Port
Scott Bakeraf599eb2017-03-21 12:43:26 -0700126 existing_port_networks = [port.network for port in Port.objects.filter(instance_id=instance.id)]
127 existing_port_network_ids = [x.id for x in existing_port_networks]
Scott Bakerb63ea792016-08-11 10:24:48 -0700128
Scott Bakeraf599eb2017-03-21 12:43:26 -0700129 networks = [ns.network for ns in NetworkSlice.objects.filter(slice_id=instance.slice.id) if ns.network.id not in existing_port_network_ids]
130 networks_ids = [x.id for x in networks]
131 controller_networks = ControllerNetwork.objects.filter(controller_id=instance.node.site_deployment.controller.id)
132 controller_networks = [x for x in controller_networks if x.id in networks_ids]
133
Scott Bakerb63ea792016-08-11 10:24:48 -0700134
Scott Baker6c69a122016-12-07 16:08:55 -0800135 for network in networks:
Scott Bakeraf599eb2017-03-21 12:43:26 -0700136 if not ControllerNetwork.objects.filter(network_id=network.id, controller_id=instance.node.site_deployment.controller.id).exists():
Scott Baker6c69a122016-12-07 16:08:55 -0800137 raise DeferredException("Instance %s Private Network %s lacks ControllerNetwork object" % (instance, network.name))
138
Scott Bakerb63ea792016-08-11 10:24:48 -0700139 for controller_network in controller_networks:
140 # Lenient exception - causes slow backoff
Andy Bavier4435bf02017-02-01 16:17:09 -0500141 if controller_network.network.template.translation == 'none':
Scott Bakerb63ea792016-08-11 10:24:48 -0700142 if not controller_network.net_id:
143 raise DeferredException("Instance %s Private Network %s has no id; Try again later" % (instance, controller_network.network.name))
144 nics.append({"kind": "net", "value": controller_network.net_id, "network": controller_network.network})
145
146 # now include network template
147 network_templates = [network.template.shared_network_name for network in networks \
148 if network.template.shared_network_name]
149
Scott Bakerb63ea792016-08-11 10:24:48 -0700150 driver = self.driver.admin_driver(tenant='admin', controller=instance.node.site_deployment.controller)
151 nets = driver.shell.neutron.list_networks()['networks']
152 for net in nets:
153 if net['name'] in network_templates:
154 nics.append({"kind": "net", "value": net['id'], "network": None})
155
156 if (not nics):
157 for net in nets:
158 if net['name']=='public':
159 nics.append({"kind": "net", "value": net['id'], "network": None})
160
161 nics = self.sort_nics(nics)
162
163 image_name = None
Scott Bakeraf599eb2017-03-21 12:43:26 -0700164 controller_images = instance.image.controllerimages.all()
165 controller_images = [x for x in controller_images if x.controller_id==instance.node.site_deployment.controller.id]
Scott Bakerb63ea792016-08-11 10:24:48 -0700166 if controller_images:
167 image_name = controller_images[0].image.name
168 logger.info("using image from ControllerImage object: " + str(image_name))
169
170 if image_name is None:
171 controller_driver = self.driver.admin_driver(controller=instance.node.site_deployment.controller)
172 images = controller_driver.shell.glanceclient.images.list()
173 for image in images:
174 if image.name == instance.image.name or not image_name:
175 image_name = image.name
176 logger.info("using image from glance: " + str(image_name))
177
178 try:
179 legacy = Config().observer_legacy
180 except:
181 legacy = False
182
183 if (legacy):
184 host_filter = instance.node.name.split('.',1)[0]
185 else:
186 host_filter = instance.node.name.strip()
187
188 availability_zone_filter = 'nova:%s'%host_filter
189 instance_name = '%s-%d'%(instance.slice.name,instance.id)
190 self.instance_name = instance_name
191
192 userData = self.get_userdata(instance, pubkeys)
193 if instance.userData:
194 userData += instance.userData
195
196 controller = instance.node.site_deployment.controller
197 fields = {'endpoint':controller.auth_url,
198 'endpoint_v3': controller.auth_url_v3,
199 'domain': controller.domain,
200 'admin_user': instance.creator.email,
201 'admin_password': instance.creator.remote_password,
202 'project_name': instance.slice.name,
203 'tenant': instance.slice.name,
204 'tenant_description': instance.slice.description,
205 'name':instance_name,
206 'ansible_tag':instance_name,
207 'availability_zone': availability_zone_filter,
208 'image_name':image_name,
209 'flavor_name':instance.flavor.name,
210 'nics':nics,
211 'meta':metadata_update,
212 'user_data':r'%s'%escape(userData)}
213 return fields
214
215
216 def map_sync_outputs(self, instance, res):
217 instance_id = res[0]['openstack']['OS-EXT-SRV-ATTR:instance_name']
218 instance_uuid = res[0]['id']
219
220 try:
221 hostname = res[0]['openstack']['OS-EXT-SRV-ATTR:hypervisor_hostname']
222 ip = socket.gethostbyname(hostname)
223 instance.ip = ip
224 except:
225 pass
226
227 instance.instance_id = instance_id
228 instance.instance_uuid = instance_uuid
229 instance.instance_name = self.instance_name
230 instance.save()
231
232
233 def map_delete_inputs(self, instance):
234 controller_register = json.loads(instance.node.site_deployment.controller.backend_register)
235
236 if (controller_register.get('disabled',False)):
237 raise InnocuousException('Controller %s is disabled'%instance.node.site_deployment.controller.name)
238
239 instance_name = '%s-%d'%(instance.slice.name,instance.id)
240 controller = instance.node.site_deployment.controller
241 input = {'endpoint':controller.auth_url,
242 'admin_user': instance.creator.email,
243 'admin_password': instance.creator.remote_password,
Andy Bavier9e65a352016-09-30 15:39:02 -0400244 'project_name': instance.slice.name,
Scott Bakerb63ea792016-08-11 10:24:48 -0700245 'tenant': instance.slice.name,
246 'tenant_description': instance.slice.description,
247 'name':instance_name,
248 'ansible_tag':instance_name,
249 'delete': True}
250 return input