blob: 432594a786609914da7babcf99a5886e44798523 [file] [log] [blame]
koder aka kdanilov4643fd62015-02-10 16:20:13 -08001import re
2import os
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +03003import stat
koder aka kdanilov4643fd62015-02-10 16:20:13 -08004import time
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +03005import os.path
koder aka kdanilove21d7472015-02-14 19:02:04 -08006import logging
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +03007import subprocess
koder aka kdanilovb7197432015-07-15 00:40:43 +03008import collections
koder aka kdanilov4643fd62015-02-10 16:20:13 -08009
koder aka kdanilovfd2cfa52015-05-20 03:17:42 +030010from concurrent.futures import ThreadPoolExecutor
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -080011
koder aka kdanilov4500a5f2015-04-17 16:55:17 +030012from novaclient.exceptions import NotFound
koder aka kdanilov4643fd62015-02-10 16:20:13 -080013from novaclient.client import Client as n_client
14from cinderclient.v1.client import Client as c_client
15
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030016import wally
17from wally.discover import Node
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030018
koder aka kdanilov4643fd62015-02-10 16:20:13 -080019
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030020logger = logging.getLogger("wally.vms")
koder aka kdanilove21d7472015-02-14 19:02:04 -080021
22
koder aka kdanilove87ae652015-04-20 02:14:35 +030023STORED_OPENSTACK_CREDS = None
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030024NOVA_CONNECTION = None
koder aka kdanilove87ae652015-04-20 02:14:35 +030025CINDER_CONNECTION = None
26
27
koder aka kdanilov416b87a2015-05-12 00:26:04 +030028def is_connected():
29 return NOVA_CONNECTION is not None
30
31
koder aka kdanilovb7197432015-07-15 00:40:43 +030032OSCreds = collections.namedtuple("OSCreds",
33 ["name", "passwd",
34 "tenant", "auth_url", "insecure"])
35
36
koder aka kdanilove87ae652015-04-20 02:14:35 +030037def ostack_get_creds():
38 if STORED_OPENSTACK_CREDS is None:
koder aka kdanilovb7197432015-07-15 00:40:43 +030039 return OSCreds(os.environ.get('OS_USERNAME'),
40 os.environ.get('OS_PASSWORD'),
41 os.environ.get('OS_TENANT_NAME'),
42 os.environ.get('OS_AUTH_URL'),
43 os.environ.get('OS_INSECURE', False))
koder aka kdanilove87ae652015-04-20 02:14:35 +030044 else:
45 return STORED_OPENSTACK_CREDS
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030046
47
koder aka kdanilovb7197432015-07-15 00:40:43 +030048def nova_connect(os_creds=None):
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030049 global NOVA_CONNECTION
koder aka kdanilove87ae652015-04-20 02:14:35 +030050 global STORED_OPENSTACK_CREDS
51
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030052 if NOVA_CONNECTION is None:
koder aka kdanilovb7197432015-07-15 00:40:43 +030053 if os_creds is None:
54 os_creds = ostack_get_creds()
koder aka kdanilove87ae652015-04-20 02:14:35 +030055 else:
koder aka kdanilovb7197432015-07-15 00:40:43 +030056 STORED_OPENSTACK_CREDS = os_creds
koder aka kdanilove87ae652015-04-20 02:14:35 +030057
koder aka kdanilovb7197432015-07-15 00:40:43 +030058 NOVA_CONNECTION = n_client('1.1',
59 os_creds.name,
60 os_creds.passwd,
61 os_creds.tenant,
62 os_creds.auth_url,
63 insecure=os_creds.insecure)
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030064 return NOVA_CONNECTION
65
66
koder aka kdanilovb7197432015-07-15 00:40:43 +030067def cinder_connect(os_creds=None):
koder aka kdanilove87ae652015-04-20 02:14:35 +030068 global CINDER_CONNECTION
69 global STORED_OPENSTACK_CREDS
70
71 if CINDER_CONNECTION is None:
koder aka kdanilovb7197432015-07-15 00:40:43 +030072 if os_creds is None:
73 os_creds = ostack_get_creds()
koder aka kdanilove87ae652015-04-20 02:14:35 +030074 else:
koder aka kdanilovb7197432015-07-15 00:40:43 +030075 STORED_OPENSTACK_CREDS = os_creds
76 CINDER_CONNECTION = c_client(os_creds.name,
77 os_creds.passwd,
78 os_creds.tenant,
79 os_creds.auth_url,
80 insecure=os_creds.insecure)
koder aka kdanilove87ae652015-04-20 02:14:35 +030081 return CINDER_CONNECTION
82
83
koder aka kdanilovb7197432015-07-15 00:40:43 +030084def prepare_os_subpr(nova, params, os_creds):
85 if os_creds is None:
86 os_creds = ostack_get_creds()
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +030087
koder aka kdanilovc368eb62015-04-28 18:22:01 +030088 MAX_VM_PER_NODE = 8
89 serv_groups = " ".join(map(params['aa_group_name'].format,
90 range(MAX_VM_PER_NODE)))
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +030091
koder aka kdanilov6ab4d432015-06-22 00:26:28 +030092 image_name = params['image']['name']
koder aka kdanilovc368eb62015-04-28 18:22:01 +030093 env = os.environ.copy()
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +030094
koder aka kdanilovc368eb62015-04-28 18:22:01 +030095 env.update(dict(
koder aka kdanilovb7197432015-07-15 00:40:43 +030096 OS_USERNAME=os_creds.name,
97 OS_PASSWORD=os_creds.passwd,
98 OS_TENANT_NAME=os_creds.tenant,
99 OS_AUTH_URL=os_creds.auth_url,
100 OS_INSECURE="1" if os_creds.insecure else "0",
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300101
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300102 FLAVOR_NAME=params['flavor']['name'],
103 FLAVOR_RAM=str(params['flavor']['ram_size']),
104 FLAVOR_HDD=str(params['flavor']['hdd_size']),
105 FLAVOR_CPU_COUNT=str(params['flavor']['cpu_count']),
106
107 SERV_GROUPS=serv_groups,
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300108
109 SECGROUP=params['security_group'],
110
koder aka kdanilov6ab4d432015-06-22 00:26:28 +0300111 IMAGE_NAME=image_name,
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300112 IMAGE_URL=params['image']['url'],
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300113
114 # KEYPAIR_NAME=params['keypair_name'],
115 # KEY_FILE_NAME=params['keypair_file_private'],
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300116 ))
117
118 spath = os.path.dirname(os.path.dirname(wally.__file__))
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300119 spath = os.path.join(spath, 'scripts/prepare.sh')
120
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300121 cmd = "bash {spath} >/dev/null 2>&1 ".format(spath=spath)
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300122 subprocess.check_call(cmd, shell=True, env=env)
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300123
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300124 while True:
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300125 status = nova.images.find(name=image_name).status
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300126 if status == 'ACTIVE':
127 break
128 msg = "Image {0} is still in {1} state. Waiting 10 more seconds"
koder aka kdanilov6ab4d432015-06-22 00:26:28 +0300129 logger.info(msg.format(image_name, status))
koder aka kdanilov7e0f7cf2015-05-01 17:24:35 +0300130 time.sleep(10)
131
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300132 create_keypair(nova,
133 params['keypair_name'],
134 params['keypair_file_public'],
135 params['keypair_file_private'])
136
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300137
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300138def find_vms(nova, name_prefix):
139 for srv in nova.servers.list():
140 if srv.name.startswith(name_prefix):
141 for ips in srv.addresses.values():
142 for ip in ips:
143 if ip.get("OS-EXT-IPS:type", None) == 'floating':
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300144 yield ip['addr'], srv.id
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300145 break
146
147
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300148def pause(ids):
149 def pause_vm(conn, vm_id):
150 vm = conn.servers.get(vm_id)
151 if vm.status == 'ACTIVE':
152 vm.pause()
153
154 conn = nova_connect()
155 with ThreadPoolExecutor(max_workers=16) as executor:
156 futures = [executor.submit(pause_vm, conn, vm_id)
157 for vm_id in ids]
158 for future in futures:
159 future.result()
160
161
162def unpause(ids, max_resume_time=10):
163 def unpause(conn, vm_id):
164 vm = conn.servers.get(vm_id)
165 if vm.status == 'PAUSED':
166 vm.unpause()
167
168 for i in range(max_resume_time * 10):
169 vm = conn.servers.get(vm_id)
170 if vm.status != 'PAUSED':
171 return
172 time.sleep(0.1)
173 raise RuntimeError("Can't unpause vm {0}".format(vm_id))
174
175 conn = nova_connect()
176 with ThreadPoolExecutor(max_workers=16) as executor:
177 futures = [executor.submit(unpause, conn, vm_id)
178 for vm_id in ids]
179
180 for future in futures:
181 future.result()
182
183
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300184def prepare_os(nova, params):
185 allow_ssh(nova, params['security_group'])
186
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300187 MAX_VM_PER_NODE = 8
188 serv_groups = " ".join(map(params['aa_group_name'].format,
189 range(MAX_VM_PER_NODE)))
190
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300191 shed_ids = []
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300192 for shed_group in serv_groups:
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300193 shed_ids.append(get_or_create_aa_group(nova, shed_group))
194
195 create_keypair(nova,
196 params['keypair_name'],
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300197 params['keypair_name'] + ".pub",
198 params['keypair_name'] + ".pem")
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300199
200 create_image(nova, params['image']['name'],
201 params['image']['url'])
202
203 create_flavor(nova, **params['flavor'])
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300204
205
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300206def create_keypair(nova, name, pub_key_path, priv_key_path):
207 pub_key_exists = os.path.exists(pub_key_path)
208 priv_key_exists = os.path.exists(priv_key_path)
209
210 try:
211 kpair = nova.keypairs.find(name=name)
212 # if file not found- delete and recreate
213 except NotFound:
214 kpair = None
215
216 if pub_key_exists and not priv_key_exists:
217 raise EnvironmentError("Private key file doesn't exists")
218
219 if not pub_key_exists and priv_key_exists:
220 raise EnvironmentError("Public key file doesn't exists")
221
222 if kpair is None:
223 if pub_key_exists:
224 with open(pub_key_path) as pub_key_fd:
225 return nova.keypairs.create(name, pub_key_fd.read())
226 else:
227 key = nova.keypairs.create(name)
228
229 with open(priv_key_path, "w") as priv_key_fd:
230 priv_key_fd.write(key.private_key)
231 os.chmod(priv_key_path, stat.S_IREAD | stat.S_IWRITE)
232
233 with open(pub_key_path, "w") as pub_key_fd:
234 pub_key_fd.write(key.public_key)
235 elif not priv_key_exists:
236 raise EnvironmentError("Private key file doesn't exists," +
237 " but key uploaded openstack." +
238 " Either set correct path to private key" +
239 " or remove key from openstack")
240
241
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300242def get_or_create_aa_group(nova, name):
243 try:
244 group = nova.server_groups.find(name=name)
245 except NotFound:
246 group = nova.server_groups.create({'name': name,
247 'policies': ['anti-affinity']})
koder aka kdanilov652cd802015-04-13 12:21:07 +0300248
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300249 return group.id
koder aka kdanilov652cd802015-04-13 12:21:07 +0300250
251
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300252def allow_ssh(nova, group_name):
253 try:
254 secgroup = nova.security_groups.find(name=group_name)
255 except NotFound:
256 secgroup = nova.security_groups.create(group_name,
257 "allow ssh/ping to node")
258
koder aka kdanilov652cd802015-04-13 12:21:07 +0300259 nova.security_group_rules.create(secgroup.id,
260 ip_protocol="tcp",
261 from_port="22",
262 to_port="22",
263 cidr="0.0.0.0/0")
264
265 nova.security_group_rules.create(secgroup.id,
266 ip_protocol="icmp",
267 from_port=-1,
268 cidr="0.0.0.0/0",
269 to_port=-1)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300270 return secgroup.id
koder aka kdanilov652cd802015-04-13 12:21:07 +0300271
272
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300273def create_image(nova, name, url):
274 pass
275
276
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300277def create_flavor(nova, name, ram_size, hdd_size, cpu_count):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300278 pass
279
280
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800281def create_volume(size, name):
koder aka kdanilove87ae652015-04-20 02:14:35 +0300282 cinder = cinder_connect()
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800283 vol = cinder.volumes.create(size=size, display_name=name)
284 err_count = 0
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300285
koder aka kdanilove87ae652015-04-20 02:14:35 +0300286 while vol.status != 'available':
287 if vol.status == 'error':
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800288 if err_count == 3:
koder aka kdanilove21d7472015-02-14 19:02:04 -0800289 logger.critical("Fail to create volume")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800290 raise RuntimeError("Fail to create volume")
291 else:
292 err_count += 1
293 cinder.volumes.delete(vol)
294 time.sleep(1)
295 vol = cinder.volumes.create(size=size, display_name=name)
296 continue
297 time.sleep(1)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300298 vol = cinder.volumes.get(vol.id)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800299 return vol
300
301
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300302def wait_for_server_active(nova, server, timeout=300):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800303 t = time.time()
304 while True:
koder aka kdanilov3f356262015-02-13 08:06:14 -0800305 time.sleep(1)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800306 sstate = getattr(server, 'OS-EXT-STS:vm_state').lower()
307
308 if sstate == 'active':
309 return True
310
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800311 if sstate == 'error':
312 return False
313
314 if time.time() - t > timeout:
315 return False
316
317 server = nova.servers.get(server)
318
319
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800320class Allocate(object):
321 pass
322
323
324def get_floating_ips(nova, pool, amount):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800325 ip_list = nova.floating_ips.list()
326
327 if pool is not None:
328 ip_list = [ip for ip in ip_list if ip.pool == pool]
329
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800330 return [ip for ip in ip_list if ip.instance_id is None][:amount]
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800331
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800332
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300333def launch_vms(params, already_has_count=0):
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300334 logger.debug("Calculating new vm count")
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300335 count = params['count']
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300336 nova = nova_connect()
337 lst = nova.services.list(binary='nova-compute')
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300338 srv_count = len([srv for srv in lst if srv.status == 'enabled'])
koder aka kdanilovda45e882015-04-06 02:24:42 +0300339
340 if isinstance(count, basestring):
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300341 if count.startswith("x"):
342 count = srv_count * int(count[1:])
343 else:
344 assert count.startswith('=')
345 count = int(count[1:]) - already_has_count
346
347 if count <= 0:
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300348 logger.debug("Not need new vms")
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300349 return
koder aka kdanilovda45e882015-04-06 02:24:42 +0300350
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300351 logger.debug("Starting new nodes on openstack")
352
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300353 assert isinstance(count, (int, long))
354
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300355 srv_params = "img: {image[name]}, flavor: {flavor[name]}".format(**params)
koder aka kdanilov66839a92015-04-11 13:22:31 +0300356 msg_templ = "Will start {0} servers with next params: {1}"
koder aka kdanilovcee43342015-04-14 22:52:53 +0300357 logger.info(msg_templ.format(count, srv_params))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300358
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300359 vm_params = dict(
360 img_name=params['image']['name'],
361 flavor_name=params['flavor']['name'],
362 group_name=params['group_name'],
363 keypair_name=params['keypair_name'],
364 vol_sz=params.get('vol_sz'),
365 network_zone_name=params.get("network_zone_name"),
366 flt_ip_pool=params.get('flt_ip_pool'),
367 name_templ=params.get('name_templ'),
368 scheduler_hints={"group": params['aa_group_name']},
369 security_group=params['security_group'],
370 sec_group_size=srv_count
371 )
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300372
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300373 # precache all errors before start creating vms
374 private_key_path = params['keypair_file_private']
375 creds = params['image']['creds']
376 creds.format(ip="1.1.1.1", private_key_path="/some_path/xx")
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300377
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300378 for ip, os_node in create_vms_mt(NOVA_CONNECTION, count, **vm_params):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300379
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300380 conn_uri = creds.format(ip=ip, private_key_path=private_key_path)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300381 yield Node(conn_uri, []), os_node.id
koder aka kdanilovda45e882015-04-06 02:24:42 +0300382
383
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300384def get_free_server_grpoups(nova, template=None):
385 for g in nova.server_groups.list():
386 if g.members == []:
387 if re.match(template, g.name):
388 yield str(g.name)
389
390
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300391def create_vms_mt(nova, amount, group_name, keypair_name, img_name,
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800392 flavor_name, vol_sz=None, network_zone_name=None,
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300393 flt_ip_pool=None, name_templ='wally-{id}',
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300394 scheduler_hints=None, security_group=None,
395 sec_group_size=None):
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800396
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800397 with ThreadPoolExecutor(max_workers=16) as executor:
koder aka kdanilov97644f92015-02-13 11:11:08 -0800398 if network_zone_name is not None:
399 network_future = executor.submit(nova.networks.find,
400 label=network_zone_name)
401 else:
402 network_future = None
403
404 fl_future = executor.submit(nova.flavors.find, name=flavor_name)
405 img_future = executor.submit(nova.images.find, name=img_name)
406
407 if flt_ip_pool is not None:
408 ips_future = executor.submit(get_floating_ips,
409 nova, flt_ip_pool, amount)
koder aka kdanilove21d7472015-02-14 19:02:04 -0800410 logger.debug("Wait for floating ip")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800411 ips = ips_future.result()
412 ips += [Allocate] * (amount - len(ips))
413 else:
414 ips = [None] * amount
415
koder aka kdanilov7dec9df2015-02-15 21:35:19 -0800416 logger.debug("Getting flavor object")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800417 fl = fl_future.result()
koder aka kdanilov7dec9df2015-02-15 21:35:19 -0800418 logger.debug("Getting image object")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800419 img = img_future.result()
420
421 if network_future is not None:
koder aka kdanilove21d7472015-02-14 19:02:04 -0800422 logger.debug("Waiting for network results")
koder aka kdanilov97644f92015-02-13 11:11:08 -0800423 nics = [{'net-id': network_future.result().id}]
424 else:
425 nics = None
426
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300427 names = []
428 for i in range(amount):
429 names.append(name_templ.format(group=group_name, id=i))
koder aka kdanilov97644f92015-02-13 11:11:08 -0800430
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800431 futures = []
koder aka kdanilov168f6092015-04-19 02:33:38 +0300432 logger.debug("Requesting new vm's")
koder aka kdanilov6e2ae792015-03-04 18:02:24 -0800433
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300434 orig_scheduler_hints = scheduler_hints.copy()
435
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300436 MAX_SHED_GROUPS = 32
437 for start_idx in range(MAX_SHED_GROUPS):
438 pass
439
440 group_name_template = scheduler_hints['group'].format("\\d+")
441 groups = list(get_free_server_grpoups(nova, group_name_template + "$"))
442 groups.sort()
443
444 for idx, (name, flt_ip) in enumerate(zip(names, ips), 2):
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300445
446 scheduler_hints = None
447 if orig_scheduler_hints is not None and sec_group_size is not None:
448 if "group" in orig_scheduler_hints:
449 scheduler_hints = orig_scheduler_hints.copy()
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300450 scheduler_hints['group'] = groups[idx // sec_group_size]
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300451
452 if scheduler_hints is None:
453 scheduler_hints = orig_scheduler_hints.copy()
454
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800455 params = (nova, name, keypair_name, img, fl,
456 nics, vol_sz, flt_ip, scheduler_hints,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300457 flt_ip_pool, [security_group])
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800458
459 futures.append(executor.submit(create_vm, *params))
koder aka kdanilove21d7472015-02-14 19:02:04 -0800460 res = [future.result() for future in futures]
461 logger.debug("Done spawning")
462 return res
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800463
464
465def create_vm(nova, name, keypair_name, img,
466 fl, nics, vol_sz=None,
467 flt_ip=False,
468 scheduler_hints=None,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300469 pool=None,
470 security_groups=None):
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800471 for i in range(3):
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800472 srv = nova.servers.create(name,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300473 flavor=fl,
474 image=img,
475 nics=nics,
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800476 key_name=keypair_name,
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300477 scheduler_hints=scheduler_hints,
478 security_groups=security_groups)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800479
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800480 if not wait_for_server_active(nova, srv):
481 msg = "Server {0} fails to start. Kill it and try again"
koder aka kdanilove21d7472015-02-14 19:02:04 -0800482 logger.debug(msg.format(srv))
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800483 nova.servers.delete(srv)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800484
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300485 try:
486 for j in range(120):
487 srv = nova.servers.get(srv.id)
488 time.sleep(1)
489 else:
490 msg = "Server {0} delete timeout".format(srv.id)
491 raise RuntimeError(msg)
492 except NotFound:
493 pass
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800494 else:
495 break
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300496 else:
497 raise RuntimeError("Failed to start server".format(srv.id))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800498
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800499 if vol_sz is not None:
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800500 vol = create_volume(vol_sz, name)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300501 nova.volumes.create_server_volume(srv.id, vol.id, None)
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800502
503 if flt_ip is Allocate:
504 flt_ip = nova.floating_ips.create(pool)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300505
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -0800506 if flt_ip is not None:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800507 srv.add_floating_ip(flt_ip)
Yulia Portnova0e64ea22015-03-20 17:27:22 +0200508
koder aka kdanilovda45e882015-04-06 02:24:42 +0300509 return flt_ip.ip, nova.servers.get(srv.id)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800510
511
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300512def clear_nodes(nodes_ids):
513 clear_all(NOVA_CONNECTION, nodes_ids, None)
gstepanov023c1e42015-04-08 15:50:19 +0300514
515
koder aka kdanilove87ae652015-04-20 02:14:35 +0300516def clear_all(nova, ids=None, name_templ=None):
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300517
518 def need_delete(srv):
519 if name_templ is not None:
520 return re.match(name_templ.format("\\d+"), srv.name) is not None
521 else:
522 return srv.id in ids
523
koder aka kdanilove87ae652015-04-20 02:14:35 +0300524 volumes_to_delete = []
525 cinder = cinder_connect()
526 for vol in cinder.volumes.list():
527 for attachment in vol.attachments:
528 if attachment['server_id'] in ids:
529 volumes_to_delete.append(vol)
530 break
531
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800532 deleted_srvs = set()
533 for srv in nova.servers.list():
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300534 if need_delete(srv):
koder aka kdanilove21d7472015-02-14 19:02:04 -0800535 logger.debug("Deleting server {0}".format(srv.name))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800536 nova.servers.delete(srv)
537 deleted_srvs.add(srv.id)
538
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300539 count = 0
540 while True:
541 if count % 60 == 0:
542 logger.debug("Waiting till all servers are actually deleted")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800543 all_id = set(srv.id for srv in nova.servers.list())
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300544 if len(all_id.intersection(deleted_srvs)) == 0:
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800545 break
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300546 count += 1
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800547 time.sleep(1)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300548 logger.debug("Done, deleting volumes")
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800549
550 # wait till vm actually deleted
551
koder aka kdanilov6b1341a2015-04-21 22:44:21 +0300552 # logger.warning("Volume deletion commented out")
553 for vol in volumes_to_delete:
554 logger.debug("Deleting volume " + vol.display_name)
555 cinder.volumes.delete(vol)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800556
koder aka kdanilove21d7472015-02-14 19:02:04 -0800557 logger.debug("Clearing done (yet some volumes may still deleting)")