-
Notifications
You must be signed in to change notification settings - Fork 1
/
vm_control.py
executable file
·308 lines (265 loc) · 11.9 KB
/
vm_control.py
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
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 27 09:42:19 2015
@author: Konstantin
"""
import keystoneclient.v2_0.client as ksclient
from novaclient import client as noclient
import configparser, time, os, copy
class VM_Control(object):
"""
A class to control VMs in OpenStack
"""
__instance = None
cred = None
KEYSTONE_CONN = None
NOVA_CONN = None
config_data = None
ssh_public_key_filename = None
pk = None
sec_group = None
def __init__(self):
execfile('openrc.py')
self.cred = self.get_nova_creds()
print self.cred
self.KEYSTONE_CONN = self.get_keystone_client(self.cred)
self.NOVA_CONN = self.get_nova_client(self.cred)
config = configparser.ConfigParser()
config.read('config.ini')
print(config.sections())
vm_credentials = dict(config['SSH_CREDENTIALS'])
ssh_public_key_filename = str(vm_credentials['ssh.public_key_filename'])
self.pk = self.ensure_public_key(self.NOVA_CONN,
ssh_public_key_filename); print self.pk
self.sec_group = self.ensure_security_group(self.NOVA_CONN)
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
execfile('openrc.py')
cls.__instance.cred = cls.__instance.get_nova_creds()
cls.__instance.KEYSTONE_CONN = cls.__instance.get_keystone_client(cls.__instance.cred)
cls.__instance.NOVA_CONN = cls.__instance.get_nova_client(cls.__instance.cred)
config = configparser.ConfigParser()
config.read('config.ini')
vm_credentials = dict(config['SSH_CREDENTIALS'])
ssh_public_key_filename = str(vm_credentials['ssh.public_key_filename'])
cls.__instance.pk = cls.__instance.ensure_public_key(cls.__instance.NOVA_CONN,
ssh_public_key_filename)
cls.__instance.sec_group = cls.__instance.ensure_security_group(cls.__instance.NOVA_CONN)
return cls.__instance
def get_nova_creds(self):
#returns credentials dictionary from os variables in nova format
cred = {}
cred['username'] = os.environ['OS_USERNAME']
cred['api_key'] = os.environ['OS_PASSWORD']
cred['auth_url'] = os.environ['OS_AUTH_URL']
cred['project_id'] = os.environ['OS_TENANT_NAME']
return cred
def get_keystone_client(self, cred):
#returns keystone client
temp = copy.copy(cred)
temp['password'] = cred['api_key']
temp.pop('api_key', None)
temp['tenant'] = cred['project_id']
temp.pop('project_id', None)
print temp
return ksclient.Client(**temp)
def get_nova_client(self, cred):
#returns nova client
KEYSTONE_CONN = self.get_keystone_client(cred)
cred['auth_token'] = KEYSTONE_CONN.get_token(KEYSTONE_CONN.session)
RAW_TOKEN = KEYSTONE_CONN.get_raw_token_from_identity_service(
auth_url=cred['auth_url'],
username=cred['username'],
password=cred['api_key'],
tenant_name=cred['project_id'])
cred['tenant_id'] = RAW_TOKEN['token']['tenant']['id']
return noclient.Client('1.1',**cred)
def ensure_public_key(self, nova_client,
public_key_filename):
KP_MANAGER = nova_client.keypairs
public_key = [line for line in open(public_key_filename)][0]
if not(KP_MANAGER.findall(name='test_key')):
pk = KP_MANAGER.create('test_key',public_key=public_key)
else:
pk = KP_MANAGER.findall(name='test_key')[0]
return pk
def ensure_security_group(self, nova_client):
SG_MANAGER = nova_client.security_groups
RULE_MANAGER = nova_client.security_group_rules
sg_new = False
if not(SG_MANAGER.findall(name='webserver')):
sec_group = SG_MANAGER.create('webserver','Allows SSH and web server access.')
sg_new = True
else:
sec_group = SG_MANAGER.findall(name='webserver')[0]
if (sg_new):
RULE_MANAGER.create(sec_group.id,ip_protocol='tcp',from_port=22,to_port=22)
RULE_MANAGER.create(sec_group.id,ip_protocol='tcp',from_port=80,to_port=80)
RULE_MANAGER.create(sec_group.id,ip_protocol='icmp',from_port=-1,to_port=-1)
return sec_group
def get_current_userid(self):
return self.KEYSTONE_CONN.user_id
def create_vm(self,
vm_name='TestVM',
image_name='ubuntu_cdn_14_04_2',
flavor_name='m1.small',
network_label=u'net',
sec_group='default',
injected_pk=None,
availability_zone='nova'):
VM_MANAGER = self.NOVA_CONN.servers
IMAGE_MANAGER = self.NOVA_CONN.images
FLAVOR_MANAGER = self.NOVA_CONN.flavors
NETWORK_MANAGER = self.NOVA_CONN.networks
image = IMAGE_MANAGER.findall(name=image_name)[0]
flavor = FLAVOR_MANAGER.findall(name=flavor_name)[0]
network = NETWORK_MANAGER.findall(label=network_label)[0]
nics = [{'net-id': network.id}]
print nics
injected_pk = self.pk
sec_group = self.sec_group
if not (VM_MANAGER.findall(name=vm_name)):
VM_MANAGER.create(name=vm_name,
image=image.id,
flavor=flavor.id,
security_groups=[sec_group.human_id],
key_name=injected_pk.name,
nics=nics)
vm_id, name, status = self.ensure_vm_active(vm_name)
return vm_id, name, status
def find_vms(self, userid='', status='ACTIVE'):
VM_MANAGER = self.NOVA_CONN.servers
if not (VM_MANAGER.findall(user_id=userid)):
return []
else:
vm_list = [vm for vm in VM_MANAGER.findall(user_id=userid) if vm.status==status]
return vm_list
def ensure_vm_active(self, vm_name):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
timeout = 60
elapsed_time = 0
while (vm.status != 'ACTIVE'):
vm = VM_MANAGER.findall(name=vm.name)[0]
if (vm.status == 'ERROR'):
print("VM ID: %s name: %s CREATION FAILED!!" % (vm.id, vm.name))
break
print("VM ID: %s name: %s in status: %s" % (vm.id, vm.name, vm.status))
time.sleep(1)
elapsed_time += 1
if (elapsed_time > timeout):
vm.delete()
print("VM ID: %s name: %s CREATION FAILED!!" % (vm.id, vm.name))
break
print("VM ID: %s name: %s %s." % (vm.id, vm.name, vm.status))
return vm.id, vm.name, vm.status
def create_vms(self, vms):
return [self.create_vm(
vm_name=vm,
image_name='ubuntu_cdn_14_04_2',
flavor_name='m1.small',
network_label='net',
sec_group=self.sec_group,
injected_pk=self.pk
) for vm in vms]
def start_vm(self,
vm_name):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
vm.start()
while (vm.status != 'ACTIVE'):
vm = VM_MANAGER.findall(name=vm.name)[0]
if (vm.status == 'ERROR'):
print("VM ID: %s name: %s START FAILED!!" % (vm.id, vm.name))
break
print("VM ID: %s name: %s in status: %s" % (vm.id, vm.name, vm.status))
time.sleep(1)
print("VM ID: %s name: %s %s." % (vm.id, vm.name, vm.status))
return vm.id, vm.name, vm.status
def start_vms(self, vms):
return [self.start_vm(
vm_name=vm
) for vm in vms]
def stop_vm(self,
vm_name):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
vm.stop()
while (vm.status != 'SHUTOFF'):
vm = VM_MANAGER.findall(name=vm.name)[0]
if (vm.status == 'ERROR'):
print("VM ID: %s name: %s STOP FAILED!!" % (vm.id, vm.name))
break
print("VM ID: %s name: %s in status: %s" % (vm.id, vm.name, vm.status))
time.sleep(1)
print("VM ID: %s name: %s %s." % (vm.id, vm.name, vm.status))
return vm.id, vm.name, vm.status
def stop_vms(self, vms):
return [self.stop_vm(
vm_name=vm
) for vm in vms]
def get_vm(self,
vm_name):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
return vm
def get_vms_data(self, vms):
return [self.get_vm(
vm_name=vm
) for vm in vms]
def get_free_floating_ips(self):
IP_MANAGER = self.NOVA_CONN.floating_ips
return [ip for ip in IP_MANAGER.list()
if ip.instance_id==None]
def assign_floating_ip_to_vm(self,
vm_name,
ip_list):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
assigned_ips = [address for address in vm.addresses.values()[0]
if address[u'OS-EXT-IPS:type']==u'floating']
if len(assigned_ips) < 1:
free_ip = ip_list[0].ip
fixed_ip = [ip[0] for ip in vm.networks.values()][0]
vm.add_floating_ip(free_ip, fixed_address=fixed_ip)
return vm
else:
return vm
def get_floating_ip(self,
vm_name):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
floating_ip = [address for address in vm.addresses.values()[0]
if address[u'OS-EXT-IPS:type']==u'floating'][0]
return floating_ip[u'addr']
def get_fixed_ip_from_floating_ip(self,
floating_ip):
FLOATING_IPS_MANAGER = self.NOVA_CONN.floating_ips
fixed = [el.fixed_ip for el in FLOATING_IPS_MANAGER.list()
if el.ip == floating_ip][0]
return fixed
def get_fixed_ip(self,
vm_name):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(name=vm_name)[0]
floating_ip = [address for address in vm.addresses.values()[0]
if address[u'OS-EXT-IPS:type']==u'fixed'][0]
return floating_ip[u'addr']
def get_fixed_ip_by_id(self,
vm_id):
VM_MANAGER = self.NOVA_CONN.servers
vm = VM_MANAGER.findall(id=vm_id)[0]
floating_ip = [address for address in vm.addresses.values()[0]
if address[u'OS-EXT-IPS:type']==u'fixed'][0]
return floating_ip[u'addr']
if __name__ == "__main__":
execfile('openrc.py')
vm_list = ['vm1','vm2']
vm_control = VM_Control()
ip_list = vm_control.get_free_floating_ips()
ip = vm_control.get_floating_ip('master')
print ip
my_id = vm_control.get_current_userid()
active_vms = vm_control.find_vms(userid=my_id)
stopped_vms = vm_control.find_vms(userid=my_id,status='SHUTOFF')