New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding reset alarm example. fixes #3 #81

merged 1 commit into from Jul 24, 2014
Changes from all commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.
+217 −0
Diff settings


Just for now

Copy path View file
@@ -0,0 +1,57 @@
Written by Michael Rice
This code has been released under the terms of the Apache-2.0 license
from __future__ import print_function

import atexit

from pyVim.connect import SmartConnect, Disconnect

from tools import alarm
from tools import cli

PARSER = cli.build_arg_parser()
# If you are unsure where to get the UUID of your HostSystem check out the
# MOB. For example in my lab I would connect directly to the host mob like so:
PARSER.add_argument("-x", "--uuid",
help="The UUID of the HostSystem to list triggered alarms"
" for.")
MY_ARGS = PARSER.parse_args()
SI = SmartConnect(,

atexit.register(Disconnect, SI)
INDEX = SI.content.searchIndex
HOST = INDEX.FindByUuid(datacenter=None, uuid=MY_ARGS.uuid, vmSearch=False)
# Since the above method will list all of the triggered alarms we will now
# prompt the user for the entity info needed to reset an alarm from red
# to green
alarm_mor = raw_input("Enter the alarm_moref from above to reset the "
"alarm to green: ")
except KeyboardInterrupt:
# this is useful in case the user decides to quit and hits control-c
raise SystemExit
if alarm_mor:
if alarm.reset_alarm(entity_moref=HOST._moId,
print("Successfully reset alarm {0} to green.".format(alarm_mor))
print("Unable to create a SearchIndex.")
Copy path View file
@@ -0,0 +1,160 @@
Written by Michael Rice
This code has been released under the terms of the Apache 2.0 licenses
from __future__ import print_function

__author__ = 'michael rice <>'

import logging
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import tostring

import requests

def reset_alarm(**kwargs):
Resets an alarm on a given HostSystem in a vCenter to the green state
without someone having to log in to do it manually.
This is done by using an unexposed API call. This requires us
to manually construct the SOAP envelope. We use the session key
that pyvmomi provides during its connection.
More information can be found about this process
in this article written by William Lam:
I adopted his process from perl to groovy:
and from groovy now to python.
SI = SmartConnect(xxx)
HOST = SI.content.searchIndex.FindByxxx(xxx)
alarm.reset_alarm(entity_moref=HOST._moId, entity_type='HostSystem',
alarm_moref='alarm-1', service_instance=SI)
:param service_instance:
:param entity_moref:
:param alarm:
:return boolean:
service_instance = kwargs.get("service_instance")
payload = _build_payload(**kwargs)
session = service_instance._stub
if not _send_request(payload, session):
return False
return True

def _build_payload(**kwargs):
Builds a SOAP envelope to send to the vCenter hidden API
:param entity_moref:
:param alarm_moref:
:param entity_type:
entity_moref = kwargs.get("entity_moref")
entity_type = kwargs.get("entity_type")
alarm_moref = kwargs.get("alarm_moref")
if not entity_moref or not entity_type or not alarm_moref:
raise ValueError("entity_moref, entity_type, and alarm_moref "
"must be set")

attribs = {
'xmlns:xsd': '',
'xmlns:xsi': '',
'xmlns:soap': ''
root = Element('soap:Envelope', attribs)
body = SubElement(root, 'soap:Body')
alarm_status = SubElement(body, 'SetAlarmStatus', {'xmlns': 'urn:vim25'})
this = SubElement(alarm_status, '_this', {
'xsi:type': 'ManagedObjectReference',
'type': 'AlarmManager'
this.text = 'AlarmManager'
alarm = SubElement(alarm_status, 'alarm', {'type': 'Alarm'})
alarm.text = alarm_moref
entity = SubElement(alarm_status, 'entity', {
'xsi:type': 'ManagedObjectReference',
'type': entity_type
entity.text = entity_moref
status = SubElement(alarm_status, 'status')
status.text = 'green'
# I hate hard coding this but I have no idea how to do it any other way
# pull requests welcome :)
return '<?xml version="1.0" encoding="UTF-8"?>{0}'.format(tostring(root))

def _send_request(payload=None, session=None):
Using requests we send a SOAP envelope directly to the
vCenter API to reset an alarm to the green state.
:param payload:
:param session:
stub = session
host_port =
# Ive seen some code in pyvmomi where it seems like we check for http vs
# https but since the default is https do people really run it on http?
url = 'https://{0}/sdk'.format(host_port)
logging.debug("Sending {0} to {1}".format(payload, url))
# I opted to ignore invalid ssl here because that happens in pyvmomi.
# Once pyvmomi validates ssl it wont take much to make it happen here.
res =, data=payload, headers={
'Cookie': stub.cookie,
'SOAPAction': 'urn:vim25',
'Content-Type': 'application/xml'
}, verify=False)
if res.status_code != 200:
logging.debug("Failed to reset alarm. HTTP Status: {0}".format(
return False
return True

def print_triggered_alarms(entity=None):
This is a useful method if you need to print out the alarm morefs
:param entity:
alarms = entity.triggeredAlarmState
for alarm in alarms:
# The alarm key looks like
print("alarm_moref: {0}".format(alarm.key.split('.')[0]))
print("alarm status: {0}".format(alarm.overallStatus))

def get_alarm_refs(entity=None):
Useful method that will return a list of dict with the moref and alarm
status for all triggered alarms on a given entity.
:param entity:
:return list: [{'alarm':'alarm-101', 'status':'red'}]
alarm_states = entity.triggeredAlarmState
ret = []
for alarm_state in alarm_states:
tdict = {
"alarm": alarm_state.key.split('.')[0],
"status": alarm_state.overallStatus
return ret
ProTip! Use n and p to navigate between commits in a pull request.