blob: 7e1c6876a29a86770c7490893e9c32faab1a0234 [file] [log] [blame]
koder aka kdanilov4643fd62015-02-10 16:20:13 -08001import re
2import os
3import time
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +03004import os.path
koder aka kdanilove21d7472015-02-14 19:02:04 -08005import logging
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +03006import subprocess
koder aka kdanilov4643fd62015-02-10 16:20:13 -08007
koder aka kdanilov416b87a2015-05-12 00:26:04 +03008from concurrent.futures import ThreadPoolExecutor, wait
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -08009
koder aka kdanilov4500a5f2015-04-17 16:55:17 +030010from novaclient.exceptions import NotFound
koder aka kdanilov4643fd62015-02-10 16:20:13 -080011from novaclient.client import Client as n_client
12from cinderclient.v1.client import Client as c_client
13
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030014import wally
15from wally.discover import Node
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030016
koder aka kdanilov4643fd62015-02-10 16:20:13 -080017
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030018logger = logging.getLogger("wally.vms")
koder aka kdanilove21d7472015-02-14 19:02:04 -080019
20
koder aka kdanilove87ae652015-04-20 02:14:35 +030021STORED_OPENSTACK_CREDS = None
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030022NOVA_CONNECTION = None
koder aka kdanilove87ae652015-04-20 02:14:35 +030023CINDER_CONNECTION = None
24
25
koder aka kdanilov416b87a2015-05-12 00:26:04 +030026def is_connected():
27 return NOVA_CONNECTION is not None
28
29
koder aka kdanilove87ae652015-04-20 02:14:35 +030030def ostack_get_creds():
31 if STORED_OPENSTACK_CREDS is None:
32 env = os.environ.get
33 name = env('OS_USERNAME')
34 passwd = env('OS_PASSWORD')
35 tenant = env('OS_TENANT_NAME')
36 auth_url = env('OS_AUTH_URL')
37 return name, passwd, tenant, auth_url
38 else:
39 return STORED_OPENSTACK_CREDS
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030040
41
42def nova_connect(name=None, passwd=None, tenant=None, auth_url=None):
43 global NOVA_CONNECTION
koder aka kdanilove87ae652015-04-20 02:14:35 +030044 global STORED_OPENSTACK_CREDS
45
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030046 if NOVA_CONNECTION is None:
47 if name is None:
48 name, passwd, tenant, auth_url = ostack_get_creds()
koder aka kdanilove87ae652015-04-20 02:14:35 +030049 else:
50 STORED_OPENSTACK_CREDS = (name, passwd, tenant, auth_url)
51
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030052 NOVA_CONNECTION = n_client('1.1', name, passwd, tenant, auth_url)
53 return NOVA_CONNECTION
54
55
koder aka kdanilove87ae652015-04-20 02:14:35 +030056def cinder_connect(name=None, passwd=None, tenant=None, auth_url=None):
57 global CINDER_CONNECTION
58 global STORED_OPENSTACK_CREDS
59
60 if CINDER_CONNECTION is None:
61 if name is None:
62 name, passwd, tenant, auth_url = ostack_get_creds()
63 else:
64 STORED_OPENSTACK_CREDS = (name, passwd, tenant, auth_url)
65 CINDER_CONNECTION = c_client(name, passwd, tenant, auth_url)
66 return CINDER_CONNECTION
67
68
koder aka kdanilovc368eb62015-04-28 18:22:01 +030069def prepare_os_subpr(params, name=None, passwd=None, tenant=None,
70 auth_url=None):
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +030071 if name is None:
72 name, passwd, tenant, auth_url = ostack_get_creds()
73
koder aka kdanilovc368eb62015-04-28 18:22:01 +030074 MAX_VM_PER_NODE = 8
75 serv_groups = " ".join(map(params['aa_group_name'].format,
76 range(MAX_VM_PER_NODE)))
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +030077
koder aka kdanilovc368eb62015-04-28 18:22:01 +030078 env = os.environ.copy()
79 env.update(dict(
80 OS_USERNAME=name,
81 OS_PASSWORD=passwd,
82 OS_TENANT_NAME=tenant,
83 OS_AUTH_URL=auth_url,
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +030084
koder aka kdanilovc368eb62015-04-28 18:22:01 +030085 FLAVOR_NAME=params['flavor']['name'],
86 FLAVOR_RAM=str(params['flavor']['ram_size']),
87 FLAVOR_HDD=str(params['flavor']['hdd_size']),
88 FLAVOR_CPU_COUNT=str(params['flavor']['cpu_count']),
89
90 SERV_GROUPS=serv_groups,
91 KEYPAIR_NAME=params['keypair_name'],
92
93 SECGROUP=params['security_group'],
94
95 IMAGE_NAME=params['image']['name'],
96 KEY_FILE_NAME=params['keypair_file_private'],
97 IMAGE_URL=params['image']['url'],
98 ))
99
100 spath = os.path.dirname(os.path.dirname(wally.__file__))
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300101 spath = os.path.join(spath, 'scripts/prepare.sh')
102
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300103 cmd = "bash {spath} >/dev/null".format(spath=spath)
104 subprocess.check_call(cmd, shell=True, env=env)
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300105
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300106 conn = nova_connect(name, passwd, tenant, auth_url)
107 while True:
108 status = conn.images.find(name='wally_ubuntu').status
109 if status == 'ACTIVE':
110 break
111 msg = "Image {0} is still in {1} state. Waiting 10 more seconds"
112 logger.info(msg.format('wally_ubuntu', status))
113 time.sleep(10)
114
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300115
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300116def find_vms(nova, name_prefix):
117 for srv in nova.servers.list():
118 if srv.name.startswith(name_prefix):
119 for ips in srv.addresses.values():
120 for ip in ips:
121 if ip.get("OS-EXT-IPS:type", None) == 'floating':
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300122 yield ip['addr'], srv.id
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300123 break
124
125
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300126def pause(ids):
127 def pause_vm(conn, vm_id):
128 vm = conn.servers.get(vm_id)
129 if vm.status == 'ACTIVE':
130 vm.pause()
131
132 conn = nova_connect()
133 with ThreadPoolExecutor(max_workers=16) as executor:
134 futures = [executor.submit(pause_vm, conn, vm_id)
135 for vm_id in ids]
136 for future in futures:
137 future.result()
138
139
140def unpause(ids, max_resume_time=10):
141 def unpause(conn, vm_id):
142 vm = conn.servers.get(vm_id)
143 if vm.status == 'PAUSED':
144 vm.unpause()
145
146 for i in range(max_resume_time * 10):
147 vm = conn.servers.get(vm_id)
148 if vm.status != 'PAUSED':
149 return
150 time.sleep(0.1)
151 raise RuntimeError("Can't unpause vm {0}".format(vm_id))
152
153 conn = nova_connect()
154 with ThreadPoolExecutor(max_workers=16) as executor:
155 futures = [executor.submit(unpause, conn, vm_id)
156 for vm_id in ids]
157
158 for future in futures:
159 future.result()
160
161
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300162def prepare_os(nova, params):
163 allow_ssh(nova, params['security_group'])
164
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300165 MAX_VM_PER_NODE = 8
166 serv_groups = " ".join(map(params['aa_group_name'].format,
167 range(MAX_VM_PER_NODE)))
168
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300169 shed_ids = []
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300170 for shed_group in serv_groups:
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300171 shed_ids.append(get_or_create_aa_group(nova, shed_group))
172
173 create_keypair(nova,
174 params['keypair_name'],
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300175 params['keypair_name'] + ".pub",
176 params['keypair_name'] + ".pem")
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300177
178 create_image(nova, params['image']['name'],
179 params['image']['url'])
180
181 create_flavor(nova, **params['flavor'])
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300182
183
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300184def get_or_create_aa_group(nova, name):
185 try:
186 group = nova.server_groups.find(name=name)
187 except NotFound:
188 group = nova.server_groups.create({'name': name,
189 'policies': ['anti-affinity']})
koder aka kdanilov652cd802015-04-13 12:21:07 +0300190
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300191 return group.id
koder aka kdanilov652cd802015-04-13 12:21:07 +0300192
193
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300194def allow_ssh(nova, group_name):
195 try:
196 secgroup = nova.security_groups.find(name=group_name)
197 except NotFound:
198 secgroup = nova.security_groups.create(group_name,
199 "allow ssh/ping to node")
200
koder aka kdanilov652cd802015-04-13 12:21:07 +0300201 nova.security_group_rules.create(secgroup.id,
202 ip_protocol="tcp",
203 from_port="22",
204 to_port="22",
205 cidr="0.0.0.0/0")
206
207 nova.security_group_rules.create(secgroup.id,
208 ip_protocol="icmp",
209 from_port=-1,
210 cidr="0.0.0.0/0",
211 to_port=-1)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300212 return secgroup.id
koder aka kdanilov652cd802015-04-13 12:21:07 +0300213
214
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300215def create_image(nova, name, url):
216 pass
217
218
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300219def create_flavor(nova, name, ram_size, hdd_size, cpu_count):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300220 pass
221
222
223def create_keypair(nova, name, pub_key_path, priv_key_path):
224 try:
225 nova.keypairs.find(name=name)
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300226 # if file not found- delete and recreate
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300227 except NotFound:
228 if os.path.exists(pub_key_path):
229 with open(pub_key_path) as pub_key_fd:
230 return nova.keypairs.create(name, pub_key_fd.read())
231 else:
232 key = nova.keypairs.create(name)
233
234 with open(priv_key_path, "w") as priv_key_fd:
235 priv_key_fd.write(key.private_key)
236
237 with open(pub_key_path, "w") as pub_key_fd:
238 pub_key_fd.write(key.public_key)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800239
240
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800241def create_volume(size, name):
koder aka kdanilove87ae652015-04-20 02:14:35 +0300242 cinder = cinder_connect()
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800243 vol = cinder.volumes.create(size=size, display_name=name)
244 err_count = 0
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300245
koder aka kdanilove87ae652015-04-20 02:14:35 +0300246 while vol.status != 'available':
247 if vol.status == 'error':
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800248 if err_count == 3:
koder aka kdanilove21d7472015-02-14 19:02:04 -0800249 logger.critical("Fail to create volume")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800250 raise RuntimeError("Fail to create volume")
251 else:
252 err_count += 1
253 cinder.volumes.delete(vol)
254 time.sleep(1)
255 vol = cinder.volumes.create(size=size, display_name=name)
256 continue
257 time.sleep(1)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300258 vol = cinder.volumes.get(vol.id)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800259 return vol
260
261
262def wait_for_server_active(nova, server, timeout=240):
263 t = time.time()
264 while True:
koder aka kdanilov3f356262015-02-13 08:06:14 -0800265 time.sleep(1)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800266 sstate = getattr(server, 'OS-EXT-STS:vm_state').lower()
267
268 if sstate == 'active':
269 return True
270
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800271 if sstate == 'error':
272 return False
273
274 if time.time() - t > timeout:
275 return False
276
277 server = nova.servers.get(server)
278
279
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800280class Allocate(object):
281 pass
282
283
284def get_floating_ips(nova, pool, amount):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800285 ip_list = nova.floating_ips.list()
286
287 if pool is not None:
288 ip_list = [ip for ip in ip_list if ip.pool == pool]
289
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800290 return [ip for ip in ip_list if ip.instance_id is None][:amount]
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800291
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800292
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300293def launch_vms(params, already_has_count=0):
koder aka kdanilovda45e882015-04-06 02:24:42 +0300294 logger.debug("Starting new nodes on openstack")
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300295 count = params['count']
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300296 nova = nova_connect()
297 lst = nova.services.list(binary='nova-compute')
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300298 srv_count = len([srv for srv in lst if srv.status == 'enabled'])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300299
300 if isinstance(count, basestring):
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300301 if count.startswith("x"):
302 count = srv_count * int(count[1:])
303 else:
304 assert count.startswith('=')
305 count = int(count[1:]) - already_has_count
306
307 if count <= 0:
308 return
koder aka kdanilovda45e882015-04-06 02:24:42 +0300309
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300310 assert isinstance(count, (int, long))
311
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300312 srv_params = "img: {image[name]}, flavor: {flavor[name]}".format(**params)
koder aka kdanilov66839a92015-04-11 13:22:31 +0300313 msg_templ = "Will start {0} servers with next params: {1}"
koder aka kdanilovcee43342015-04-14 22:52:53 +0300314 logger.info(msg_templ.format(count, srv_params))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300315
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300316 vm_params = dict(
317 img_name=params['image']['name'],
318 flavor_name=params['flavor']['name'],
319 group_name=params['group_name'],
320 keypair_name=params['keypair_name'],
321 vol_sz=params.get('vol_sz'),
322 network_zone_name=params.get("network_zone_name"),
323 flt_ip_pool=params.get('flt_ip_pool'),
324 name_templ=params.get('name_templ'),
325 scheduler_hints={"group": params['aa_group_name']},
326 security_group=params['security_group'],
327 sec_group_size=srv_count
328 )
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300329
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300330 # precache all errors before start creating vms
331 private_key_path = params['keypair_file_private']
332 creds = params['image']['creds']
333 creds.format(ip="1.1.1.1", private_key_path="/some_path/xx")
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300334
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300335 for ip, os_node in create_vms_mt(NOVA_CONNECTION, count, **vm_params):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300336
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300337 conn_uri = creds.format(ip=ip, private_key_path=private_key_path)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300338 yield Node(conn_uri, []), os_node.id
koder aka kdanilovda45e882015-04-06 02:24:42 +0300339
340
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300341def get_free_server_grpoups(nova, template=None):
342 for g in nova.server_groups.list():
343 if g.members == []:
344 if re.match(template, g.name):
345 yield str(g.name)
346
347
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300348def create_vms_mt(nova, amount, group_name, keypair_name, img_name,
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800349 flavor_name, vol_sz=None, network_zone_name=None,
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300350 flt_ip_pool=None, name_templ='wally-{id}',
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300351 scheduler_hints=None, security_group=None,
352 sec_group_size=None):
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800353
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800354 with ThreadPoolExecutor(max_workers=16) as executor:
koder aka kdanilov97644f92015-02-13 11:11:08 -0800355 if network_zone_name is not None:
356 network_future = executor.submit(nova.networks.find,
357 label=network_zone_name)
358 else:
359 network_future = None
360
361 fl_future = executor.submit(nova.flavors.find, name=flavor_name)
362 img_future = executor.submit(nova.images.find, name=img_name)
363
364 if flt_ip_pool is not None:
365 ips_future = executor.submit(get_floating_ips,
366 nova, flt_ip_pool, amount)
koder aka kdanilove21d7472015-02-14 19:02:04 -0800367 logger.debug("Wait for floating ip")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800368 ips = ips_future.result()
369 ips += [Allocate] * (amount - len(ips))
370 else:
371 ips = [None] * amount
372
koder aka kdanilov7dec9df2015-02-15 21:35:19 -0800373 logger.debug("Getting flavor object")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800374 fl = fl_future.result()
koder aka kdanilov7dec9df2015-02-15 21:35:19 -0800375 logger.debug("Getting image object")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800376 img = img_future.result()
377
378 if network_future is not None:
koder aka kdanilove21d7472015-02-14 19:02:04 -0800379 logger.debug("Waiting for network results")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800380 nics = [{'net-id': network_future.result().id}]
381 else:
382 nics = None
383
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300384 names = []
385 for i in range(amount):
386 names.append(name_templ.format(group=group_name, id=i))
koder aka kdanilov97644f92015-02-13 11:11:08 -0800387
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800388 futures = []
koder aka kdanilov168f6092015-04-19 02:33:38 +0300389 logger.debug("Requesting new vm's")
koder aka kdanilov6e2ae792015-03-04 18:02:24 -0800390
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300391 orig_scheduler_hints = scheduler_hints.copy()
392
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300393 MAX_SHED_GROUPS = 32
394 for start_idx in range(MAX_SHED_GROUPS):
395 pass
396
397 group_name_template = scheduler_hints['group'].format("\\d+")
398 groups = list(get_free_server_grpoups(nova, group_name_template + "$"))
399 groups.sort()
400
401 for idx, (name, flt_ip) in enumerate(zip(names, ips), 2):
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300402
403 scheduler_hints = None
404 if orig_scheduler_hints is not None and sec_group_size is not None:
405 if "group" in orig_scheduler_hints:
406 scheduler_hints = orig_scheduler_hints.copy()
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300407 scheduler_hints['group'] = groups[idx // sec_group_size]
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300408
409 if scheduler_hints is None:
410 scheduler_hints = orig_scheduler_hints.copy()
411
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800412 params = (nova, name, keypair_name, img, fl,
413 nics, vol_sz, flt_ip, scheduler_hints,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300414 flt_ip_pool, [security_group])
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800415
416 futures.append(executor.submit(create_vm, *params))
koder aka kdanilove21d7472015-02-14 19:02:04 -0800417 res = [future.result() for future in futures]
418 logger.debug("Done spawning")
419 return res
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800420
421
422def create_vm(nova, name, keypair_name, img,
423 fl, nics, vol_sz=None,
424 flt_ip=False,
425 scheduler_hints=None,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300426 pool=None,
427 security_groups=None):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800428 for i in range(3):
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800429 srv = nova.servers.create(name,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300430 flavor=fl,
431 image=img,
432 nics=nics,
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800433 key_name=keypair_name,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300434 scheduler_hints=scheduler_hints,
435 security_groups=security_groups)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800436
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800437 if not wait_for_server_active(nova, srv):
438 msg = "Server {0} fails to start. Kill it and try again"
koder aka kdanilove21d7472015-02-14 19:02:04 -0800439 logger.debug(msg.format(srv))
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800440 nova.servers.delete(srv)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800441
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300442 try:
443 for j in range(120):
444 srv = nova.servers.get(srv.id)
445 time.sleep(1)
446 else:
447 msg = "Server {0} delete timeout".format(srv.id)
448 raise RuntimeError(msg)
449 except NotFound:
450 pass
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800451 else:
452 break
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300453 else:
454 raise RuntimeError("Failed to start server".format(srv.id))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800455
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800456 if vol_sz is not None:
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800457 vol = create_volume(vol_sz, name)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300458 nova.volumes.create_server_volume(srv.id, vol.id, None)
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800459
460 if flt_ip is Allocate:
461 flt_ip = nova.floating_ips.create(pool)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300462
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800463 if flt_ip is not None:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800464 srv.add_floating_ip(flt_ip)
Yulia Portnova0e64ea22015-03-20 17:27:22 +0200465
koder aka kdanilovda45e882015-04-06 02:24:42 +0300466 return flt_ip.ip, nova.servers.get(srv.id)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800467
468
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300469def clear_nodes(nodes_ids):
470 clear_all(NOVA_CONNECTION, nodes_ids, None)
gstepanov023c1e42015-04-08 15:50:19 +0300471
472
koder aka kdanilove87ae652015-04-20 02:14:35 +0300473def clear_all(nova, ids=None, name_templ=None):
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300474
475 def need_delete(srv):
476 if name_templ is not None:
477 return re.match(name_templ.format("\\d+"), srv.name) is not None
478 else:
479 return srv.id in ids
480
koder aka kdanilove87ae652015-04-20 02:14:35 +0300481 volumes_to_delete = []
482 cinder = cinder_connect()
483 for vol in cinder.volumes.list():
484 for attachment in vol.attachments:
485 if attachment['server_id'] in ids:
486 volumes_to_delete.append(vol)
487 break
488
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800489 deleted_srvs = set()
490 for srv in nova.servers.list():
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300491 if need_delete(srv):
koder aka kdanilove21d7472015-02-14 19:02:04 -0800492 logger.debug("Deleting server {0}".format(srv.name))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800493 nova.servers.delete(srv)
494 deleted_srvs.add(srv.id)
495
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300496 count = 0
497 while True:
498 if count % 60 == 0:
499 logger.debug("Waiting till all servers are actually deleted")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800500 all_id = set(srv.id for srv in nova.servers.list())
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300501 if len(all_id.intersection(deleted_srvs)) == 0:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800502 break
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300503 count += 1
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800504 time.sleep(1)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300505 logger.debug("Done, deleting volumes")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800506
507 # wait till vm actually deleted
508
koder aka kdanilov6b1341a2015-04-21 22:44:21 +0300509 # logger.warning("Volume deletion commented out")
510 for vol in volumes_to_delete:
511 logger.debug("Deleting volume " + vol.display_name)
512 cinder.volumes.delete(vol)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800513
koder aka kdanilove21d7472015-02-14 19:02:04 -0800514 logger.debug("Clearing done (yet some volumes may still deleting)")