blob: c5331628bf34d31d0654e1ed9747e2d1e50489b5 [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 kdanilovfd2cfa52015-05-20 03:17:42 +03008from concurrent.futures import ThreadPoolExecutor
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
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300262def wait_for_server_active(nova, server, timeout=300):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800263 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 kdanilov4af1c1d2015-05-18 15:48:58 +0300294 logger.debug("Calculating new vm count")
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:
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300308 logger.debug("Not need new vms")
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300309 return
koder aka kdanilovda45e882015-04-06 02:24:42 +0300310
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300311 logger.debug("Starting new nodes on openstack")
312
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300313 assert isinstance(count, (int, long))
314
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300315 srv_params = "img: {image[name]}, flavor: {flavor[name]}".format(**params)
koder aka kdanilov66839a92015-04-11 13:22:31 +0300316 msg_templ = "Will start {0} servers with next params: {1}"
koder aka kdanilovcee43342015-04-14 22:52:53 +0300317 logger.info(msg_templ.format(count, srv_params))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300318
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300319 vm_params = dict(
320 img_name=params['image']['name'],
321 flavor_name=params['flavor']['name'],
322 group_name=params['group_name'],
323 keypair_name=params['keypair_name'],
324 vol_sz=params.get('vol_sz'),
325 network_zone_name=params.get("network_zone_name"),
326 flt_ip_pool=params.get('flt_ip_pool'),
327 name_templ=params.get('name_templ'),
328 scheduler_hints={"group": params['aa_group_name']},
329 security_group=params['security_group'],
330 sec_group_size=srv_count
331 )
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300332
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300333 # precache all errors before start creating vms
334 private_key_path = params['keypair_file_private']
335 creds = params['image']['creds']
336 creds.format(ip="1.1.1.1", private_key_path="/some_path/xx")
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300337
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300338 for ip, os_node in create_vms_mt(NOVA_CONNECTION, count, **vm_params):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300339
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300340 conn_uri = creds.format(ip=ip, private_key_path=private_key_path)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300341 yield Node(conn_uri, []), os_node.id
koder aka kdanilovda45e882015-04-06 02:24:42 +0300342
343
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300344def get_free_server_grpoups(nova, template=None):
345 for g in nova.server_groups.list():
346 if g.members == []:
347 if re.match(template, g.name):
348 yield str(g.name)
349
350
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300351def create_vms_mt(nova, amount, group_name, keypair_name, img_name,
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800352 flavor_name, vol_sz=None, network_zone_name=None,
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300353 flt_ip_pool=None, name_templ='wally-{id}',
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300354 scheduler_hints=None, security_group=None,
355 sec_group_size=None):
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800356
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800357 with ThreadPoolExecutor(max_workers=16) as executor:
koder aka kdanilov97644f92015-02-13 11:11:08 -0800358 if network_zone_name is not None:
359 network_future = executor.submit(nova.networks.find,
360 label=network_zone_name)
361 else:
362 network_future = None
363
364 fl_future = executor.submit(nova.flavors.find, name=flavor_name)
365 img_future = executor.submit(nova.images.find, name=img_name)
366
367 if flt_ip_pool is not None:
368 ips_future = executor.submit(get_floating_ips,
369 nova, flt_ip_pool, amount)
koder aka kdanilove21d7472015-02-14 19:02:04 -0800370 logger.debug("Wait for floating ip")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800371 ips = ips_future.result()
372 ips += [Allocate] * (amount - len(ips))
373 else:
374 ips = [None] * amount
375
koder aka kdanilov7dec9df2015-02-15 21:35:19 -0800376 logger.debug("Getting flavor object")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800377 fl = fl_future.result()
koder aka kdanilov7dec9df2015-02-15 21:35:19 -0800378 logger.debug("Getting image object")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800379 img = img_future.result()
380
381 if network_future is not None:
koder aka kdanilove21d7472015-02-14 19:02:04 -0800382 logger.debug("Waiting for network results")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800383 nics = [{'net-id': network_future.result().id}]
384 else:
385 nics = None
386
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300387 names = []
388 for i in range(amount):
389 names.append(name_templ.format(group=group_name, id=i))
koder aka kdanilov97644f92015-02-13 11:11:08 -0800390
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800391 futures = []
koder aka kdanilov168f6092015-04-19 02:33:38 +0300392 logger.debug("Requesting new vm's")
koder aka kdanilov6e2ae792015-03-04 18:02:24 -0800393
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300394 orig_scheduler_hints = scheduler_hints.copy()
395
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300396 MAX_SHED_GROUPS = 32
397 for start_idx in range(MAX_SHED_GROUPS):
398 pass
399
400 group_name_template = scheduler_hints['group'].format("\\d+")
401 groups = list(get_free_server_grpoups(nova, group_name_template + "$"))
402 groups.sort()
403
404 for idx, (name, flt_ip) in enumerate(zip(names, ips), 2):
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300405
406 scheduler_hints = None
407 if orig_scheduler_hints is not None and sec_group_size is not None:
408 if "group" in orig_scheduler_hints:
409 scheduler_hints = orig_scheduler_hints.copy()
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300410 scheduler_hints['group'] = groups[idx // sec_group_size]
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300411
412 if scheduler_hints is None:
413 scheduler_hints = orig_scheduler_hints.copy()
414
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800415 params = (nova, name, keypair_name, img, fl,
416 nics, vol_sz, flt_ip, scheduler_hints,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300417 flt_ip_pool, [security_group])
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800418
419 futures.append(executor.submit(create_vm, *params))
koder aka kdanilove21d7472015-02-14 19:02:04 -0800420 res = [future.result() for future in futures]
421 logger.debug("Done spawning")
422 return res
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800423
424
425def create_vm(nova, name, keypair_name, img,
426 fl, nics, vol_sz=None,
427 flt_ip=False,
428 scheduler_hints=None,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300429 pool=None,
430 security_groups=None):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800431 for i in range(3):
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800432 srv = nova.servers.create(name,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300433 flavor=fl,
434 image=img,
435 nics=nics,
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800436 key_name=keypair_name,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300437 scheduler_hints=scheduler_hints,
438 security_groups=security_groups)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800439
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800440 if not wait_for_server_active(nova, srv):
441 msg = "Server {0} fails to start. Kill it and try again"
koder aka kdanilove21d7472015-02-14 19:02:04 -0800442 logger.debug(msg.format(srv))
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800443 nova.servers.delete(srv)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800444
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300445 try:
446 for j in range(120):
447 srv = nova.servers.get(srv.id)
448 time.sleep(1)
449 else:
450 msg = "Server {0} delete timeout".format(srv.id)
451 raise RuntimeError(msg)
452 except NotFound:
453 pass
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800454 else:
455 break
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300456 else:
457 raise RuntimeError("Failed to start server".format(srv.id))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800458
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800459 if vol_sz is not None:
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800460 vol = create_volume(vol_sz, name)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300461 nova.volumes.create_server_volume(srv.id, vol.id, None)
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800462
463 if flt_ip is Allocate:
464 flt_ip = nova.floating_ips.create(pool)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300465
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800466 if flt_ip is not None:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800467 srv.add_floating_ip(flt_ip)
Yulia Portnova0e64ea22015-03-20 17:27:22 +0200468
koder aka kdanilovda45e882015-04-06 02:24:42 +0300469 return flt_ip.ip, nova.servers.get(srv.id)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800470
471
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300472def clear_nodes(nodes_ids):
473 clear_all(NOVA_CONNECTION, nodes_ids, None)
gstepanov023c1e42015-04-08 15:50:19 +0300474
475
koder aka kdanilove87ae652015-04-20 02:14:35 +0300476def clear_all(nova, ids=None, name_templ=None):
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300477
478 def need_delete(srv):
479 if name_templ is not None:
480 return re.match(name_templ.format("\\d+"), srv.name) is not None
481 else:
482 return srv.id in ids
483
koder aka kdanilove87ae652015-04-20 02:14:35 +0300484 volumes_to_delete = []
485 cinder = cinder_connect()
486 for vol in cinder.volumes.list():
487 for attachment in vol.attachments:
488 if attachment['server_id'] in ids:
489 volumes_to_delete.append(vol)
490 break
491
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800492 deleted_srvs = set()
493 for srv in nova.servers.list():
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300494 if need_delete(srv):
koder aka kdanilove21d7472015-02-14 19:02:04 -0800495 logger.debug("Deleting server {0}".format(srv.name))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800496 nova.servers.delete(srv)
497 deleted_srvs.add(srv.id)
498
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300499 count = 0
500 while True:
501 if count % 60 == 0:
502 logger.debug("Waiting till all servers are actually deleted")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800503 all_id = set(srv.id for srv in nova.servers.list())
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300504 if len(all_id.intersection(deleted_srvs)) == 0:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800505 break
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300506 count += 1
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800507 time.sleep(1)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300508 logger.debug("Done, deleting volumes")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800509
510 # wait till vm actually deleted
511
koder aka kdanilov6b1341a2015-04-21 22:44:21 +0300512 # logger.warning("Volume deletion commented out")
513 for vol in volumes_to_delete:
514 logger.debug("Deleting volume " + vol.display_name)
515 cinder.volumes.delete(vol)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800516
koder aka kdanilove21d7472015-02-14 19:02:04 -0800517 logger.debug("Clearing done (yet some volumes may still deleting)")