Merge "Initial vROPs plugin work for MON module. Configure alarm & enable notificatio...
[osm/MON.git] / plugins / vRealiseOps / mon_plugin_vrops.py
1 # -*- coding: utf-8 -*-
2 """
3 Montoring metrics & creating Alarm definations in vROPs
4 """
5
6 import requests
7 import logging as log
8 from pyvcloud.vcloudair import VCA
9 from xml.etree import ElementTree as XmlElementTree
10 import traceback
11
12 OPERATION_MAPPING = {'GE':'GT_EQ', 'LE':'LT_EQ', 'GT':'GT', 'LT':'LT', 'EQ':'EQ'}
13 SEVERITY_MAPPING = {'WARNING':'WARNING', 'MINOR':'WARNING', 'MAJOR':"IMMEDIATE", 'CRITICAL':'CRITICAL'}
14
15
16 class MonPlugin():
17 """MON Plugin class for vROPs telemetry plugin
18 """
19 def __init__(self, access_config={}):
20 """Constructor of MON plugin
21 Params:
22 'access_config': dictionary with VIM access information based on VIM type.
23 This contains a consolidate version of VIM & monitoring tool config at creation and
24 particular VIM config at their attachment.
25 For VIM type: 'vmware', access_config - {'vrops_site':<>, 'vrops_user':<>, 'vrops_password':<>,
26 'vcloud-site':<>,'admin_username':<>,'admin_password':<>,
27 'nsx_manager':<>,'nsx_user':<>,'nsx_password':<>,
28 'vcenter_ip':<>,'vcenter_port':<>,'vcenter_user':<>,'vcenter_password':<>,
29 'vim_tenant_name':<>,'orgname':<>}
30
31 #To Do
32 Returns: Raise an exception if some needed parameter is missing, but it must not do any connectivity
33 check against the VIM
34 """
35 self.access_config = access_config
36 self.vrops_site = access_config['vrops_site']
37 self.vrops_user = access_config['vrops_user']
38 self.vrops_password = access_config['vrops_password']
39 self.vcloud_site = access_config['vcloud_site']
40 self.vcloud_username = access_config['vcloud_username']
41 self.vcloud_password = access_config['vcloud_password']
42
43 def configure_alarm(self, config_dict = {}):
44 """Configures or creates a new alarm using the input parameters in config_dict
45 Params:
46 "alarm_name": Alarm name in string format
47 "description": Description of alarm in string format
48 "resource_uuid": Resource UUID for which alarm needs to be configured. in string format
49 "Resource type": String resource type: 'VDU' or 'host'
50 "Severity": 'WARNING', 'MINOR', 'MAJOR', 'CRITICAL'
51 "metric": Metric key in string format
52 "operation": One of ('GE', 'LE', 'GT', 'LT', 'EQ')
53 "threshold_value": Defines the threshold (up to 2 fraction digits) that, if crossed, will trigger the alarm.
54 "unit": Unit of measurement in string format
55 "statistic": AVERAGE, MINIMUM, MAXIMUM, COUNT, SUM
56
57 Default parameters for each alarm are read from the plugin specific config file.
58 Dict of default parameters is as follows:
59 default_params keys = {'cancel_cycles','wait_cycles','resource_kind','adapter_kind','alarm_type','alarm_subType',impact}
60
61 Returns the UUID of created alarm or None
62 """
63 alarm_def_uuid = None
64 #1) get alarm & metrics parameters from plugin specific file
65 def_params = self.get_default_Params(config_dict['alarm_name'])
66 metric_key_params = self.get_default_Params(config_dict['metric'])
67 #2) create symptom definition
68 #TO DO - 'metric_key':config_dict['metric'] - mapping from file def_params
69 symptom_params ={'cancel_cycles': (def_params['cancel_period']/300)*def_params['cancel_cycles'],
70 'wait_cycles': (def_params['period']/300)*def_params['evaluation'],
71 'resource_kind_key': def_params['resource_kind'],'adapter_kind_key': def_params['adapter_kind'],
72 'symptom_name':config_dict['alarm_name'],'severity': SEVERITY_MAPPING[config_dict['severity']],
73 'metric_key':metric_key_params['metric_key'],'operation':OPERATION_MAPPING[config_dict['operation']],
74 'threshold_value':config_dict['threshold_value']}
75 symptom_uuid = self.create_symptom(symptom_params)
76 if symptom_uuid is not None:
77 log.info("Symptom defined: {} with ID: {}".format(symptom_params['symptom_name'],symptom_uuid))
78 else:
79 log.warn("Failed to create Symptom: {}".format(symptom_params['symptom_name']))
80 return None
81 #3) create alert definition
82 #To Do - Get type & subtypes for all 5 alarms
83 alarm_params = {'name':config_dict['alarm_name'],
84 'description':config_dict['description'] if config_dict['description'] is not None else config_dict['alarm_name'],
85 'adapterKindKey':def_params['adapter_kind'], 'resourceKindKey':def_params['resource_kind'],
86 'waitCycles':1, 'cancelCycles':1,
87 'type':def_params['alarm_type'], 'subType':def_params['alarm_subType'],
88 'severity':SEVERITY_MAPPING[config_dict['severity']],
89 'symptomDefinitionId':symptom_uuid,
90 'impact':def_params['impact']}
91
92 alarm_def_uuid = self.create_alarm_definition(alarm_params)
93 if alarm_def_uuid is None:
94 log.warn("Failed to create Alert: {}".format(alarm_params['name']))
95 return None
96
97 log.info("Alarm defined: {} with ID: {}".format(alarm_params['name'],alarm_def_uuid))
98
99 #4) Find vm_moref_id from vApp uuid in vCD
100 vm_moref_id = self.get_vm_moref_id(config_dict['resource_uuid'])
101 if vm_moref_id is None:
102 log.warn("Failed to find vm morefid for vApp in vCD: {}".format(config_dict['resource_uuid']))
103 return None
104
105 #5) Based on vm_moref_id, find VM's corresponding resource_id in vROPs to set notification
106 resource_id = self.get_vm_resource_id(vm_moref_id)
107 if resource_id is None:
108 log.warn("Failed to find resource in vROPs: {}".format(config_dict['resource_uuid']))
109 return None
110
111 #6) Configure alarm notification for a particular VM using it's resource_id
112 notification_id = self.create_alarm_notification(config_dict['alarm_name'], alarm_def_uuid, resource_id)
113 if notification_id is None:
114 return None
115 else:
116 log.info("Alarm defination created with notification: {} with ID: {}".format(alarm_params['name'],alarm_def_uuid))
117 return alarm_def_uuid
118
119 def get_default_Params(self, metric_alarm_name):
120 """
121 Read the default config parameters from plugin specific file stored with plugin file.
122 Params:
123 metric_alarm_name: Name of the alarm, whose congif params to be read from the config file.
124 """
125 tree = XmlElementTree.parse('vROPs_default_config.xml')
126 alarms = tree.getroot()
127 a_params = {}
128 for alarm in alarms:
129 if alarm.tag == metric_alarm_name:
130 for param in alarm:
131 if param.tag in ("period", "evaluation", "cancel_period", "alarm_type", "cancel_cycles", "alarm_subType"):
132 a_params[param.tag] = int(param.text)
133 elif param.tag in ("enabled", "repeat"):
134 if(param.text == "True" or param.text == "true"):
135 a_params[param.tag] = True
136 else:
137 a_params[param.tag] = False
138 else:
139 a_params[param.tag] = param.text
140
141 if not a_params:
142 log.warn("No such '{}' alarm found!.".format(alarm))
143
144 return a_params
145
146
147 def create_symptom(self, symptom_params):
148 """Create Symptom definition for an alarm
149 Params:
150 symptom_params: Dict of parameters required for defining a symptom as follows
151 cancel_cycles
152 wait_cycles
153 resource_kind_key = "VirtualMachine"
154 adapter_kind_key = "VMWARE"
155 symptom_name = Test_Memory_Usage_TooHigh
156 severity
157 metric_key
158 operation = GT_EQ
159 threshold_value = 85
160 Returns the uuid of Symptom definition
161 """
162 symptom_id = None
163
164 try:
165 api_url = '/suite-api/api/symptomdefinitions'
166 headers = {'Content-Type': 'application/xml'}
167 data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
168 <ops:symptom-definition cancelCycles="{0:s}" waitCycles="{1:s}" resourceKindKey="{2:s}" adapterKindKey="{3:s}" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ops="http://webservice.vmware.com/vRealizeOpsMgr/1.0/">
169 <ops:name>{4:s}</ops:name>
170 <ops:state severity="{5:s}">
171 <ops:condition xsi:type="ops:htCondition">
172 <ops:key>{6:s}</ops:key>
173 <ops:operator>{7:s}</ops:operator>
174 <ops:value>{8:s}</ops:value>
175 <ops:valueType>NUMERIC</ops:valueType>
176 <ops:instanced>false</ops:instanced>
177 <ops:thresholdType>STATIC</ops:thresholdType>
178 </ops:condition>
179 </ops:state>
180 </ops:symptom-definition>""".format(str(symptom_params['cancel_cycles']),str(symptom_params['wait_cycles']),symptom_params['resource_kind_key'],
181 symptom_params['adapter_kind_key'],symptom_params['symptom_name'],symptom_params['severity'],
182 symptom_params['metric_key'],symptom_params['operation'],str(symptom_params['threshold_value']))
183
184 resp = requests.post(self.vrops_site + api_url,
185 auth=(self.vrops_user, self.vrops_password),
186 headers=headers,
187 verify = False,
188 data=data)
189
190 if resp.status_code != 201:
191 log.warn("Failed to create Symptom definition: {}, response {}".format(symptom_params['symptom_name'], resp.content))
192 return None
193
194 symptom_xmlroot = XmlElementTree.fromstring(resp.content)
195 if symptom_xmlroot is not None and 'id' in symptom_xmlroot.attrib:
196 symptom_id = symptom_xmlroot.attrib['id']
197
198 return symptom_id
199
200 except Exception as exp:
201 log.warn("Error creating symptom definition : {}\n{}".format(exp, traceback.format_exc()))
202
203
204 def create_alarm_definition(self, alarm_params):
205 """
206 Create an alarm definition in vROPs
207 Params:
208 'name': Alarm Name,
209 'description':Alarm description,
210 'adapterKindKey': Adapter type in vROPs "VMWARE",
211 'resourceKindKey':Resource type in vROPs "VirtualMachine",
212 'waitCycles': No of wait cycles,
213 'cancelCycles': No of cancel cycles,
214 'type': Alarm type: ,
215 'subType': Alarm subtype: ,
216 'severity': Severity in vROPs "CRITICAL",
217 'symptomDefinitionId':symptom Definition uuid,
218 'impact': impact 'risk'
219 Returns:
220 'alarm_uuid': returns alarm uuid
221 """
222
223 alarm_uuid = None
224
225 try:
226 api_url = '/suite-api/api/alertdefinitions'
227 headers = {'Content-Type': 'application/xml'}
228 data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
229 <ops:alert-definition xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ops="http://webservice.vmware.com/vRealizeOpsMgr/1.0/">
230 <ops:name>{0:s}</ops:name>
231 <ops:description>{1:s}</ops:description>
232 <ops:adapterKindKey>{2:s}</ops:adapterKindKey>
233 <ops:resourceKindKey>{3:s}</ops:resourceKindKey>
234 <ops:waitCycles>1</ops:waitCycles>
235 <ops:cancelCycles>1</ops:cancelCycles>
236 <ops:type>{4:s}</ops:type>
237 <ops:subType>{5:s}</ops:subType>
238 <ops:states>
239 <ops:state severity="{6:s}">
240 <ops:symptom-set>
241 <ops:symptomDefinitionIds>
242 <ops:symptomDefinitionId>{7:s}</ops:symptomDefinitionId>
243 </ops:symptomDefinitionIds>
244 <ops:relation>SELF</ops:relation>
245 <ops:aggregation>ALL</ops:aggregation>
246 <ops:symptomSetOperator>AND</ops:symptomSetOperator>
247 </ops:symptom-set>
248 <ops:impact>
249 <ops:impactType>BADGE</ops:impactType>
250 <ops:detail>{8:s}</ops:detail>
251 </ops:impact>
252 </ops:state>
253 </ops:states>
254 </ops:alert-definition>""".format(alarm_params['name'],alarm_params['description'],alarm_params['adapterKindKey'],
255 alarm_params['resourceKindKey'],str(alarm_params['type']),str(alarm_params['subType']),
256 alarm_params['severity'],alarm_params['symptomDefinitionId'],alarm_params['impact'])
257
258 resp = requests.post(self.vrops_site + api_url,
259 auth=(self.vrops_user, self.vrops_password),
260 headers=headers,
261 verify = False,
262 data=data)
263
264 if resp.status_code != 201:
265 log.warn("Failed to create Alarm definition: {}, response {}".format(alarm_params['name'], resp.content))
266 return None
267
268 alarm_xmlroot = XmlElementTree.fromstring(resp.content)
269 for child in alarm_xmlroot:
270 if child.tag.split("}")[1] == 'id':
271 alarm_uuid = child.text
272
273 return alarm_uuid
274
275 except Exception as exp:
276 log.warn("Error creating alarm definition : {}\n{}".format(exp, traceback.format_exc()))
277
278
279 def configure_rest_plugin(self, plugin_name, webhook_url, certificate):
280 """
281 Creates REST Plug-in for vROPs outbound alerts
282
283 Params:
284 plugin_name: name of REST plugin instance
285 pluginTypeId - RestPlugin
286 Optional configValues
287 "Url">https://dev14136.service-now.com:8080</ops:configValue> - reqd
288 "Username">admin</ops:configValue> - optional
289 "Password">VMware1!</ops:configValue> - optional
290 "Content-type">application/xml</ops:configValue> - reqd
291 "Certificate">abcdefgh123456</ops:configValue> - get n set
292 "ConnectionCount" - 20 - default
293 """
294 plugin_id = None
295
296 api_url = '/suite-api/api/alertplugins'
297 headers = {'Content-Type': 'application/xml'}
298 data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
299 <ops:notification-plugin version="0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ops="http://webservice.vmware.com/vRealizeOpsMgr/1.0/">
300 <ops:pluginTypeId>RestPlugin</ops:pluginTypeId>
301 <ops:name>{0:s}</ops:name>
302 <ops:configValues>
303 <ops:configValue name="Url">{1:s}</ops:configValue>
304 <ops:configValue name="Content-type">application/xml</ops:configValue>
305 <ops:configValue name="Certificate">{2:s}</ops:configValue>
306 <ops:configValue name="ConnectionCount">20</ops:configValue>
307 </ops:configValues>
308 </ops:notification-plugin>""".format(plugin_name, webhook_url, certificate)
309
310 resp = requests.post(self.vrops_site + api_url,
311 auth=(self.vrops_user, self.vrops_password),
312 headers=headers,
313 verify = False,
314 data=data)
315
316 if resp.status_code is not 201:
317 log.warn("Failed to create REST Plugin: {} for url: {}, \nresponse code: {},\nresponse content: {}"\
318 .format(plugin_name, webhook_url, resp.status_code, resp.content))
319 return None
320
321 plugin_xmlroot = XmlElementTree.fromstring(resp.content)
322 if plugin_xmlroot is not None:
323 for child in plugin_xmlroot:
324 if child.tag.split("}")[1] == 'pluginId':
325 plugin_id = plugin_xmlroot.find('{http://webservice.vmware.com/vRealizeOpsMgr/1.0/}pluginId').text
326
327 if plugin_id is None:
328 log.warn("Failed to get REST Plugin ID for {}, url: {}".format(plugin_name, webhook_url))
329 return None
330 else:
331 log.info("Created REST Plugin: {} with ID : {} for url: {}".format(plugin_name, plugin_id, webhook_url))
332 status = self.enable_rest_plugin(plugin_id, plugin_name)
333 if status is False:
334 log.warn("Failed to enable created REST Plugin: {} for url: {}".format(plugin_name, webhook_url))
335 return None
336 else:
337 log.info("Enabled REST Plugin: {} for url: {}".format(plugin_name, webhook_url))
338 return plugin_id
339
340
341 def enable_rest_plugin(self, plugin_id, plugin_name):
342 """
343 Enable the REST plugin using plugin_id
344 Params: plugin_id: plugin ID string that is to be enabled
345 Returns: status (Boolean) - True for success, False for failure
346 """
347
348 if plugin_id is None or plugin_name is None:
349 log.debug("enable_rest_plugin() : Plugin ID or plugin_name not provided for {} plugin".format(plugin_name))
350 return False
351
352 try:
353 api_url = "/suite-api/api/alertplugins/{}/enable/True".format(plugin_id)
354
355 resp = requests.put(self.vrops_site + api_url, auth=(self.vrops_user, self.vrops_password), verify = False)
356
357 if resp.status_code is not 204:
358 log.warn("Failed to enable REST plugin {}. \nResponse code {}\nResponse Content: {}"\
359 .format(plugin_name, resp.status_code, resp.content))
360 return False
361
362 log.info("Enabled REST plugin {}.".format(plugin_name))
363 return True
364
365 except Exception as exp:
366 log.warn("Error enabling REST plugin for {} plugin: Exception: {}\n{}".format(plugin_name, exp, traceback.format_exc()))
367
368 def create_alarm_notification(self, alarm_name, alarm_id, resource_id):
369 """
370 Create notification for each alarm
371 Params:
372 alarm_name
373 alarm_id
374 resource_id
375
376 Returns:
377 notification_id: notification_id or None
378 """
379 notification_name = 'notify_' + alarm_name
380 notification_id = None
381
382 #1) Find the REST Plugin id details for - MON_module_REST_Plugin
383 api_url = '/suite-api/api/alertplugins'
384 headers = {'Accept': 'application/xml'}
385 namespace = {'params':"http://webservice.vmware.com/vRealizeOpsMgr/1.0/"}
386
387 resp = requests.get(self.vrops_site + api_url,
388 auth=(self.vrops_user, self.vrops_password),
389 verify = False, headers = headers)
390
391 if resp.status_code is not 200:
392 log.warn("Failed to REST GET Alarm plugin details \nResponse code: {}\nResponse content: {}"\
393 .format(resp.status_code, resp.content))
394 return None
395
396 # Look for specific plugin & parse pluginId for 'MON_module_REST_Plugin'
397 xmlroot_resp = XmlElementTree.fromstring(resp.content)
398 for notify_plugin in xmlroot_resp.findall('params:notification-plugin',namespace):
399 if notify_plugin.find('params:name',namespace) is not None and notify_plugin.find('params:pluginId',namespace) is not None:
400 if notify_plugin.find('params:name',namespace).text == 'MON_module_REST_Plugin':
401 plugin_id = notify_plugin.find('params:pluginId',namespace).text
402
403 if plugin_id is None:
404 log.warn("Failed to get REST plugin_id for : {}".format('MON_module_REST_Plugin'))
405 return None
406
407 #2) Create Alarm notification rule
408 api_url = '/suite-api/api/notifications/rules'
409 headers = {'Content-Type': 'application/xml'}
410 data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
411 <ops:notification-rule xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ops="http://webservice.vmware.com/vRealizeOpsMgr/1.0/">
412 <ops:name>{0:s}</ops:name>
413 <ops:pluginId>{1:s}</ops:pluginId>
414 <ops:resourceFilter resourceId="{2:s}">
415 <ops:matchResourceIdOnly>true</ops:matchResourceIdOnly>
416 </ops:resourceFilter>
417 <ops:alertDefinitionIdFilters>
418 <ops:values>{3:s}</ops:values>
419 </ops:alertDefinitionIdFilters>
420 </ops:notification-rule>""".format(notification_name, plugin_id, resource_id, alarm_id)
421
422 resp = requests.post(self.vrops_site + api_url,
423 auth=(self.vrops_user, self.vrops_password),
424 headers=headers,
425 verify = False,
426 data=data)
427
428 if resp.status_code is not 201:
429 log.warn("Failed to create Alarm notification {} for {} alarm. \nResponse code: {}\nResponse content: {}"\
430 .format(notification_name, alarm_name, resp.status_code, resp.content))
431 return None
432
433 #parse notification id from response
434 xmlroot_resp = XmlElementTree.fromstring(resp.content)
435 if xmlroot_resp is not None and 'id' in xmlroot_resp.attrib:
436 notification_id = xmlroot_resp.attrib.get('id')
437
438 log.info("Created Alarm notification rule {} for {} alarm.".format(notification_name, alarm_name))
439 return notification_id
440
441 def get_vm_moref_id(self, vapp_uuid):
442 """
443 Get the moref_id of given VM
444 """
445 try:
446 if vapp_uuid:
447 vm_details = self.get_vapp_details_rest(vapp_uuid)
448 if vm_details and "vm_vcenter_info" in vm_details:
449 vm_moref_id = vm_details["vm_vcenter_info"].get("vm_moref_id", None)
450
451 log.info("Found vm_moref_id: {} for vApp UUID: {}".format(vm_moref_id, vapp_uuid))
452 return vm_moref_id
453
454 except Exception as exp:
455 log.warn("Error occurred while getting VM moref ID for VM : {}\n{}".format(exp, traceback.format_exc()))
456
457
458 def get_vapp_details_rest(self, vapp_uuid=None):
459 """
460 Method retrieve vapp detail from vCloud director
461
462 Args:
463 vapp_uuid - is vapp identifier.
464
465 Returns:
466 Returns VM MOref ID or return None
467 """
468
469 parsed_respond = {}
470 vca = None
471
472 vca = self.connect_as_admin()
473
474 if not vca:
475 log.warn("connect() to vCD is failed")
476 if vapp_uuid is None:
477 return None
478
479 url_list = [vca.host, '/api/vApp/vapp-', vapp_uuid]
480 get_vapp_restcall = ''.join(url_list)
481
482 if vca.vcloud_session and vca.vcloud_session.organization:
483 response = requests.get(get_vapp_restcall,
484 headers=vca.vcloud_session.get_vcloud_headers(),
485 verify=vca.verify)
486
487 if response.status_code != 200:
488 log.warn("REST API call {} failed. Return status code {}".format(get_vapp_restcall, response.content))
489 return parsed_respond
490
491 try:
492 xmlroot_respond = XmlElementTree.fromstring(response.content)
493
494 namespaces = {'vm': 'http://www.vmware.com/vcloud/v1.5',
495 "vmext":"http://www.vmware.com/vcloud/extension/v1.5",
496 "xmlns":"http://www.vmware.com/vcloud/v1.5"
497 }
498
499 # parse children section for other attrib
500 children_section = xmlroot_respond.find('vm:Children/', namespaces)
501 if children_section is not None:
502 vCloud_extension_section = children_section.find('xmlns:VCloudExtension', namespaces)
503 if vCloud_extension_section is not None:
504 vm_vcenter_info = {}
505 vim_info = vCloud_extension_section.find('vmext:VmVimInfo', namespaces)
506 vmext = vim_info.find('vmext:VmVimObjectRef', namespaces)
507 if vmext is not None:
508 vm_vcenter_info["vm_moref_id"] = vmext.find('vmext:MoRef', namespaces).text
509 parsed_respond["vm_vcenter_info"]= vm_vcenter_info
510
511 except Exception as exp :
512 log.warn("Error occurred calling rest api for getting vApp details: {}\n{}".format(exp, traceback.format_exc()))
513
514 return parsed_respond
515
516
517 def connect_as_admin(self):
518 """ Method connect as pvdc admin user to vCloud director.
519 There are certain action that can be done only by provider vdc admin user.
520 Organization creation / provider network creation etc.
521
522 Returns:
523 The return vca object that letter can be used to connect to vcloud direct as admin for provider vdc
524 """
525
526 log.info("Logging in to a VCD org as admin.")
527
528 vca_admin = VCA(host=self.vcloud_site,
529 username=self.vcloud_username,
530 service_type='standalone',
531 version='5.9',
532 verify=False,
533 log=False)
534 result = vca_admin.login(password=self.vcloud_password, org='System')
535 if not result:
536 log.warn("Can't connect to a vCloud director as: {}".format(self.vcloud_username))
537 result = vca_admin.login(token=vca_admin.token, org='System', org_url=vca_admin.vcloud_session.org_url)
538 if result is True:
539 log.info("Successfully logged to a vcloud direct org: {} as user: {}".format('System', self.vcloud_username))
540
541 return vca_admin
542
543
544 def get_vm_resource_id(self, vm_moref_id):
545 """ Find resource ID in vROPs using vm_moref_id
546 """
547 if vm_moref_id is None:
548 return None
549
550 api_url = '/suite-api/api/resources'
551 headers = {'Accept': 'application/xml'}
552 namespace = {'params':"http://webservice.vmware.com/vRealizeOpsMgr/1.0/"}
553
554 resp = requests.get(self.vrops_site + api_url,
555 auth=(self.vrops_user, self.vrops_password),
556 verify = False, headers = headers)
557
558 if resp.status_code is not 200:
559 log.warn("Failed to get resource details from vROPs for {}\nResponse code:{}\nResponse Content: {}"\
560 .format(vm_moref_id, resp.status_code, resp.content))
561 return None
562
563 try:
564 xmlroot_respond = XmlElementTree.fromstring(resp.content)
565 for resource in xmlroot_respond.findall('params:resource',namespace):
566 if resource is not None:
567 resource_key = resource.find('params:resourceKey',namespace)
568 if resource_key is not None:
569 if resource_key.find('params:adapterKindKey',namespace).text == 'VMWARE' and \
570 resource_key.find('params:resourceKindKey',namespace).text == 'VirtualMachine':
571 for child in resource_key:
572 if child.tag.split('}')[1]=='resourceIdentifiers':
573 resourceIdentifiers = child
574 for r_id in resourceIdentifiers:
575 if r_id.find('params:value',namespace).text == vm_moref_id:
576 log.info("Found Resource ID : {} in vROPs for {}".format(resource.attrib['identifier'], vm_moref_id))
577 return resource.attrib['identifier']
578 except Exception as exp:
579 log.warn("Error in parsing {}\n{}".format(exp, traceback.format_exc()))
580