def getAdapter(self, adapterId): url = "https://" + self.config[ 'host'] + "/suite-api/api/adapters/" + adapterId response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) if response.status_code < 300: response_parsed = json.loads(response.text) return response_parsed else: # Search didn't work, try to do search across all adapters urlall = "https://" + self.config[ 'host'] + "/suite-api/api/adapters" r = requests.request("GET", urlall, headers=clilib.get_token_header( self.token['token']), verify=False) r_parsed = json.loads(r.text) for instance in r_parsed["adapterInstancesInfoDto"]: if adapterId in instance["resourceKey"]["name"]: return instance # if we get to this point, exit entire script...nothing found print("No adapter found for " + adapterId) r.raise_for_status()
def getAllCredentials(self): '''-> Return all credentials defined in the vROps system ''' url = "https://" + self.config['host'] + "/suite-api/api/credentials" response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) credssum = {} response_parsed = json.loads(response.text) csvheader = [] csvrows = [] csvheader = ["id", "name", "adapterKind"] for credentialInstances in response_parsed['credentialInstances']: arow = {} arow["id"] = credentialInstances["id"] arow["name"] = credentialInstances["name"] arow["adapterKind"] = credentialInstances["adapterKindKey"] csvrows.append(arow) csvwr = csv.DictWriter(sys.stdout, fieldnames=csvheader, quoting=csv.QUOTE_ALL) csvwr.writeheader() for row in csvrows: csvwr.writerow(row)
def updateAlertDefinitions(self, alertConfigFile): '''-> Update alert defintions from a file producted by the getAlertsDefinitionsByAdapterKind routine ALERTCONFIGFILE: JSON file of alerts to update ''' with open(alertConfigFile) as jsonFile: alertDefinitions = json.load(jsonFile) url = 'https://' + self.config[ 'host'] + '/suite-api/api/alertdefinitions' for alertDefinition in alertDefinitions["alertDefinitions"]: r = requests.put(url, data=json.dumps(alertDefinition), headers=clilib.get_token_header( self.token['token']), verify=False) if r.status_code < 300: print(alertDefinition["name"] + ' updated successfully.') else: # Print error, but continue processing print(alertDefinition["name"] + ' updated failed!.') print(r.text())
def setVropsLicense(self, license_key): '''-> Set the license key for vROps itself LICENSE_KEY: The liense key for vROps ''' url = 'https://' + self.config[ 'host'] + '/suite-api/api/deployment/licenses' data = { 'solutionLicenses': [{ 'id': None, 'licenseKey': license_key, 'others': [], 'otherAttributes': {} }] } r = requests.post(url, data=json.dumps(data), headers=clilib.get_token_header(self.token['token']), verify=False) if r.status_code == 200: print('license key installed') return True else: print('Failed to license vrops') print(str(r.status_code)) return False
def setSolutionLicense(self, solutionId, license): '''-> Set solution license SOLUTIONID: Id of solution or string search for Solution type. Id can be found from getSolution action LICENSE: License string for the solution ''' data = { 'solutionLicenses': [{ 'licenseKey': license, }] } url = 'https://' + self.config[ 'host'] + '/suite-api/api/solutions/' + solutionId + '/licenses' r = requests.post(url, data=json.dumps(data), headers=clilib.get_token_header(self.token['token']), verify=False) if r.status_code < 300: print('license key installed') return True else: print('Failed to install license for ' + solutionId) print(str(r.status_code)) return False
def createAdapterInstances(self, resourceConfigFile, autostart=False): '''-> Create adapter instances with a CSV file generated by getAdapterConfig or getAdapterConfigs RESOURCECONFIGFILE: The CSV file with the new adapter configurations AUTOSTART: If the adapters should be started after creation. Defaults to false. ''' resourceConfigData = open(resourceConfigFile, newline='') resourceConfig = csv.DictReader(resourceConfigData) for row in resourceConfig: # Suite-API specifically expects a list of dictionary objects, with only two ides of "name" and "value". Not even asking why... resourceConfigItems = [] for name, value in row.items(): if (name == 'name') or (name == 'description') or ( name == 'resourceKind' ) or (name == 'adapterKind') or (name == 'adapterkey') or ( name == 'credentialId') or (name == 'collectorId'): continue resourceConfigItems.append({"name": name, 'value': value}) newadapterdata = { "name": row['name'], "description": row['description'], "collectorId": row['collectorId'], "adapterKindKey": row['adapterKind'], "resourceIdentifiers": resourceConfigItems, "credential": { "id": row['credentialId'] } } url = 'https://' + self.config['host'] + '/suite-api/api/adapters' r = requests.post(url, data=json.dumps(newadapterdata), headers=clilib.get_token_header( self.token['token']), verify=False) if r.status_code < 300: print(row['name'] + ' Adapter Successfully Installed') if autostart == True: returndata = json.loads(r.text) self.startAdapterInstance(adapterId=returndata["id"]) else: try: r.raise_for_status() except requests.exceptions.HTTPError as e: error_data = json.loads(e.response.text) if "Resource with same key already exists" in error_data[ "moreInformation"][1]["value"]: print( "Adatper Instance " + row['name'] + "already exists, or shares resources marked unique with another adapter" ) else: raise
def updateAdapterInstances(self, resourceConfigFile, autostart=False): '''-> Update adapter instances with a CSV file generated by getAdapterConfig or getAdapterConfigs RESOURCECONFIGFILE: The CSV file with the new adapter configurations AUTOSTART: If the adapters should be started after update. Defaults to false. ''' resourceConfigData = open(resourceConfigFile, newline='') resourceConfig = csv.DictReader(resourceConfigData) for row in resourceConfig: resourceConfigItems = [] for name, value in row.items(): if (name == 'name') or (name == 'description') or ( name == 'resourceKind' ) or (name == 'adapterKind') or (name == 'adapterkey') or ( name == 'credentialId') or (name == 'collectorId'): continue resourceConfigItems.append({ "identifierType": { "name": name, "dataType": "STRING" }, 'value': value }) newadapterdata = { "resourceKey": { "name": row['name'], "resourceKindKey": row['resourceKind'], "adapterKindKey": row['adapterKind'], "resourceIdentifiers": resourceConfigItems }, "id": row['adapterkey'], "credentialInstanceId": row['credentialId'], "description": row['description'], "collectorId": row['collectorId'] } url = 'https://' + self.config['host'] + '/suite-api/api/adapters' r = requests.put(url, data=json.dumps(newadapterdata), headers=clilib.get_token_header( self.token['token']), verify=False) if r.status_code < 300: print(row['name'] + ' Adapter Successfully Updated - ' + str(r.status_code)) if autostart == True: returndata = json.loads(r.text) self.startAdapterInstance(adapterId=returndata["id"]) else: #Not Raising excpetion as we want to continue processing the file print(row['name'] + ' Failed!') print(str(r.status_code)) print(r.text)
def deleteAlertDefinition(self, alertDefinitionKey): url = 'https://' + self.config[ 'host'] + '/suite-api/api/alertdefinitions/' + alertDefinitionKey r = requests.delete(url, headers=clilib.get_token_header( self.token['token']), verify=False) if r.status_code < 300: print(alertDefinitionKey + ' alert successfully deleted.') else: r.raise_for_status()
def getVropsLicense(self): '''-> Get installed VROps license ''' url = 'https://' + self.config[ 'host'] + '/suite-api/api/deployment/licenses' r = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) return json.loads(r.text)
def getAdapterCollectionStatus(self, adapterId): '''-> Get Current adater collection status ADAPTERID: Id of solution or string search for the adapter name. Id can be found from getAdapters action ''' # Use adapter search adapter = self.getAdapter(adapterId) #set the url for the adapter instance url = 'https://' + self.config[ 'host'] + '/suite-api/api/resources/' + adapter["id"] # Grab the specific adapter "resource" resources = requests.get(url, headers=clilib.get_token_header( self.token['token']), verify=False) #filter down to the collection status #Currently grabs everything within the resourceStatusStates and needs to be filtered down to just resourceStatus #If the object is down let the user know resourceState = (json.loads( resources.text)["resourceStatusStates"][0]["resourceState"]) #There is the option for it to be UNKNOWN and it isn't accounted for if resourceState == "NOT_EXISTING" or resourceState == "STOPPED": print("The adapter is powered off") sys.exit(1) elif resourceState == "STARTED": if "resourceStatus" not in json.loads( resources.text)["resourceStatusStates"][0]: print("The adapter is on, but Status is BLANK") sys.exit(1) else: resourceStatus = (json.loads( resources.text)["resourceStatusStates"][0] ["resourceStatus"]) #if the resourceStatus is DATA_RECEIVING let the user know they are collecting data if resourceStatus == "DATA_RECEIVING": print("The adapter is on and collecting successfully") sys.exit(0) elif resourceStatus == "NO_PARENT_MONITORING": print("The adapter is powered off") sys.exit(1) else: print( "The adapter in on, but not collecting. Status is " + resourceStatus) sys.exit(1) else: print("Unknown adapter state: " + resourceState) sys.exit(1)
def getCredential(self, credentialId): '''-> Return an individual credential for vROps adapters, in CSV format. CREDENTIALID: The ID of the credential, or a string of the credential name ''' url = "https://" + self.config[ 'host'] + "/suite-api/api/credentials/" + credentialId headers = { 'authorization': "vRealizeOpsToken " + self.token['token'], 'accept': "application/json", } response = requests.request("GET", url, headers=headers, verify=False) if response.status_code < 300: r_parsed = json.loads(response.text) else: # Search didn't work, try to do search across all adapters urlall = "https://" + self.config[ 'host'] + "/suite-api/api/credentials" r = requests.request("GET", urlall, headers=clilib.get_token_header( self.token['token']), verify=False) rall_parsed = json.loads(r.text) found = False for instance in rall_parsed["credentialInstances"]: if credentialId in instance["name"]: r_parsed = instance found = True # if we get to this point, exit entire script...nothing found if found == False: print("No credential found for " + credentialId) sys.exit(1) csvheader = [] csvrow = {} csvheader = ["name", "adapterKindKey", "credentialKindKey"] csvrow["name"] = r_parsed["name"] csvrow["adapterKindKey"] = r_parsed["adapterKindKey"] csvrow["credentialKindKey"] = r_parsed["credentialKindKey"] for credfield in r_parsed["fields"]: csvheader.append(credfield["name"]) if "value" in credfield: csvrow[credfield["name"]] = credfield["value"] csvwr = csv.DictWriter(sys.stdout, fieldnames=csvheader, quoting=csv.QUOTE_ALL) csvwr.writeheader() csvwr.writerow(csvrow)
def getAdapters(self): url = "https://" + self.config['host'] + "/suite-api/api/adapters" response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) response_parsed = json.loads(response.text) print("id,Name,Type") for instance in response_parsed["adapterInstancesInfoDto"]: print(instance["id"] + "," + instance["resourceKey"]["name"] + "," + instance["resourceKey"]["adapterKindKey"])
def deleteAdapterInstance(self, adapterkey): # Use adapter search adapter = self.getAdapter(adapterkey) url = 'https://' + self.config[ 'host'] + '/suite-api/api/adapters/' + adapter["id"] r = requests.delete(url, headers=clilib.get_token_header( self.token['token']), verify=False) if r.status_code < 300: print(adapterkey + ' adapter successfully deleted.') else: r.raise_for_status()
def getAdapterKindConfigParams(self, adapterKind): url = "https://" + self.config[ 'host'] + "/suite-api/api/adapterkinds/" + adapterKind + '/resourcekinds/' response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) response_parsed = json.loads(response.text) key = "" for resource in response_parsed["resource-kind"]: if "ADAPTER_INSTANCE" in resource["resourceKindType"]: key = resource["key"] if key == "": print("No key found for " + adapterKind) rsurl = "https://" + self.config[ 'host'] + "/suite-api/api/adapterkinds/" + adapterKind + '/resourcekinds/' + key rsresponse = requests.request("GET", rsurl, headers=clilib.get_token_header( self.token['token']), verify=False) return (json.loads(rsresponse.text)['resourceIdentifierTypes'])
def createAlertDefinition(self, alertJSON): url = 'https://' + self.config[ 'host'] + '/suite-api/api/alertdefinitions' r = requests.post(url, data=json.dumps(alertJSON), headers=clilib.get_token_header(self.token['token']), verify=False) if r.status_code == 201: print(alertJSON["name"] + ' alert successfully created.') print("Return Code: " + str(r.status_code)) else: print(alertJSON["name"] + ' creation failed!') print(str(r.status_code)) print(r.text)
def getAdapterConfigs(self, adapterKindKey): '''-> Return a CSV configuration for all adapters of the same adapter kind ADAPTERKINDKEY: The adatper kind key, which can get listed by calling getAdapterKinds ''' url = "https://" + self.config[ 'host'] + "/suite-api/api/adapters/?adapterKindKey=" + adapterKindKey response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) csvheader = [ "adapterkey", "adapterKind", "resourceKind", "credentialId", "collectorId", "name", "description" ] settingsinfo = {} firstRun = 'true' response_parsed = json.loads(response.text) for adapterInfo in response_parsed["adapterInstancesInfoDto"]: csvrow = {} csvrow["adapterkey"] = adapterInfo["id"] csvrow["adapterKind"] = adapterInfo["resourceKey"][ "adapterKindKey"] csvrow["resourceKind"] = adapterInfo["resourceKey"][ "resourceKindKey"] csvrow["credentialId"] = adapterInfo["credentialInstanceId"] csvrow["collectorId"] = adapterInfo["collectorId"] csvrow["name"] = adapterInfo["resourceKey"]["name"] csvrow["description"] = adapterInfo["description"] for configparam in adapterInfo["resourceKey"][ "resourceIdentifiers"]: if (firstRun == 'true'): csvheader.append(configparam["identifierType"]["name"]) csvrow[configparam["identifierType"] ["name"]] = configparam["value"] if (firstRun == 'true'): csvwr = csv.DictWriter(sys.stdout, fieldnames=csvheader, quoting=csv.QUOTE_ALL) csvwr.writeheader() csvwr.writerow(csvrow) firstRun = 'false'
def getSolution(self): '''-> Get all solutions installed ''' url = 'https://' + self.config['host'] + '/suite-api/api/solutions' r = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) print("id,name,version,adapterKind") for solution in json.loads(r.text)["solution"]: print(solution["id"] + "," + solution["name"] + "," + str(solution["version"]) + "," + solution["adapterKindKeys"][0])
def getSolutionLicense(self, solutionId): '''-> Get available solution license (for user installed Paks) SOLUTIONID: Id of solution or string search for Solution type. Id can be found from getSolution action ''' url = 'https://' + self.config[ 'host'] + '/suite-api/api/solutions/' + solutionId + '/licenses' r = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) return json.loads(r.text)
def getCollectors(self): '''-> Return all collectors, including their ID ''' url = "https://" + self.config['host'] + "/suite-api/api/collectors" response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) response_parsed = json.loads(response.text) print("id,Name,State") for instance in response_parsed["collector"]: print(instance["id"] + "," + instance["name"] + "," + instance["state"])
def createCredentials(self, credConfigFile): '''-> Creates credentials based on a CSV file generated by the createCredential Routine CREDCONFIGFILE: Credentail CSV file (with passwords added by user) ''' credConfigData = open(credConfigFile, newline='') credConfig = csv.DictReader(credConfigData) for row in credConfig: # Suite-API specifically expects a list of dictionary objects, with only two ides of "name" and "value". Not even asking why... credConfigItems = [] for name, value in row.items(): if (name == 'name') or (name == 'adapterKindKey') or ( name == 'credentialKindKey'): continue credConfigItems.append({"name": name, 'value': value}) newcreddata = { "name": row['name'], "adapterKindKey": row['adapterKindKey'], "credentialKindKey": row['credentialKindKey'], "fields": credConfigItems, } url = 'https://' + self.config[ 'host'] + '/suite-api/api/credentials' r = requests.post(url, data=json.dumps(newcreddata), headers=clilib.get_token_header( self.token['token']), verify=False) if r.status_code < 300: returndata = json.loads(r.text) print(row['name'] + ' Credentail Successfully Created with ID ' + returndata["id"]) else: # Not raising exception as we want to process the entire file, if possible print(row['name'] + ' Failed!') print(str(r.status_code)) print(r.text)
def getAlertsDefinitionsByAdapterKind(self, adapterKindKey): '''-> Produce the JSON definition of all alert definition for a particular adapter kind ADAPTERKINDKEY: Adapter kind, which can be found by calling getAdapterKinds ''' url = "https://" + self.config[ 'host'] + "/suite-api/api/alertdefinitions?adapterKind=" + adapterKindKey response = requests.request("GET", url, headers=clilib.get_token_header( self.token['token']), verify=False) response_parsed = json.loads(response.text) print("{\"alertDefinitions\": " + json.dumps(response_parsed["alertDefinitions"]) + "}")