Skip to content

Instantly share code, notes, and snippets.

@VLogin
Created July 3, 2022 11:35
Show Gist options
  • Save VLogin/89f19fa7322592f80728ac3b56794435 to your computer and use it in GitHub Desktop.
Save VLogin/89f19fa7322592f80728ac3b56794435 to your computer and use it in GitHub Desktop.
[vcofrmn.py] #python #vro #vco
#!/bin/env python
"""
Python wrapper for calling vCO workflows.
Author: AV
Date: 2018-06-14
Version: 0.6
History:
0.2 - added workflow tracking
0.3 - added vm operations like startVM, poweroffVM,
makeVMSnapshot, deleteVMSnapshot, revertVMSnapshot
0.4 - vco-related and rt-related parts have been moved out
to the separate module vcofrmnlib.py for better reusability
0.5 - VM_SetIOPS wrapper has been added
0.6 - DNS_UnregisterDNSRecord wrapper has been added
0.7 - vmDecommission wrapper has been added
"""
from __future__ import print_function
import os, sys
import getopt
import json
import vcofrmnlib
### validators
def validateIP( ip ):
"""IPv4 validation function, used for DNS registration"""
if ip: ip = ip.strip()
import re
ipt = re.compile( '^(?:\d{1,3}\.){3}\d{1,3}$' )
if ip and ipt.match( ip ):
import socket
try:
iNet = socket.inet_aton( ip )
except:
ip = None
else:
ip = None
return ip
def getVCOProviderFromRTData( rtData ):
return vcofrmnlib.getValueFromRTDataByKey( 'vcoprovider', rtData )
### workflow public wrapper functions
def getPuppetNoStringifyFacts( content ):
"""
Helper function which check if parameter puppet_no_stringify_facts exists
under the output-parameters structure returned by getVCOWorkflowOutputParameters
"""
data = json.loads( content )
puppet_no_stringify_facts=False
if not data is None \
and type(data) is dict \
and 'output-parameters' in data.keys():
out=data['output-parameters']
for x in out:
if 'value' in x.keys() and 'properties' in x['value'] \
and 'property' in x['value']['properties'].keys() \
and type( x['value']['properties']['property'] ) is list:
for y in x['value']['properties']['property']:
if 'key' in y.keys() and 'value' in y.keys():
if y['key'] == 'puppet_no_stringify_facts' \
and 'string' in y['value'].keys() \
and 'value' in y['value']['string'].keys() \
and y['value']['string']['value'].lower() == '"true"':
puppet_no_stringify_facts=True
break
if puppet_no_stringify_facts:
break
return puppet_no_stringify_facts
def checkPuppetNoStringifyFacts( server, user, passw, location, swe ):
"""The callable method which returns value of puppet_no_stringify_facts for designated hostrgoup"""
data="""{ "parameters": [
{ "value": { "string": { "value": "%s" } }, "type": "string", "name": "location" },
{ "value": { "string": { "value": "%s" } }, "type": "string", "name": "SWE" }
] }""" % ( location, swe )
wfName = 'FRP_GetHGParameters'
( httpStatus, wfID, execID, execStatus, result ) = vcofrmnlib.internalWorkflowCall( server, user, passw, wfName, data )
( wfID, execID, httpStatus, result ) = vcofrmnlib.getVCOWorkflowOutputParameters( server, wfID, execID, user, passw )
if ( httpStatus == 200 or httpStatus == 202 and result > '' ):
return getPuppetNoStringifyFacts( result )
else:
raise Exception( "The VCO Workflow %s with execution id %s has returned non OK HTTP status %s" % ( wfID, execID, httpStatus ) )
def destroyCertificateOnPuppetMaster( server, user, passw, fqdn, puppetmaster ):
"""Helper function which destroys certificate on puppet master"""
data = """{ "parameters": [
{ "value": { "string": { "value": "%s" } }, "type": "string", "name": "fqdn" },
{ "value": { "string": { "value": "%s" } }, "type": "string", "name": "puppetServer" }
] }""" % ( fqdn, puppetmaster )
wfName = "FRP_PuppetAgentCertDestroy"
( httpStatus, wfID, execID, execStatus, result ) = vcofrmnlib.internalWorkflowCall( server, user, passw, wfName, data )
result = execStatus
return ( wfID, execID, httpStatus, execStatus )
def registerHostForemanHG( server, user, passw, location, fqdn, sweversion ):
"""This one registers host record on the foreman server with designated sweversion"""
data="""{ "parameters":[
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "location" },
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "hostname" },
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "SWE" }
] }""" % ( location, fqdn, sweversion )
wfName = "FRP_RegisterHostForeman"
( httpStatus, wfID, execID, execStatus, result ) = vcofrmnlib.internalWorkflowCall( server, user, passw, wfName, data )
result = execStatus
return ( wfID, execID, httpStatus, execStatus )
def registerDNSRecord( server, user, passw, recType, fqdn, ipAddress ):
"""
This method allows to register host DNS record, A and PTR.
The IP address should be a valid IPv4 address.
The reverse notation for PTR record will be done here.
"""
origAddress = ipAddress
if ( recType == 'PTR' ):
ipAddress = '.'.join( reversed( ipAddress.split( '.' ) ) ) + '.in-addr.arpa'
data="""{ "parameters":[
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "value" },
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "type" },
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "fqdn" }
] }""" % ( ipAddress, recType, fqdn )
wfName = 'DNS_RegisterDNSrecord'
( httpStatus, wfID, execID, execStatus, result ) = vcofrmnlib.internalWorkflowCall( server, user, passw, wfName, data )
result = execStatus
return ( wfID, execID, httpStatus, execStatus )
def unregisterDNSRecord( server, user, passw, recType, value ):
"""
This method allows to unregister host DNS record, A and PTR.
The value depends on recType. In case recType is A, then value should be FQDN.
In case recType is PTR, then value should be valid IP.
This procedure will translate IP to the valid in-addr.arpa notation.
"""
origAddress = value
if ( recType == 'PTR' ):
value = '.'.join( reversed( value.split( '.' ) ) ) + '.in-addr.arpa'
data="""{ "parameters":[
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "value" },
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "type" }
] }""" % ( value, recType )
wfName = 'DNS_UnregisterDNSrecord'
( httpStatus, wfID, execID, execStatus, result ) = vcofrmnlib.internalWorkflowCall( server, user, passw, wfName, data )
result = execStatus
return ( wfID, execID, httpStatus, execStatus )
def vmDecommission( server, user, passw, location, vmName ):
"""
This method allows to decomiss VM. It deletes VM from vCenter, removes DNS records
removes Foreman record, removes RT VM object. Use carefully.
"""
data="""{ "parameters":[
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "location" },
{ "value": { "string": { "value":"%s" } }, "type": "string", "name": "vmName" }
] }""" % ( location, vmName )
wfName = 'VM_Decommission'
( httpStatus, wfID, execID, execStatus, result ) = vcofrmnlib.internalWorkflowCall( server, user, passw, wfName, data )
result = execStatus
return ( wfID, execID, httpStatus, execStatus )
def internalWorkflowCall( server, user, passw, wfName, data ):
"""Used internally in wrapper functions"""
result = False
( wfID, execID, httpStatus, execStatus ) = vcofrmnlib.executeVCOWorkflow( server, wfName, user, passw, data )
if ( httpStatus == 200 or httpStatus == 202 and execStatus == 'completed' ):
return ( httpStatus, wfID, execID, execStatus, result )
else:
if httpStatus != 200 and httpStatus != 202:
raise Exception( "There was an error running VCO Workflow %s, the HTTP status code: %s" % ( wfName, httpStatus ) )
if execStatus != "completed":
raise Exception(
"""The execution status of VCO Workflow %s is not completed, but %s.
Check the status of workflow with id %s and execution id %s""" % \
( wfName, execStatus, wfID, execID )
)
def listVMSnapshots( vcouser, vcopass, vmData, printOutputParams ):
data = """{ "parameters":[
{ "value": { "string":{ "value":"%s"}},"type": "string", "name": "vmName"},
{ "value": { "string":{ "value":"#location#"}},"type": "string","name": "location"}
]}""" % ( vmData['vmName'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], "VM_ListVMSnapshots", data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def startVM( vcouser, vcopass, vmData, printOutputParams ):
data = """{ "parameters":[
{ "value": { "string":{ "value": "%s"}}, "type": "string", "name": "vmName"},
{ "value": { "string":{ "value": "#location#"}}, "type": "string", "name": "location"}
]}""" % ( vmData['vmName'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], "VM_StartVM", data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def poweroffVM( vcouser, vcopass, vmData, printOutputParams ):
data = """{ "parameters":[
{ "value": { "string":{ "value": "%s"}}, "type": "string", "name": "vmName"},
{ "value": { "string":{ "value": "#location#"}}, "type": "string", "name": "location"}
]}""" % ( vmData['vmName'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], "VM_PowerOffVM", data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def makeVMSnapshot( vcouser, vcopass, vmData, printOutputParams ):
data = """{"parameters":[
{"value": {"string":{ "value":"%s"}},"type": "string","name": "vmName"},
{"value": {"string":{ "value":"#location#"}},"type": "string","name": "location"},
{"value": {"string":{ "value":"%s"}},"type": "string","name": "name"}]}""" % ( vmData['vmName'], vmData['snapshotName'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], "VM_TakeVMSnapshot", data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def revertVMSnapshot( vcouser, vcopass, vmData, printOutputParams ):
data = """{"parameters":[
{"value": {"string":{ "value":"%s"}},"type": "string","name": "vmName"},
{"value": {"string":{ "value":"#location#"}},"type": "string","name": "location"},
{"value": {"string":{ "value":"%s"}},"type": "string","name": "name"}]}""" % ( vmData['vmName'], vmData['snapshotName'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], "VM_RevertVMSnapshot", data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def deleteVMSnapshot( vcouser, vcopass, vmData, printOutputParams ):
data = """{"parameters":[
{"value": {"string":{ "value":"%s"}},"type": "string","name": "vmName"},
{"value": {"string":{ "value":"#location#"}},"type": "string","name": "location"},
{"value": {"string":{ "value":"%s"}},"type": "string","name": "name"}]}""" % ( vmData['vmName'], vmData['snapshotName'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], "VM_RemoveVMSnapshots", data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def setVMIOPS( vcouser, vcopass, vmData, printOutputParams ):
data = """{"parameters":[
{"value": {"string":{ "value":"#location#"}},"type": "string","name": "location"},
{"value": {"string":{ "value":"%s"}},"type": "string","name": "vmName"},
{"value": {"string":{ "value":"%s"}},"type": "string","name": "iops"}]}""" % ( vmData['vmName'], vmData['iops'] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = vcofrmnlib.makeVMOperationGenericWrapper( vcouser, vcopass, vmData['vmName'], 'VM_SetIOPS', data, printOutputParams )
return ( wfID, execID, httpStatus, execStatus, result, resultOP )
def printUsage():
"""
Basically print help screen function
"""
helpData = [ 'Usage is following:',
'python vcofrmn.py <action> <options>',
' general options:',
' --help: this help screen',
' --action: one of the allowed actions, see below',
' --server: vCO provider server. FQDN along with scheme.',
' Example https://ams02-vro.eurolab.ringcentral.com:8281',
' --user: vCO provider user',
' --password: vCO provider password',
' --verbose: be more verbose',
' --debug: enable debug mode',
' --max-attempts: maximum attempts for vCO workflow status poll.',
' Default value is 10',
' --interval: interval between vCO workflow status poll in seconds.',
' Default value is 15',
' --tracklogs: poll vCO logs and output these while workflow is running',
'',
' action: callVCOWorkflow',
' --workflow: workflow name to execute',
' --data: workflow post data as json string',
' --action callVCOWorkflow --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --workflow <workflow name> --data <json data>',
' In case json data starts with @ sign, the value after @ sign',
' is interpreted as file name',
'',
' action: getVCOWorkflowLogs',
' --workflowid: the ID of workflow on the vCO provider server',
' --executionid: the execution ID of workflow to poll',
' --action getVCOWorkflowLogs --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --workflowid <workflow id> --executionid <execution id>',
'',
' action: getVCOWorkflowOutputParams',
' --workflowid: the ID of workflow on the vCO provider server',
' --executionid: the execution ID of workflow to poll',
' --action getVCOWorkflowOutputParams --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --workflowid <workflow id> --executionid <execution id>',
'',
' action: getPuppetNoStringifyFacts',
' --location: location',
' --swe: swe name to check',
' --action getPuppetNoStringifyFacts --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --location <location> --swe <sweversion>',
'',
' action: destroyCertificateOnPuppetMaster',
' --fqdn: FQDN referring the host of certificate to destroy',
' --puppetmaster: fully qualified name of puppetmaster server',
' --action destroyCertificateOnPuppetMaster --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --puppetmaster <puppetmaster> --fqdn <host fqdn>',
'',
' action: registerHostForemanHG',
' --fqdn: FQDN referring the host which you want to register on Foreman',
' --location: location of host which you want to register on Foreman',
' --swe: swe of host which you want to regsiter on Foreman',
' --action registerHostForemanHG --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --location <location> --fqdn <host fqdn> --swe <sweversion>',
'',
' action: registerDNSRecord',
' --iprectype: IP record type (A or PTR)',
' --fqdn: FQDN referring the host which you want to register in DNS',
' --ipaddress: IP address to register. In case you want to register PTR record provide direct IP.',
' The reverse IP notation for x.y.z.in-addr.arpa will be generated based on it.',
' --action registerDNSRecord --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --iprectype <A|PTR> --fqdn <host fqdn> --ipaddress <ipaddress>',
'',
' action: unregisterDNSRecord',
' --iprectype: IP record type (A or PTR)',
' --value: FQDN referring the host which you want to unregister in case of A record',
' IP address in case you are handling PTR record',
' Reverse IP notation for x.y.z.in-addr.arpa will be generated based on it.',
' --action unregisterDNSRecord --server <vcoserver> --user <vcouser> \\',
' --password <vcopass> --iprectype <A|PTR> --value <host fqdn|IP>',
'',
' action: getVCOProviderForVM',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --action getVCOProviderForVM --vmname <vmname>',
'',
' action: listVMSnapshots',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action listVMSnapshots --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> ',
'',
' action: startVM',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action startVM --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> ',
'',
' action: poweroffVM',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action poweroffVM --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> ',
'',
' action: makeVMSnapshot',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --snapname: snapshot name',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action makeVMSnapshot --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> --snapname <snapshot name>',
'',
' action: revertVMSnapshot',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --snapname: snapshot name',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action revertVMSnapshot --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> --snapname <snapshot name>',
'',
' action: deleteVMSnapshot',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --snapname: snapshot name',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action deleteVMSnapshot --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> --snapname <snapshot name>',
'',
' action: setIOPS',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --iops: desired IOPS value. One of following values: -1, 100, 200, 300, 500, 1000',
' --printoutputparams: print workflow output parameters at the end if needed',
' --action poweroffVM --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> ',
'',
' action: vmDecomission',
' --vmname: host record of virtual machine, the data should exist in the RackTables',
' --location: location of host which you want to decommiss',
' --action vmDecommission --user <vcouser> --password <vcopass> \\',
' --vmname <vmname> --location <location>',
'',
'To avoid passing credentials in file options you can create $HOME/'+vcofrmnlib.getUserConfigFileName()+' file with contents',
'VCOUSER=<user>',
'VCOPASS=<pass>',
'' ]
for x in helpData:
print(x)
def main( argv ):
opts = {}
try:
opts, args = getopt.getopt( argv, '',
[ "help", "action=", "debug",
"verbose", "user=", "password=", "server=", "max-attempts=",
"interval=",
"workflow=", "data=",
"workflowid=", "executionid=",
"location=", "swe=",
"puppetmaster=", "fqdn=",
"ipaddress=", "iprectype=",
"tracklogs", "vmname=", "snapname=",
"printoutputparams",
"hwe=", "redeployment=", "makess0=",
"usertrecord=", "serverrole=", "podcl=",
"domain=", "environment=", "comment=",
"adsready=", "iops=", "container=",
"segment=", "cpuarch=",
"value="
] )
except getopt.GetoptError as err:
vcofrmnlib.errprint(err)
printUsage()
sys.exit(1)
action = ''
vcouser = ''
vcopass = ''
vcoprovider = ''
wfName = ''
data = ''
wfID = ''
execID = ''
location = ''
sweversion = ''
fqdn = ''
puppetmaster = ''
ipRecordType = ''
ipAddress = ''
vmName = ''
snapshotName = ''
iops = ''
value = ''
printOutputParams = False
[ vcouser, vcopass ] = vcofrmnlib.getDefaultVCOCredentials()
isVerbose = False
isDebug = False
MAX_ATTEMPTS = 30
POLL_INTERVAL = 10
doTrackLogs = False
for opt, arg in opts:
if opt in [ "--help" ]:
printUsage()
sys.exit( 0 )
if opt in [ "--action" ]:
action = arg.lower()
if opt in [ "--debug" ]:
isDebug = True
vcofrmnlib.setDebug( isDebug )
if opt in [ "--user" ]:
vcouser = arg
if opt in [ "--password" ]:
vcopass = arg
if opt in [ "--server" ]:
vcoprovider = arg
if opt in [ "--verbose" ]:
isVerbose = True
if opt in [ "--workflow" ]:
wfName = arg
if opt in [ "--data" ]:
data = arg
if opt in [ "--location" ]:
location = arg
if opt in [ "--swe" ]:
sweversion = arg
if opt in [ "--workflowid" ]:
wfID = arg
if opt in [ "--executionid" ]:
execID = arg
if opt in [ "--max-attempts" ]:
try:
MAX_ATTEMPTS = int( arg )
except:
MAX_ATTEMPTS = 30
if MAX_ATTEMPTS < 5:
MAX_ATTEMPTS = 5
vcofrmnlib.setMaxAttempts( MAX_ATTEMPTS )
if opt in [ "--interval" ]:
try:
POLL_INTERVAL = int( arg )
except:
POLL_INTERVAL = 1
if POLL_INTERVAL < 5:
POLL_INTERVAL = 5
vcofrmnlib.setPollInterval( POLL_INTERVAL )
if opt in [ "--puppetmaster" ]:
puppetmaster = arg
if opt in [ "--fqdn" ]:
fqdn = arg
if opt in [ "--iprectype" ]:
ipRecordType = arg
if opt in [ "--ipaddress" ]:
ipAddress = arg
if opt in [ "--tracklogs" ]:
doTrackLogs = True
vcofrmnlib.setTrackLogs( doTrackLogs )
if opt in [ "--vmname" ]:
vmName = arg
if opt in [ "--snapname" ]:
snapshotName = arg
if opt in [ "--printoutputparams" ]:
printOutputParams = True
if opt in ["--iops"]:
iops = arg
if opt in ["--value"]:
value = arg
allowedActions = (
'callVCOWorkflow'.lower(),
'getVCOWorkflowLogs'.lower(),
'getVCOWorkflowOutputParams'.lower(),
'getPuppetNoStringifyFacts'.lower(),
'destroyCertificateOnPuppetMaster'.lower(),
'registerHostForemanHG'.lower(),
'registerDNSRecord'.lower(),
'unregisterDNSRecord'.lower(),
'getVCOProviderForVM'.lower(),
'listVMSnapshots'.lower(),
'startVM'.lower(),
'poweroffVM'.lower(),
'makeVMSnapshot'.lower(),
'revertVMSnapshot'.lower(),
'deleteVMSnapshot'.lower(),
'setIOPS'.lower(),
'vmDecommission'.lower()
)
if not action in allowedActions:
vcofrmnlib.errprint("The action named '%s' is invalid" % ( action ))
printUsage()
sys.exit(1)
if ( action == 'getVCOProviderForVM'.lower() ):
if vmName == '':
vcofrmnlib.errprint("The name of VM should be passed as vmname argument")
printUsage()
sys.exit(1)
( headers, httpStatus, vmData ) = getRTDataForVM( vmName )
result = ''
if not vmData is None:
result = getVCOProviderFromRTData( vmData )
if result == '':
sys.exit(1)
print(result)
sys.exit(0)
elif action in [ 'setIOPS'.lower() ]:
if vmName == '':
vcofrmnlib.errprint("The name of VM should be passed as vmname argument")
printUsage()
sys.exit(1)
if iops == '':
vcofrmnlib.errprint("The IOPS value should be set for setIOPS action")
printUsage()
sys.exit(1)
if not iops in [ "-1", "100", "200", "300", "500", "1000" ]:
vcofrmnlib.errprint("The IOPS value should be one of following: [ -1, 100, 200, 300, 500, 100 ]")
printUsage()
sys.exit(2)
params = { 'vmName': vmName, 'iops': iops }
( wfID, execID, httpStatus, execStatus, result, resultOP ) = \
setVMIOPS( vcouser, vcopass, params, printOutputParams )
if printOutputParams and httpStatus in ( 200, 202 ) \
and execStatus == 'completed':
print(json.dumps( json.loads( resultOP ), indent = True ))
sys.exit( 0 if httpStatus in ( 200, 202 ) else 1 )
elif action in [ 'listVMSnapshots'.lower(), 'startVM'.lower(),
'poweroffVM'.lower(), 'makeVMSnapshot'.lower(),
'revertVMSnapshot'.lower(), 'deleteVMSnapshot'.lower() ]:
if vmName == '':
vcofrmnlib.errprint("The name of VM should be passed as vmname argument")
printUsage()
sys.exit(1)
if action in [ 'makeVMSnapshot'.lower(),
'revertVMSnapshot'.lower(), 'deleteVMSnapshot'.lower() ] \
and snapshotName == '':
vcofrmnlib.errprint("The name of VM snapshot should be passed as snapshotName argument")
printUsage()
sys.exit(1)
if vcouser == '' or vcopass == '':
vcofrmnlib.errprint("The vCO credentials should be set")
printUsage()
sys.exit(1)
fMap = {
'listVMSnapshots'.lower(): 'listVMSnapshots',
'startVM'.lower(): 'startVM',
'poweroffVM'.lower(): 'poweroffVM',
'makeVMSnapshot'.lower(): 'makeVMSnapshot',
'revertVMSnapshot'.lower(): 'revertVMSnapshot',
'deleteVMSnapshot'.lower(): 'deleteVMSnapshot'
}
params = { 'vmName': vmName, 'snapshotName': snapshotName }
func = getattr( sys.modules[__name__], fMap[action] )
( wfID, execID, httpStatus, execStatus, result, resultOP ) = \
func( vcouser, vcopass, params, printOutputParams )
if printOutputParams and httpStatus in ( 200, 202 ) \
and execStatus == 'completed':
print(json.dumps( json.loads( resultOP ), indent = True ))
sys.exit( 0 if httpStatus in ( 200, 202 ) else 1 )
if vcoprovider == '':
vcofrmnlib.errprint("The vCO provider address can't be empty")
printUsage()
sys.exit(1)
vcoprovider = vcofrmnlib.sanitizeVCOProvider( vcoprovider )
if vcouser == '' or vcopass == '':
vcofrmnlib.errprint("The vCO credentials should be set")
printUsage()
sys.exit(1)
if ( action == 'callVCOWorkflow'.lower() ):
if wfName == '' or data == '':
vcofrmnlib.errprint("The callVCOWorkflow action should specify both workflow and data to post")
printUsage()
sys.exit(1)
if data.startswith( '@' ):
fname = data[1:]
if os.path.isfile( fname ):
with open( fname ) as f:
data = f.read()
else:
print('The data references non-existing file %s' % ( fname ))
try:
dummy = json.loads( data )
except:
vcofrmnlib.errprint('The data passed is not a valid JSON. Please check syntax')
sys.exit(8)
( wfID, execID, httpStatus, execStatus ) = executeVCOWorkflow( vcoprovider, wfName, vcouser, vcopass, data )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('EXECUTION_STATUS=%s' % ( execStatus ))
sys.exit( 0 if execStatus != 'completed' else 1 )
elif ( action == 'getVCOWorkflowLogs'.lower() ):
if wfID == '' or execID == '':
vcofrmnlib.errprint("The getVCOWorkflowLogs action requires to specify workflow id and execution id")
printUsage()
sys.exit(1)
( wfID, execID, httpStatus, result ) = vcofrmnlib.getVCOWorkflowLogs( vcoprovider, wfID, execID, vcouser, vcopass )
if httpStatus in ( 200, 202 ) and not result is None:
entries = vcofrmnlib.extractLogs( result )
vcofrmnlib.printWFLogs( entries )
else:
vcofrmnlib.errprint("There was an error while we've tried to get logs for workflow %s, %s, %s" % (vcoprovider, wfID, execID) )
sys.exit(3)
elif ( action == 'getVCOWorkflowOutputParams'.lower() ):
if wfID == '' or execID == '':
vcofrmnlib.errprint("The getVCOWorkflowOutputParams action requires to specify workflow id and execution id")
printUsage()
sys.exit(1)
( wfID, execID, httpStatus, result ) = getVCOWorkflowOutputParameters( vcoprovider, wfID, execID, vcouser, vcopass )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('HTTP_STATUS=%s' % ( httpStatus ))
print(result)
elif ( action == 'getPuppetNoStringifyFacts'.lower() ):
if location == '' or sweversion == '':
vcofrmnlib.errprint("Location and SWE should be specified for getPuppetNoStringifyFacts action")
sys.exit(1)
hasError = False
try:
puppet_no_stringify_facts = checkPuppetNoStringifyFacts( vcoprovider, vcouser, vcopass, location, sweversion )
except Exception as err:
hasError = True
vcofrmnlib.errprint(err)
if not hasError:
print( "puppet_no_stringify_facts=%s" % ( "true" if puppet_no_stringify_facts else "false" ))
sys.exit( 1 if hasError else 0 )
elif ( action == 'destroyCertificateOnPuppetMaster'.lower() ):
if puppetmaster == '' or fqdn == '':
vcofrmnlib.errprint("Both puppetmaster and fqdn should be set")
printUsage()
sys.exit(1)
( wfID, execID, httpStatus, execStatus ) = destroyCertificateOnPuppetMaster( vcoprovider, vcouser, vcopass, fqdn, puppetmaster )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('HTTP_STATUS=%s' % ( httpStatus ))
print('EXECUTION_STATUS=%s' % ( execStatus ))
elif ( action == 'registerHostForemanHG'.lower() ):
if fqdn == '' or location == '' or sweversion == '':
vcofrmnlib.errprint("fqdn, location and sweversion should be set for registerHostForemanHG action")
sys.exit(1)
( wfID, execID, httpStatus, execStatus ) = registerHostForemanHG( vcoprovider, vcouser, vcopass, location, fqdn, sweversion )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('HTTP_STATUS=%s' % ( httpStatus ))
print('EXECUTION_STATUS=%s' % ( execStatus ))
elif ( action == 'registerDNSRecord'.lower() ):
if ipRecordType == '' or ipAddress == '':
vcofrmnlib.errprint("IP record type and IP address should be set")
printUsage()
sys.exit(1)
ipRecordType = ipRecordType.upper()
if not ipRecordType in ( 'A', 'PTR' ):
vcofrmnlib.errprint("IP record type should be either A or PTR")
printUsage()
sys.exit(2)
if not validateIP( ipAddress ):
vcofrmnlib.errprint("IP address should be a valid dotted IPv4 address")
printUsage()
sys.exit(2)
( wfID, execID, httpStatus, execStatus ) = registerDNSRecord( vcoprovider, vcouser, vcopass, ipRecordType, fqdn, ipAddress )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('HTTP_STATUS=%s' % ( httpStatus ))
print('EXECUTION_STATUS=%s' % ( execStatus ))
elif ( action == 'unregisterDNSRecord'.lower() ):
if ipRecordType == '' or value == '':
vcofrmnlib.errprint("IP record type and value should be set")
printUsage()
sys.exit(1)
ipRecordType = ipRecordType.upper()
if not ipRecordType in ( 'A', 'PTR' ):
vcofrmnlib.errprint("IP record type should be either A or PTR")
printUsage()
sys.exit(2)
if ipRecordType == 'PTR' and validateIP( value ) is None:
vcofrmnlib.errprint("value must be valid IP when PTR record is listed")
printUsage()
sys.exit(2)
( wfID, execID, httpStatus, execStatus ) = unregisterDNSRecord( vcoprovider, vcouser, vcopass, ipRecordType, value )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('HTTP_STATUS=%s' % ( httpStatus ))
print('EXECUTION_STATUS=%s' % ( execStatus ))
elif ( action == 'vmDecommission'.lower() ):
if vmName == '' or location == '':
vcofrmnlib.errprint("vmname and location value should be set")
printUsage()
sys.exit(1)
vmName = vmName.lower()
location = location.upper()
( wfID, execID, httpStatus, execStatus ) = vmDecommission( vcoprovider, vcouser, vcopass, location, vmName )
if ( isVerbose ):
print('WORKFLOW_ID=%s' % ( wfID ))
print('EXECUTION_ID=%s' % ( execID ))
print('HTTP_STATUS=%s' % ( httpStatus ))
print('EXECUTION_STATUS=%s' % ( execStatus ))
else:
printUsage()
sys.exit(1)
return 0
if __name__ == '__main__':
result = main( sys.argv[1:] )
sys.exit( result )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment