diff --git a/examples/alerts.py b/examples/alerts.py index 56ba4a52b..3457ba429 100644 --- a/examples/alerts.py +++ b/examples/alerts.py @@ -15,12 +15,12 @@ # limitations under the License. ### -from hpeOneView.oneview_client import OneViewClient +from pprint import pprint from config_loader import try_load_from_file from hpeOneView.resources.resource import extract_id_from_uri -from pprint import pprint +from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "172.16.102.59", "credentials": { "userName": "administrator", @@ -28,61 +28,63 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -_client = OneViewClient(config) +_CLIENT = OneViewClient(CONFIG) -# Getting the first 5 alerts -print("\nGetting the first 5 alerts") -alerts = _client.alerts.get_all(0, 5) -for alert in alerts: +# Getting the first 5 ALERTS +print("\nGetting the first 5 ALERTS") +ALERTS = _CLIENT.alerts.get_all(0, 5) +for alert in ALERTS: print("uri: '{uri}' | type: '{type}' | alertState: '{alertState}'".format(**alert)) # Get a specific alert (first of the list that was obtained in previous item) print("\nGet a specific alert") -id_alert_by_id = extract_id_from_uri(alerts[0]['uri']) -print("Find id == %s" % id_alert_by_id) -alert_by_id = _client.alerts.get(id_alert_by_id) -print("uri: '%s' | alertState: '%s'" % (alert_by_id['uri'], alert_by_id['alertState'])) +ID_ALERT_BY_ID = extract_id_from_uri(ALERTS[0]['uri']) +print("Find id == %s" % ID_ALERT_BY_ID) +ALERT_BY_ID = _CLIENT.alerts.get(ID_ALERT_BY_ID) +print("uri: '%s' | alertState: '%s'" % (ALERT_BY_ID['uri'], ALERT_BY_ID['alertState'])) # Get by Uri print("Find uri == %s" % (alert['uri'])) -alert_by_uri = _client.alerts.get(alert['uri']) -print("uri: '%s' | alertState: '%s'" % (alert_by_uri['uri'], alert_by_uri['alertState'])) +ALERT_BY_URI = _CLIENT.alerts.get(alert['uri']) +print("uri: '%s' | alertState: '%s'" % (ALERT_BY_URI['uri'], ALERT_BY_URI['alertState'])) # Find first alert by state print("\nGet first alert by state: Cleared") -alert_by_state = _client.alerts.get_by('alertState', 'Cleared')[0] -print("Found alert by state: '%s' | uri: '%s'" % (alert_by_state['alertState'], alert_by_state['uri'])) +ALERT_BY_STATE = _CLIENT.alerts.get_by('alertState', 'Cleared')[0] +print("Found alert by state: '%s' | uri: '%s'" % (ALERT_BY_STATE['alertState'],\ + ALERT_BY_STATE['uri'])) # Updates state alert and add note print("\nUpdate state alert and add a note") -alert_to_update = { - 'uri': alert_by_state['uri'], +ALERT_TO_UPDATE = { + 'uri': ALERT_BY_STATE['uri'], 'alertState': 'Active', 'notes': 'A note to delete!' } -alert_updated = _client.alerts.update(alert_to_update) -print("uri = '%s' | alertState = '%s'" % (alert_by_state['uri'], alert_by_state['alertState'])) +ALERT_UPDATED = _CLIENT.alerts.update(ALERT_TO_UPDATE) +print("uri = '%s' | alertState = '%s'" % (ALERT_BY_STATE['uri'], ALERT_BY_STATE['alertState'])) print("Update alert successfully.") -pprint(alert_updated) +pprint(ALERT_UPDATED) # Filter by state -print("\nGet all alerts filtering by alertState") -alerts = _client.alerts.get_all(filter="\"alertState='Locked'\"", view="day", count=10) -for alert in alerts: - print("'%s' | type: '%s' | alertState: '%s'" % (alert['uri'], alert['type'], alert['alertState'])) +print("\nGet all ALERTS filtering by alertState") +ALERTS = _CLIENT.alerts.get_all(filter="\"alertState='Locked'\"", view="day", count=10) +for alert in ALERTS: + print("'%s' | type: '%s' | alertState: '%s'" % (alert['uri'], alert['type'],\ + alert['alertState'])) # Deletes the alert print("\nDelete an alert") -_client.alerts.delete(alert_by_id) +_CLIENT.alerts.delete(ALERT_BY_ID) print("Successfully deleted alert") # Deletes the AlertChangeLog item identified by URI print("\nDelete alert change log by URI") # filter by user entered logs -list_change_logs = [x for x in alert_updated['changeLog'] if x['userEntered'] is True] -uri_note = list_change_logs[-1]['uri'] -_client.alerts.delete_alert_change_log(uri_note) -print("Note with URI '%s' deleted" % uri_note) +LIST_CHANGE_LOGS = [x for x in ALERT_UPDATED['changeLog'] if x['userEntered'] is True] +URI_NOTE = LIST_CHANGE_LOGS[-1]['uri'] +_CLIENT.alerts.delete_alert_change_log(URI_NOTE) +print("Note with URI '%s' deleted" % URI_NOTE) diff --git a/examples/appliance_configuration_timeconfig.py b/examples/appliance_configuration_timeconfig.py index c0a655c52..3dc00b60c 100644 --- a/examples/appliance_configuration_timeconfig.py +++ b/examples/appliance_configuration_timeconfig.py @@ -18,20 +18,20 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -time_config = oneview_client.appliance_configuration_timeconfig +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +TIME_CONFIG = oneview_client.appliance_configuration_timeconfig # Get all the supported locales -timeconfig = time_config.get_all() +TIMECONFIG = TIME_CONFIG.get_all() print("\nGot appliance supported locales successfully!") -for timeandlocale in timeconfig: +for timeandlocale in TIMECONFIG: print("\nLocale = {}".format(timeandlocale['locale'])) diff --git a/examples/appliance_device_read_community.py b/examples/appliance_device_read_community.py index 724ae4418..21adb9984 100644 --- a/examples/appliance_device_read_community.py +++ b/examples/appliance_device_read_community.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,33 +27,33 @@ } } -options = { +OPTIONS = { "communityString": "public" } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Lists the appliance device read community -read_community = oneview_client.appliance_device_read_community.get() +READ_COMMUNITY = oneview_client.appliance_device_read_community.get() print("\n## Got appliance device read community successfully!") -pprint(read_community) +pprint(READ_COMMUNITY) # Backup original values -bkp = {} -bkp['communityString'] = read_community['communityString'] +BKP = {} +BKP['communityString'] = READ_COMMUNITY['communityString'] # Update Read Community # Set to use appliance device read community -read_community['communityString'] = options['communityString'] -read_community = oneview_client.appliance_device_read_community.update(read_community) +READ_COMMUNITY['communityString'] = OPTIONS['communityString'] +READ_COMMUNITY = oneview_client.appliance_device_read_community.update(READ_COMMUNITY) print("\n## Updated appliance device read community string successfully!") -pprint(read_community) +pprint(READ_COMMUNITY) # Revert the changes made -read_community['communityString'] = bkp['communityString'] -read_community = oneview_client.appliance_device_read_community.update(read_community) +READ_COMMUNITY['communityString'] = BKP['communityString'] +READ_COMMUNITY = oneview_client.appliance_device_read_community.update(READ_COMMUNITY) print("\n## Reverted appliance device read community string successfully!") -pprint(read_community) +pprint(READ_COMMUNITY) diff --git a/examples/appliance_device_snmp_v1_trap_destinations.py b/examples/appliance_device_snmp_v1_trap_destinations.py index 2edfd2947..261f0327d 100644 --- a/examples/appliance_device_snmp_v1_trap_destinations.py +++ b/examples/appliance_device_snmp_v1_trap_destinations.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,65 +27,68 @@ } } -options = { +OPTIONS = { "destination": "1.1.1.2", "communityString": "testOne", "port": 162 } -destination_ip = '2.2.2.2' +DESTINATION_IP = '2.2.2.2' -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -appliance_device_snmp_v1_trap_destinations = oneview_client.appliance_device_snmp_v1_trap_destinations +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS = oneview_client.\ + appliance_device_snmp_v1_trap_destinations # Lists the appliance device SNMP v1 Trap Destination print("\n Get list of appliance SNMP v1 trap destination") -snmp_v1_trap_all = appliance_device_snmp_v1_trap_destinations.get_all() -for snmp_trap in snmp_v1_trap_all: +SNMP_V1_TRAP_ALL = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.get_all() +for snmp_trap in SNMP_V1_TRAP_ALL: print(' - {}: {}'.format(snmp_trap['destination'], snmp_trap['uri'])) # Add appliance device SNMP v1 Trap Destination -snmp_v1_trap = appliance_device_snmp_v1_trap_destinations.create(options) +SNMP_V1_TRAP = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.create(OPTIONS) print("\n Created appliance SNMP v1 trap destination successfully!") -pprint(snmp_v1_trap.data) +pprint(SNMP_V1_TRAP.data) # Get by name print("\n## Find an SNMPv1 trap destination by name") -snmp_v1_trap = appliance_device_snmp_v1_trap_destinations.get_by_name(snmp_v1_trap.data['destination']) -pprint(snmp_v1_trap.data) +SNMP_V1_TRAP = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.\ + get_by_name(SNMP_V1_TRAP.data['destination']) +pprint(SNMP_V1_TRAP.data) # Add appliance device SNMP v1 Trap Destination with ID -trap_id = 9 -options['destination'] = destination_ip -snmp_v1_trap_id = appliance_device_snmp_v1_trap_destinations.create(options, trap_id) +TRAP_ID = 9 +OPTIONS['destination'] = DESTINATION_IP +SNMP_V1_TRAP_ID = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.create(OPTIONS, TRAP_ID) print("\n Created appliance SNMP v1 trap destination by id successfully!") -pprint(snmp_v1_trap_id.data) +pprint(SNMP_V1_TRAP_ID.data) # Get the appliance device SNMP v1 Trap Destination by id print("\n Get appliance SNMP v1 trap destination by id") -snmp_v1_trap_by_id = appliance_device_snmp_v1_trap_destinations.get_by_id(1) -pprint(snmp_v1_trap_by_id.data) +SNMP_V1_TRAP_BY_ID = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.get_by_id(1) +pprint(SNMP_V1_TRAP_BY_ID.data) # Lists the appliance device SNMP v1 Trap Destination by destination (unique) print("\n## Get appliance SNMP v1 trap by destination..") -snmp_v1_traps = appliance_device_snmp_v1_trap_destinations.get_by('destination', options['destination']) -for snmp_trap in snmp_v1_traps: +SNMP_V1_TRAPS = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.get_by('destination',\ + OPTIONS['destination']) +for snmp_trap in SNMP_V1_TRAPS: print(' - {} : {}'.format(snmp_trap['destination'], snmp_trap['communityString'])) # Get by URI print("\n Find an SNMP v1 trap destination by URI") -snmp_v1_trap = appliance_device_snmp_v1_trap_destinations.get_by_uri(snmp_v1_trap.data['uri']) -pprint(snmp_v1_trap.data) +SNMP_V1_TRAP = APPLIANCE_DEVICE_SNMP_V1_TRAP_DESTINATIONS.get_by_uri(SNMP_V1_TRAP.data['uri']) +pprint(SNMP_V1_TRAP.data) # Change appliance device SNMP v1 Trap Destination - Only Community String and Port can be changed -data = {'communityString': 'testTwo'} -snmp_v1_trap = snmp_v1_trap.update(data) +DATA = {'communityString': 'testTwo'} +SNMP_V1_TRAP = SNMP_V1_TRAP.update(DATA) print("\n## Update appliance SNMP v1 trap destination successfully!") -pprint(snmp_v1_trap.data) +pprint(SNMP_V1_TRAP.data) # Delete Created Entry -snmp_v1_trap.delete() -snmp_v1_trap_id.delete() +SNMP_V1_TRAP.delete() +SNMP_V1_TRAP_ID.delete() print("\n## Delete appliance SNMP v1 trap destination successfully!") diff --git a/examples/appliance_device_snmp_v3_trap_destinations.py b/examples/appliance_device_snmp_v3_trap_destinations.py index 9e0b1f3d8..ca17df831 100644 --- a/examples/appliance_device_snmp_v3_trap_destinations.py +++ b/examples/appliance_device_snmp_v3_trap_destinations.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,54 +27,56 @@ } } -options = { +OPTIONS = { "type": "Destination", "destinationAddress": "1.1.1.1", "port": 162, "existingDestinations": ['2.3.2.3'] } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -appliance_device_snmp_v3_trap_destinations = oneview_client.appliance_device_snmp_v3_trap_destinations -appliance_device_snmp_v3_users = oneview_client.appliance_device_snmp_v3_users +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +APPLIANCE_DEVICE_SNMP_V3_TRAP_DESTINATIONS = oneview_client.\ + appliance_device_snmp_v3_trap_destinations +APPLIANCE_DEVICE_SNMP_V3_USERS = oneview_client.appliance_device_snmp_v3_users # Get all snmpv3 users # snmp v3 user must be there to create this -snmp_users = appliance_device_snmp_v3_users.get_all() -if snmp_users: - snmp_userId = snmp_users[0]['id'] +SNMP_USERS = APPLIANCE_DEVICE_SNMP_V3_USERS.get_all() +if SNMP_USERS: + SNMP_USERID = SNMP_USERS[0]['id'] # Adding userId to snmpv3 users payload - options['userId'] = snmp_userId + OPTIONS['userId'] = SNMP_USERID # Add appliance device SNMP v3 Trap Destination - snmp_v3_trap = appliance_device_snmp_v3_trap_destinations.create(options) + SNMP_V3_TRAP = APPLIANCE_DEVICE_SNMP_V3_TRAP_DESTINATIONS.create(OPTIONS) print("\n## Created appliance SNMPv3 trap destination successfully!") - pprint(snmp_v3_trap.data) + pprint(SNMP_V3_TRAP.data) # Lists the appliance device SNMP v3 Trap Destination print("\n## Get list of appliance SNMPv3 trap destination") -snmp_v3_trap_all = appliance_device_snmp_v3_trap_destinations.get_all() -for snmp_trap in snmp_v3_trap_all: +SNMP_V3_TRAP_ALL = APPLIANCE_DEVICE_SNMP_V3_TRAP_DESTINATIONS.get_all() +for snmp_trap in SNMP_V3_TRAP_ALL: print(' - {}: {}'.format(snmp_trap['destinationAddress'], snmp_trap['uri'])) # Get by name print("\n## Find an SNMPv3 trap destination by name") -snmp_v3_trap = appliance_device_snmp_v3_trap_destinations.get_by_name(snmp_v3_trap.data['destinationAddress']) -pprint(snmp_v3_trap.data) +SNMP_V3_TRAP = APPLIANCE_DEVICE_SNMP_V3_TRAP_DESTINATIONS.get_by_name\ + (SNMP_V3_TRAP.data['destinationAddress']) +pprint(SNMP_V3_TRAP.data) # Get by URI print("\n## Find an SNMPv3 trap destination by URI") -snmp_v3_trap = appliance_device_snmp_v3_trap_destinations.get_by_uri(snmp_v3_trap.data['uri']) -pprint(snmp_v3_trap.data) +SNMP_V3_TRAP = APPLIANCE_DEVICE_SNMP_V3_TRAP_DESTINATIONS.get_by_uri(SNMP_V3_TRAP.data['uri']) +pprint(SNMP_V3_TRAP.data) # Change appliance device SNMP v3 Trap Destination - Only Community String and Port can be changed -snmpv3_data = {"port": 170} -snmp_v3_trap = snmp_v3_trap.update(snmpv3_data) +SNMPV3_DATA = {"port": 170} +SNMP_V3_TRAP = SNMP_V3_TRAP.update(SNMPV3_DATA) print("\n## Update appliance SNMPv3 trap destination successfully!") -pprint(snmp_v3_trap.data) +pprint(SNMP_V3_TRAP.data) # Delete Created Entry -snmp_v3_trap.delete(snmp_v3_trap) +SNMP_V3_TRAP.delete(SNMP_V3_TRAP) print("\n## Delete appliance SNMPv3 trap destination successfully!") diff --git a/examples/appliance_device_snmp_v3_users.py b/examples/appliance_device_snmp_v3_users.py index fc0daa82b..9b98ec3b0 100644 --- a/examples/appliance_device_snmp_v3_users.py +++ b/examples/appliance_device_snmp_v3_users.py @@ -20,7 +20,7 @@ from config_loader import try_load_from_file # Set api_version to 600, default is 300 and this API has been introduced since API 600. -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,7 +29,7 @@ "api_version": 600 } -options = { +OPTIONS = { "type": "Users", "userName": "user1239", "securityLevel": "Authentication and privacy", @@ -39,48 +39,48 @@ "privacyPassphrase": "1234567812345678" } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -appliance_device_snmp_v3_users = oneview_client.appliance_device_snmp_v3_users +oneview_client = OneViewClient(CONFIG) +APPLIANCE_DEVICE_SNMP_V3_USERS = oneview_client.appliance_device_snmp_v3_users # Add appliance device SNMP v3 users -snmp_v3_user = appliance_device_snmp_v3_users.create(options) -snmp_v3_user_uri = snmp_v3_user.data['uri'] +SNMP_V3_USER = APPLIANCE_DEVICE_SNMP_V3_USERS.create(OPTIONS) +SNMP_V3_USER_URI = SNMP_V3_USER.data['uri'] print("\n## Create appliance SNMP v3 user successfully!") -pprint(snmp_v3_user.data) +pprint(SNMP_V3_USER.data) # Lists the appliance SNMPv3 users -snmp_v3_users_list = appliance_device_snmp_v3_users.get_all() +SNMP_V3_USERS_LIST = APPLIANCE_DEVICE_SNMP_V3_USERS.get_all() print("\n## Got appliance SNMP v3 users successfully!") -pprint(snmp_v3_users_list) +pprint(SNMP_V3_USERS_LIST) # Get first element of the List -snmp_v3_users = snmp_v3_users_list.pop() +SNMP_V3_USERS = SNMP_V3_USERS_LIST.pop() # Get by name print("\n## Find an SNMPv3 Users by username") -snmp_v3_user = appliance_device_snmp_v3_users.get_by_name(snmp_v3_user.data['userName']) -pprint(snmp_v3_user.data) +SNMP_V3_USER = APPLIANCE_DEVICE_SNMP_V3_USERS.get_by_name(SNMP_V3_USER.data['userName']) +pprint(SNMP_V3_USER.data) # Get by URI print("Find an SNMP v3 user by URI") -snmp_v3_user = appliance_device_snmp_v3_users.get_by_uri(snmp_v3_user_uri) -pprint(snmp_v3_user.data) +SNMP_V3_USER = APPLIANCE_DEVICE_SNMP_V3_USERS.get_by_uri(SNMP_V3_USER_URI) +pprint(SNMP_V3_USER.data) # hange appliance device SNMP v3 Users -snmpv3_data = {"authenticationPassphrase": "newAuthPass", "privacyPassphrase": "8765432187654321"} -snmp_v3_user = snmp_v3_user.update(snmpv3_data) +SNMPV3_DATA = {"authenticationPassphrase": "newAuthPass", "privacyPassphrase": "8765432187654321"} +SNMP_V3_USER = SNMP_V3_USER.update(SNMPV3_DATA) print("\n## Update appliance SNMPv3 User successfully!") -pprint(snmp_v3_user.data) +pprint(SNMP_V3_USER.data) # Delete Created Entry -snmp_v3_user.delete() +SNMP_V3_USER.delete() print("\n## Delete appliance SNMP v3 user successfully!") # Add appliance device SNMP v3 users for Automation -snmp_v3_user = appliance_device_snmp_v3_users.create(options) -snmp_v3_user_uri = snmp_v3_user.data['uri'] +SNMP_V3_USER = APPLIANCE_DEVICE_SNMP_V3_USERS.create(OPTIONS) +SNMP_V3_USER_URI = SNMP_V3_USER.data['uri'] print("\n## Created appliance SNMP v3 user") -pprint(snmp_v3_user.data) +pprint(SNMP_V3_USER.data) diff --git a/examples/appliance_health_status.py b/examples/appliance_health_status.py index 8894b8b38..27959ac19 100644 --- a/examples/appliance_health_status.py +++ b/examples/appliance_health_status.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,12 +27,12 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -app_health = oneview_client.appliance_health_status +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +APP_HEALTH = oneview_client.appliance_health_status # Get health status information from appliance print("\nGet health status information from appliance:\n ") -health_status = app_health.get_health_status() -pprint(health_status.data) +HEALTH_STATUS = APP_HEALTH.get_health_status() +pprint(HEALTH_STATUS.data) diff --git a/examples/appliance_network_interfaces.py b/examples/appliance_network_interfaces.py index 0834009bf..0928f6cb4 100644 --- a/examples/appliance_network_interfaces.py +++ b/examples/appliance_network_interfaces.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,74 +27,75 @@ } } -uri = '/rest/appliance/network-interfaces' +URI = '/rest/appliance/network-interfaces' -# Try load config from a file -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -network_interface = oneview_client.appliance_network_interfaces +# Try load CONFIG from a file +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +NETWORK_INTERFACE = oneview_client.appliance_network_interfaces -# Get configured network interface from appliance +# Get CONFIGured network interface from appliance print("\nGet network interface details from appliance:\n ") -network_interfaces = network_interface.get_all().data['applianceNetworks'] -for net_interface in network_interfaces: +NETWORK_INTERFACES = NETWORK_INTERFACE.get_all().data['applianceNetworks'] +for net_interface in NETWORK_INTERFACES: pprint(net_interface['hostname']) pprint(net_interface['interfaceName']) # Create network interface if it doesn't exist print("\nCreate network interface on the appliance:\n") -ni_details = {"applianceNetworks": [{ - "interfaceName": "Appliance test", - "device": "eth0", - "macAddress": "00:11:22:33:ff:3e", - "ipv4Type": "STATIC", - "ipv6Type": "UNCONFIGURE", - "hostname": "test.com", - "app1Ipv4Addr": "", - "app2Ipv4Addr": "", - "virtIpv4Addr": "", - "ipv4Subnet": "", - "ipv4Gateway": "", - "ipv4NameServers": [ - "", - "" - ]}]} +NI_DETAILS = {"applianceNetworks": [{ + "interfaceName": "Appliance test", + "device": "eth0", + "macAddress": "00:11:22:33:ff:3e", + "ipv4Type": "STATIC", + "ipv6Type": "UNCONFIGURE", + "hostname": "test.com", + "app1Ipv4Addr": "", + "app2Ipv4Addr": "", + "virtIpv4Addr": "", + "ipv4Subnet": "", + "ipv4Gateway": "", + "ipv4NameServers": [ + "", + "" + ]}]} -new_network_interface = network_interface.create(ni_details) -pprint(new_network_interface.data) +NEW_NETWORK_INTERFACE = NETWORK_INTERFACE.create(NI_DETAILS) +pprint(NEW_NETWORK_INTERFACE.data) print("\nNetwork Interface created successfully") # Updates dns servers of the network interface # For update, we use the same create method # as PUT not supported for this resource print("\nUpdate dns servers of the network interface:\n") -updated_details = {"applianceNetworks": [{ - "interfaceName": "Appliance test", - "device": "eth0", - "macAddress": "00:11:22:33:ff:3e", - "ipv4Type": "STATIC", - "ipv6Type": "UNCONFIGURE", - "hostname": "test.com", - "app1Ipv4Addr": "", - "app2Ipv4Addr": "", - "virtIpv4Addr": "", - "ipv4Subnet": "", - "ipv4Gateway": "", - "ipv4NameServers": [ - "", - "" - ]}]} -updated_network_interface = network_interface.create(updated_details) -pprint(updated_network_interface.data) +UPDATED_DETAILS = {"applianceNetworks": [{ + "interfaceName": "Appliance test", + "device": "eth0", + "macAddress": "00:11:22:33:ff:3e", + "ipv4Type": "STATIC", + "ipv6Type": "UNCONFIGURE", + "hostname": "test.com", + "app1Ipv4Addr": "", + "app2Ipv4Addr": "", + "virtIpv4Addr": "", + "ipv4Subnet": "", + "ipv4Gateway": "", + "ipv4NameServers": [ + "", + "" + ]}]} +UPDATED_NETWORK_INTERFACE = NETWORK_INTERFACE.create(UPDATED_DETAILS) +pprint(UPDATED_NETWORK_INTERFACE.data) print("\nNetwork Interface updated successfully") -# Get network configuration by the mac address +# Get network CONFIGuration by the mac address print("\nGet network interface details from appliance:\n ") -if network_interfaces: - network_interface_by_mac = network_interface.get_by_mac_address(network_interfaces[0]['macAddress']) - pprint(network_interface_by_mac.data) +if NETWORK_INTERFACES: + NETWORK_INTERFACE_BY_MAC = NETWORK_INTERFACE.get_by_mac_address\ + (NETWORK_INTERFACES[0]['macAddress']) + pprint(NETWORK_INTERFACE_BY_MAC.data) -# Get unconfigured network interfaces on the appliance -print("\nGet unconfigured network interfaces from appliance:\n ") -network_interface_unconfigured = network_interface.get_all_mac_address() -pprint(network_interface_unconfigured) +# Get unCONFIGured network interfaces on the appliance +print("\nGet unCONFIGured network interfaces from appliance:\n ") +NETWORK_INTERFACE_UNCONFIGURED = NETWORK_INTERFACE.get_all_mac_address() +pprint(NETWORK_INTERFACE_UNCONFIGURED) diff --git a/examples/appliance_node_information.py b/examples/appliance_node_information.py index 92080bdb6..0388a46ab 100644 --- a/examples/appliance_node_information.py +++ b/examples/appliance_node_information.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,17 +27,17 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -app_node_info = oneview_client.appliance_node_information +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +APP_NODE_INFO = oneview_client.appliance_node_information # Get node status information from appliance print("\nGet node status information from appliance:\n ") -node_status = app_node_info.get_status() -pprint(node_status.data) +NODE_STATUS = APP_NODE_INFO.get_status() +pprint(NODE_STATUS.data) # Get node version information from appliance print("\nGet node version information from appliance\n") -node_version = app_node_info.get_version() -pprint(node_version.data) +NODE_VERSION = APP_NODE_INFO.get_version() +pprint(NODE_VERSION.data) diff --git a/examples/appliance_proxy_configuration.py b/examples/appliance_proxy_configuration.py index fac82d619..b42f60228 100644 --- a/examples/appliance_proxy_configuration.py +++ b/examples/appliance_proxy_configuration.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,16 +27,16 @@ } } -uri = '/rest/appliance/proxy-config' +URI = '/rest/appliance/PROXY-CONFIG' -# Try load config from a file -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -proxy = oneview_client.appliance_proxy_configuration +# Try load CONFIG from a file +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +PROXY = oneview_client.appliance_proxy_configuration -# Configure proxy with HTTP protocol -print("\nCreating proxy with HTTP:\n") -proxy_config = { +# Configure PROXY with HTTP protocol +print("\nCreating PROXY with HTTP:\n") +PROXY_CONFIG = { "server": "", "port": 443, "username": "", @@ -44,16 +44,16 @@ "communicationProtocol": "HTTP" } -new_proxy = proxy.create(proxy_config) -pprint(new_proxy.data) +NEW_PROXY = PROXY.create(PROXY_CONFIG) +pprint(NEW_PROXY.data) print("Proxy created successfully\n") -# Get proxy configuration from appliance -print("\nGet proxy configuration from appliance:\n ") -proxy_info = proxy.get_by_proxy(proxy_config["server"]) -pprint(proxy_info.data) +# Get PROXY CONFIGuration from appliance +print("\nGet PROXY CONFIGuration from appliance:\n ") +PROXY_INFO = PROXY.get_by_proxy(PROXY_CONFIG["server"]) +pprint(PROXY_INFO.data) -# Delete proxy configured on the appliance +# Delete PROXY CONFIGured on the appliance print("\nDelete Proxy") -proxy.delete() +PROXY.delete() print("Proxy deleted successfully") diff --git a/examples/appliance_ssh_access.py b/examples/appliance_ssh_access.py index e8850d4e1..30f51e679 100644 --- a/examples/appliance_ssh_access.py +++ b/examples/appliance_ssh_access.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,25 +27,25 @@ } } -options = { +OPTIONS = { "allowSshAccess": False } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -ssh_access = oneview_client.appliance_ssh_access +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +SSH_ACCESS = ONEVIEW_CLIENT.appliance_ssh_access -# Get the SSH access configuration for the appliance. -ssh_config = ssh_access.get_all() -print("\nGot SSH access configuration successfully!") -pprint(ssh_config.data) +# Get the SSH access CONFIGuration for the appliance. +SSH_CONFIG = SSH_ACCESS.get_all() +print("\nGot SSH access CONFIGuration successfully!") +pprint(SSH_CONFIG.data) -# Set the SSH access configuration for the appliance as False. -ssh_config = ssh_config.update(data=options) -print("\nUpdated SSH access configuration successfully!") +# Set the SSH access CONFIGuration for the appliance as False. +SSH_CONFIG = SSH_CONFIG.update(data=OPTIONS) +print("\nUpdated SSH access CONFIGuration successfully!") -# Set the SSH access configuration for the appliance as True. -options["allowSshAccess"] = True -ssh_config = ssh_config.update(data=options) -print("\nUpdated SSH access configuration successfully!") +# Set the SSH access CONFIGuration for the appliance as True. +OPTIONS["allowSshAccess"] = True +SSH_CONFIG = SSH_CONFIG.update(data=OPTIONS) +print("\nUpdated SSH access CONFIGuration successfully!") diff --git a/examples/appliance_time_and_locale_configuration.py b/examples/appliance_time_and_locale_configuration.py index 8e71afb2e..4442cee55 100644 --- a/examples/appliance_time_and_locale_configuration.py +++ b/examples/appliance_time_and_locale_configuration.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,49 +27,48 @@ } } -options = { +OPTIONS = { "locale": "en_US.UTF-8", "timezone": "UTC", "ntpServers": ["127.0.0.1"], } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -time_and_locales = oneview_client.appliance_time_and_locale_configuration +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +TIME_AND_LOCALES = ONEVIEW_CLIENT.appliance_time_and_locale_configuration -# Lists the appliance time and locale configuration -time_and_locale = time_and_locales.get_all() -if time_and_locale: - print("\n## Got appliance time and locale configurations successfully!") - pprint(time_and_locale.data) +# Lists the appliance time and locale CONFIGuration +TIME_AND_LOCALE = TIME_AND_LOCALES.get_all() +if TIME_AND_LOCALE: + print("\n## Got appliance time and locale CONFIGurations successfully!") + pprint(TIME_AND_LOCALE.data) else: - # Create a time and locale with the options provided - time_and_locale = time_and_locales.create(data=options) - print("\n## Created appliance time and locale configurations successfully!") - pprint(time_and_locale.data) + # Create a time and locale with the OPTIONS provided + TIME_AND_LOCALE = TIME_AND_LOCALES.create(data=OPTIONS) + print("\n## Created appliance time and locale CONFIGurations successfully!") + pprint(TIME_AND_LOCALE.data) -time_and_locale = time_and_locale.data +TIME_AND_LOCALE = TIME_AND_LOCALE.data # Set to use appliance local time and date server -time_and_locale['ntpServers'] = ['127.0.0.1'] +TIME_AND_LOCALE['ntpServers'] = ['127.0.0.1'] # Set locale to Chinese (China) with charset UTF-8 -time_and_locale['locale'] = 'zh_CN.UTF-8' +TIME_AND_LOCALE['locale'] = 'zh_CN.UTF-8' # Remove the date and time, we do not want to update it manually -time_and_locale.pop('dateTime') -time_and_locale = time_and_locales.create(data=time_and_locale) -print("\n## Created appliance time and locale configurations successfully!") -pprint(time_and_locale.data) +TIME_AND_LOCALE.pop('dateTime') +TIME_AND_LOCALE = TIME_AND_LOCALES.create(data=TIME_AND_LOCALE) +print("\n## Created appliance time and locale CONFIGurations successfully!") +pprint(TIME_AND_LOCALE.data) # Note: Changing the time and locale will only be fully effective after resetting the appliance. # Until then we cannot run the below create function ''' try: # Revert the changes made - time_and_locale = time_and_locales.create(data=options) - print("\n## Reverted appliance time and locale configurations successfully!") - pprint(time_and_locale.data) + TIME_AND_LOCALE = TIME_AND_LOCALES.create(data=OPTIONS) + print("\n## Reverted appliance time and locale CONFIGurations successfully!") + pprint(TIME_AND_LOCALE.data) except HPEOneViewTaskError: print("\n## Appliance will be rebooted to make the changes made previously.") - ''' diff --git a/examples/backups.py b/examples/backups.py index f58b438fa..956a7c4fd 100644 --- a/examples/backups.py +++ b/examples/backups.py @@ -20,7 +20,7 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "172.16.102.59", "credentials": { "userName": "administrator", @@ -28,56 +28,57 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) # Create a new appliance backup print("\n## Create a new appliance backup") -backup_details = oneview_client.backups.create() -pprint(backup_details) +BACKUP_DETAILS = ONEVIEW_CLIENT.backups.create() +pprint(BACKUP_DETAILS) -filename = backup_details['id'] +FILENAME = BACKUP_DETAILS['id'] # Download the backup archive print("\n## Download the previously created backup archive") -response = oneview_client.backups.download(backup_details['downloadUri'], filename) -print(response) +RESPONSE = ONEVIEW_CLIENT.backups.download(BACKUP_DETAILS['downloadUri'], FILENAME) +print(RESPONSE) # Upload the backup archive print("\n## Upload the previously downloaded backup archive") -backup_details = oneview_client.backups.upload(filename) -pprint(backup_details) +BACKUP_DETAILS = ONEVIEW_CLIENT.backups.upload(FILENAME) +pprint(BACKUP_DETAILS) # Get by URI print("\n## Find recently created backup by URI") -backup_by_uri = oneview_client.backups.get(backup_details['uri']) -pprint(backup_by_uri) +BACKUP_BY_URI = ONEVIEW_CLIENT.backups.get(BACKUP_DETAILS['uri']) +pprint(BACKUP_BY_URI) # Get all backups print("\n## Get all backups") -backups = oneview_client.backups.get_all() -pprint(backups) +BACKUPS = ONEVIEW_CLIENT.backups.get_all() +pprint(BACKUPS) -# Get the details of the backup configuration -print("\n## Get the details of the backup configuration for the remote server and automatic backup schedule") -config = oneview_client.backups.get_config() -pprint(config) +# Get the details of the backup CONFIGuration +print("\nGet the details of the backup configuration for the remote server and automatic backup\ + schedule") +CONFIG = ONEVIEW_CLIENT.backups.get_config() +pprint(CONFIG) -# Update the backup configuration +# Update the backup CONFIGuration try: - print("\n## Update the backup configuration") - config['scheduleTime'] = '23:00' - updated_config = oneview_client.backups.update_config(config) - pprint(updated_config) -except HPEOneViewException as e: - print(e.msg) + print("\n## Update the backup CONFIGuration") + CONFIG['scheduleTime'] = '23:00' + UPDATED_CONFIG = ONEVIEW_CLIENT.backups.update_config(CONFIG) + pprint(UPDATED_CONFIG) +except HPEOneViewException as err: + print(err.msg) -# Save the backup file to a previously-configured remote location +# Save the backup file to a previously-CONFIGured remote location try: - print("\n## Save the backup file to a previously-configured remote location") - backup_details = oneview_client.backups.update_remote_archive(backup_details['saveUri']) - pprint(backup_details) -except HPEOneViewException as e: - print(e.msg) + print("\n## Save the backup file to a previously-CONFIGured remote location") + BACKUP_DETAILS = ONEVIEW_CLIENT.backups.update_remote_archive(BACKUP_DETAILS['saveUri']) + pprint(BACKUP_DETAILS) +except HPEOneViewException as err: + print(err.msg) diff --git a/examples/certificate_authority.py b/examples/certificate_authority.py index 8a999b5ce..4a51cba62 100644 --- a/examples/certificate_authority.py +++ b/examples/certificate_authority.py @@ -20,7 +20,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,30 +28,30 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -certificate_authority = oneview_client.certificate_authority +ONEVIEW_CLIENT = OneViewClient(CONFIG) +CERTIFICATE_AUTHORITY = ONEVIEW_CLIENT.certificate_authority # Retrieve Internal CA Certificate print("\n\nGet all the internal Certificate Authorities:\n") -certificates_all = certificate_authority.get_all(cert_details=False) -print(certificates_all) +CERTIFICATES_ALL = CERTIFICATE_AUTHORITY.get_all(cert_details=False) +print(CERTIFICATES_ALL) -# Retrieve Internal CA Certificate with certificate details -print("\n\nGet the certificate details of internal Certificate Authority:\n") -certificate = certificate_authority.get_all() -for cert in certificate: - if cert['certificateDetails']['aliasName'] == 'localhostSelfSignedCertificate': - print(cert['certificateDetails']['base64Data']) +# Retrieve Internal CA Certificate with CERTIFICATE details +print("\n\nGet the CERTIFICATE details of internal Certificate Authority:\n") +CERTIFICATE = CERTIFICATE_AUTHORITY.get_all() +for cert in CERTIFICATE: + if cert['CERTIFICATEDetails']['aliasName'] == 'localhostSelfSignedCertificate': + print(cert['CERTIFICATEDetails']['base64Data']) # Retrieve Certificate Revocation List print("\n\nGetting the Certificate Revocation List:\n") -certificate_visual_content = certificate_authority.get_crl() -pprint(certificate_visual_content.data) +CERTIFICATE_VISUAL_CONTENT = CERTIFICATE_AUTHORITY.get_crl() +pprint(CERTIFICATE_VISUAL_CONTENT.data) # Revoke Internal CA Signed Certificate print("\n\nRevoking Internal CA Signed Certificate\n") -# success = certificate_authority.delete("default") +# success = CERTIFICATE_AUTHORITY.delete("default") # print(success) diff --git a/examples/certificate_rabbitmq.py b/examples/certificate_rabbitmq.py index 8671ad932..04b01b7ef 100644 --- a/examples/certificate_rabbitmq.py +++ b/examples/certificate_rabbitmq.py @@ -21,7 +21,7 @@ from hpeOneView.exceptions import HPEOneViewException from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -30,16 +30,16 @@ } # Try load config from a file (if there is a config file) -config = try_load_from_file(config) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) -certificate_ca_signed_client = { +CERTIFICATE_CA_SIGNED_CLIENT = { "commonName": "default", "type": "RabbitMqClientCertV2" } -certificate_self_signed_client = { +CERTIFICATE_SELF_SIGNED_CLIENT = { "commonName": "any", "signedCert": "false", "type": "RabbitMqClientCertV2" @@ -49,44 +49,44 @@ # Generate a CA Signed Certificate print('Generate a CA Signed Certificate') try: - response = oneview_client.certificate_rabbitmq.generate(certificate_ca_signed_client) - pprint(response) -except HPEOneViewException as e: - print (e.msg) - if e.oneview_response: - print e.oneview_response.get('recommendedActions') + RESPONSE = ONEVIEW_CLIENT.certificate_rabbitmq.generate(CERTIFICATE_CA_SIGNED_CLIENT) + pprint(RESPONSE) +except HPEOneViewException as err: + print(err.msg) + if err.oneview_response: + print(err.oneview_response.get('recommendedActions')) # Generate a Self Signed Certificate print('\nGenerate a Self Signed Certificate') try: - response = oneview_client.certificate_rabbitmq.generate(certificate_self_signed_client) - pprint(response) -except HPEOneViewException as e: - print (e.msg) - if e.oneview_response: - print e.oneview_response.get('recommendedActions') + RESPONSE = ONEVIEW_CLIENT.certificate_rabbitmq.generate(CERTIFICATE_SELF_SIGNED_CLIENT) + pprint(RESPONSE) +except HPEOneViewException as err: + print(err.msg) + if err.oneview_response: + print(err.oneview_response.get('recommendedActions')) # Get by Alias Name print('\nGet by Alias Name') -response = oneview_client.certificate_rabbitmq.get('default') -pprint(response) +RESPONSE = ONEVIEW_CLIENT.certificate_rabbitmq.get('default') +pprint(RESPONSE) # Get a Key Pair print('\nGet a Key Pair') -response = oneview_client.certificate_rabbitmq.get_key_pair('default') -pprint(response) +RESPONSE = ONEVIEW_CLIENT.certificate_rabbitmq.get_key_pair('default') +pprint(RESPONSE) # Get Keys in Base64 format print('\nGet Keys in Base64 format') -response = oneview_client.certificate_rabbitmq.get_keys('default', 'Base64') -pprint(response) +RESPONSE = ONEVIEW_CLIENT.certificate_rabbitmq.get_keys('default', 'Base64') +pprint(RESPONSE) # Get Keys in PKCS12 format print('\nGet Keys in PKCS12 format') -response = oneview_client.certificate_rabbitmq.get_keys('default', 'PKCS12') -pprint(response) +RESPONSE = ONEVIEW_CLIENT.certificate_rabbitmq.get_keys('default', 'PKCS12') +pprint(RESPONSE) diff --git a/examples/certificates_server.py b/examples/certificates_server.py index 252e8aeaf..61f253ed2 100644 --- a/examples/certificates_server.py +++ b/examples/certificates_server.py @@ -20,7 +20,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,66 +28,68 @@ } } -remote_server_options = { +REMOTE_SERVER_OPTIONS = { "name": "172.18.13.11", } -options = { - "certificateDetails": [ - { - "aliasName": "vcenter", - "base64Data": "", - "type": "CertificateDetailV2" - } - ], +OPTIONS = { + "certificateDetails": [{ + "aliasName": "vcenter", + "base64Data": "", + "type": "CertificateDetailV2" + }], } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -certificate_server = oneview_client.certificates_server +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +CERTIFICATE_SERVER = ONEVIEW_CLIENT.certificates_server # Fetch server certificate of remote server print("\nGet server certificate of remote server by ip address") -remote_server_cert = certificate_server.get_remote(remote_server_options['name']) -if remote_server_cert: - ca_certificate = remote_server_cert.data['certificateDetails'][0]['base64Data'] - print(ca_certificate) +REMOTE_SERVER_CERT = CERTIFICATE_SERVER.get_remote(REMOTE_SERVER_OPTIONS['name']) +if REMOTE_SERVER_CERT: + CA_CERTIFICATE = REMOTE_SERVER_CERT.data['certificateDetails'][0]['base64Data'] + print(CA_CERTIFICATE) # Fetch certificate by alias name print("\nGet server certificate by alias name") -server_certificate = certificate_server.get_by_alias_name("vcenter") -if server_certificate: - print("\nFound server certificate by aliasName: {}.\n uri = {}".format( - server_certificate.data['certificateDetails'][0]['aliasName'], server_certificate.data['uri'])) +SERVER_CERTIFICATE = CERTIFICATE_SERVER.get_by_alias_name("vcenter") +if SERVER_CERTIFICATE: + print("\nFound server certificate by aliasName: {}.\n uri = {}".format(\ + SERVER_CERTIFICATE.data['certificateDetails'][0]['aliasName'], \ + SERVER_CERTIFICATE.data['uri'])) else: - # Add a server certificate with the options provided - options['certificateDetails'][0]['base64Data'] = ca_certificate - options['certificateDetails'][0]['type'] = remote_server_cert.data['certificateDetails'][0]['type'] - server_certificate = certificate_server.create(data=options) - print("\nAdded a server certificate with aliasName: {}.\n uri = {}".format( - server_certificate.data['certificateDetails'][0]['aliasName'], server_certificate.data['uri'])) + # Add a server certificate with the OPTIONS provided + OPTIONS['certificateDetails'][0]['base64Data'] = CA_CERTIFICATE + OPTIONS['certificateDetails'][0]['type'] = REMOTE_SERVER_CERT.\ + data['certificateDetails'][0]['type'] + SERVER_CERTIFICATE = CERTIFICATE_SERVER.create(data=OPTIONS) + print("\nAdded a server certificate with aliasName: {}.\n uri = {}".format(\ + SERVER_CERTIFICATE.data['certificateDetails'][0]['aliasName'],\ + SERVER_CERTIFICATE.data['uri'])) # Get by uri print("\nGet a server certificate by uri") -server_cert_by_uri = certificate_server.get_by_uri(server_certificate.data['uri']) -pprint(server_cert_by_uri.data) +SERVER_CERT_BY_URI = CERTIFICATE_SERVER.get_by_uri(SERVER_CERTIFICATE.data['uri']) +pprint(SERVER_CERT_BY_URI.data) # Update alias name of recently added certificate print("\nUpdate recently created server certificate") -data_to_update = {'name': 'Updated vcenter'} -server_certificate.update(data=data_to_update) -print("\nUpdated server certificate {} successfully.\n".format( - server_certificate.data['certificateDetails'][0]['aliasName'])) +DATA_TO_UPDATE = {'name': 'Updated vcenter'} +SERVER_CERTIFICATE.update(data=DATA_TO_UPDATE) +print("\nUpdated server certificate {} successfully.\n".format(\ + SERVER_CERTIFICATE.data['certificateDetails'][0]['aliasName'])) # Delete the added server certificate -server_certificate.delete() +SERVER_CERTIFICATE.delete() print("\nSuccessfully deleted server certificate") # Create server certificate for automation -options['certificateDetails'][0]['base64Data'] = ca_certificate -options['certificateDetails'][0]['type'] = remote_server_cert.data['certificateDetails'][0]['type'] -server_certificate = certificate_server.create(data=options) -print("\nAdded a server certificate with aliasName: {}.\n uri = {}".format( - server_certificate.data['certificateDetails'][0]['aliasName'], server_certificate.data['uri'])) +OPTIONS['certificateDetails'][0]['base64Data'] = CA_CERTIFICATE +OPTIONS['certificateDetails'][0]['type'] = REMOTE_SERVER_CERT.data['certificateDetails'][0]['type'] +SERVER_CERTIFICATE = CERTIFICATE_SERVER.create(data=OPTIONS) +print("\nAdded a server certificate with aliasName: {}.\n uri = {}".format(\ + SERVER_CERTIFICATE.data['certificateDetails'][0]['aliasName'],\ + SERVER_CERTIFICATE.data['uri'])) diff --git a/examples/config_loader.py b/examples/config_loader.py index a7610ecf5..3959f35e4 100644 --- a/examples/config_loader.py +++ b/examples/config_loader.py @@ -14,17 +14,19 @@ # See the License for the specific language governing permissions and # limitations under the License. ### + from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals +import json +import os + from future import standard_library standard_library.install_aliases() -import json -import os CUR_MODULE_DIR = os.path.dirname(__file__) DEFAULT_EXAMPLE_CONFIG_FILE = os.path.join(CUR_MODULE_DIR, 'config.json') diff --git a/examples/connection_templates.py b/examples/connection_templates.py index 76193c491..dd6c44447 100644 --- a/examples/connection_templates.py +++ b/examples/connection_templates.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,39 +28,39 @@ "api_version": 800 } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -connection_templates = oneview_client.connection_templates +ONEVIEW_CLIENT = OneViewClient(CONFIG) +CONNECTION_TEMPLATES = ONEVIEW_CLIENT.connection_templates # The name and ID of an existent Connection Template must be set to run this example -connection_template_name = 'defaultConnectionTemplate' +CONNECTION_TEMPLATE_NAME = 'defaultConnectionTemplate' # Get all connection templates print("Get all connection templates") -con_templates = connection_templates.get_all() -pprint(con_templates) +CON_TEMPLATES = CONNECTION_TEMPLATES.get_all() +pprint(CON_TEMPLATES) # Get all sorting by name descending print("Get all connection templates sorting by name") -con_templates_sorted = connection_templates.get_all(sort='name:descending') -pprint(con_templates_sorted) +CON_TEMPLATES_SORTED = CONNECTION_TEMPLATES.get_all(sort='name:descending') +pprint(CON_TEMPLATES_SORTED) # Get default template print("Get default connection template") -con_template_default = connection_templates.get_default() -pprint(con_template_default) +CON_TEMPLATE_DEFAULT = CONNECTION_TEMPLATES.get_default() +pprint(CON_TEMPLATE_DEFAULT) # Get by name print("Get a connection_template by name") -con_template_byname = connection_templates.get_by_name(connection_template_name) -pprint(con_template_byname.data) +CON_TEMPLATE_BYNAME = CONNECTION_TEMPLATES.get_by_name(CONNECTION_TEMPLATE_NAME) +pprint(CON_TEMPLATE_BYNAME.data) # Update the connection_template retrieved in the last operation print("Update the retrieved connection_template typicalBandwidth") -if con_template_byname: - template_byname = con_template_byname.data.copy() - template_byname['bandwidth']['typicalBandwidth'] = 5000 - con_template_updated = con_template_byname.update(template_byname) - pprint(con_template_updated.data) +if CON_TEMPLATE_BYNAME: + TEMPLATE_BYNAME = CON_TEMPLATE_BYNAME.data.copy() + TEMPLATE_BYNAME['bandwidth']['typicalBandwidth'] = 5000 + CON_TEMPLATE_UPDATED = CON_TEMPLATE_BYNAME.update(TEMPLATE_BYNAME) + pprint(CON_TEMPLATE_UPDATED.data) diff --git a/examples/connections.py b/examples/connections.py index 6e5f64acd..c806e1c46 100644 --- a/examples/connections.py +++ b/examples/connections.py @@ -22,7 +22,7 @@ # You can use username/password or sessionID for authentication. # Be sure to inform a valid and active sessionID. -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -32,45 +32,45 @@ } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) # Get all connections print("Get all connections") -cons = oneview_client.connections.get_all() -pprint(cons) +CONS = ONEVIEW_CLIENT.connections.get_all() +pprint(CONS) -# Get all connections with interconnectUri filter +# Get all connections with interconnectUri FILTER try: print("Get connections based on interconnect uri") - filter = "interconnectUri='/rest/interconnects/794079a2-7eb4-4992-8027-e9743a40f5b0'" - cons_interconnectUri = oneview_client.connections.get_all(filter=filter) - pprint(cons_interconnectUri) -except HPEOneViewException as e: - print(e.msg) + FILTER = "interconnectUri='/rest/interconnects/794079a2-7eb4-4992-8027-e9743a40f5b0'" + CONS = ONEVIEW_CLIENT.connections.get_all(FILTER=FILTER) + pprint(CONS) +except HPEOneViewException as err: + print(err.msg) # Get first 10 connections, sorted by name print("Get first 10 connections, sorting by name") -cons_sorted = oneview_client.connections.get_all(0, 10, sort='name:descending') -pprint(cons_sorted) +CONS_SORTED = ONEVIEW_CLIENT.connections.get_all(0, 10, sort='name:descending') +pprint(CONS_SORTED) # Find connection by name try: print("Get connection by name") - con_byName = oneview_client.connections.get_by( + CON_BYNAME = ONEVIEW_CLIENT.connections.get_by( 'name', "name981375475-1465399560370") - pprint(con_byName) -except HPEOneViewException as e: - print(e.msg) + pprint(CON_BYNAME) +except HPEOneViewException as err: + print(err.msg) # Get by Uri try: print("Get connection by uri") - con_byUri = oneview_client.connections.get( + CON_BYURI = ONEVIEW_CLIENT.connections.get( '/rest/connections/58ffb307-3087-4c9d-8574-44e8a79e0d6e') - pprint(con_byUri) -except HPEOneViewException as e: - print(e.msg) + pprint(CON_BYURI) +except HPEOneViewException as err: + print(err.msg) diff --git a/examples/datacenters.py b/examples/datacenters.py index fb9e236f8..ace8cf9e2 100644 --- a/examples/datacenters.py +++ b/examples/datacenters.py @@ -17,10 +17,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,43 +28,43 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -datacenter_information = { +DATACENTER_INFORMATION = { "name": "MyDatacenter", "width": 5000, "depth": 5000 } # Add a Datacenter -datacenter_added = oneview_client.datacenters.add(datacenter_information) -print("\nAdded Datacenter '{name}' successfully\n".format(**datacenter_added)) +DATACENTER_ADDED = oneview_client.DATACENTERs.add(DATACENTER_INFORMATION) +print("\nAdded Datacenter '{name}' successfully\n".format(**DATACENTER_ADDED)) # Retrieve Datacenter by URI -datacenter = oneview_client.datacenters.get(datacenter_added['uri']) -print("\nGet Datacenter by URI: retrieved '{name}' successfully\n".format(**datacenter)) +DATACENTER = oneview_client.DATACENTERs.get(DATACENTER_ADDED['uri']) +print("\nGet Datacenter by URI: retrieved '{name}' successfully\n".format(**DATACENTER)) # Update the Datacenter -datacenter['name'] = "New Datacenter Name" -datacenter = oneview_client.datacenters.update(datacenter) -print("\nDatacenter '{name}' updated successfully\n".format(**datacenter)) +DATACENTER['name'] = "New Datacenter Name" +DATACENTER = oneview_client.DATACENTERs.update(DATACENTER) +print("\nDatacenter '{name}' updated successfully\n".format(**DATACENTER)) # Get the Datacenter by name -datacenter_list = oneview_client.datacenters.get_by('name', "New Datacenter Name") -print("\nGet Datacenter device by name: '{name}'\n".format(**datacenter)) +DATACENTER_list = oneview_client.DATACENTERs.get_by('name', "New Datacenter Name") +print("\nGet Datacenter device by name: '{name}'\n".format(**DATACENTER)) # Get the Datacenter visual content print("Getting the Datacenter visual content...") -datacenter_visual_content = oneview_client.datacenters.get_visual_content(datacenter['uri']) -pprint(datacenter_visual_content) +DATACENTER_visual_content = oneview_client.DATACENTERs.get_visual_content(DATACENTER['uri']) +pprint(DATACENTER_visual_content) # Remove added Datacenter -oneview_client.datacenters.remove(datacenter) -print("\nSuccessfully removed the datacenter") +oneview_client.DATACENTERs.remove(DATACENTER) +print("\nSuccessfully removed the DATACENTER") -# Add a datacenter again and call Remove All -datacenter_added = oneview_client.datacenters.add(datacenter_information) -oneview_client.datacenters.remove_all(filter="name matches '%'") -print("\nSuccessfully removed all datacenters") +# Add a DATACENTER again and call Remove All +DATACENTER_ADDED = oneview_client.DATACENTERs.add(DATACENTER_INFORMATION) +oneview_client.DATACENTERs.remove_all(filter="name matches '%'") +print("\nSuccessfully removed all DATACENTERs") diff --git a/examples/drive_enclosures.py b/examples/drive_enclosures.py index 155320a88..2ab1c26ee 100644 --- a/examples/drive_enclosures.py +++ b/examples/drive_enclosures.py @@ -21,7 +21,7 @@ # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,43 +29,45 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) print("Get all drive enclosures") -drive_enclosures = oneview_client.drive_enclosures.get_all() -pprint(drive_enclosures) +DRIVE_ENCLOSURES = ONEVIEW_CLIENT.drive_enclosures.get_all() +pprint(DRIVE_ENCLOSURES) -if drive_enclosures: +if DRIVE_ENCLOSURES: - first_drive_enclosure = drive_enclosures[0] - drive_enclosure_uri = first_drive_enclosure["uri"] + FIRST_DRIVE_ENCLOSURE = DRIVE_ENCLOSURES[0] + DRIVE_ENCLOSURE_URI = FIRST_DRIVE_ENCLOSURE["uri"] print("\nGet the drive enclosure by URI") - drive_enclosure_by_uri = oneview_client.drive_enclosures.get(drive_enclosure_uri) - pprint(drive_enclosure_by_uri) + DRIVE_ENCLOSURE_BY_URI = ONEVIEW_CLIENT.drive_enclosures.get(DRIVE_ENCLOSURE_URI) + pprint(DRIVE_ENCLOSURE_BY_URI) - product_name = first_drive_enclosure['productName'] + PRODUCT_NAME = FIRST_DRIVE_ENCLOSURE['productName'] print("\nGet the drive enclosure by product name") - drive_enclosure_by_product_name = oneview_client.drive_enclosures.get_by('productName', product_name) - pprint(drive_enclosure_by_product_name) + DRIVE_ENCLOSURE_BY_PRODUCT_NAME = ONEVIEW_CLIENT.drive_enclosures.get_by('productName',\ + PRODUCT_NAME) + pprint(DRIVE_ENCLOSURE_BY_PRODUCT_NAME) print("\nGet the drive enclosure port map") - port_map = oneview_client.drive_enclosures.get_port_map(drive_enclosure_uri) - pprint(port_map) + PORT_MAP = ONEVIEW_CLIENT.drive_enclosures.get_port_map(DRIVE_ENCLOSURE_URI) + pprint(PORT_MAP) print("\nRefresh the drive enclosure") - refresh_config = dict(refreshState="RefreshPending") - refreshed_drive_enclosure = oneview_client.drive_enclosures.refresh_state(drive_enclosure_uri, refresh_config) - pprint(refreshed_drive_enclosure) + REFRESH_CONFIG = dict(refreshState="RefreshPending") + REFRESHED_DRIVE_ENCLOSURE = ONEVIEW_CLIENT.drive_enclosures.refresh_state(DRIVE_ENCLOSURE_URI,\ + REFRESH_CONFIG) + pprint(REFRESHED_DRIVE_ENCLOSURE) print("\nPower off a drive enclosure") - drive_enclosure_powered_off = oneview_client.drive_enclosures.patch( - id_or_uri=drive_enclosure_uri, + DRIVE_ENCLOSURE_POWERED_OFF = ONEVIEW_CLIENT.drive_enclosures.patch( + id_or_uri=DRIVE_ENCLOSURE_URI, operation="replace", path="/powerState", value="Off" ) - pprint(drive_enclosure_powered_off) + pprint(DRIVE_ENCLOSURE_POWERED_OFF) diff --git a/examples/enclosure_groups.py b/examples/enclosure_groups.py index b32ca7fa1..3ea2c54d4 100755 --- a/examples/enclosure_groups.py +++ b/examples/enclosure_groups.py @@ -21,7 +21,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,27 +29,27 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -api_variant = 'Synergy' -oneview_client = OneViewClient(config) -enclosure_groups = oneview_client.enclosure_groups -scopes = oneview_client.scopes -logical_interconnect_groups = oneview_client.logical_interconnect_groups +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +API_VARIANT = 'Synergy' +ONEVIEW_CLIENT = OneViewClient(CONFIG) +ENCLOSURE_GROUPS = ONEVIEW_CLIENT.enclosure_groups +SCOPES = ONEVIEW_CLIENT.scopes +LOGICAL_INTERCONNECT_GROUPS = ONEVIEW_CLIENT.logical_interconnect_groups -lig_name = 'LIG' -lig_uri = logical_interconnect_groups.get_by_name(lig_name).data['uri'] +LIG_NAME = 'LIG' +LIG_URI = LOGICAL_INTERCONNECT_GROUPS.get_by_name(LIG_NAME).data['uri'] -eg_options = { +EG_OPTIONS = { "name": "EG", "interconnectBayMappings": [ { "interconnectBay": 3, - "logicalInterconnectGroupUri": lig_uri + "logicalInterconnectGroupUri": LIG_URI }, { "interconnectBay": 6, - "logicalInterconnectGroupUri": lig_uri + "logicalInterconnectGroupUri": LIG_URI } ], "ipAddressingMode": "External", @@ -68,80 +68,84 @@ # Get the first 10 records, sorting by name descending print("Get the ten first Enclosure Groups, sorting by name descending") -egs = enclosure_groups.get_all(0, 10, sort='name:descending') -pprint(egs) +EGS = ENCLOSURE_GROUPS.get_all(0, 10, sort='name:descending') +pprint(EGS) -print("\n## Create the scope") -scope_options = { +print("\n## Create the SCOPE") +SCOPE_OPTIONS = { "name": "SampleScopeForTest", - "description": "Sample Scope description" + "deSCRIPTion": "Sample Scope deSCRIPTion" } -scope = scopes.get_by_name(scope_options['name']) -if not scope: - scope = scopes.create(scope_options) - -# Get Enclosure Group by scope_uris -if oneview_client.api_version >= 600: - eg_by_scope_uris = enclosure_groups.get_all(scope_uris=scope.data['uri']) - if len(eg_by_scope_uris) > 0: - print("Found Enclosure Group by scope_uris: '%s'.\n uri = '%s'" % (eg_by_scope_uris[0]['name'], eg_by_scope_uris[0]['uri'])) - pprint(eg_by_scope_uris) +SCOPE = SCOPES.get_by_name(SCOPE_OPTIONS['name']) +if not SCOPE: + SCOPE = SCOPES.create(SCOPE_OPTIONS) + +# Get Enclosure Group by SCOPE_uris +if ONEVIEW_CLIENT.api_version >= 600: + EG_BY_SCOPE_URIS = ENCLOSURE_GROUPS.get_all(SCOPE_uris=SCOPE.data['uri']) + if len(EG_BY_SCOPE_URIS) > 0: + print("Found Enclosure Group by SCOPE_uris: '%s'.\n uri = '%s'" %\ + (EG_BY_SCOPE_URIS[0]['name'], EG_BY_SCOPE_URIS[0]['uri'])) + pprint(EG_BY_SCOPE_URIS) else: print("No Enclosure Group found.") # Get by name -enclosure_group = enclosure_groups.get_by_name(eg_options["name"]) -if not enclosure_group: +ENCLOSURE_GROUP = ENCLOSURE_GROUPS.get_by_name(EG_OPTIONS["name"]) +if not ENCLOSURE_GROUP: # Create a Enclosure Group print("Create a Enclosure Group") - if oneview_client.api_version <= 500: - options = {"stackingMode": "Enclosure"} - options.update(eg_options) - enclosure_group = enclosure_groups.create(options) + if ONEVIEW_CLIENT.api_version <= 500: + OPTIONS = {"stackingMode": "Enclosure"} + OPTIONS.update(EG_OPTIONS) + ENCLOSURE_GROUP = ENCLOSURE_GROUPS.create(OPTIONS) else: - enclosure_group = enclosure_groups.create(eg_options) -print("Created enclosure group of name - '{}' with uri - '{}'".format(enclosure_group.data['name'], enclosure_group.data['uri'])) + ENCLOSURE_GROUP = ENCLOSURE_GROUPS.create(EG_OPTIONS) +print("Created enclosure group of name - '{}' with uri - '{}'".format\ + (ENCLOSURE_GROUP.data['name'], ENCLOSURE_GROUP.data['uri'])) # Get all, with default print("Get all Enclosure Groups") -egs = enclosure_groups.get_all() -pprint(egs) +EGS = ENCLOSURE_GROUPS.get_all() +pprint(EGS) # Get by uri print("Get an Enclosure Group by uri") -eg_byuri = enclosure_groups.get_by_uri(egs[0]["uri"]) -pprint(eg_byuri.data) +EG_BYURI = ENCLOSURE_GROUPS.get_by_uri(EGS[0]["uri"]) +pprint(EG_BYURI.data) # Update an Enclosure Group -resource = {"name": "Renamed EG"} +RESOURCE = {"name": "Renamed EG"} print("Renaming the enclosure Group") -enclosure_group.update(resource) -pprint(enclosure_group.data) +ENCLOSURE_GROUP.update(RESOURCE) +pprint(ENCLOSURE_GROUP.data) # Update an Enclosure Group Script -if api_variant == 'C7000': - # update_script is available for API version 300 in Synergy and in all versions in C7000 +if API_VARIANT == 'C7000': + # update_SCRIPT is available for API version 300 in Synergy and in all versions in C7000 print("Update an Enclosure Group Script") - script = "#TEST COMMAND" - update_script_result = enclosure_group.update_script(script) - pprint(update_script_result) + SCRIPT = "#TEST COMMAND" + UPDATE_SCRIPT_RESULT = ENCLOSURE_GROUP.update_SCRIPT(SCRIPT) + pprint(UPDATE_SCRIPT_RESULT) - # Gets the configuration script of a Enclosure Group - # get_script is available for API version 300 in Synergy and in all versions in C7000 - print("Gets the configuration script of an Enclosure Group") - script = enclosure_group.get_script() - print(script) + # Gets the CONFIGuration SCRIPT of a Enclosure Group + # get_SCRIPT is available for API version 300 in Synergy and in all versions in C7000 + print("Gets the CONFIGuration SCRIPT of an Enclosure Group") + SCRIPT = ENCLOSURE_GROUP.get_SCRIPT() + print(SCRIPT) # Delete an Enclosure Group print("Delete the created Enclosure Group") -enclosure_group.delete() +ENCLOSURE_GROUP.delete() print("Successfully deleted Enclosure Group") -scope.delete() +SCOPE.delete() # Create EG & EG-2 for automation -enclosure_group = enclosure_groups.create(eg_options) -print("Created enclosure group of name - '{}' with uri - '{}'".format(enclosure_group.data['name'], enclosure_group.data['uri'])) - -eg_options['name'] = "EG-2" -enclosure_group = enclosure_groups.create(eg_options) -print("Created enclosure group of name - '{}' with uri - '{}'".format(enclosure_group.data['name'], enclosure_group.data['uri'])) +ENCLOSURE_GROUP = ENCLOSURE_GROUPS.create(EG_OPTIONS) +print("Created enclosure group of name - '{}' with uri - '{}'".format(ENCLOSURE_GROUP.data['name'],\ + ENCLOSURE_GROUP.data['uri'])) + +EG_OPTIONS['name'] = "EG-2" +ENCLOSURE_GROUP = ENCLOSURE_GROUPS.create(EG_OPTIONS) +print("Created enclosure group of name - '{}' with uri - '{}'".format(ENCLOSURE_GROUP.data['name'],\ + ENCLOSURE_GROUP.data['uri'])) diff --git a/examples/enclosures.py b/examples/enclosures.py index f40c18e0f..e1993ca65 100644 --- a/examples/enclosures.py +++ b/examples/enclosures.py @@ -21,141 +21,142 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -# This example is compatible only for C7000 enclosures -config = { +# This example is compatible only for C7000 ENCLOSURES +CONFIG = { "ip": "", "credentials": { "userName": "", "password": "" }, "api_version": "", - "enclosure_group_uri": "/rest/enclosure-groups/06475bf3-084b-4874", - "enclosure_hostname": "", - "enclosure_username": "", - "enclosure_password": "", + "ENCLOSURE_group_URI": "/rest/ENCLOSURE-groups/06475bf3-084b-4874", + "ENCLOSURE_hostname": "", + "ENCLOSURE_username": "", + "ENCLOSURE_password": "", } -enclosure_name = "0000A66101" +ENCLOSURE_NAME = "0000A66101" # Specify variant of your appliance before running this example -api_variant = "Synergy" +API_VARIANT = "Synergy" -# Declare a CA signed certificate file path. -certificate_file = "" +# Declare a CA signed CERTIFICATE file path. +CERTIFICATE_FILE = "" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -# The hostname, enclosure group URI, username, and password must be set on the configuration file -options = { - "enclosureGroupUri": config['enclosure_group_uri'], - "hostname": config['enclosure_hostname'], - "username": config['enclosure_username'], - "password": config['enclosure_password'], +# The hostname, ENCLOSURE group URI, username, and password must be set on the CONFIGURATION file +OPTIONS = { + "ENCLOSUREGroupUri": CONFIG['ENCLOSURE_group_URI'], + "hostname": CONFIG['ENCLOSURE_hostname'], + "username": CONFIG['ENCLOSURE_username'], + "password": CONFIG['ENCLOSURE_password'], "licensingIntent": "OneView" } # Get Enclosure resource object -oneview_client = OneViewClient(config) -enclosure_resource = oneview_client.enclosures -scopes = oneview_client.scopes - -# Get all enclosures -print("Get all enclosures") -enclosures = enclosure_resource.get_all() -for enc in enclosures: +oneview_client = OneViewClient(CONFIG) +ENCLOSURE_RESOURCE = oneview_client.enclosures +SCOPES = oneview_client.scopes + +# Get all ENCLOSURES +print("Get all ENCLOSURES") +ENCLOSURES = ENCLOSURE_RESOURCE.get_all() +for enc in ENCLOSURES: print(' {name}'.format(**enc)) -enclosure = enclosure_resource.get_by_name(enclosure_name) -if not enclosure: - # Creates an enclosure and returns created enclosure object - enclosure = enclosure_resource.add(options) -print("Enclosure '{name}'.\n URI = '{uri}'".format(**enclosure.data)) +ENCLOSURE = ENCLOSURE_RESOURCE.get_by_name(ENCLOSURE_NAME) +if not ENCLOSURE: + # Creates an ENCLOSURE and returns created ENCLOSURE object + ENCLOSURE = ENCLOSURE_RESOURCE.add(OPTIONS) +print("Enclosure '{name}'.\n URI = '{URI}'".format(**ENCLOSURE.data)) # Get by URI. -print("Find an enclosure by URI") -uri = enclosure.data['uri'] -enclosure = enclosure_resource.get_by_uri(uri) -pprint(enclosure.data) - -# Update name of the newly added enclosure -update_name = enclosure_name + "-Updated" -print("Updating the enclosure with name " + update_name) -headers = {'If-Match': '*'} -enclosure.patch('replace', '/name', update_name, custom_headers=headers) -print(" Done.\n URI = '{uri}', name = {name}".format(**enclosure.data)) - -# Revert the name of the enclosure -print("Reverting the enclosure name " + enclosure_name) -headers = {'If-Match': '*'} -enclosure.patch('replace', '/name', enclosure_name, custom_headers=headers) -print(" Done.\n URI = '{uri}', name = {name}".format(**enclosure.data)) - -# Update configuration -print("Reapplying the appliance's configuration on the enclosure") +print("Find an ENCLOSURE by URI") +URI = ENCLOSURE.data['URI'] +ENCLOSURE = ENCLOSURE_RESOURCE.get_by_uri(URI) +pprint(ENCLOSURE.data) + +# Update name of the newly added ENCLOSURE +UPDATE_NAME = ENCLOSURE_NAME + "-Updated" +print("Updating the ENCLOSURE with name " + UPDATE_NAME) +HEADERS = {'If-Match': '*'} +ENCLOSURE.patch('replace', '/name', UPDATE_NAME, custom_HEADERS=HEADERS) +print(" Done.\n URI = '{URI}', name = {name}".format(**ENCLOSURE.data)) + +# Revert the name of the ENCLOSURE +print("Reverting the ENCLOSURE name " + ENCLOSURE_NAME) +HEADERS = {'If-Match': '*'} +ENCLOSURE.patch('replace', '/name', ENCLOSURE_NAME, custom_HEADERS=HEADERS) +print(" Done.\n URI = '{URI}', name = {name}".format(**ENCLOSURE.data)) + +# Update CONFIGURATION +print("Reapplying the appliance's CONFIGURATION on the ENCLOSURE") try: - enclosure.update_configuration() + ENCLOSURE.update_CONFIGURATION() print(" Done.") -except HPEOneViewException as e: - print(e.msg) +except HPEOneViewException as err: + print(err.msg) -print("Retrieve the environmental configuration data for the enclosure") +print("Retrieve the environmental CONFIGURATION data for the ENCLOSURE") try: - environmental_configuration = enclosure.get_environmental_configuration() - print(" Enclosure calibratedMaxPower = {calibratedMaxPower}".format(**environmental_configuration)) -except HPEOneViewException as e: - print(e.msg) + ENVIRONMENTAL_CONFIGURATION = ENCLOSURE.get_ENVIRONMENTAL_CONFIGURATION() + print(" Enclosure calibratedMaxPower = {calibratedMaxPower}".\ + format(**ENVIRONMENTAL_CONFIGURATION)) +except HPEOneViewException as err: + print(err.msg) -# Set the calibrated max power of an unmanaged or unsupported enclosure -# update_environmental_configuration is available only in C7000 -if api_variant == 'C7000': - print("Set the calibrated max power of an unmanaged or unsupported enclosure") +# Set the calibrated max power of an unmanaged or unsupported ENCLOSURE +# update_ENVIRONMENTAL_CONFIGURATION is available only in C7000 +if API_VARIANT == 'C7000': + print("Set the calibrated max power of an unmanaged or unsupported ENCLOSURE") try: - configuration = { + CONFIGURATION = { "calibratedMaxPower": 2500 } - enclosure_updated_encConf = enclosure.update_environmental_configuration(configuration) + ENCLOSURE_UPDATED_ENCCONF = ENCLOSURE.update_ENVIRONMENTAL_CONFIGURATION(CONFIGURATION) print(" Done.") - except HPEOneViewException as e: - print(e.msg) + except HPEOneViewException as err: + print(err.msg) -# Refresh the enclosure -print("Refreshing the enclosure") +# Refresh the ENCLOSURE +print("Refreshing the ENCLOSURE") try: - refresh_state = {"refreshState": "RefreshPending"} - enclosure.refresh_state(refresh_state) + REFRESH_STATE = {"refreshState": "RefreshPending"} + ENCLOSURE.REFRESH_STATE(REFRESH_STATE) print(" Done") -except HPEOneViewException as e: - print(e.msg) +except HPEOneViewException as err: + print(err.msg) # Buid the SSO URL parameters # get_sso is available only in C7000 -if api_variant == 'C7000': - print("Build the SSO (Single Sign-On) URL parameters for the enclosure") +if API_VARIANT == 'C7000': + print("Build the SSO (Single Sign-On) URL parameters for the ENCLOSURE") try: - sso_url_parameters = enclosure.get_sso('Active') - pprint(sso_url_parameters) - except HPEOneViewException as e: - print(e.msg) + SSO_URL_PARAMETERS = ENCLOSURE.get_sso('Active') + pprint(SSO_URL_PARAMETERS) + except HPEOneViewException as err: + print(err.msg) # Get Statistics specifying parameters -print("Get the enclosure statistics") +print("Get the ENCLOSURE statistics") try: - enclosure_statistics = enclosure.get_utilization(fields='AveragePower', + ENCLOSURE_STATISTICS = ENCLOSURE.get_utilization(fields='AveragePower', filter='startDate=2016-06-30T03:29:42.000Z', view='day') - pprint(enclosure_statistics) -except HPEOneViewException as e: - print(e.msg) + pprint(ENCLOSURE_STATISTICS) +except HPEOneViewException as err: + print(err.msg) -# Create a Certificate Signing Request (CSR) for the enclosure. -if api_variant == 'C7000': - bay_number = 1 # Required for C7000 enclosure +# Create a Certificate Signing Request (CSR) for the ENCLOSURE. +if API_VARIANT == 'C7000': + BAY_NUMBER = 1 # Required for C7000 ENCLOSURE else: - bay_number = None + BAY_NUMBER = None -csr_data = { +CSR_DATA = { "type": "CertificateDtoV2", "organization": "organization", "organizationalUnit": "organization unit", @@ -165,66 +166,67 @@ "commonName": "name" } try: - enclosure.generate_csr(csr_data, bay_number=bay_number) - print("Generated CSR for the enclosure.") -except HPEOneViewException as e: - print(e.msg) + ENCLOSURE.generate_CSR(CSR_DATA, BAY_NUMBER=BAY_NUMBER) + print("Generated CSR for the ENCLOSURE.") +except HPEOneViewException as err: + print(err.msg) -# Get the certificate Signing Request (CSR) that was generated by previous POST. +# Get the CERTIFICATE Signing Request (CSR) that was generated by previous POST. try: - csr = enclosure.get_csr(bay_number=bay_number) - with open('enclosure.csr', 'w') as csr_file: - csr_file.write(csr["base64Data"]) - print("Saved CSR(generated by previous POST) to 'enclosure.csr' file") -except HPEOneViewException as e: - print(e.msg) - -# Import CA signed certificate to the enclosure. + CSR = ENCLOSURE.get_CSR(BAY_NUMBER=BAY_NUMBER) + with open('ENCLOSURE.CSR', 'w') as CSR_file: + CSR_file.write(CSR["base64Data"]) + print("Saved CSR(generated by previous POST) to 'ENCLOSURE.CSR' file") +except HPEOneViewException as err: + print(err.msg) + +# Import CA signed CERTIFICATE to the ENCLOSURE. try: # Certificate has to be signed by CA before running the task. - certificate_file = "enclosure.csr" - certificate = open(certificate_file).read() + CERTIFICATE_FILE = "ENCLOSURE.CSR" + CERTIFICATE = open(CERTIFICATE_FILE).read() - certificate_data = { + CERTIFICATE_DATA = { "type": "CertificateDataV2", - "base64Data": certificate + "base64Data": CERTIFICATE } - enclosure.import_certificate(certificate_data, bay_number=bay_number) - print("Imported Signed Certificate to the enclosure.") -except HPEOneViewException as e: - print(e.msg) -except Exception as e: - print(e) + ENCLOSURE.import_CERTIFICATE(CERTIFICATE_DATA, BAY_NUMBER=BAY_NUMBER) + print("Imported Signed Certificate to the ENCLOSURE.") +except HPEOneViewException as err: + print(err.msg) +except Exception as err: + print(err) -print("\n## Create the scope") -options = { +print("\n## Create the SCOPE") +OPTIONS = { "name": "SampleScopeForTest", "description": "Sample Scope description" } -scope = scopes.create(options) +SCOPE = SCOPES.create(OPTIONS) -# Get Enclosure by scope_uris +# Get Enclosure by SCOPE_URIs if oneview_client.api_version >= 600: try: - enclosures_by_scope_uris = enclosure.get_all(scope_uris=scope.data['uri']) - if len(enclosures_by_scope_uris) > 0: - print("Found %d Enclosures" % (len(enclosures_by_scope_uris))) + ENCLOSURES_BY_SCOPE_URIS = ENCLOSURE.get_all(SCOPE_URIs=SCOPE.data['URI']) + if len(ENCLOSURES_BY_SCOPE_URIS) > 0: + print("Found %d Enclosures" % (len(ENCLOSURES_BY_SCOPE_URIS))) i = 0 - while i < len(enclosures_by_scope_uris): - print("Found Enclosures by scope_uris: '%s'.\n uri = '%s'" % (enclosures_by_scope_uris[i]['name'], enclosures_by_scope_uris[i]['uri'])) + while i < len(ENCLOSURES_BY_SCOPE_URIS): + print("Found Enclosures by SCOPE_URIs: '%s'.\n URI = '%s'" %\ + (ENCLOSURES_BY_SCOPE_URIS[i]['name'], ENCLOSURES_BY_SCOPE_URIS[i]['URI'])) i += 1 - pprint(enclosures_by_scope_uris) + pprint(ENCLOSURES_BY_SCOPE_URIS) else: - print("No Enclosures found with scope.") - except HPEOneViewException as e: - print(e.msg) + print("No Enclosures found with SCOPE.") + except HPEOneViewException as err: + print(err.msg) -# Delete the scope -scope.delete() +# Delete the SCOPE +SCOPE.delete() print("\n## Scope deleted successfully.") -if api_variant == 'C7000': - # Remove the recently added enclosure - enclosure.remove() +if API_VARIANT == 'C7000': + # Remove the recently added ENCLOSURE + ENCLOSURE.remove() print("Enclosure removed successfully") diff --git a/examples/endpoints.py b/examples/endpoints.py index ffab5c1bc..5d4a15c20 100644 --- a/examples/endpoints.py +++ b/examples/endpoints.py @@ -20,7 +20,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,20 +29,20 @@ } # To run this example, you must specify a WWN -wwn = None +WWN = None -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) # Get all endpoints print("Get all endpoints") -endpoints_all = oneview_client.endpoints.get_all() -pprint(endpoints_all) +ENDPOINTS_ALL = ONEVIEW_CLIENT.endpoints.get_all() +pprint(ENDPOINTS_ALL) # Get endpoints filtered to only the one with a specified WWN print("Get endpoints filtered to only the one with a specified WWN") -query = "wwn eq '{}'".format(wwn) -enpoints_with_query = oneview_client.endpoints.get_all(0, -1, query=query) -pprint(enpoints_with_query) +QUERY = "WWN eq '{}'".format(WWN) +ENPOINTS_WITH_QUERY = ONEVIEW_CLIENT.endpoints.get_all(0, -1, QUERY=QUERY) +pprint(ENPOINTS_WITH_QUERY) diff --git a/examples/ethernet_networks.py b/examples/ethernet_networks.py index 9a1e3df8d..65f181ae4 100755 --- a/examples/ethernet_networks.py +++ b/examples/ethernet_networks.py @@ -17,12 +17,13 @@ from pprint import pprint +from copy import deepcopy + from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -from copy import deepcopy -# To run this example fill the ip and the credentials below or use a configuration file -config = { +# To run this example fill the ip and the credentials below or use a CONFIGuration file +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -31,7 +32,7 @@ "api_version": "" } -options = { +OPTIONS = { "name": "OneViewSDK Test Ethernet Network", "vlanId": 200, "ethernetNetworkType": "Tagged", @@ -41,7 +42,7 @@ "connectionTemplateUri": None } -options_bulk = { +OPTIONS_BULK = { "vlanIdRange": "1-5,7", "purpose": "General", "namePrefix": "TestNetwork", @@ -55,137 +56,141 @@ # Scope name to perform the patch operation -scope_name = "" -ethernet_name = "OneViewSDK Test Ethernet Network" +SCOPE_NAME = "" +ETHERNET_NAME = "OneViewSDK Test Ethernet Network" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -ethernet_networks = oneview_client.ethernet_networks -scopes = oneview_client.scopes +ONEVIEW_CLIENT = OneViewClient(CONFIG) +ETHERNET_NETWORKS = ONEVIEW_CLIENT.ethernet_networks +SCOPES = ONEVIEW_CLIENT.scopes # Filter by name print("\nGet all ethernet-networks filtering by name") -ethernet_nets_filtered = ethernet_networks.get_all( +ETHERNET_NETS_FILTERED = ETHERNET_NETWORKS.get_all( filter="\"'name'='OneViewSDK Test Ethernet Network'\"") -for net in ethernet_nets_filtered: +for net in ETHERNET_NETS_FILTERED: print(" '{name}' at uri: '{uri}'".format(**net)) # Get all sorting by name descending print("\nGet all ethernet-networks sorting by name") -ethernet_nets_sorted = ethernet_networks.get_all(sort='name:descending') -for net in ethernet_nets_sorted: +ETHERNET_NETS_SORTED = ETHERNET_NETWORKS.get_all(sort='name:descending') +for net in ETHERNET_NETS_SORTED: print(" '{name}' at uri: '{uri}'".format(**net)) # Get the first 10 records print("\nGet the first ten ethernet-networks") -ethernet_nets_limited = ethernet_networks.get_all(0, 10) -for net in ethernet_nets_limited: +ETHERNET_NETS_LIMITED = ETHERNET_NETWORKS.get_all(0, 10) +for net in ETHERNET_NETS_LIMITED: print(" '{name}' at uri: '{uri}'".format(**net)) # Find network by name print("\nFind network by name") -ethernet_network = ethernet_networks.get_by_name(ethernet_name) -if ethernet_network: - print("Found ethernet-network by name: '{name}'.\n uri = '{uri}'" .format(**ethernet_network.data)) +ETHERNET_NETWORK = ETHERNET_NETWORKS.get_by_name(ETHERNET_NAME) +if ETHERNET_NETWORK: + print("Found ethernet-network by name: '{name}'.\n uri = '{uri}'"\ + .format(**ETHERNET_NETWORK.data)) else: # Create an ethernet Network print("\nCreate an ethernet network") - ethernet_network = ethernet_networks.create(options) - print("Created ethernet-network '{name}' successfully.\n uri = '{uri}'" .format(**ethernet_network.data)) + ETHERNET_NETWORK = ETHERNET_NETWORKS.create(OPTIONS) + print("Created ethernet-network '{name}' successfully.\n uri = '{uri}'"\ + .format(**ETHERNET_NETWORK.data)) # Create bulk ethernet networks -bulkNetworkUris = [] +BULKNETWORKURIS = [] print("\nCreate bulk ethernet networks") -ethernet_nets_bulk = ethernet_networks.create_bulk(options_bulk) -for eth in ethernet_nets_bulk: - bulkNetworkUris.append(eth['uri']) -pprint(ethernet_nets_bulk) +ETHERNET_NETS_BULK = ETHERNET_NETWORKS.create_bulk(OPTIONS_BULK) +for eth in ETHERNET_NETS_BULK: + BULKNETWORKURIS.append(eth['uri']) +pprint(ETHERNET_NETS_BULK) # Get all, with defaults print("\nGet all ethernet-networks") -ethernet_nets = ethernet_networks.get_all() -for net in ethernet_nets: +ETHERNET_NETS = ETHERNET_NETWORKS.get_all() +for net in ETHERNET_NETS: print(" '{name}' at uri: '{uri}'".format(**net)) # Get by Uri print("\nGet an ethernet-network by uri") -ethernet_network_uri = ethernet_nets[0]['uri'] -ethernet_nets_by_uri = ethernet_networks.get_by_uri(ethernet_network_uri) -pprint(ethernet_nets_by_uri.data) +ETHERNET_NETWORK_URI = ETHERNET_NETS[0]['uri'] +ETHERNET_NETS_BY_URI = ETHERNET_NETWORKS.get_by_uri(ETHERNET_NETWORK_URI) +pprint(ETHERNET_NETS_BY_URI.data) # Update purpose recently created network print("\nUpdate the purpose attribute from the recently created network") -ethernet_data_copy = deepcopy(ethernet_network.data) -ethernet_data_copy['purpose'] = 'Management' -ethernet_network_update = ethernet_network.update(ethernet_data_copy) -print("Updated ethernet-network '{name}' successfully.\n uri = '{uri}'\n with attribute ['purpose': {purpose}]" - .format(**ethernet_network_update.data)) +ETHERNET_DATA_COPY = deepcopy(ETHERNET_NETWORK.data) +ETHERNET_DATA_COPY['purpose'] = 'Management' +ETHERNET_NETWORK_UPDATE = ETHERNET_NETWORK.update(ETHERNET_DATA_COPY) +print("Updated ethernet-network '{name}' successfully.\n uri = '{uri}'\n with attribute\ + ['purpose': {purpose}]".format(**ETHERNET_NETWORK_UPDATE.data)) # Get URIs of associated profiles print("\nGet associated profiles uri(s)") -if ethernet_network: - associated_profiles = ethernet_network.get_associated_profiles() - pprint(associated_profiles) +if ETHERNET_NETWORK: + ASSOCIATED_PROFILES = ETHERNET_NETWORK.get_ASSOCIATED_PROFILES() + pprint(ASSOCIATED_PROFILES) # Get URIs of uplink port group print("\nGet uplink port group uri(s)") -if ethernet_network: - uplink_group_uris = ethernet_network.get_associated_uplink_groups() - pprint(uplink_group_uris) +if ETHERNET_NETWORK: + UPLINK_GROUP_URIS = ETHERNET_NETWORK.get_associated_uplink_groups() + pprint(UPLINK_GROUP_URIS) # Get the associated uplink set resources print("\nGet associated uplink sets") -uplink_sets = oneview_client.uplink_sets -for uri in uplink_group_uris: - uplink = uplink_sets.get_by_uri(uri) +UPLINK_SETS = ONEVIEW_CLIENT.uplink_sets +for uri in UPLINK_GROUP_URIS: + uplink = UPLINK_SETS.get_by_uri(uri) pprint(uplink.data) -# Adds Ethernet network to scope defined only for V300 and V500 -if scope_name and 300 <= oneview_client.api_version <= 500: - print("\nGet scope then add the network to it") - scope = scopes.get_by_name(scope_name) - ethernet_with_scope = ethernet_network.patch('replace', - '/scopeUris', - [scope.data['uri']]) - pprint(ethernet_with_scope) +# Adds Ethernet network to SCOPE defined only for V300 and V500 +if SCOPE_NAME and 300 <= ONEVIEW_CLIENT.api_version <= 500: + print("\nGet SCOPE then add the network to it") + SCOPE = SCOPES.get_by_name(SCOPE_NAME) + ETHERNET_WITH_SCOPE = ETHERNET_NETWORK.patch('replace', + '/SCOPEUris', + [SCOPE.data['uri']]) + pprint(ETHERNET_WITH_SCOPE) # Delete bulk ethernet networks -if oneview_client.api_version >= 1600: - options_bulk_delete = {"networkUris": bulkNetworkUris} - ethernet_network.delete_bulk(options_bulk_delete) +if ONEVIEW_CLIENT.api_version >= 1600: + OPTIONS_BULK_DELETE = {"networkUris": BULKNETWORKURIS} + ETHERNET_NETWORK.delete_bulk(OPTIONS_BULK_DELETE) print("Successfully deleted bulk ethernet networks") # Delete the created network print("\nDelete the ethernet network") -ethernet_network.delete() +ETHERNET_NETWORK.delete() print("Successfully deleted ethernet-network") # Create networks for automation 'mgmt_nw' and 'iscsi_nw' -mgmt_subnet = '10.1.0.0' -iscsi_subnet = '192.168.10.0' -all_subnets = oneview_client.id_pools_ipv4_subnets.get_all() - -for subnet in all_subnets: - if subnet['networkId'] == mgmt_subnet: - mgmt_subnet_uri = subnet['uri'] - if subnet['networkId'] == iscsi_subnet: - iscsi_subnet_uri = subnet['uri'] - -mgmt_network_body = options.copy() -mgmt_network_body['name'] = 'mgmt_nw' -mgmt_network_body['ethernetNetworkType'] = "Untagged" -mgmt_network_body['purpose'] = "Management" -mgmt_network_body['subnetUri'] = mgmt_subnet_uri -management_network = ethernet_networks.create(mgmt_network_body) -print("Created ethernet-network '{name}' successfully.\n uri = '{uri}'" .format(**management_network.data)) - -iscsi_network_body = options.copy() -iscsi_network_body['name'] = 'iscsi_nw' -iscsi_network_body['ethernetNetworkType'] = "Tagged" -iscsi_network_body['vlanId'] = 1209 -iscsi_network_body['purpose'] = "ISCSI" -iscsi_network_body['subnetUri'] = iscsi_subnet_uri -iscsi_network = ethernet_networks.create(iscsi_network_body) -print("Created ethernet-network '{name}' successfully.\n uri = '{uri}'" .format(**iscsi_network.data)) +MGMT_SUBNET = '10.1.0.0' +ISCSI_SUBNET = '192.168.10.0' +ALL_SUBNETS = ONEVIEW_CLIENT.id_pools_ipv4_subnets.get_all() + +for subnet in ALL_SUBNETS: + if subnet['networkId'] == MGMT_SUBNET: + MGMT_SUBNET_uri = subnet['uri'] + if subnet['networkId'] == ISCSI_SUBNET: + ISCSI_SUBNET_uri = subnet['uri'] + +MGMT_NETWORK_BODY = OPTIONS.copy() +MGMT_NETWORK_BODY['name'] = 'mgmt_nw' +MGMT_NETWORK_BODY['ethernetNetworkType'] = "Untagged" +MGMT_NETWORK_BODY['purpose'] = "Management" +MGMT_NETWORK_BODY['subnetUri'] = MGMT_SUBNET_uri +MANAGEMENT_NETWORK = ETHERNET_NETWORKS.create(MGMT_NETWORK_BODY) +print("Created ethernet-network '{name}' successfully.\n uri = '{uri}'"\ + .format(**MANAGEMENT_NETWORK.data)) + +ISCSI_NETWORK_BODY = OPTIONS.copy() +ISCSI_NETWORK_BODY['name'] = 'iscsi_nw' +ISCSI_NETWORK_BODY['ethernetNetworkType'] = "Tagged" +ISCSI_NETWORK_BODY['vlanId'] = 1209 +ISCSI_NETWORK_BODY['purpose'] = "ISCSI" +ISCSI_NETWORK_BODY['subnetUri'] = ISCSI_SUBNET_uri +ISCSI_NETWORK = ETHERNET_NETWORKS.create(ISCSI_NETWORK_BODY) +print("Created ethernet-network '{name}' successfully.\n uri = '{uri}'"\ + .format(**ISCSI_NETWORK.data)) diff --git a/examples/events.py b/examples/events.py index 44a17bac7..e60790dc8 100644 --- a/examples/events.py +++ b/examples/events.py @@ -18,7 +18,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "administrator", @@ -26,8 +26,8 @@ } } -options = { - "description": "This is a very simple test event", +OPTIONS = { + "description": "This is a very simple test EVENT", "serviceEventSource": "true", "serviceEventDetails": { "caseId": "1234", @@ -36,38 +36,38 @@ }, "severity": "OK", "healthCategory": "PROCESSOR", - "eventTypeID": "hp.justATest", + "EVENTTypeID": "hp.justATest", "rxTime": "2012-05-14T20:23:56.688Z", "urgency": "None", - "eventDetails": - [{"eventItemName": "ipv4Address", - "eventItemValue": "198.51.100.5", - "isThisVarbindData": "false", - "varBindOrderIndex": -1}] + "EVENTDetails": + [{"EVENTItemName": "ipv4Address", + "EVENTItemValue": "198.51.100.5", + "isThisVarbindData": "false", + "varBindOrderIndex": -1}] } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -_client = OneViewClient(config) +_CLIENT = OneViewClient(CONFIG) -# Getting the first 5 events -print("\nGetting the first 5 events:") -events = _client.events.get_all(0, 5) -for event in events: - print("eventTypeID: '%s' | description: %s " % (event['description'], event['eventTypeID'])) +# Getting the first 5 EVENTS +print("\nGetting the first 5 EVENTS:") +EVENTS = _CLIENT.events.get_all(0, 5) +for EVENT in EVENTS: + print("EVENTTypeID: '%s' | description: %s " % (EVENT['description'], EVENT['EVENTTypeID'])) # Create an Event -event = _client.events.create(options) -print("\nCreated event successfully.\n uri = '%s'" % (event['uri'])) +EVENT = _CLIENT.events.create(OPTIONS) +print("\nCreated EVENT successfully.\n uri = '%s'" % (EVENT['uri'])) # Get by Uri -print("\nFind uri == %s" % ('/rest/events/24')) -event_by_uri = _client.events.get('/rest/events/24') -print("uri: '%s' | eventTypeID: '%s' \n" % (event_by_uri['uri'], event_by_uri['eventTypeID'])) +print("\nFind uri == %s" % ('/rest/EVENTS/24')) +EVENT_BY_URI = _CLIENT.events.get('/rest/EVENTS/24') +print("uri: '%s' | EVENTTypeID: '%s' \n" % (EVENT_BY_URI['uri'], EVENT_BY_URI['EVENTTypeID'])) # Filter by state -print("\nGet all events filtering by eventTypeID") -events = _client.events.get_all(filter="\"eventTypeID='StatusPoll.EnclosureStatus'\"", count=10) -for event in events: - print("uri: '%s' | eventTypeID: '%s'" % (event['uri'], event['eventTypeID'])) +print("\nGet all EVENTS filtering by EVENTTypeID") +EVENTS = _CLIENT.events.get_all(filter="\"EVENTTypeID='StatusPoll.EnclosureStatus'\"", count=10) +for EVENT in EVENTS: + print("uri: '%s' | EVENTTypeID: '%s'" % (EVENT['uri'], EVENT['EVENTTypeID'])) diff --git a/examples/fabrics.py b/examples/fabrics.py index c0b318bd4..e823a5ec3 100644 --- a/examples/fabrics.py +++ b/examples/fabrics.py @@ -21,7 +21,7 @@ from hpeOneView.exceptions import HPEOneViewException from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -30,48 +30,49 @@ } # To run the get operations by ID, an ID must be defined bellow -fabric_id = 'a7896ce7-c11d-4658-829d-142bc66a85e4' +FABRIC_ID = 'a7896ce7-c11d-4658-829d-142bc66a85e4' -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) # Get all fabrics print("Get all fabrics") -fabrics = oneview_client.fabrics.get_all() -pprint(fabrics) +FABRICS = ONEVIEW_CLIENT.fabrics.get_all() +pprint(FABRICS) # Get all sorting by name descending print("\nGet all fabrics sorting by name") -fabrics_sorted = oneview_client.fabrics.get_all(sort='name:descending') -pprint(fabrics_sorted) +FABRICS_SORTED = ONEVIEW_CLIENT.fabrics.get_all(sort='name:descending') +pprint(FABRICS_SORTED) # Get by Id try: print("\nGet a fabric by id") - fabrics_byid = oneview_client.fabrics.get(fabric_id) - pprint(fabrics_byid) -except HPEOneViewException as e: - print(e.msg) + FABRICS_BYID = ONEVIEW_CLIENT.fabrics.get(FABRIC_ID) + pprint(FABRICS_BYID) +except HPEOneViewException as err: + print(err.msg) # Get by name print("\nGet a fabrics by name") -fabric_byname = oneview_client.fabrics.get_by('name', 'DefaultFabric')[0] -pprint(fabric_byname) +FABRIC_BYNAME = ONEVIEW_CLIENT.fabrics.get_by('name', 'DefaultFabric')[0] +pprint(FABRIC_BYNAME) # These methods are available for API version 300 or later -if oneview_client.api_version >= 300: +if ONEVIEW_CLIENT.api_version >= 300: # Get reserved vlan ID range for the fabric. - print("\nGet reserved vlan ID range for the fabric '%s'." % fabric_byname['name']) - vlan_pool = oneview_client.fabrics.get_reserved_vlan_range(fabric_byname['uri']) - pprint(vlan_pool) + print("\nGet reserved vlan ID range for the fabric '%s'." % FABRIC_BYNAME['name']) + VLAN_POOL = ONEVIEW_CLIENT.fabrics.get_reserved_vlan_range(FABRIC_BYNAME['uri']) + pprint(VLAN_POOL) # Update the reserved vlan ID range for the fabric - vlan_pool_data = { + VLAN_POOL_DATA = { "start": 100, "length": 100 } - print("\nUpdate the reserved vlan ID range for the fabric '%s'." % fabric_byname['name']) - fabric_byname = oneview_client.fabrics.update_reserved_vlan_range(fabric_byname['uri'], vlan_pool_data) - pprint(fabric_byname) + print("\nUpdate the reserved vlan ID range for the fabric '%s'." % FABRIC_BYNAME['name']) + FABRIC_BYNAME = ONEVIEW_CLIENT.fabrics.update_reserved_vlan_range(FABRIC_BYNAME['uri'],\ + VLAN_POOL_DATA) + pprint(FABRIC_BYNAME) diff --git a/examples/fc_networks.py b/examples/fc_networks.py index 6defa9cf8..4b9c53a8e 100644 --- a/examples/fc_networks.py +++ b/examples/fc_networks.py @@ -20,8 +20,8 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -# To run this example fill the ip and the credentials below or use a configuration file -config = { +# To run this example fill the ip and the credentials below or use a CONFIGuration file +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -30,7 +30,7 @@ "api_version": "" } -options = { +OPTIONS = { "name": "OneViewSDK Test FC Network", "connectionTemplateUri": None, "autoLoginRedistribution": True, @@ -39,95 +39,101 @@ } # Scope name to perform the patch operation -scope_name = "test_scope" +SCOPE_NAME = "test_SCOPE" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -fc_networks = oneview_client.fc_networks -scopes = oneview_client.scopes +ONEVIEW_CLIENT = OneViewClient(CONFIG) +FC_NETWORKS = ONEVIEW_CLIENT.fc_networks +SCOPES = ONEVIEW_CLIENT.scopes # Get all, with defaults print("\nGet all fc-networks") -fc_nets = fc_networks.get_all() -pprint(fc_nets) +FC_NETS = FC_NETWORKS.get_all() +pprint(FC_NETS) # Get the first 10 records print("\nGet the first ten fc-networks") -fc_nets_limited = fc_networks.get_all(0, 10) -pprint(fc_nets_limited) +FC_NETS_LIMITED = FC_NETWORKS.get_all(0, 10) +pprint(FC_NETS_LIMITED) # Filter by name print("\nGet all fc-networks filtering by name") -fc_nets_filtered = fc_networks.get_all(filter="\"'name'='Updated FC'\"") -pprint(fc_nets_filtered) +FC_NETS_FILTERED = FC_NETWORKS.get_all(filter="\"'name'='Updated FC'\"") +pprint(FC_NETS_FILTERED) # Get all sorting by name descending print("\nGet all fc-networks sorting by name") -fc_nets_sorted = fc_networks.get_all(sort='name:descending') -pprint(fc_nets_sorted) +FC_NETS_SORTED = FC_NETWORKS.get_all(sort='name:descending') +pprint(FC_NETS_SORTED) # Find recently created network by name print("\nGet FC Network by name") -fc_network = fc_networks.get_by_name(options['name']) +FC_NETWORK = FC_NETWORKS.get_by_name(OPTIONS['name']) -if fc_network: - print("\nFound fc-network by name: '%s'.\n uri = '%s'" % (fc_network.data['name'], fc_network.data['uri'])) +if FC_NETWORK: + print("\nFound fc-network by name: '%s'.\n uri = '%s'" % (FC_NETWORK.data['name'],\ + FC_NETWORK.data['uri'])) else: - # Create a FcNetWork with the options provided - fc_network = fc_networks.create(data=options) - print("\nCreated a fc-network with name: '%s'.\n uri = '%s'" % (fc_network.data['name'], fc_network.data['uri'])) + # Create a FcNetWork with the OPTIONS provided + FC_NETWORK = FC_NETWORKS.create(data=OPTIONS) + print("\nCreated a fc-network with name: '%s'.\n uri = '%s'" % (FC_NETWORK.data['name'],\ + FC_NETWORK.data['uri'])) # Get by uri print("\nGet a fc-network by uri") -fc_nets_by_uri = fc_networks.get_by_uri(fc_network.data['uri']) -pprint(fc_nets_by_uri.data) +FC_NETS_BY_URI = FC_NETWORKS.get_by_uri(FC_NETWORK.data['uri']) +pprint(FC_NETS_BY_URI.data) # Update autoLoginRedistribution from recently created network -data_to_update = {'autoLoginRedistribution': False, +DATA_TO_UPDATE = {'autoLoginRedistribution': False, 'name': 'Updated FC'} -fc_network.update(data=data_to_update) -print("\nUpdated fc-network '%s' successfully.\n uri = '%s'" % (fc_network.data['name'], fc_network.data['uri'])) -print(" with attribute {'autoLoginRedistribution': %s}" % fc_network.data['autoLoginRedistribution']) - -# Adds fc-network to scope defined only for V300 and V500 -if scope_name and 300 <= oneview_client.api_version <= 500: - print("\nGet scope then add the network to it") - scope = scopes.get_by_name(scope_name) - print(scope['uri']) +FC_NETWORK.update(data=DATA_TO_UPDATE) +print("\nUpdated fc-network '%s' successfully.\n uri = '%s'" % (FC_NETWORK.data['name'],\ + FC_NETWORK.data['uri'])) +print(" with attribute {'autoLoginRedistribution': %s}" % \ + FC_NETWORK.data['autoLoginRedistribution']) + +# Adds fc-network to SCOPE defined only for V300 and V500 +if SCOPE_NAME and 300 <= ONEVIEW_CLIENT.api_version <= 500: + print("\nGet SCOPE then add the network to it") + SCOPE = SCOPES.get_by_name(SCOPE_NAME) + print(SCOPE['uri']) try: - fc_with_scope = fc_network.patch('replace', - '/scopeUris', - [scope.data['uri']]) - pprint(fc_with_scope) - except HPEOneViewException as e: - print(e) + FC_WITH_SCOPE = FC_NETWORK.patch('replace', + '/SCOPEUris', + [SCOPE.data['uri']]) + pprint(FC_WITH_SCOPE) + except HPEOneViewException as err: + print(err) # Delete the created network -fc_network.delete() +FC_NETWORK.delete() print("\nSuccessfully deleted fc-network") # Creates bulk fc-networks for i in range(4): - fc_network_body = options.copy() - fc_network_body['name'] = "OneViewSDK Test FC Network" + str(i) - bulk_fc_network = fc_networks.create(data=fc_network_body) - print("\nCreated bulk fc-networks with name: '%s'.\n uri = '%s'" % (bulk_fc_network.data['name'], bulk_fc_network.data['uri'])) + FC_NETWORK_body = OPTIONS.copy() + FC_NETWORK_body['name'] = "OneViewSDK Test FC Network" + str(i) + bulk_FC_NETWORK = FC_NETWORKS.create(data=FC_NETWORK_body) + print("\nCreated bulk fc-networks with name: '%s'.\n uri = '%s'" %\ + (bulk_FC_NETWORK.data['name'], bulk_FC_NETWORK.data['uri'])) # Delete bulk fcnetworks -if oneview_client.api_version >= 1600: - bulk_network_uris = [] +if ONEVIEW_CLIENT.api_version >= 1600: + BULK_NETWORK_URIS = [] for i in range(4): - fc_network_name = "OneViewSDK Test FC Network" + str(i) - bulk_fc_network = fc_networks.get_by_name(fc_network_name) - bulk_network_uris.append(bulk_fc_network.data['uri']) + FC_NETWORK_name = "OneViewSDK Test FC Network" + str(i) + bulk_FC_NETWORK = FC_NETWORKS.get_by_name(FC_NETWORK_name) + BULK_NETWORK_URIS.append(bulk_FC_NETWORK.data['uri']) print("\nDelete bulk fc-networks") - options_bulk_delete = {"networkUris": bulk_network_uris} - fc_network.delete_bulk(options_bulk_delete) + OPTIONS_BULK_DELETE = {"networkUris": BULK_NETWORK_URIS} + FC_NETWORK.delete_bulk(OPTIONS_BULK_DELETE) print("Successfully deleted bulk fc-networks") # Automation tasks for FC networks -fc_network_body['name'] = "FC_fabric_nw" -fc_network = fc_networks.create(data=fc_network_body) -print("\nCreated fc-networks with name: '%s'.\n uri = '%s'" % (fc_network.data['name'], fc_network.data['uri'])) +FC_NETWORK_body['name'] = "FC_fabric_nw" +FC_NETWORK = FC_NETWORKS.create(data=FC_NETWORK_body) +print("\nCreated fc-networks with name: '%s'.\n uri = '%s'" % (FC_NETWORK.data['name'],\ + FC_NETWORK.data['uri'])) diff --git a/examples/fcoe_networks.py b/examples/fcoe_networks.py index e6f427234..a6038fcd7 100644 --- a/examples/fcoe_networks.py +++ b/examples/fcoe_networks.py @@ -15,13 +15,14 @@ # limitations under the License. ### +from copy import deepcopy + from pprint import pprint from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -from copy import deepcopy -# To run this example fill the ip and the credentials below or use a configuration file -config = { +# To run this example fill the ip and the credentials below or use a CONFIGuration file +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -30,99 +31,103 @@ "api_version": "" } -options = { +OPTIONS = { "name": "OneViewSDK Test FCoE Network", "vlanId": "201", "connectionTemplateUri": None, } # Scope name to perform the patch operation -scope_name = "" +SCOPE_NAME = "" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -fcoe_networks = oneview_client.fcoe_networks -scopes = oneview_client.scopes +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +FCOE_NETWORKS = ONEVIEW_CLIENT.fcoe_networks +SCOPES = ONEVIEW_CLIENT.scopes # Get all, with defaults print("\nGet all fcoe-networks") -fcoe_nets = fcoe_networks.get_all() -pprint(fcoe_nets) +FCOE_NETS = FCOE_NETWORKS.get_all() +pprint(FCOE_NETS) # Filter by name print("\nGet all fcoe-networks filtering by name") -fcoe_nets_filtered = fcoe_networks.get_all(filter="\"'name'='OneViewSDK Test FCoE Network'\"") -pprint(fcoe_nets_filtered) +FCOE_NETS_FILTERED = FCOE_NETWORKS.get_all(filter="\"'name'='OneViewSDK Test FCoE Network'\"") +pprint(FCOE_NETS_FILTERED) # Get all sorting by name descending print("\nGet all fcoe-networks sorting by name") -fcoe_nets_sorted = fcoe_networks.get_all(sort='name:descending') -pprint(fcoe_nets_sorted) +FCOE_NETS_SORTED = FCOE_NETWORKS.get_all(sort='name:descending') +pprint(FCOE_NETS_SORTED) # Get the first 10 records print("\nGet the first ten fcoe-networks") -fcoe_nets_limited = fcoe_networks.get_all(0, 10) -pprint(fcoe_nets_limited) +FCOE_NETS_LIMITED = FCOE_NETWORKS.get_all(0, 10) +pprint(FCOE_NETS_LIMITED) # Get by name -fcoe_network = fcoe_networks.get_by_name(options['name']) -if fcoe_network: - print("\nGot fcoe-network by name uri={}".format(fcoe_network.data['uri'])) +FCOE_NETWORK = FCOE_NETWORKS.get_by_name(OPTIONS['name']) +if FCOE_NETWORK: + print("\nGot fcoe-network by name uri={}".format(FCOE_NETWORK.data['uri'])) else: # Create a FC Network - fcoe_network = fcoe_networks.create(options) - print("\nCreated fcoe-network '%s' successfully.\n uri = '%s'" % (fcoe_network.data['name'], fcoe_network.data['uri'])) + FCOE_NETWORK = FCOE_NETWORKS.create(OPTIONS) + print("\nCreated fcoe-network '%s' successfully.\n uri = '%s'" % (FCOE_NETWORK.data['name'],\ + FCOE_NETWORK.data['uri'])) # Update autoLoginRedistribution from recently created network -resource = deepcopy(fcoe_network.data) -resource['status'] = 'Warning' -resource['name'] = "{}-Renamed".format(options["name"]) -fcoe_network_updated = fcoe_network.update(resource) -print("\nUpdated fcoe-network '%s' successfully.\n uri = '%s'" % (fcoe_network_updated.data['name'], fcoe_network_updated.data['uri'])) -print(" with attribute {'status': %s}" % fcoe_network_updated.data['status']) +RESOURCE = deepcopy(FCOE_NETWORK.data) +RESOURCE['status'] = 'Warning' +RESOURCE['name'] = "{}-Renamed".format(OPTIONS["name"]) +FCOE_NETWORK_UPDATED = FCOE_NETWORK.update(RESOURCE) +print("\nUpdated fcoe-network '%s' successfully.\n uri = '%s'" % (FCOE_NETWORK_UPDATED.\ + data['name'], FCOE_NETWORK_UPDATED.data['uri'])) +print(" with attribute {'status': %s}" % FCOE_NETWORK_UPDATED.data['status']) # Get by Uri print("\nGet a fcoe-network by uri") -fcoe_nets_by_uri = fcoe_networks.get_by_uri(fcoe_network.data['uri']) -pprint(fcoe_nets_by_uri.data) - -# Adds FCOE network to scope defined only for V300 and V500 -if scope_name and 300 <= oneview_client.api_version <= 500: - print("\nGet scope then add the network to it") - scope = scopes.get_by_name(scope_name) - fcoe_with_scope = fcoe_network.patch('replace', - '/scopeUris', - [scope.data['uri']]) - pprint(fcoe_with_scope.data) +FCOE_NETS_BY_URI = FCOE_NETWORKS.get_by_uri(FCOE_NETWORK.data['uri']) +pprint(FCOE_NETS_BY_URI.data) + +# Adds FCOE network to SCOPE defined only for V300 and V500 +if SCOPE_NAME and 300 <= ONEVIEW_CLIENT.api_version <= 500: + print("\nGet SCOPE then add the network to it") + SCOPE = SCOPES.get_by_name(SCOPE_NAME) + FCOE_WITH_SCOPE = FCOE_NETWORK.patch('replace', + '/SCOPEUris', + [SCOPE.data['uri']]) + pprint(FCOE_WITH_SCOPE.data) # Delete the created network -fcoe_network.delete() +FCOE_NETWORK.delete() print("\nSuccessfully deleted fcoe-network") # Creates bulk fcoe-networks for i in range(4): - options = { + OPTIONS = { "name": "OneViewSDK Test FCoE Network" + str(i), "vlanId": int("201") + int(i), "connectionTemplateUri": None, } - bulk_fcoe_network = fcoe_networks.create(options) - print("\nCreated bulk fcoe-networks with name: '%s'.\n uri = '%s'" % (bulk_fcoe_network.data['name'], bulk_fcoe_network.data['uri'])) + bulk_FCOE_NETWORK = FCOE_NETWORKS.create(OPTIONS) + print("\nCreated bulk fcoe-networks with name: '%s'.\n uri = '%s'" %\ + (bulk_FCOE_NETWORK.data['name'], bulk_FCOE_NETWORK.data['uri'])) # Delete bulk fcoe-networks -if oneview_client.api_version >= 1600: - bulk_network_uris = [] +if ONEVIEW_CLIENT.api_version >= 1600: + BULK_NETWORK_URIS = [] for i in range(4): - fcoe_network_name = "OneViewSDK Test FCoE Network" + str(i) - bulk_fcoe_network = fcoe_networks.get_by_name(fcoe_network_name) - bulk_network_uris.append(bulk_fcoe_network.data['uri']) + FCOE_NETWORK_name = "OneViewSDK Test FCoE Network" + str(i) + bulk_FCOE_NETWORK = FCOE_NETWORKS.get_by_name(FCOE_NETWORK_name) + BULK_NETWORK_URIS.append(bulk_FCOE_NETWORK.data['uri']) print("\nDelete bulk fcoe-networks") - options_bulk_delete = {"networkUris": bulk_network_uris} - fcoe_network.delete_bulk(options_bulk_delete) + OPTIONS_BULK_DELETE = {"networkUris": BULK_NETWORK_URIS} + FCOE_NETWORK.delete_bulk(OPTIONS_BULK_DELETE) print("Successfully deleted bulk fcoe-networks") # Create a FCoE Network for automation -options['name'] = "Test_fcoeNetwork" -fcoe_network = fcoe_networks.create(options) -print("\nCreated fcoe-network '%s' successfully.\n uri = '%s'" % (fcoe_network.data['name'], fcoe_network.data['uri'])) +OPTIONS['name'] = "Test_fcoeNetwork" +FCOE_NETWORK = FCOE_NETWORKS.create(OPTIONS) +print("\nCreated fcoe-network '%s' successfully.\n uri = '%s'" % (FCOE_NETWORK.data['name'],\ + FCOE_NETWORK.data['uri'])) diff --git a/examples/firmware_bundles.py b/examples/firmware_bundles.py index 4b39476a2..d3cea6f07 100644 --- a/examples/firmware_bundles.py +++ b/examples/firmware_bundles.py @@ -19,7 +19,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,42 +28,42 @@ } # To run this example you must define a path to a valid file -spp_path = "" -hotfix_path = "" -compsig_path = "" +SPP_PATH = "" +HOTFIX_PATH = "" +COMPSIG_PATH = "" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -firmware_bundles = oneview_client.firmware_bundles -firmware_drivers = oneview_client.firmware_drivers +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +FIRMWARE_BUNDLES = ONEVIEW_CLIENT.firmware_bundles +FIRMWARE_DRIVERS = ONEVIEW_CLIENT.firmware_drivers -# Upload a firmware bundle -firmware = firmware_bundles.get_by_name(spp_path) -if not firmware: - print("\nUpload a firmware bundle") - firmware_bundle_information = firmware_bundles.upload(file_path=spp_path) +# Upload a FIRMWARE bundle +FIRMWARE = FIRMWARE_BUNDLES.get_by_name(SPP_PATH) +if not FIRMWARE: + print("\nUpload a FIRMWARE bundle") + FIRMWARE_BUNDLE_INFORMATION = FIRMWARE_BUNDLES.upload(file_path=SPP_PATH) print("\n Upload successful! Firmware information returned: \n") - pprint(firmware_bundle_information) + pprint(FIRMWARE_BUNDLE_INFORMATION) else: print("\n Firmware Bundle already present") -# Upload a hotfix -hotfix = firmware_bundles.get_by_name(hotfix_path) -if not hotfix: - print("\nUpload a hotfix") - hotfix_information = firmware_bundles.upload(file_path=hotfix_path) +# Upload a HOTFIX +HOTFIX = FIRMWARE_BUNDLES.get_by_name(HOTFIX_PATH) +if not HOTFIX: + print("\nUpload a HOTFIX") + HOTFIX_INFORMATION = FIRMWARE_BUNDLES.upload(file_path=HOTFIX_PATH) print("\n Upload successful! Hotfix information returned: \n") - pprint(hotfix_information) + pprint(HOTFIX_INFORMATION) else: print("\n Hotfix already present") -# Upload a compsig to hotfix -compsig = firmware_bundles.get_by_name(compsig_path) -if compsig and compsig.data['resourceState'] == 'AddFailed': - print("\nUpload a compsig to hotfix") - compsig_information = firmware_bundles.upload_compsig(file_path=compsig_path) +# Upload a COMPSIG to HOTFIX +COMPSIG = FIRMWARE_BUNDLES.get_by_name(COMPSIG_PATH) +if COMPSIG and COMPSIG.data['resourceState'] == 'AddFailed': + print("\nUpload a COMPSIG to HOTFIX") + COMPSIG_INFORMATION = FIRMWARE_BUNDLES.upload_compsig(file_path=COMPSIG_PATH) print("\n Upload successful! CompSig information returned: \n") - pprint(compsig_information) + pprint(COMPSIG_INFORMATION) else: - print("\nHotfix is not present or compsig is already added") + print("\nHotfix is not present or COMPSIG is already added") diff --git a/examples/firmware_drivers.py b/examples/firmware_drivers.py index 057b57302..7e9b4b4f4 100644 --- a/examples/firmware_drivers.py +++ b/examples/firmware_drivers.py @@ -21,7 +21,7 @@ from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,61 +29,63 @@ } } -# NOTE: This example requires a SPP and a hotfix inside the appliance. +# NOTE: This example requires a SPP and a HOTFIX inside the appliance. -options = { +OPTIONS = { "customBaselineName": "Service Pack for Synergy", } -version = "SY-2021.02.01" +VERSION = "SY-2021.02.01" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -firmware_drivers = oneview_client.firmware_drivers +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +FIRMWARE_DRIVERS = ONEVIEW_CLIENT.firmware_drivers # Get all firmwares print("\nGet list of firmwares managed by the appliance.") -all_firmwares = firmware_drivers.get_all() -for firmware in all_firmwares: +ALL_FIRMWARES = FIRMWARE_DRIVERS.get_all() +for firmware in ALL_FIRMWARES: print(' - {}'.format(firmware['name'])) # Get firmware driver schema -firmware_schema = firmware_drivers.get_schema() -pprint(firmware_schema) +FIRMWARE_SCHEMA = FIRMWARE_DRIVERS.get_schema() +pprint(FIRMWARE_SCHEMA) -# Get a firmware by name (version is optional) +# Get a firmware by name (VERSION is optional) print("\nGet firmware by name.") -if all_firmwares: - firmware_driver = firmware_drivers.get_by_name(options["customBaselineName"], version) +if ALL_FIRMWARES: + FIRMWARE_DRIVER = FIRMWARE_DRIVERS.get_by_name(OPTIONS["customBaselineName"], VERSION) -if firmware_driver: - print("\nFound a firmware by name: '{}'.\n uri = '{}'".format(firmware_driver.data['name'], firmware_driver.data['uri'])) +if FIRMWARE_DRIVER: + print("\nFound a firmware by name: '{}'.\n uri = '{}'".format(FIRMWARE_DRIVER.data['name'],\ + FIRMWARE_DRIVER.data['uri'])) else: - # Getting a SPP and a hotfix from within the Appliance to use in the custom SPP creation. + # Getting a SPP and a HOTFIX from within the Appliance to use in the custom SPP creation. try: - spp = firmware_drivers.get_by('bundleType', "ServicePack")[0] - options['baselineUri'] = spp['uri'] - print("\nSPP named '{}' found within appliance. Saving for custom SPP.".format(spp['name'])) + SPP = FIRMWARE_DRIVERS.get_by('bundleType', "ServicePack")[0] + OPTIONS['baselineUri'] = SPP['uri'] + print("\nSPP named '{}' found within appliance. Saving for custom SPP.".format(SPP['name'])) except IndexError: raise HPEOneViewException('No available SPPs found within appliance. Stopping run.') try: - hotfix = firmware_drivers.get_by('bundleType', "Hotfix")[0] - options['hotfixUris'] = [hotfix['uri']] - print("\nHotfix named '{}' found within appliance. Saving for custom SPP.".format(hotfix['name'])) + HOTFIX = FIRMWARE_DRIVERS.get_by('bundleType', "Hotfix")[0] + OPTIONS['HOTFIXUris'] = [HOTFIX['uri']] + print("\nHotfix named '{}' found within appliance. Saving for custom\ + SPP.".format(HOTFIX['name'])) except IndexError: - raise HPEOneViewException('No available hotfixes found within appliance. Stopping run.') + raise HPEOneViewException('No available HOTFIXes found within appliance. Stopping run.') # Create the custom SPP - print("\nCreate the custom SPP '{}'".format(options['customBaselineName'])) - firmware_driver = firmware_drivers.create(options) - print("\nCustom SPP '%s' created successfully" % options['customBaselineName']) + print("\nCreate the custom SPP '{}'".format(OPTIONS['customBaselineName'])) + FIRMWARE_DRIVER = FIRMWARE_DRIVERS.create(OPTIONS) + print("\nCustom SPP '%s' created successfully" % OPTIONS['customBaselineName']) # Get by Uri print("\nGet firmware resource by URI.") -firmware_data = firmware_drivers.get_by_uri(firmware_driver.data['uri']) -pprint(firmware_data.data) +FIRMWARE_DATA = FIRMWARE_DRIVERS.get_by_uri(FIRMWARE_DRIVER.data['uri']) +pprint(FIRMWARE_DATA.data) # Remove the firmware driver -firmware_driver.delete() -print("\nCustom SPP '{}' deleted successfully".format(firmware_driver.data['name'])) +FIRMWARE_DRIVER.delete() +print("\nCustom SPP '{}' deleted successfully".format(FIRMWARE_DRIVER.data['name'])) diff --git a/examples/ha_nodes.py b/examples/ha_nodes.py index b4f14edc1..22c7be44a 100644 --- a/examples/ha_nodes.py +++ b/examples/ha_nodes.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,33 +27,33 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -ha_nodes = oneview_client.ha_nodes +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +HA_NODES = ONEVIEW_CLIENT.ha_nodes # Get all HA nodes from appliance print("\nGet all HA nodes from appliance:\n ") -all_nodes = ha_nodes.get_all() -for node in all_nodes: +ALL_NODES = HA_NODES.get_all() +for node in ALL_NODES: print(" - {}".format(node['name'])) # Get HA node by uri from appliance print("\nGet HA node by uri from appliance\n") -node_by_uri = ha_nodes.get_by_uri(all_nodes[0]['uri']) -pprint(node_by_uri.data) +NODE_BY_URI = HA_NODES.get_by_uri(ALL_NODES[0]['uri']) +pprint(NODE_BY_URI.DATA) # update role of HA node -data = {'role': 'Standby'} -ha_node = node_by_uri.update(data) +DATA = {'role': 'Standby'} +HA_NODE = NODE_BY_URI.update(DATA) print("\n## Update HA node successfully!") -pprint(ha_node.data) +pprint(HA_NODE.DATA) # Patch update role print("\nUpdate the HA node using patch") -ha_node.patch(operation="replace", path="/role", value="Active") -pprint(ha_node.data) +HA_NODE.patch(operation="replace", path="/role", value="Active") +pprint(HA_NODE.DATA) # Delete HA node -ha_node.delete() +HA_NODE.delete() print("\n## Delete HA node successfully!") diff --git a/examples/hypervisor_cluster_profiles.py b/examples/hypervisor_cluster_profiles.py index 0e70b4dfa..f068f903a 100644 --- a/examples/hypervisor_cluster_profiles.py +++ b/examples/hypervisor_cluster_profiles.py @@ -23,7 +23,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -31,24 +31,24 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -hypervisor_cluster_profiles = oneview_client.hypervisor_cluster_profiles -hypervisor_managers = oneview_client.hypervisor_managers -profile_templates = oneview_client.server_profile_templates -os_deployment_plans = oneview_client.os_deployment_plans +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +HYPERVISOR_CLUSTER_PROFILES = ONEVIEW_CLIENT.hypervisor_cluster_profiles +HYPERVISOR_MANAGERS = ONEVIEW_CLIENT.hypervisor_managers +PROFILE_TEMPLATES = ONEVIEW_CLIENT.server_profile_templates +OS_DEPLOYMENT_PLANS = ONEVIEW_CLIENT.os_deployment_plans -hypervisor_manager = "172.18.13.11" -spt_name = "ProfileTemplate-1" # spt without os deployment plan and one mgmt connection -deployment_plan = "Basic Deployment Plan" +HYPERVISOR_MANAGER = "172.18.13.11" +SPT_NAME = "ProfileTemplate-1" # spt without os deployment plan and one mgmt connection +DEPLOYMENT_PLAN = "Basic Deployment Plan" # Getting the uris from name -hyp_mgr_uri = hypervisor_managers.get_by_name(hypervisor_manager).data['uri'] -spt_uri = profile_templates.get_by_name(spt_name).data['uri'] -dp_uri = os_deployment_plans.get_by_name(deployment_plan).data['uri'] +HYP_MGR_URI = HYPERVISOR_MANAGERS.get_by_name(HYPERVISOR_MANAGER).data['uri'] +SPT_URI = PROFILE_TEMPLATES.get_by_name(SPT_NAME).data['uri'] +DP_URI = OS_DEPLOYMENT_PLANS.get_by_name(DEPLOYMENT_PLAN).data['uri'] -options = { +OPTIONS = { "name": "Test_cluster_profile", "description": "test cluster", "hypervisorType": "Vmware", @@ -60,9 +60,9 @@ "virtualSwitchType": "Standard" }, "hypervisorHostProfileTemplate": { - "serverProfileTemplateUri": spt_uri, + "serverProfileTemplateUri": SPT_URI, "deploymentPlan": { - "deploymentPlanUri": dp_uri, + "deploymentPlanUri": DP_URI, "serverPassword": "", "deploymentCustomArgs": [] }, @@ -74,83 +74,85 @@ }, "virtualSwitchConfigPolicy": { "manageVirtualSwitches": True, - "configurePortGroups": True + "CONFIGurePortGroups": True } }, "mgmtIpSettingsOverride": None, - "hypervisorManagerUri": hyp_mgr_uri, + "hypervisorManagerUri": HYP_MGR_URI, "path": "DC1", "initialScopeUris": [] } -vswitch_options = { - "hypervisorManagerUri": hyp_mgr_uri, - "serverProfileTemplateUri": spt_uri +VSWITCH_OPTIONS = { + "hypervisorManagerUri": HYP_MGR_URI, + "serverProfileTemplateUri": SPT_URI } # Get all cluster profiles print("\nGet all hypervisor cluster profiles") -cluster_profiles_all = hypervisor_cluster_profiles.get_all() -for profile in cluster_profiles_all: +CLUSTER_PROFILES_ALL = HYPERVISOR_CLUSTER_PROFILES.get_all() +for profile in CLUSTER_PROFILES_ALL: print(' - {}'.format(profile['name'])) # Find recently created hypervisor cluster profile by name print("\nGet Hypervisor cluster profile by name") -hypervisor_cluster_profile = hypervisor_cluster_profiles.get_by_name(options['name']) +HYPERVISOR_CLUSTER_PROFILE = HYPERVISOR_CLUSTER_PROFILES.get_by_name(OPTIONS['name']) -if hypervisor_cluster_profile: +if HYPERVISOR_CLUSTER_PROFILE: print("\nFound hypervisor cluster profile by name: {}.\n uri = {}".format( - hypervisor_cluster_profile.data['name'], hypervisor_cluster_profile.data['uri'])) + HYPERVISOR_CLUSTER_PROFILE.data['name'], HYPERVISOR_CLUSTER_PROFILE.data['uri'])) else: # Create virtual switch layout print("\nCreate virtual switch layout") - vswitch_layout = hypervisor_cluster_profiles.create_virtual_switch_layout(data=vswitch_options) - pprint(vswitch_layout) + VSWITCH_LAYOUT = HYPERVISOR_CLUSTER_PROFILES.create_virtual_switch_layout(data=VSWITCH_OPTIONS) + pprint(VSWITCH_LAYOUT) - # Create a Hypervisor Cluster Profile with the options provided - options['hypervisorHostProfileTemplate']['virtualSwitches'] = vswitch_layout + # Create a Hypervisor Cluster Profile with the OPTIONS provided + OPTIONS['hypervisorHostProfileTemplate']['virtualSwitches'] = VSWITCH_LAYOUT - hypervisor_cluster_profile = hypervisor_cluster_profiles.create(data=options) + HYPERVISOR_CLUSTER_PROFILE = HYPERVISOR_CLUSTER_PROFILES.create(data=OPTIONS) print("\nCreated a hypervisor cluster profile with name: {}.\n uri = {}".format( - hypervisor_cluster_profile.data['name'], hypervisor_cluster_profile.data['uri'])) + HYPERVISOR_CLUSTER_PROFILE.data['name'], HYPERVISOR_CLUSTER_PROFILE.data['uri'])) # Get the first 10 records print("\nGet the first ten hypervisor cluster profiles") -cluster_profiles_top_ten = hypervisor_cluster_profiles.get_all(0, 10) -for profile in cluster_profiles_top_ten: +CLUSTER_PROFILES_TOP_TEN = HYPERVISOR_CLUSTER_PROFILES.get_all(0, 10) +for profile in CLUSTER_PROFILES_TOP_TEN: print(' - {}'.format(profile['name'])) # Filter by hypervisor type print("\nGet all hypervisor cluster profiles filtering by hypervisor type") -cluster_profiles_filtered = hypervisor_cluster_profiles.get_all(filter="\"'hypervisorType'='Vmware'\"") -for profile in cluster_profiles_filtered: +CLUSTER_PROFILES_FILTERED = HYPERVISOR_CLUSTER_PROFILES.get_all\ + (filter="\"'hypervisorType'='Vmware'\"") +for profile in CLUSTER_PROFILES_FILTERED: print("Cluster profile with type 'Vmware' - {}".format(profile['name'])) # Get all sorting by name descending print("\nGet all hypervisor cluster profiles sorting by name") -clusters_sorted = hypervisor_cluster_profiles.get_all(sort='name:descending') -for profile in clusters_sorted: +CLUSTERS_SORTED = HYPERVISOR_CLUSTER_PROFILES.get_all(sort='name:descending') +for profile in CLUSTERS_SORTED: print(' - {}'.format(profile['name'])) # Get by uri print("\nGet a hypervisor cluster profile by uri") -cluster_profile_by_uri = hypervisor_cluster_profiles.get_by_uri(hypervisor_cluster_profile.data['uri']) -pprint(cluster_profile_by_uri.data) +CLUSTER_PROFILE_BY_URI = HYPERVISOR_CLUSTER_PROFILES.get_by_uri\ + (HYPERVISOR_CLUSTER_PROFILE.data['uri']) +pprint(CLUSTER_PROFILE_BY_URI.data) # Update the name of recently created hypervisor cluster profile -data_to_update = {'name': 'Updated cluster'} -if hypervisor_cluster_profile: - hypervisor_cluster_profile.update(data=data_to_update) +DATA_TO_UPDATE = {'name': 'Updated cluster'} +if HYPERVISOR_CLUSTER_PROFILE: + HYPERVISOR_CLUSTER_PROFILE.update(data=DATA_TO_UPDATE) print("\nUpdated hypervisor cluster profile name - {0} to {1}".format( - options['name'], hypervisor_cluster_profile.data['name'])) + OPTIONS['name'], HYPERVISOR_CLUSTER_PROFILE.data['name'])) # Get compliance preview of cluster profile -if hypervisor_cluster_profile: - profile_compliance = hypervisor_cluster_profile.get_compliance_preview() - print(" - Compliance preview: '{}'".format(profile_compliance)) +if HYPERVISOR_CLUSTER_PROFILE: + PROFILE_COMPLIANCE = HYPERVISOR_CLUSTER_PROFILE.get_compliance_preview() + print(" - Compliance preview: '{}'".format(PROFILE_COMPLIANCE)) # Delete the created hypervisor cluster profile -if hypervisor_cluster_profile: - hypervisor_cluster_profile.delete(soft_delete=True, force=True) +if HYPERVISOR_CLUSTER_PROFILE: + HYPERVISOR_CLUSTER_PROFILE.delete(soft_delete=True, force=True) print("\nSuccessfully deleted hypervisor cluster profile") diff --git a/examples/hypervisor_managers.py b/examples/hypervisor_managers.py index f668d1841..4e7f36093 100644 --- a/examples/hypervisor_managers.py +++ b/examples/hypervisor_managers.py @@ -20,7 +20,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,7 +28,7 @@ } } -options = { +OPTIONS = { "name": "172.18.13.11", "displayName": "vcenter", "hypervisorType": "Vmware", @@ -36,60 +36,64 @@ "password": "dcs", } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -hypervisor_managers = oneview_client.hypervisor_managers +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +ONEVIEW_CLIENT = OneViewClient(CONFIG) +HYPERVISOR_MANAGERS = ONEVIEW_CLIENT.hypervisor_managers # Find recently created hypervisor manager by name print("\nGet Hypervisor Manager by name") -hypervisor_manager = hypervisor_managers.get_by_name(options['name']) +HYPERVISOR_MANAGER = HYPERVISOR_MANAGERS.get_by_name(OPTIONS['name']) -if hypervisor_manager: - print("\nFound hypervisor-manager by name: {}.\n uri = {}".format(hypervisor_manager.data['name'], hypervisor_manager.data['uri'])) +if HYPERVISOR_MANAGER: + print("\nFound hypervisor-manager by name: {}.\n uri = {}".format(HYPERVISOR_MANAGER.\ + data['name'], HYPERVISOR_MANAGER.data['uri'])) else: - # Create a HypervisorManager with the options provided - hypervisor_manager = hypervisor_managers.create(data=options) - print("\nCreated a hypervisor-manager with name: {}.\n uri = {}".format(hypervisor_manager.data['name'], hypervisor_manager.data['uri'])) + # Create a HypervisorManager with the OPTIONS provided + HYPERVISOR_MANAGER = HYPERVISOR_MANAGERS.create(data=OPTIONS) + print("\nCreated a hypervisor-manager with name: {}.\n uri = {}".format(HYPERVISOR_MANAGER.\ + data['name'], HYPERVISOR_MANAGER.data['uri'])) # Get all, with defaults print("\nGet all hypervisor managers") -hyp_managers_all = hypervisor_managers.get_all() -for hyp in hyp_managers_all: +HYP_MANAGERS_ALL = HYPERVISOR_MANAGERS.get_all() +for hyp in HYP_MANAGERS_ALL: print(' - {}'.format(hyp['name'])) # Get the first 10 records print("\nGet the first ten hypervisor managers") -hyp_mgrs_top_ten = hypervisor_managers.get_all(0, 10) -for hyp in hyp_mgrs_top_ten: +HYP_MGRS_TOP_TEN = HYPERVISOR_MANAGERS.get_all(0, 10) +for hyp in HYP_MGRS_TOP_TEN: print(' - {}'.format(hyp['name'])) # Filter by hypervisor type print("\nGet all hypervisor managers filtering by hypervisor type") -hyp_mgrs_filtered = hypervisor_managers.get_all(filter="\"'hypervisorType'='Vmware'\"") -for hyp in hyp_mgrs_filtered: +HYP_MGRS_FILTERED = HYPERVISOR_MANAGERS.get_all(filter="\"'hypervisorType'='Vmware'\"") +for hyp in HYP_MGRS_FILTERED: print("Hypervisor with type 'Vmware' - {}".format(hyp['name'])) # Get all sorting by name descending print("\nGet all hypervisor managers sorting by name") -hyp_mgrs_sorted = hypervisor_managers.get_all(sort='name:descending') -pprint(hyp_mgrs_sorted) +HYP_MGRS_SORTED = HYPERVISOR_MANAGERS.get_all(sort='name:descending') +pprint(HYP_MGRS_SORTED) # Get by uri print("\nGet a hypervisor managers by uri") -hyp_mgrs_by_uri = hypervisor_managers.get_by_uri(hypervisor_manager.data['uri']) -pprint(hyp_mgrs_by_uri.data) +HYP_MGRS_BY_URI = HYPERVISOR_MANAGERS.get_by_uri(HYPERVISOR_MANAGER.data['uri']) +pprint(HYP_MGRS_BY_URI.data) # Update display name of recently created hypervisor manager -data_to_update = {'displayName': 'Updated vcenter'} -hypervisor_manager.update(data=data_to_update) -print("\nUpdated hypervisor manager {} successfully.\n uri = {}".format(hypervisor_manager.data['name'], hypervisor_manager.data['uri'])) -print(" with attribute 'displayName': {}".format(hypervisor_manager.data['displayName'])) +DATA_TO_UPDATE = {'displayName': 'Updated vcenter'} +HYPERVISOR_MANAGER.update(data=DATA_TO_UPDATE) +print("\nUpdated hypervisor manager {} successfully.\n uri = {}".format(HYPERVISOR_MANAGER.\ + data['name'], HYPERVISOR_MANAGER.data['uri'])) +print(" with attribute 'displayName': {}".format(HYPERVISOR_MANAGER.data['displayName'])) # Delete the created hypervisor manager -hypervisor_manager.delete() +HYPERVISOR_MANAGER.delete() print("\nSuccessfully deleted hypervisor manager") # Create a HypervisorManager for automation -hypervisor_manager = hypervisor_managers.create(data=options) -print("\nCreated a hypervisor-manager with name: {}.\n uri = {}".format(hypervisor_manager.data['name'], hypervisor_manager.data['uri'])) +HYPERVISOR_MANAGER = HYPERVISOR_MANAGERS.create(data=OPTIONS) +print("\nCreated a hypervisor-manager with name: {}.\n uri = {}".format(HYPERVISOR_MANAGER.\ + data['name'], HYPERVISOR_MANAGER.data['uri'])) diff --git a/examples/id_pools.py b/examples/id_pools.py index 9c3f9e3dd..2c38df422 100644 --- a/examples/id_pools.py +++ b/examples/id_pools.py @@ -20,7 +20,7 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,70 +28,70 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) -pool_type_vsn = 'vsn' -pool_type_vwwn = 'vwwn' -pool_type_vmac = 'vmac' -pool_type_ipv4 = 'ipv4' +POOL_TYPE_VSN = 'vsn' +POOL_TYPE_VWWN = 'vwwn' +POOL_TYPE_VMAC = 'vmac' +POOL_TYPE_IPV4 = 'ipv4' -id_pools = oneview_client.id_pools -print("\n Gets schema: ") -schema = id_pools.get_schema() -pprint(schema) +ID_POOLS = ONEVIEW_CLIENT.id_pools +print("\n Gets SCHEMA: ") +SCHEMA = ID_POOLS.get_schema() +pprint(SCHEMA) -print("\n Gets the Pool: " + pool_type_vsn) -id_pool = id_pools.get_pool_type(pool_type_vsn) -pprint(id_pool.data) +print("\n Gets the Pool: " + POOL_TYPE_VSN) +ID_POOL = ID_POOLS.get_pool_type(POOL_TYPE_VSN) +pprint(ID_POOL.data) -print("\n Gets the Pool: " + pool_type_vwwn) -id_pool = id_pools.get_pool_type(pool_type_vwwn) -pprint(id_pool.data) +print("\n Gets the Pool: " + POOL_TYPE_VWWN) +ID_POOL = ID_POOLS.get_pool_type(POOL_TYPE_VWWN) +pprint(ID_POOL.data) -print("\n Gets the Pool: " + pool_type_ipv4) -id_pool = id_pools.get_pool_type(pool_type_ipv4) -pprint(id_pool.data) +print("\n Gets the Pool: " + POOL_TYPE_IPV4) +ID_POOL = ID_POOLS.get_pool_type(POOL_TYPE_IPV4) +pprint(ID_POOL.data) -print("\n Gets the Pool: " + pool_type_vmac) -id_pool = id_pools.get_pool_type(pool_type_vmac) -pprint(id_pool.data) +print("\n Gets the Pool: " + POOL_TYPE_VMAC) +ID_POOL = ID_POOLS.get_pool_type(POOL_TYPE_VMAC) +pprint(ID_POOL.data) print("\n Enable the Id Pool") -data = { - "rangeUris": id_pool.data['rangeUris'], +DATA = { + "rangeUris": ID_POOL.data['rangeUris'], "type": "Pool", "enabled": True } -id_pool = id_pools.update_pool_type(data, pool_type_vmac) +ID_POOL = ID_POOLS.update_pool_type(DATA, POOL_TYPE_VMAC) print(" Id Pool Updated") print("\n Generates a random range") -rnd_range = id_pools.generate(pool_type_vsn) -pprint(rnd_range.data) +RND_RANGE = ID_POOLS.generate(POOL_TYPE_VSN) +pprint(RND_RANGE.data) print("\n Allocates a set of IDs from a pool") -allocated_ids = id_pools.allocate({"count": 10}, pool_type_vsn) -pprint(allocated_ids) +ALLOCATED_IDS = ID_POOLS.allocate({"count": 10}, POOL_TYPE_VSN) +pprint(ALLOCATED_IDS) print("\n Checks the range availability in the Id pool") -range_availability = id_pools.get_check_range_availability(pool_type_vsn, allocated_ids['idList']) -pprint(range_availability.data) +RANGE_AVAILABILITY = ID_POOLS.get_check_range_availability(POOL_TYPE_VSN, ALLOCATED_IDS['idList']) +pprint(RANGE_AVAILABILITY.data) print("\n Validates a set of user specified IDs to reserve in the pool") -ids = [str(x)[:-3] + '200' for x in allocated_ids['idList']] -validated = id_pools.validate({'idList': ids}, pool_type_vsn) -pprint(validated) +IDS = [str(x)[:-3] + '200' for x in ALLOCATED_IDS['idList']] +VALIDATED = ID_POOLS.validate({'idList': IDS}, POOL_TYPE_VSN) +pprint(VALIDATED) print("\n Validates an Id Pool") -get_validate = id_pools.validate_id_pool(pool_type_ipv4, ['172.18.9.11']) -pprint(get_validate.data) +GET_VALIDATE = ID_POOLS.validate_id_pool(POOL_TYPE_IPV4, ['172.18.9.11']) +pprint(GET_VALIDATE.data) print("\n Collect a set of IDs back to Id Pool") try: - collected_ids = id_pools.collect({"idList": allocated_ids['idList']}, pool_type_vsn) - pprint(collected_ids) -except HPEOneViewException as e: - print(e.msg) + COLLECTED_IDS = ID_POOLS.collect({"idList": ALLOCATED_IDS['idList']}, POOL_TYPE_VSN) + pprint(COLLECTED_IDS) +except HPEOneViewException as err: + print(err.msg) diff --git a/examples/id_pools_ipv4_ranges.py b/examples/id_pools_ipv4_ranges.py index 8dc560445..ae77beeb0 100644 --- a/examples/id_pools_ipv4_ranges.py +++ b/examples/id_pools_ipv4_ranges.py @@ -18,9 +18,8 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file - -# Try load config from a file (if there is a config file) -config = { +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,14 +28,14 @@ "api_version": "" } -config = try_load_from_file(config) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -enclosure_groups = oneview_client.enclosure_groups -id_pool_ipv4_range = oneview_client.id_pools_ipv4_ranges -id_pool_ipv4_subnet = oneview_client.id_pools_ipv4_subnets +ONEVIEW_CLIENT = OneViewClient(CONFIG) +ENCLOSURE_GROUPS = ONEVIEW_CLIENT.enclosure_groups +ID_POOL_IPV4_RANGE = ONEVIEW_CLIENT.id_pools_ipv4_ranges +ID_POOL_IPV4_SUBNET = ONEVIEW_CLIENT.id_pools_ipv4_subnets -options = { +OPTIONS = { "name": "IPv4", "rangeCategory": "Custom", "startAddress": "", @@ -44,101 +43,101 @@ "subnetUri": "" } -subnet_options = { +SUBNET_OPTIONS = { "name": "iscsi_Subnet", - "networkId": config['subnet_networkid'], - "subnetmask": config['subnet_mask'], - "gateway": config['subnet_gateway'], + "networkId": CONFIG['subnet_networkid'], + "subnetmask": CONFIG['subnet_mask'], + "gateway": CONFIG['subnet_gateway'], "domain": "example.com", } print('\n Create IPv4 subnet to have Range of IPs') -ipv4_subnet = id_pool_ipv4_subnet.create(subnet_options) -pprint(ipv4_subnet.data) +IPV4_SUBNET = ID_POOL_IPV4_SUBNET.create(SUBNET_OPTIONS) +pprint(IPV4_SUBNET.data) -option = { +OPTION = { "name": "IPv4", "startStopFragments": [ { - "startAddress": config['range_start_address'], - "endAddress": config['range_end_address'] + "startAddress": CONFIG['range_start_address'], + "endAddress": CONFIG['range_end_address'] } ], - "subnetUri": ipv4_subnet.data['uri'] + "subnetUri": IPV4_SUBNET.data['uri'] } print("\n Create an IPv4 Range for id pools") -if oneview_client.api_version > 1000: - ipv4_range = id_pool_ipv4_range.create(option).data +if ONEVIEW_CLIENT.api_version > 1000: + IPV4_RANGE = ID_POOL_IPV4_RANGE.create(OPTION).data else: - ipv4_range = id_pool_ipv4_range.create(options).data -pprint(ipv4_range) + IPV4_RANGE = ID_POOL_IPV4_RANGE.create(OPTIONS).data +pprint(IPV4_RANGE) print("\n Get the IPv4 range by uri") -ipv4Range = id_pool_ipv4_range.get_by_uri(ipv4_range['uri']) -pprint(ipv4Range.data) +IPV4RANGE = ID_POOL_IPV4_RANGE.get_by_uri(IPV4_RANGE['uri']) +pprint(IPV4RANGE.data) print("Getting Schema") -schema = ipv4Range.get_schema() -pprint(schema) +SCHEMA = IPV4RANGE.get_SCHEMA() +pprint(SCHEMA) print("\n Update the IPv4 Range") -update_ipv4Range = ipv4Range.data -update_ipv4Range['name'] = 'New Name' -ipv4_range = ipv4Range.update(update_ipv4Range) -pprint(ipv4_range.data) +UPDATE_IPV4RANGE = IPV4RANGE.data +UPDATE_IPV4RANGE['name'] = 'New Name' +IPV4_RANGE = IPV4RANGE.update(UPDATE_IPV4RANGE) +pprint(IPV4_RANGE.data) print("\n Enable an IPv4 range") -ipv4_range = ipv4Range.enable( +IPV4_RANGE = IPV4RANGE.enable( { "type": "Range", "enabled": True }, - ipv4_range.data['uri']) + IPV4_RANGE.data['uri']) print(" IPv4 range enabled successfully.") print("\nAssociate EG with range for allocation") -eg_options = { +EG_OPTIONS = { "name": "RangeEG", "ipAddressingMode": "ipPool", - "ipRangeUris": [ipv4_range['uri']], + "ipRangeUris": [IPV4_RANGE['uri']], "enclosureCount": 3, } -enclosure_group = enclosure_groups.create(eg_options) +ENCLOSURE_GROUP = ENCLOSURE_GROUPS.create(EG_OPTIONS) print("\nAllocates a set of IDs from an IPv4 range") -ipv4_range_updated = ipv4Range.update_allocator({ +IPV4_RANGE_UPDATED = IPV4RANGE.update_allocator({ "count": 2, -}, ipv4_range['uri']) -pprint(ipv4_range_updated) +}, IPV4_RANGE['uri']) +pprint(IPV4_RANGE_UPDATED) print("Allocated set of ID to ipv4 Range") print("\n Get all allocated fragments in IPv4 range") -allocated_fragments = ipv4Range.get_allocated_fragments(ipv4_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = IPV4RANGE.get_ALLOCATED_FRAGMENTS(IPV4_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) print("\n Get all free fragments in IPv4 range") -allocated_fragments = ipv4Range.get_free_fragments(ipv4_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = IPV4RANGE.get_free_fragments(IPV4_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) print("Collects a set of IDs back to an IPv4 range.") -ipv4_range_collector = ipv4Range.update_collector({ - "idList": ipv4_range_updated['idList'] -}, ipv4_range['uri']) -print(ipv4_range_collector) +IPV4_RANGE_COLLECTOR = IPV4RANGE.update_collector({ + "idList": IPV4_RANGE_UPDATED['idList'] +}, IPV4_RANGE['uri']) +print(IPV4_RANGE_COLLECTOR) print("\nRemove associated EG before deletion") -enclosure_group.delete() +ENCLOSURE_GROUP.delete() print("\n Disable an IPv4 range") -ipv4_range = ipv4Range.enable({ +IPV4_RANGE = IPV4RANGE.enable({ "type": "Range", "enabled": False -}, ipv4_range['uri']) +}, IPV4_RANGE['uri']) print(" IPv4 range disabled successfully.") print("\n Delete the IPv4_range") -ipv4Range.delete() +IPV4RANGE.delete() print(" Successfully deleted IPv4 range") diff --git a/examples/id_pools_ipv4_subnets.py b/examples/id_pools_ipv4_subnets.py index 2c470f7a1..71b2d8905 100644 --- a/examples/id_pools_ipv4_subnets.py +++ b/examples/id_pools_ipv4_subnets.py @@ -20,7 +20,7 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,41 +28,41 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) -options = { +OPTIONS = { "name": "IPv4Subnet", - "networkId": config['subnet_networkid'], - "subnetmask": config['subnet_mask'], - "gateway": config['subnet_gateway'], + "networkId": CONFIG['subnet_networkid'], + "subnetmask": CONFIG['subnet_mask'], + "gateway": CONFIG['subnet_gateway'], "domain": "example.com", "dnsServers": [] } -id_pools_ipv4_subnets = oneview_client.id_pools_ipv4_subnets -ethernet_networks = oneview_client.ethernet_networks +ID_POOLS_IPV4_SUBNETS = ONEVIEW_CLIENT.id_pools_ipv4_subnets +ETHERNET_NETWORKS = ONEVIEW_CLIENT.ethernet_networks print('\n Create IPv4 subnet for id pools') -ipv4_subnet = id_pools_ipv4_subnets.create(options) -pprint(ipv4_subnet.data) +IPV4_SUBNET = ID_POOLS_IPV4_SUBNETS.create(OPTIONS) +pprint(IPV4_SUBNET.data) print('\n Update IPv4 subnet for id pools') -updated_data = {'name': 'Changed Name'} -ipv4_subnet = ipv4_subnet.update(updated_data) +UPDATED_DATA = {'name': 'Changed Name'} +IPV4_SUBNET = IPV4_SUBNET.update(UPDATED_DATA) print('\n Get IPv4 subnet by uri') -ipv4_subnet_byuri = id_pools_ipv4_subnets.get_by_uri(ipv4_subnet.data['uri']) -pprint(ipv4_subnet_byuri.data) +IPV4_SUBNET_BYURI = ID_POOLS_IPV4_SUBNETS.get_by_uri(IPV4_SUBNET.data['uri']) +pprint(IPV4_SUBNET_BYURI.data) print('\n Get all IPv4 subnet') -all_subnets = id_pools_ipv4_subnets.get_all() -pprint(all_subnets) +ALL_SUBNETS = ID_POOLS_IPV4_SUBNETS.get_all() +pprint(ALL_SUBNETS) print('\nAssociate Subnet with Ethernet for ID allocation') -options = { +OPTIONS = { "name": "SubnetEthernet", "vlanId": 209, "ethernetNetworkType": "Tagged", @@ -70,43 +70,43 @@ "smartLink": False, "privateNetwork": False, "connectionTemplateUri": None, - "subnetUri": ipv4_subnet.data['uri'] + "subnetUri": IPV4_SUBNET.data['uri'] } -ethernet_network = ethernet_networks.create(options) +ETHERNET_NETWORK = ETHERNET_NETWORKS.create(OPTIONS) print('\nCreate Range with set of IDs') -option = { +OPTION = { "name": "IPv4", "startStopFragments": [ { - "startAddress": config['range_start_address'], - "endAddress": config['range_end_address'] + "startAddress": CONFIG['range_start_address'], + "endAddress": CONFIG['range_end_address'] } ], - "subnetUri": ipv4_subnet.data['uri'] + "subnetUri": IPV4_SUBNET.data['uri'] } -id_pool_ipv4_range = oneview_client.id_pools_ipv4_ranges -ipv4_range = id_pool_ipv4_range.create(option).data +ID_POOL_IPV4_RANGE = ONEVIEW_CLIENT.id_pools_ipv4_ranges +IPV4_RANGE = ID_POOL_IPV4_RANGE.create(OPTION).data -subnet_id = ipv4_subnet.data['allocatorUri'].split('/')[-2] +SUBNET_ID = IPV4_SUBNET.data['allocatorUri'].split('/')[-2] print("\n Allocates a set of IDs from a pool") try: - allocated_ids = id_pools_ipv4_subnets.allocate({"count": 2}, subnet_id) - pprint(allocated_ids) -except HPEOneViewException as e: - print(e.msg) + ALLOCATED_IDS = ID_POOLS_IPV4_SUBNETS.allocate({"count": 2}, SUBNET_ID) + pprint(ALLOCATED_IDS) +except HPEOneViewException as err: + print(err.msg) print("\n Collect a set of IDs back to Id Pool") try: - collected_ids = id_pools_ipv4_subnets.collect({"idList": allocated_ids['idList']}, subnet_id) - pprint(collected_ids) -except HPEOneViewException as e: - print(e.msg) + COLLECTED_IDS = ID_POOLS_IPV4_SUBNETS.collect({"idList": ALLOCATED_IDS['idList']}, SUBNET_ID) + pprint(COLLECTED_IDS) +except HPEOneViewException as err: + print(err.msg) print('\nDelete assocaited resource before deleting subnet') -ethernet_network.delete() +ETHERNET_NETWORK.delete() print('\n Delete IPv4 subnet') -ipv4_subnet.delete() +IPV4_SUBNET.delete() print(" Successfully deleted IPv4 subnet") diff --git a/examples/id_pools_vmac_ranges.py b/examples/id_pools_vmac_ranges.py index 6f0bb8bc7..a442ad217 100644 --- a/examples/id_pools_vmac_ranges.py +++ b/examples/id_pools_vmac_ranges.py @@ -20,7 +20,7 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "administrator", @@ -28,19 +28,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) -options = { +OPTIONS = { "type": "Range", "startAddress": "E2:13:C5:F0:00:00", "endAddress": "E2:13:C5:FF:FF:FF", "rangeCategory": "Custom" } -options_additional = { +OPTIONS_ADDITIONAL = { "type": "Range", "name": None, "prefix": None, @@ -57,9 +57,11 @@ "/rest/id-pools/vmac/ranges/5613a502-9253-45c6-aa78-a83635241cf8/collector", "reservedIdCount": 0, "freeFragmentUri": - "/rest/id-pools/vmac/ranges/5613a502-9253-45c6-aa78-a83635241cf8/free-fragments?start=0&count=-1", + "/rest/id-pools/vmac/ranges/5613a502-9253-45c6-aa78-a83635241cf8/free-fragments?start=0&\ + count=-1", "allocatedFragmentUri": - "/rest/id-pools/vmac/ranges/5613a502-9253-45c6-aa78-a83635241cf8/allocated-fragments?start=0&count=-1", + "/rest/id-pools/vmac/ranges/5613a502-9253-45c6-aa78-a83635241cf8/allocated-fragments?start=0\ + &count=-1", "uri": "/rest/id-pools/vmac/ranges/5613a502-9253-45c6-aa78-a83635241cf8", "category": "id-range-VMAC", @@ -70,79 +72,79 @@ } # Create vmac Range for id pools -vmac_range = oneview_client.id_pools_vmac_ranges.create(options) -pprint(vmac_range) +VMAC_RANGE = ONEVIEW_CLIENT.id_pools_vmac_ranges.create(OPTIONS) +pprint(VMAC_RANGE) # Get vmac range by uri -vmac_range_byuri = oneview_client.id_pools_vmac_ranges.get(vmac_range['uri']) -print("Got vmac range from '{}' to '{}' by uri:\n '{}'".format(vmac_range_byuri[ - 'startAddress'], vmac_range_byuri['endAddress'], vmac_range_byuri['uri'])) +VMAC_RANGE_BY_URI = ONEVIEW_CLIENT.id_pools_vmac_ranges.get(VMAC_RANGE['uri']) +print("Got vmac range from '{}' to '{}' by uri:\n '{}'".format(VMAC_RANGE_BY_URI[\ + 'startAddress'], VMAC_RANGE_BY_URI['endAddress'], VMAC_RANGE_BY_URI['uri'])) # Get vmac range by id -vmac_range_byId = oneview_client.id_pools_vmac_ranges.get(vmac_range['uri']) -print("Got vmac range from '{}' to '{}' by uri:\n '{}'".format(vmac_range_byId[ - 'startAddress'], vmac_range_byId['endAddress'], vmac_range_byId['uri'])) +VMAC_RANGE_BY_ID = ONEVIEW_CLIENT.id_pools_vmac_ranges.get(VMAC_RANGE['uri']) +print("Got vmac range from '{}' to '{}' by uri:\n '{}'".format(VMAC_RANGE_BY_ID[\ + 'startAddress'], VMAC_RANGE_BY_ID['endAddress'], VMAC_RANGE_BY_ID['uri'])) # Enable a vMAC range -information = { +INFORMATION = { "type": "Range", "enabled": True } -vmac_range = oneview_client.id_pools_vmac_ranges.enable( - information, vmac_range['uri']) -print("Successfully enabled vmac range at\n 'uri': {}\n with 'enabled': {}".format( - vmac_range['uri'], vmac_range['enabled'])) +VMAC_RANGE = ONEVIEW_CLIENT.id_pools_vmac_ranges.enable( + INFORMATION, VMAC_RANGE['uri']) +print("Successfully enabled vmac range at\n 'uri': {}\n with 'enabled': {}".format(\ + VMAC_RANGE['uri'], VMAC_RANGE['enabled'])) # Allocate a set of IDs from vmac range -information = { +INFORMATION = { "count": 10 } -successfully_allocated_ids = oneview_client.id_pools_vmac_ranges.allocate( - information, vmac_range['uri']) +SUCCESSFULLY_ALLOCATED_IDS = ONEVIEW_CLIENT.id_pools_vmac_ranges.allocate(\ + INFORMATION, VMAC_RANGE['uri']) print("Successfully allocated IDs:") -pprint(successfully_allocated_ids) +pprint(SUCCESSFULLY_ALLOCATED_IDS) # Get all allocated fragments in vmac range print("Get all allocated fragments in vmac range") -allocated_fragments = oneview_client.id_pools_vmac_ranges.get_allocated_fragments( - vmac_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = ONEVIEW_CLIENT.id_pools_vmac_ranges.get_allocated_fragments( + VMAC_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) # Get all free fragments in vmac range print("Get all free fragments in vmac range") -allocated_fragments = oneview_client.id_pools_vmac_ranges.get_free_fragments( - vmac_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = ONEVIEW_CLIENT.id_pools_vmac_ranges.get_free_fragments( + VMAC_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) # Collect a set of IDs back to vmac range try: - information = { - "idList": successfully_allocated_ids['idList'] + INFORMATION = { + "idList": SUCCESSFULLY_ALLOCATED_IDS['idList'] } - successfully_collected_ids = oneview_client.id_pools_vmac_ranges.collect( - information, vmac_range['uri']) -except HPEOneViewException as e: - print(e.msg) + SUCCESSFULLY_COLLECTED_IDS = ONEVIEW_CLIENT.id_pools_vmac_ranges.collect( + INFORMATION, VMAC_RANGE['uri']) +except HPEOneViewException as err: + print(err.msg) # Disable a vmac range -information = { +INFORMATION = { "type": "Range", "enabled": False } -vmac_range = oneview_client.id_pools_vmac_ranges.enable( - information, vmac_range['uri']) +VMAC_RANGE = ONEVIEW_CLIENT.id_pools_vmac_ranges.enable( + INFORMATION, VMAC_RANGE['uri']) print("Successfully disabled vmac range at\n 'uri': {}\n with 'enabled': {}".format( - vmac_range['uri'], vmac_range['enabled'])) + VMAC_RANGE['uri'], VMAC_RANGE['enabled'])) -# Delete vmac_range -oneview_client.id_pools_vmac_ranges.delete(vmac_range) +# Delete VMAC_RANGE +ONEVIEW_CLIENT.id_pools_vmac_ranges.delete(VMAC_RANGE) print("Successfully deleted vmac range") -# Create vmac Range for id pools with more options specified -print("Create vMAC range with more options specified for id pools") -vmac_range = oneview_client.id_pools_vmac_ranges.create(options_additional) -pprint(vmac_range) +# Create vmac Range for id pools with more OPTIONS specified +print("Create vMAC range with more OPTIONS specified for id pools") +VMAC_RANGE = ONEVIEW_CLIENT.id_pools_vmac_ranges.create(OPTIONS_ADDITIONAL) +pprint(VMAC_RANGE) -# Delete vmac_range -oneview_client.id_pools_vmac_ranges.delete(vmac_range) +# Delete VMAC_RANGE +ONEVIEW_CLIENT.id_pools_vmac_ranges.delete(VMAC_RANGE) print("Successfully deleted newly created vMAC range") diff --git a/examples/id_pools_vsn_ranges.py b/examples/id_pools_vsn_ranges.py index c11157602..a352af6f3 100644 --- a/examples/id_pools_vsn_ranges.py +++ b/examples/id_pools_vsn_ranges.py @@ -20,7 +20,7 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "administrator", @@ -28,19 +28,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) -options = { +OPTIONS = { "type": "Range", "startAddress": "VCUS6EI000", "endAddress": "VCUS6EIZZZ", "rangeCategory": "Custom" } -options_additional = { +OPTIONS_ADDITIONAL = { "type": "Range", "name": "VSN", "prefix": None, @@ -58,9 +58,11 @@ "/rest/id-pools/vsn/ranges/ae2df099-5570-4f9e-9503-16531324d9a4/collector", "reservedIdCount": 0, "freeFragmentUri": - "/rest/id-pools/vsn/ranges/ae2df099-5570-4f9e-9503-16531324d9a4/free-fragments?start=0&count=-1", + "/rest/id-pools/vsn/ranges/ae2df099-5570-4f9e-9503-16531324d9a4/free-fragments?start=0&\ + count=-1", "allocatedFragmentUri": - "/rest/id-pools/vsn/ranges/ae2df099-5570-4f9e-9503-16531324d9a4/allocated-fragments?start=0&count=-1", + "/rest/id-pools/vsn/ranges/ae2df099-5570-4f9e-9503-16531324d9a4/allocated-fragments?start=\ + 0&count=-1", "category": "id-range-VSN", "uri": "/rest/id-pools/vsn/ranges/ae2df099-5570-4f9e-9503-16531324d9a4", @@ -70,79 +72,79 @@ } # Create VSN Range for id pools -vsn_range = oneview_client.id_pools_vsn_ranges.create(options) -pprint(vsn_range) +VSN_RANGE = ONEVIEW_CLIENT.id_pools_vsn_ranges.create(OPTIONS) +pprint(VSN_RANGE) # Get vsn range by uri -vsn_range_byuri = oneview_client.id_pools_vsn_ranges.get(vsn_range['uri']) -print("Got vsn range from '{}' to '{}' by uri:\n '{}'".format(vsn_range_byuri[ - 'startAddress'], vsn_range_byuri['endAddress'], vsn_range_byuri['uri'])) +VSN_RANGE_BY_URI = ONEVIEW_CLIENT.id_pools_vsn_ranges.get(VSN_RANGE['uri']) +print("Got vsn range from '{}' to '{}' by uri:\n '{}'".format(VSN_RANGE_BY_URI[\ + 'startAddress'], VSN_RANGE_BY_URI['endAddress'], VSN_RANGE_BY_URI['uri'])) # Get vsn range by id -vsn_range_byId = oneview_client.id_pools_vsn_ranges.get(vsn_range['uri']) -print("Got vsn range from '{}' to '{}' by uri:\n '{}'".format(vsn_range_byId[ - 'startAddress'], vsn_range_byId['endAddress'], vsn_range_byId['uri'])) +VSN_RANGE_BY_ID = ONEVIEW_CLIENT.id_pools_vsn_ranges.get(VSN_RANGE['uri']) +print("Got vsn range from '{}' to '{}' by uri:\n '{}'".format(VSN_RANGE_BY_ID[\ + 'startAddress'], VSN_RANGE_BY_ID['endAddress'], VSN_RANGE_BY_ID['uri'])) # Enable a vSN range -information = { +INFORMATION = { "type": "Range", "enabled": True } -vsn_range = oneview_client.id_pools_vsn_ranges.enable( - information, vsn_range['uri']) -print("Successfully enabled vsn range at\n 'uri': {}\n with 'enabled': {}".format( - vsn_range['uri'], vsn_range['enabled'])) +VSN_RANGE = ONEVIEW_CLIENT.id_pools_vsn_ranges.enable( + INFORMATION, VSN_RANGE['uri']) +print("Successfully enabled vsn range at\n 'uri': {}\n with 'enabled': {}".format(\ + VSN_RANGE['uri'], VSN_RANGE['enabled'])) # Allocate a set of IDs from vsn range -information = { +INFORMATION = { "count": 10 } -successfully_allocated_ids = oneview_client.id_pools_vsn_ranges.allocate( - information, vsn_range['uri']) +SUCCESSFULLY_ALLOCATED_IDS = ONEVIEW_CLIENT.id_pools_vsn_ranges.allocate(\ + INFORMATION, VSN_RANGE['uri']) print("Successfully allocated IDs:") -pprint(successfully_allocated_ids) +pprint(SUCCESSFULLY_ALLOCATED_IDS) # Get all allocated fragments in vsn range print("Get all allocated fragments in vsn range") -allocated_fragments = oneview_client.id_pools_vsn_ranges.get_allocated_fragments( - vsn_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = ONEVIEW_CLIENT.id_pools_vsn_ranges.get_allocated_fragments( + VSN_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) # Get all free fragments in vsn range print("Get all free fragments in vsn range") -allocated_fragments = oneview_client.id_pools_vsn_ranges.get_free_fragments( - vsn_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = ONEVIEW_CLIENT.id_pools_vsn_ranges.get_free_fragments( + VSN_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) # Collect a set of IDs back to vsn range try: - information = { - "idList": successfully_allocated_ids['idList'] + INFORMATION = { + "idList": SUCCESSFULLY_ALLOCATED_IDS['idList'] } - successfully_collected_ids = oneview_client.id_pools_vsn_ranges.collect( - information, vsn_range['uri']) -except HPEOneViewException as e: - print(e.msg) + SUCCESSFULLY_COLLECTED_IDS = ONEVIEW_CLIENT.id_pools_vsn_ranges.collect( + INFORMATION, VSN_RANGE['uri']) +except HPEOneViewException as err: + print(err.msg) # Disable a vsn range -information = { +INFORMATION = { "type": "Range", "enabled": False } -vsn_range = oneview_client.id_pools_vsn_ranges.enable( - information, vsn_range['uri']) +VSN_RANGE = ONEVIEW_CLIENT.id_pools_vsn_ranges.enable( + INFORMATION, VSN_RANGE['uri']) print("Successfully disabled vsn range at\n 'uri': {}\n with 'enabled': {}".format( - vsn_range['uri'], vsn_range['enabled'])) + VSN_RANGE['uri'], VSN_RANGE['enabled'])) -# Delete vsn_range -oneview_client.id_pools_vsn_ranges.delete(vsn_range) +# Delete VSN_RANGE +ONEVIEW_CLIENT.id_pools_vsn_ranges.delete(VSN_RANGE) print("Successfully deleted vsn range") -# Create vsn Range for id pools with more options specified -print("Create vsn range with more options specified for id pools") -vsn_range = oneview_client.id_pools_vsn_ranges.create(options_additional) -pprint(vsn_range) +# Create vsn Range for id pools with more OPTIONS specified +print("Create vsn range with more OPTIONS specified for id pools") +VSN_RANGE = ONEVIEW_CLIENT.id_pools_vsn_ranges.create(OPTIONS_ADDITIONAL) +pprint(VSN_RANGE) -# Delete vsn_range -oneview_client.id_pools_vsn_ranges.delete(vsn_range) +# Delete VSN_RANGE +ONEVIEW_CLIENT.id_pools_vsn_ranges.delete(VSN_RANGE) print("Successfully deleted newly created vsn range") diff --git a/examples/id_pools_vwwn_ranges.py b/examples/id_pools_vwwn_ranges.py index 9ab97cdbc..87081b7dc 100644 --- a/examples/id_pools_vwwn_ranges.py +++ b/examples/id_pools_vwwn_ranges.py @@ -20,7 +20,7 @@ from hpeOneView.exceptions import HPEOneViewException from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "administrator", @@ -28,19 +28,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) -options = { +OPTIONS = { "type": "Range", "startAddress": "10:00:38:9d:20:60:00:00", "endAddress": "10:00:38:9d:20:6f:ff:ff", "rangeCategory": "Custom" } -options_additional = { +OPTIONS_ADDITIONAL = { "type": "Range", "name": "VWWN", "prefix": None, @@ -58,9 +58,11 @@ "/rest/id-pools/vwwn/ranges/daa36872-03b1-463b-aaf7-09d58b650142/collector", "reservedIdCount": 0, "freeFragmentUri": - "/rest/id-pools/vwwn/ranges/daa36872-03b1-463b-aaf7-09d58b650142/free-fragments?start=0&count=-1", + "/rest/id-pools/vwwn/ranges/daa36872-03b1-463b-aaf7-09d58b650142/free-fragments?start=0&\ + count=-1", "allocatedFragmentUri": - "/rest/id-pools/vwwn/ranges/daa36872-03b1-463b-aaf7-09d58b650142/allocated-fragments?start=0&count=-1", + "/rest/id-pools/vwwn/ranges/daa36872-03b1-463b-aaf7-09d58b650142/allocated-fragments?start\ + =0&count=-1", "category": "id-range-VWWN", "uri": "/rest/id-pools/vwwn/ranges/daa36872-03b1-463b-aaf7-09d58b650142", @@ -71,79 +73,79 @@ # Create vwwn Range for id pools print("create vWWN range for id pools") -vwwn_range = oneview_client.id_pools_vwwn_ranges.create(options) -pprint(vwwn_range) +VWWN_RANGE = ONEVIEW_CLIENT.id_pools_vwwn_ranges.create(OPTIONS) +pprint(VWWN_RANGE) # Get vwwn range by uri -vwwn_range_byuri = oneview_client.id_pools_vwwn_ranges.get(vwwn_range['uri']) -print("Got vwwn range from '{}' to '{}' by uri:\n '{}'".format(vwwn_range_byuri[ - 'startAddress'], vwwn_range_byuri['endAddress'], vwwn_range_byuri['uri'])) +VWWN_RANGE_BY_URI = ONEVIEW_CLIENT.id_pools_vwwn_ranges.get(VWWN_RANGE['uri']) +print("Got vwwn range from '{}' to '{}' by uri:\n '{}'".format(VWWN_RANGE_BY_URI[\ + 'startAddress'], VWWN_RANGE_BY_URI['endAddress'], VWWN_RANGE_BY_URI['uri'])) # Get vwwn range by id -vwwn_range_byId = oneview_client.id_pools_vwwn_ranges.get(vwwn_range['uri']) -print("Got vwwn range from '{}' to '{}' by uri:\n '{}'".format(vwwn_range_byId[ - 'startAddress'], vwwn_range_byId['endAddress'], vwwn_range_byId['uri'])) +VWWN_RANGE_BY_ID = ONEVIEW_CLIENT.id_pools_vwwn_ranges.get(VWWN_RANGE['uri']) +print("Got vwwn range from '{}' to '{}' by uri:\n '{}'".format(VWWN_RANGE_BY_ID[\ + 'startAddress'], VWWN_RANGE_BY_ID['endAddress'], VWWN_RANGE_BY_ID['uri'])) # Enable a vWWN range -information = { +INFORMATION = { "type": "Range", "enabled": True } -vwwn_range = oneview_client.id_pools_vwwn_ranges.enable( - information, vwwn_range['uri']) -print("Successfully enabled vwwn range at\n 'uri': {}\n with 'enabled': {}".format( - vwwn_range['uri'], vwwn_range['enabled'])) +VWWN_RANGE = ONEVIEW_CLIENT.id_pools_vwwn_ranges.enable( + INFORMATION, VWWN_RANGE['uri']) +print("Successfully enabled vwwn range at\n 'uri': {}\n with 'enabled': {}".format(\ + VWWN_RANGE['uri'], VWWN_RANGE['enabled'])) # Allocate a set of IDs from vwwn range -information = { +INFORMATION = { "count": 10 } -successfully_allocated_ids = oneview_client.id_pools_vwwn_ranges.allocate( - information, vwwn_range['uri']) +SUCCESSFULLY_ALLOCATED_IDS = ONEVIEW_CLIENT.id_pools_vwwn_ranges.allocate(\ + INFORMATION, VWWN_RANGE['uri']) print("Successfully allocated IDs:") -pprint(successfully_allocated_ids) +pprint(SUCCESSFULLY_ALLOCATED_IDS) # Get all allocated fragments in vwwn range print("Get all allocated fragments in vwwn range") -allocated_fragments = oneview_client.id_pools_vwwn_ranges.get_allocated_fragments( - vwwn_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = ONEVIEW_CLIENT.id_pools_vwwn_ranges.get_allocated_fragments(\ + VWWN_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) # Get all free fragments in vwwn range print("Get all free fragments in vwwn range") -allocated_fragments = oneview_client.id_pools_vwwn_ranges.get_free_fragments( - vwwn_range['uri']) -pprint(allocated_fragments) +ALLOCATED_FRAGMENTS = ONEVIEW_CLIENT.id_pools_vwwn_ranges.get_free_fragments( + VWWN_RANGE['uri']) +pprint(ALLOCATED_FRAGMENTS) # Collect a set of IDs back to vwwn range try: - information = { - "idList": successfully_allocated_ids['idList'] + INFORMATION = { + "idList": SUCCESSFULLY_ALLOCATED_IDS['idList'] } - successfully_collected_ids = oneview_client.id_pools_vwwn_ranges.collect( - information, vwwn_range['uri']) -except HPEOneViewException as e: - print(e.msg) + SUCCESSFULLY_COLLECTED_IDS = ONEVIEW_CLIENT.id_pools_vwwn_ranges.collect( + INFORMATION, VWWN_RANGE['uri']) +except HPEOneViewException as err: + print(err.msg) # Disable a vwwn range -information = { +INFORMATION = { "type": "Range", "enabled": False } -vwwn_range = oneview_client.id_pools_vwwn_ranges.enable( - information, vwwn_range['uri']) +VWWN_RANGE = ONEVIEW_CLIENT.id_pools_vwwn_ranges.enable( + INFORMATION, VWWN_RANGE['uri']) print("Successfully disabled vwwn range at\n 'uri': {}\n with 'enabled': {}".format( - vwwn_range['uri'], vwwn_range['enabled'])) + VWWN_RANGE['uri'], VWWN_RANGE['enabled'])) -# Delete vwwn_range -oneview_client.id_pools_vwwn_ranges.delete(vwwn_range) +# Delete VWWN_RANGE +ONEVIEW_CLIENT.id_pools_vwwn_ranges.delete(VWWN_RANGE) print("Successfully deleted vwwn range") -# Create vwwn Range for id pools with more options specified -print("Create vWWN range with more options specified for id pools") -vwwn_range = oneview_client.id_pools_vwwn_ranges.create(options_additional) -pprint(vwwn_range) +# Create vwwn Range for id pools with more OPTIONS specified +print("Create vWWN range with more OPTIONS specified for id pools") +VWWN_RANGE = ONEVIEW_CLIENT.id_pools_vwwn_ranges.create(OPTIONS_ADDITIONAL) +pprint(VWWN_RANGE) -# Delete vwwn_range -oneview_client.id_pools_vwwn_ranges.delete(vwwn_range) +# Delete VWWN_RANGE +ONEVIEW_CLIENT.id_pools_vwwn_ranges.delete(VWWN_RANGE) print("Successfully deleted newly created vwwn range") diff --git a/examples/index_resources.py b/examples/index_resources.py index db8e840d7..63dba5568 100644 --- a/examples/index_resources.py +++ b/examples/index_resources.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,25 +27,26 @@ } } -attribute = 'Model' -category = 'server-hardware' +ATTRIBUTE = 'Model' +CATEGORY = 'server-hardware' -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -index_resource_obj = oneview_client.index_resources -server_hardware_obj = oneview_client.server_hardware +ONEVIEW_CLIENT = OneViewClient(CONFIG) +INDEX_RESOURCE_OBJ = ONEVIEW_CLIENT.index_resources +SERVER_HARDWARE_OBJ = ONEVIEW_CLIENT.server_hardware print('\nGetting all index resources:') -index_resources = index_resource_obj.get_all() -pprint(index_resources) - -sh = server_hardware_obj.get_all()[0] -print('\nGetting index resource for server hardware with uri "{0}":'.format(sh['uri'])) -index_resource = index_resource_obj.get_by_uri(sh['uri']) -pprint(index_resource.data) - -print('\nGetting aggregated index resources with attribute: "{0}" and category: "{1}"'.format(attribute, category)) -index_resources_aggr = index_resource_obj.get_aggregated(attribute, category) -pprint(index_resources_aggr.data) +INDEX_RESOURCES = INDEX_RESOURCE_OBJ.get_all() +pprint(INDEX_RESOURCES) + +SH = SERVER_HARDWARE_OBJ.get_all()[0] +print('\nGetting index resource for server hardware with uri "{0}":'.format(SH['uri'])) +INDEX_RESOURCE = INDEX_RESOURCE_OBJ.get_by_uri(SH['uri']) +pprint(INDEX_RESOURCE.data) + +print('\nGetting aggregated index resources with ATTRIBUTE: "{0}" and CATEGORY:\ + "{1}"'.format(ATTRIBUTE, CATEGORY)) +INDEX_RESOURCES_AGGR = INDEX_RESOURCE_OBJ.get_aggregated(ATTRIBUTE, CATEGORY) +pprint(INDEX_RESOURCES_AGGR.data) diff --git a/examples/interconnect_link_topologies.py b/examples/interconnect_link_topologies.py index f55ecfa1e..ae2111fda 100644 --- a/examples/interconnect_link_topologies.py +++ b/examples/interconnect_link_topologies.py @@ -22,7 +22,7 @@ # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { "userName": "administrator", @@ -30,38 +30,40 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +ONEVIEW_CLIENT = OneViewClient(CONFIG) # Get all interconnect link topologies print("Get all interconnect link topologies") -interconnect_link_topologies = oneview_client.interconnect_link_topologies.get_all() -pprint(interconnect_link_topologies) +INTERCONNECT_LINK_TOPOLOGIES = ONEVIEW_CLIENT.interconnect_link_topologies.get_all() +pprint(INTERCONNECT_LINK_TOPOLOGIES) # Get all sorting by name descending print("Get all interconnect link topologies sorting by name") -interconnect_link_topologies_sorted = oneview_client.interconnect_link_topologies.get_all(sort='name:descending') -pprint(interconnect_link_topologies_sorted) +INTERCONNECT_LINK_TOPOLOGIES_SORTED = ONEVIEW_CLIENT.interconnect_link_topologies.get_all\ + (sort='name:descending') +pprint(INTERCONNECT_LINK_TOPOLOGIES_SORTED) # Get by uri -if interconnect_link_topologies: +if INTERCONNECT_LINK_TOPOLOGIES: print("Get an interconnect link topology by uri") - ilt_uri = interconnect_link_topologies[0]['uri'] - ilt_byuri = oneview_client.interconnect_link_topologies.get(ilt_uri) - print(" Found '{name}' at uri: {uri}".format(**ilt_byuri)) + ILT_URI = INTERCONNECT_LINK_TOPOLOGIES[0]['uri'] + ILT_BYURI = ONEVIEW_CLIENT.interconnect_link_topologies.get(ILT_URI) + print(" Found '{name}' at uri: {uri}".format(**ILT_BYURI)) # Get by Id -if interconnect_link_topologies: +if INTERCONNECT_LINK_TOPOLOGIES: print("Get an interconnect link topology by id") - ilt_id = re.sub("/rest/interconnect-link-topologies/", '', interconnect_link_topologies[0]['uri']) - ilt_byid = oneview_client.interconnect_link_topologies.get(ilt_id) - print(" Found '{name}' at uri: {uri}".format(**ilt_byid)) + ILT_ID = re.sub("/rest/interconnect-link-topologies/", '', INTERCONNECT_LINK_TOPOLOGIES\ + [0]['uri']) + ILT_BYID = ONEVIEW_CLIENT.interconnect_link_topologies.get(ILT_ID) + print(" Found '{name}' at uri: {uri}".format(**ILT_BYID)) # Get by name -if interconnect_link_topologies: +if INTERCONNECT_LINK_TOPOLOGIES: print("Get an interconnect link topology by name") - ilt_byname = oneview_client.interconnect_link_topologies.get_by( - 'name', interconnect_link_topologies[0]['name'])[0] - print(" Found '{name}' at uri: {uri}".format(**ilt_byname)) + ILT_BYNAME = ONEVIEW_CLIENT.interconnect_link_topologies.get_by( + 'name', INTERCONNECT_LINK_TOPOLOGIES[0]['name'])[0] + print(" Found '{name}' at uri: {uri}".format(**ILT_BYNAME)) diff --git a/examples/interconnect_types.py b/examples/interconnect_types.py index a930f50d8..def82035e 100644 --- a/examples/interconnect_types.py +++ b/examples/interconnect_types.py @@ -17,37 +17,37 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { - "userName": "", + "userName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -interconnect_types = oneview_client.interconnect_types +oneview_client = OneViewClient(CONFIG) +INTERCONNECT_TYPES = oneview_client.INTERCONNECT_TYPES # Get all supported interconnect types print(">>> Get all supported interconnect types") -all_interconnect_types = interconnect_types.get_all() -for interconn in all_interconnect_types: - print(" - {}".format(interconn['name'])) +ALL_INTERCONNECT_TYPES = INTERCONNECT_TYPES.get_all() +for interconn in ALL_INTERCONNECT_TYPES: + print(" - {}".format(interconn['NAME'])) -# Get all sorting by name descending -print(">>> Get all interconnect-types sorting by name") -interconnect_types_sorted = interconnect_types.get_all(sort='name:descending') -for interconn in interconnect_types_sorted: - print(" - {}".format(interconn['name'])) +# Get all sorting by NAME descending +print(">>> Get all interconnect-types sorting by NAME") +INTERCONNECT_TYPES_SORTED = INTERCONNECT_TYPES.get_all(sort='NAME:descending') +for interconn in INTERCONNECT_TYPES_SORTED: + print(" - {}".format(interconn['NAME'])) -# Get by name -print("Get an interconnect_type by name") -if interconnect_types_sorted: - name = interconnect_types_sorted[0]["name"] - interconnect_type_byname = interconnect_types.get_by_name(name) - pprint(interconnect_type_byname.data, depth=1) +# Get by NAME +print("Get an interconnect_type by NAME") +if INTERCONNECT_TYPES_SORTED: + NAME = INTERCONNECT_TYPES_SORTED[0]["NAME"] + INTERCONNECT_TYPE_BYNAME = INTERCONNECT_TYPES.get_by_NAME(NAME) + pprint(INTERCONNECT_TYPE_BYNAME.data, depth=1) diff --git a/examples/interconnects.py b/examples/interconnects.py index 3a085e2b6..d86f3dc17 100644 --- a/examples/interconnects.py +++ b/examples/interconnects.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,172 +28,173 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -interconnects = oneview_client.interconnects +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +INTERCONNECTS = oneview_client.INTERCONNECTS -# To run this example you must define an interconnect, otherwise, it will get the first one automatically -interconnect_uri = interconnects.get_all(0, 1)[0]['uri'] -interconnect_id = interconnect_uri.replace('/rest/interconnects/', '') -interconnect = interconnects.get_by_uri(interconnect_uri) +# To run this example you must define an INTERCONNECT, otherwise, it will get the first one +# automatically +INTERCONNECT_URI = INTERCONNECTS.get_all(0, 1)[0]['uri'] +INTERCONNECT_ID = INTERCONNECT_URI.replace('/rest/INTERCONNECTS/', '') +INTERCONNECT = INTERCONNECTS.get_by_uri(INTERCONNECT_URI) -port_d1 = { +PORT_D1 = { "type": "port", "portName": "d1", "bayNumber": 1, "enabled": False, - "portId": "{0}:d1".format(interconnect_id) + "portId": "{0}:d1".format(INTERCONNECT_ID) } -port_d2 = { +PORT_D2 = { "portName": "d2", "enabled": False, - "portId": "{0}:d2".format(interconnect_id) + "portId": "{0}:d2".format(INTERCONNECT_ID) } -ports_for_update = [port_d1, port_d2] +PORTS_FOR_UPDATE = [PORT_D1, PORT_D2] # Get the first two Interconnects -print("\nGet the first two interconnects") -interconnects_all = interconnects.get_all(0, 2) -pprint(interconnects_all) +print("\nGet the first two INTERCONNECTS") +INTERCONNECTS_ALL = INTERCONNECTS.get_all(0, 2) +pprint(INTERCONNECTS_ALL) # Get Interconnects Statistics -print("\nGet the interconnect statistics") -interconnect_statistics = interconnect.get_statistics() -if interconnect_statistics: - pprint(interconnect_statistics['moduleStatistics']) +print("\nGet the INTERCONNECT STATISTICS") +INTERCONNECT_STATISTICS = INTERCONNECT.get_STATISTICS() +if INTERCONNECT_STATISTICS: + pprint(INTERCONNECT_STATISTICS['moduleStatistics']) else: - pprint("\nThere are no statistics for the interconnect {0}".format(interconnect.data["name"])) + pprint("\nThere are no STATISTICS for the INTERCONNECT {0}".format(INTERCONNECT.data["name"])) # Get the Statistics from a port of an Interconnects -print("\nGet the port statistics for downlink port 1 on the interconnect " +print("\nGet the port STATISTICS for downlink port 1 on the INTERCONNECT " "that matches the specified ID") try: - statistics = interconnect.get_statistics(port_d1["portName"]) - pprint(statistics) + STATISTICS = INTERCONNECT.get_STATISTICS(PORT_D1["portName"]) + pprint(STATISTICS) except HPEOneViewException as e: print(e.msg) # Get the subport Statistics from a port of an Interconnects -print("\nGet the subport statistics for subport 1 on downlink port 2 on the interconnect " +print("\nGet the subport STATISTICS for subport 1 on downlink port 2 on the INTERCONNECT " "that matches the specified ID") try: - statistics = interconnect.get_subport_statistics(port_d1["portName"], - port_d1["bayNumber"]) - pprint(statistics) + STATISTICS = INTERCONNECT.get_subport_STATISTICS(PORT_D1["portName"], + PORT_D1["bayNumber"]) + pprint(STATISTICS) except HPEOneViewException as e: print(e.msg) # Get by hostName -print("\nGet an interconnect by hostName") +print("\nGet an INTERCONNECT by hostName") try: - interconnect_by_host = interconnects.get_by('hostName', interconnect.data["hostName"])[0] - pprint(interconnect_by_host) + INTERCONNECT_BY_HOST = INTERCONNECTS.get_by('hostName', INTERCONNECT.data["hostName"])[0] + pprint(INTERCONNECT_BY_HOST) except HPEOneViewException as e: print(e.msg) # Get by name -print("\nGet an interconnect by name") +print("\nGet an INTERCONNECT by name") try: - interconnect_by_name = interconnects.get_by_name(interconnect.data["name"]) - pprint(interconnect_by_name.data) + INTERCONNECT_BY_NAME = INTERCONNECTS.get_by_name(INTERCONNECT.data["name"]) + pprint(INTERCONNECT_BY_NAME.data) except HPEOneViewException as e: print(e.msg) # Turn the power off -print("\nTurn the power off and the UID light to 'Off' for interconnect " + +print("\nTurn the power off and the UID light to 'Off' for INTERCONNECT " + "that matches the specified ID") try: - interconnect_patch = interconnect.patch( + INTERCONNECT_PATCH = INTERCONNECT.patch( operation='replace', path='/powerState', value='Off' ) - pprint(interconnect_patch.data) + pprint(INTERCONNECT_PATCH.data) except HPEOneViewException as e: print(e.msg) -# Updates an interconnect port. -print("\nUpdate the interconnect port") +# Updates an INTERCONNECT port. +print("\nUpdate the INTERCONNECT port") try: - port_for_update = port_d1.copy() - port_for_update["enabled"] = False + PORT_FOR_UPDATE = PORT_D1.copy() + PORT_FOR_UPDATE["enabled"] = False - updated = interconnect.update_port(port_for_update) - pprint(updated) + UPDATED = INTERCONNECT.update_port(PORT_FOR_UPDATE) + pprint(UPDATED) except HPEOneViewException as e: print(e.msg) # Reset of port protection. -print("\nTrigger a reset of port protection of the interconnect that matches the specified ID") +print("\nTrigger a reset of port protection of the INTERCONNECT that matches the specified ID") try: - result = interconnect.reset_port_protection() - pprint(result) + RESULT = INTERCONNECT.reset_port_protection() + pprint(RESULT) except HPEOneViewException as e: print(e.msg) # Get name servers -print("\nGet the named servers for the interconnect that matches the specified ID") +print("\nGet the named servers for the INTERCONNECT that matches the specified ID") try: - interconnect_ns = interconnect.get_name_servers() - pprint(interconnect_ns) + INTERCONNECT_NS = INTERCONNECT.get_name_servers() + pprint(INTERCONNECT_NS) except HPEOneViewException as e: print(e.msg) -# Get the interconnect ports. +# Get the INTERCONNECT PORTS. try: - print("\nGet all the interconnect ports.") - ports = interconnect.get_ports() - pprint(ports) + print("\nGet all the INTERCONNECT PORTS.") + PORTS = INTERCONNECT.get_PORTS() + pprint(PORTS) - print("\nGet an interconnect port.") - ports = interconnect.get_port(port_d1["portId"]) - pprint(ports) + print("\nGet an INTERCONNECT port.") + PORTS = INTERCONNECT.get_port(PORT_D1["portId"]) + pprint(PORTS) except HPEOneViewException as e: print(e.msg) -# Updates the interconnect ports. -print("\nUpdate the interconnect ports again") +# Updates the INTERCONNECT PORTS. +print("\nUpdate the INTERCONNECT PORTS again") try: - updated = interconnect.update_ports(ports_for_update) + UPDATED = INTERCONNECT.update_PORTS(PORTS_FOR_UPDATE) - # filtering only updated ports - names = [port_d1["portName"], port_d2["portName"]] - updated_ports = [port for port in updated["ports"] if port["portName"] in names] + # filtering only UPDATED PORTS + NAMES = [PORT_D1["portName"], PORT_D2["portName"]] + UPDATED_PORTS = [port for port in UPDATED["PORTS"] if port["portName"] in NAMES] - pprint(updated_ports) + pprint(UPDATED_PORTS) except HPEOneViewException as e: print(e.msg) -# Updates the interconnect configuration. -print("\nUpdate the interconnect configuration") +# Updates the INTERCONNECT CONFIGuration. +print("\nUpdate the INTERCONNECT CONFIGuration") try: - updated = interconnect.update_configuration() - pprint(updated) + UPDATED = INTERCONNECT.update_CONFIGuration() + pprint(UPDATED) except HPEOneViewException as e: print(e.msg) -# Gets the interconnect configuration. -print("\nGet the interconnect pluggable module information") +# Gets the INTERCONNECT CONFIGuration. +print("\nGet the INTERCONNECT pluggable module information") try: - plug_info = interconnect.get_pluggable_module_information() - pprint(plug_info) + PLUG_INFO = INTERCONNECT.get_pluggable_module_information() + pprint(PLUG_INFO) except HPEOneViewException as e: print(e.msg) # Turn the power on -print("\nTurn the power on and the UID light to 'On' for interconnect " + +print("\nTurn the power on and the UID light to 'On' for INTERCONNECT " + "that matches the specified ID") try: - interconnect_patch = interconnect.patch( + INTERCONNECT_PATCH = INTERCONNECT.patch( operation='replace', path='/powerState', value='On' ) - pprint(interconnect_patch.data) + pprint(INTERCONNECT_PATCH.data) except HPEOneViewException as e: print(e.msg) diff --git a/examples/internal_link_sets.py b/examples/internal_link_sets.py index e5a6a26ec..f5b7c0abd 100644 --- a/examples/internal_link_sets.py +++ b/examples/internal_link_sets.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,19 +27,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -internal_link_sets = oneview_client.internal_link_sets +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +INTERNAL_LINK_SETS = oneview_client.INTERNAL_LINK_SETS # Get all, with defaults print("Get all internal-link-sets") -internal_links = internal_link_sets.get_all() -pprint(internal_links) +INTERNAL_LINKS = INTERNAL_LINK_SETS.get_all() +pprint(INTERNAL_LINKS) -internal_link_set_uri = internal_links[0]['uri'] -internal_link_set_name = internal_links[0]['name'] +INTERNAL_LINK_SET_URI = INTERNAL_LINKS[0]['uri'] +INTERNAL_LINK_SET_NAME = INTERNAL_LINKS[0]['name'] # Find by name -internal_links_by_name = internal_link_sets.get_by_name(internal_links[0]["name"]) -print("\nFound the internal-link-sets by name: '{}':".format(internal_links_by_name.data["name"])) +INTERNAL_LINKS_BY_NAME = INTERNAL_LINK_SETS.get_by_name(INTERNAL_LINKS[0]["name"]) +print("\nFound the internal-link-sets by name: '{}':".format(INTERNAL_LINKS_BY_NAME.data["name"])) diff --git a/examples/labels.py b/examples/labels.py index bf0079b2f..8a183383b 100644 --- a/examples/labels.py +++ b/examples/labels.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,53 +27,53 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -label = oneview_client.labels +oneview_client = OneViewClient(CONFIG) +LABEL = oneview_client.LABELs -resource_uri = "/rest/enclosures/0000000000A66102" +RESOURCE_URI = "/rest/enclosures/0000000000A66102" -print("\nSet the labels assigned to a resource") -labels_to_create = dict( - resourceUri=resource_uri, - labels=["labelSample", "enclosureDemo"] +print("\nSet the LABELs assigned to a resource") +LABELS_TO_CREATE = dict( + resourceUri=RESOURCE_URI, + LABELs=["LABELSample", "enclosureDemo"] ) -resource_labels = label.create(labels_to_create) -pprint(resource_labels.data) +RESOURCE_LABELS = LABEL.create(LABELS_TO_CREATE) +pprint(RESOURCE_LABELS.data) -print("\nGet all labels") -all_labels = label.get_all(category=['fc-networks', 'enclosures'], name_prefix="label") -pprint(all_labels) +print("\nGet all LABELs") +ALL_LABELS = LABEL.get_all(category=['fc-networks', 'enclosures'], name_prefix="LABEL") +pprint(ALL_LABELS) -label_name = all_labels[0]["name"] -print("\nGet a label by name: ", label_name) -label_by_name = label.get_by_name(label_name) -pprint(label_by_name.data) +LABEL_NAME = ALL_LABELS[0]["name"] +print("\nGet a LABEL by name: ", LABEL_NAME) +LABEL_BY_NAME = LABEL.get_by_name(LABEL_NAME) +pprint(LABEL_BY_NAME.data) -label_uri = all_labels[0]["uri"] -print("\nGet a label by uri: ", label_uri) -label_by_uri = label.get_by_uri(label_uri) -pprint(label_by_uri.data) +LABEL_URI = ALL_LABELS[0]["uri"] +print("\nGet a LABEL by uri: ", LABEL_URI) +LABEL_BY_URI = LABEL.get_by_uri(LABEL_URI) +pprint(LABEL_BY_URI.data) -print("\nGet all the labels for the resource %s" % resource_uri) -labels_by_resource = label.get_by_resource(resource_uri) -pprint(labels_by_resource.data) +print("\nGet all the LABELs for the resource %s" % RESOURCE_URI) +LABELS_BY_RESOURCE = LABEL.get_by_resource(RESOURCE_URI) +pprint(LABELS_BY_RESOURCE.data) -print("\nGets all resources assigned with label name: "), all_labels[0]["name"] -assigned_resources = label.get_assigned_resources(all_labels[0]["name"]) -pprint(assigned_resources) +print("\nGets all resources assigned with LABEL name: "), ALL_LABELS[0]["name"] +ASSIGNED_RESOURCES = LABEL.get_ASSIGNED_RESOURCES(ALL_LABELS[0]["name"]) +pprint(ASSIGNED_RESOURCES) -print("\nUpdate the resource labels") -labels_to_update = dict( - labels=[ - dict(name="renamed label", uri=labels_by_resource.data['labels'][0]['uri']), +print("\nUpdate the resource LABELs") +LABELS_TO_UPDATE = dict( + LABELs=[ + dict(name="renamed LABEL", uri=LABELS_BY_RESOURCE.data['LABELs'][0]['uri']), dict(name="enclosureDemo1") ] ) -updated_resource_labels = labels_by_resource.update(labels_to_update) -pprint(updated_resource_labels.data) +UPDATED_RESOURCE_LABELS = LABELS_BY_RESOURCE.update(LABELS_TO_UPDATE) +pprint(UPDATED_RESOURCE_LABELS.data) -print("\nDelete all the labels for a resource") -labels_by_resource.delete() +print("\nDelete all the LABELs for a resource") +LABELS_BY_RESOURCE.delete() diff --git a/examples/logger.py b/examples/logger.py index 4e327e479..12bb05551 100644 --- a/examples/logger.py +++ b/examples/logger.py @@ -17,25 +17,25 @@ import logging -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient """ -hpeOneView do not add any handlers other than NullHandler. -The configuration of handlers is the prerogative of the developer who uses hpeOneView library. +hpeOneView do not add any HANDLERs other than NullHandler. +The CONFIGuration of HANDLERs is the prerogative of the developer who uses hpeOneView library. This example uses a StreamHandler to send the logging output to streams sys.stdout and sys.stderr. """ -logger = logging.getLogger('hpeOneView') +LOGGER = logging.getLogger('hpeOneView') -handler = logging.StreamHandler() -formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)-12s %(message)s') -handler.setFormatter(formatter) -logger.addHandler(handler) -logger.setLevel(logging.DEBUG) +HANDLER = logging.StreamHandler() +FORMATTER = logging.Formatter('%(asctime)s %(levelname)-8s %(name)-12s %(message)s') +HANDLER.setFormatter(FORMATTER) +LOGGER.addHandler(HANDLER) +LOGGER.setLevel(logging.DEBUG) -config = { +CONFIG = { "ip": "172.16.102.59", "credentials": { "userName": "administrator", @@ -43,20 +43,20 @@ } } -options = { +OPTIONS = { "name": "OneViewSDK Test FC Network", "connectionTemplateUri": None, "autoLoginRedistribution": True, "fabricType": "FabricAttach", } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Create a FC Network -fc_network = oneview_client.fc_networks.create(options) +fc_network = oneview_client.fc_networks.create(OPTIONS) # Find recently created network by name fc_network = oneview_client.fc_networks.get_by('name', 'OneViewSDK Test FC Network')[0] @@ -68,7 +68,8 @@ # Get all, with defaults fc_nets = oneview_client.fc_networks.get_all() # Filter by name -fc_nets_filtered = oneview_client.fc_networks.get_all(filter="\"'name'='OneViewSDK Test FC Network'\"") +fc_nets_filtered = oneview_client.fc_networks.get_all(filter="\"'name'='OneViewSDK Test FC + Network'\"") # Get all sorting by name descending fc_nets_sorted = oneview_client.fc_networks.get_all(sort='name:descending') diff --git a/examples/logical_downlinks.py b/examples/logical_downlinks.py index 308263fee..24c1335bd 100644 --- a/examples/logical_downlinks.py +++ b/examples/logical_downlinks.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,50 +28,50 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # An existent Logical Downlink ID is required to run this example -logical_downlink_id = '5b0f2e7a-394f-47e9-aed0-e4be225e0e19' -logical_downlink_name = 'LD49f094dd-1732-48c5-9aa8-2ff827578887 (HP VC FlexFabric-20/40 F8 Module)' +LOGICAL_DOWNLINK_ID = '5b0f2e7a-394f-47e9-aed0-e4be225e0e19' +LOGICAL_DOWNLINK_NAME = 'LD49f094dd-1732-48c5-9aa8-2ff827578887 (HP VC FlexFabric-20/40 F8 Module)' # Get logical downlink by id try: print("\nGet logical downlink by id") - log_downlink = oneview_client.logical_downlinks.get(logical_downlink_id) - pprint(log_downlink) + LOG_DOWNLINK = oneview_client.logical_downlinks.get(LOGICAL_DOWNLINK_ID) + pprint(LOG_DOWNLINK) except HPEOneViewException as e: print(e.msg) # Get logical downlink by id without Ethernet networks try: print("\nGet logical downlink by id without Ethernet networks") - log_downlink_without_ethernet = oneview_client.logical_downlinks.get_without_ethernet(logical_downlink_id) - pprint(log_downlink_without_ethernet) + LOG_DOWNLINK_without_ethernet = oneview_client.logical_downlinks.get_without_ethernet(LOGICAL_DOWNLINK_ID) + pprint(LOG_DOWNLINK_without_ethernet) except HPEOneViewException as e: print(e.msg) # Get logical downlink by name try: print("\nGet logical downlink by name") - log_downlink_by_name = oneview_client.logical_downlinks.get_by('name', logical_downlink_name) - pprint(log_downlink_by_name) + LOG_DOWNLINK_by_name = oneview_client.logical_downlinks.get_by('name', LOGICAL_DOWNLINK_NAME) + pprint(LOG_DOWNLINK_by_name) except HPEOneViewException as e: print(e.msg) # Get all logical downlinks print("\nGet all logical downlinks") -log_downlinks = oneview_client.logical_downlinks.get_all() -pprint(log_downlinks) +LOG_DOWNLINKs = oneview_client.logical_downlinks.get_all() +pprint(LOG_DOWNLINKs) # Get all sorting by name descending print("\nGet all logical downlinks sorting by name") -log_downlinks_sorted = oneview_client.logical_downlinks.get_all(sort='name:descending') -pprint(log_downlinks_sorted) +LOG_DOWNLINKs_sorted = oneview_client.logical_downlinks.get_all(sort='name:descending') +pprint(LOG_DOWNLINKs_sorted) # Get all logical downlinks without Ethernet print("\nGet all logical downlinks without Ethernet") -log_downlinks_without_ethernet = oneview_client.logical_downlinks.get_all_without_ethernet() -pprint(log_downlinks_without_ethernet) +LOG_DOWNLINKs_without_ethernet = oneview_client.logical_downlinks.get_all_without_ethernet() +pprint(LOG_DOWNLINKs_without_ethernet) diff --git a/examples/logical_enclosures.py b/examples/logical_enclosures.py index 2a68e0e12..ca8c39aff 100644 --- a/examples/logical_enclosures.py +++ b/examples/logical_enclosures.py @@ -19,9 +19,9 @@ from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,155 +29,156 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) -enclosure_groups = oneview_client.enclosure_groups +ENCLOSURE_GROUPs = oneview_client.ENCLOSURE_GROUPs enclosures = oneview_client.enclosures -logical_enclosures = oneview_client.logical_enclosures -scopes = oneview_client.scopes -firmware_drivers = oneview_client.firmware_drivers +LOGICAL_ENCLOSUREs = oneview_client.LOGICAL_ENCLOSUREs +SCOPEs = oneview_client.SCOPEs +FIRMWARE_DRIVERs = oneview_client.FIRMWARE_DRIVERs # The valid enclosure URIs need to be inserted sorted by URI # The number of enclosure URIs must be equal to the enclosure count in the enclosure group -options = dict( +OPTIONS = dict( enclosureUris=[], enclosureGroupUri="EG", forceInstallFirmware=False, name="LE" ) -variant = 'synergy' -scope_name = 'test_scope' -firmware_driver_name = "SPP_2018_06_20180709_for_HPE_Synergy_Z7550-96524" +VARIANT = 'synergy' +SCOPE_NAME = 'test_SCOPE' +FIRMWARE_DRIVER_NAME = "SPP_2018_06_20180709_for_HPE_Synergy_Z7550-96524" -# Create scope -scope_options = { - "name": scope_name, - "description": "Sample Scope description" +# Create SCOPE +SCOPE_OPTIONS = { + "name": SCOPE_NAME, + "deSCRIPTion": "Sample Scope deSCRIPTion" } -scope = scopes.get_by_name(scope_name) -if scope: - print("Scope '{}' already exists".format(scope_name)) +SCOPE = SCOPEs.get_by_name(SCOPE_NAME) +if SCOPE: + print("Scope '{}' already exists".format(SCOPE_NAME)) else: - print(" Creating the scope '{}'".format(scope_name)) - scope = scopes.create(scope_options) + print(" Creating the SCOPE '{}'".format(SCOPE_NAME)) + SCOPE = SCOPEs.create(SCOPE_OPTIONS) # Get all logical enclosures print("Get all logical enclosures") -logical_enclosures_all = logical_enclosures.get_all() -for enc in logical_enclosures_all: +LOGICAL_ENCLOSURES_ALL = LOGICAL_ENCLOSUREs.get_all() +for enc in LOGICAL_ENCLOSURES_ALL: print(' %s' % enc['name']) # Get first logical enclosure -logical_enclosure_all = logical_enclosures.get_all() -if logical_enclosure_all: - logical_enclosure = logical_enclosure_all[0] +LOGICAL_ENCLOSURE_ALL = LOGICAL_ENCLOSUREs.get_all() +if LOGICAL_ENCLOSURE_ALL: + LOGICAL_ENCLOSURE = LOGICAL_ENCLOSURE_ALL[0] print("Found logical enclosure '{}' at\n uri: '{}'".format( - logical_enclosure['name'], logical_enclosure['uri'])) + LOGICAL_ENCLOSURE['name'], LOGICAL_ENCLOSURE['uri'])) # Get logical enclosure by uri - logical_enclosure = logical_enclosures.get_by_uri(logical_enclosure['uri']) + LOGICAL_ENCLOSURE = LOGICAL_ENCLOSUREs.get_by_uri(LOGICAL_ENCLOSURE['uri']) print("Got logical enclosure '{}' by\n uri: '{}'".format( - logical_enclosure.data['name'], logical_enclosure.data['uri'])) + LOGICAL_ENCLOSURE.data['name'], LOGICAL_ENCLOSURE.data['uri'])) -# Get Logical Enclosure by scope_uris +# Get Logical Enclosure by SCOPE_uris if oneview_client.api_version >= 600: - le_by_scope_uris = logical_enclosures.get_all(scope_uris=scope.data['uri']) - if len(le_by_scope_uris) > 0: - print("Got Logical Enclosure by scope_uris: '%s'.\n uri = '%s'" % (le_by_scope_uris[0]['name'], le_by_scope_uris[0]['uri'])) - pprint(le_by_scope_uris) + le_by_SCOPE_uris = LOGICAL_ENCLOSUREs.get_all(SCOPE_uris=SCOPE.data['uri']) + if len(le_by_SCOPE_uris) > 0: + print("Got Logical Enclosure by SCOPE_uris: '%s'.\n uri = '%s'" % (le_by_SCOPE_uris[0]['name'], le_by_SCOPE_uris[0]['uri'])) + pprint(le_by_SCOPE_uris) else: - print("No Logical Enclosure found by scope_uris") + print("No Logical Enclosure found by SCOPE_uris") # Get Logical Enclosure by name -logical_enclosure = logical_enclosures.get_by_name(options["name"]) -if not logical_enclosure: +LOGICAL_ENCLOSURE = LOGICAL_ENCLOSUREs.get_by_name(OPTIONS["name"]) +if not LOGICAL_ENCLOSURE: # Get enclosure group uri for creating logical enclosure - enclosure_group = enclosure_groups.get_by_name(options['enclosureGroupUri']) - options["enclosureGroupUri"] = enclosure_group.data["uri"] - enclosure_count = enclosure_group.data["enclosureCount"] + ENCLOSURE_GROUP = ENCLOSURE_GROUPs.get_by_name(OPTIONS['enclosureGroupUri']) + OPTIONS["enclosureGroupUri"] = ENCLOSURE_GROUP.data["uri"] + ENCLOSURE_COUNT = ENCLOSURE_GROUP.data["enclosureCount"] # Get enclosures - enclosures_all = enclosures.get_all() - enclosure_uris = [] - for i in range(0, enclosure_count): - enclosure_uris.append(enclosures_all[i]["uri"]) - options["enclosureUris"] = sorted(enclosure_uris) - print(options) + ENCLOSURES_ALL = enclosures.get_all() + ENCLOSURE_URIS = [] + for i in range(0, ENCLOSURE_COUNT): + ENCLOSURE_URIS.append(ENCLOSURES_ALL[i]["uri"]) + OPTIONS["enclosureUris"] = sorted(ENCLOSURE_URIS) + print(OPTIONS) # Create a logical enclosure # This method is only available on HPE Synergy. try: - logical_enclosure = logical_enclosures.create(options) + LOGICAL_ENCLOSURE = LOGICAL_ENCLOSUREs.create(OPTIONS) print("Created logical enclosure'%s' successfully.\n uri = '%s'" % ( - logical_enclosure.data['name'], - logical_enclosure.data['uri']) + LOGICAL_ENCLOSURE.data['name'], + LOGICAL_ENCLOSURE.data['uri']) ) except HPEOneViewException as e: print(e.msg) # Update the logical enclosure name print("Update the logical enclosure to have a name of '%s'" % - options["name"]) -resource = logical_enclosure.data.copy() -previous_name = resource["name"] -resource["name"] = resource["name"] + "-Renamed" -logical_enclosure.update(resource) + OPTIONS["name"]) +RESOURCE = LOGICAL_ENCLOSURE.data.copy() +PREVIOUS_NAME = RESOURCE["name"] +RESOURCE["name"] = RESOURCE["name"] + "-Renamed" +LOGICAL_ENCLOSURE.update(RESOURCE) print(" Done. uri: '%s', 'name': '%s'" % - (logical_enclosure.data['uri'], logical_enclosure.data['name'])) + (LOGICAL_ENCLOSURE.data['uri'], LOGICAL_ENCLOSURE.data['name'])) print("Reset name") -resource = logical_enclosure.data.copy() -resource["name"] = previous_name -logical_enclosure.update(resource) +RESOURCE = LOGICAL_ENCLOSURE.data.copy() +RESOURCE["name"] = PREVIOUS_NAME +LOGICAL_ENCLOSURE.update(RESOURCE) print(" Done. uri: '%s', 'name': '%s'" % - (logical_enclosure.data['uri'], - logical_enclosure.data['name'])) + (LOGICAL_ENCLOSURE.data['uri'], + LOGICAL_ENCLOSURE.data['name'])) -# Update configuration -print("Reapply the appliance's configuration to the logical enclosure") -logical_enclosure.update_configuration() +# Update CONFIGuration +print("Reapply the appliance's CONFIGuration to the logical enclosure") +LOGICAL_ENCLOSURE.update_CONFIGuration() print(" Done.") -# Update and get script +# Update and get SCRIPT # This method is available for API version 300 in synergy and in all API versions in c7000 -if variant == 'synergy' and oneview_client.api_version == 300: - print("Update script") - script = "# TEST COMMAND" - logical_enclosure_updated = logical_enclosure.update_script(logical_enclosure.data['uri'], script) - print(" updated script: '{}'".format(logical_enclosure.get_script())) +if VARIANT == 'synergy' and oneview_client.api_version == 300: + print("Update SCRIPT") + SCRIPT = "# TEST COMMAND" + LOGICAL_ENCLOSURE_updated = LOGICAL_ENCLOSURE.update_SCRIPT(LOGICAL_ENCLOSURE.data['uri'], SCRIPT) + print(" updated SCRIPT: '{}'".format(LOGICAL_ENCLOSURE.get_SCRIPT())) # Create support dumps print("Generate support dump") -info = { +INFO = { "errorCode": "MyDump16", "encrypt": True, "excludeApplianceDump": False } -support_dump = logical_enclosure.generate_support_dump(info) +SUPPORT_DUMP = LOGICAL_ENCLOSURE.generate_SUPPORT_DUMP(INFO) print(" Done") # update from group try: print("Update from group") - logical_enclosure_updated = logical_enclosure.update_from_group() + LOGICAL_ENCLOSURE_updated = LOGICAL_ENCLOSURE.update_from_group() print(" Done") except Exception as e: print(e) # Replace firmware of LE -firmware_driver = firmware_drivers.get_by('name', firmware_driver_name) +FIRMWARE_DRIVER = FIRMWARE_DRIVERs.get_by('name', FIRMWARE_DRIVER_NAME) if oneview_client.api_version >= 300: - if logical_enclosure and len(firmware_driver) != 0: - print("Update firmware for a logical enclosure with the logical-interconnect validation set as true.") + if LOGICAL_ENCLOSURE and len(FIRMWARE_DRIVER) != 0: + print("Update firmware for a logical enclosure with the logical-interconnect validation set + as true.") - logical_enclosure_updated = logical_enclosure.patch( + LOGICAL_ENCLOSURE_updated = LOGICAL_ENCLOSURE.patch( operation="replace", path="/firmware", value={ - "firmwareBaselineUri": firmware_driver[0]['uri'], + "firmwareBaselineUri": FIRMWARE_DRIVER[0]['uri'], "firmwareUpdateOn": "EnclosureOnly", "forceInstallFirmware": "true", "validateIfLIFirmwareUpdateIsNonDisruptive": "true", @@ -186,9 +187,9 @@ }, custom_headers={"if-Match": "*"} ) - pprint(logical_enclosure_updated.data) + pprint(LOGICAL_ENCLOSURE_updated.data) -# Delete the logical enclosure created (commented this to achieve continuty of automation script execution) +# Delete the logical enclosure created (commented this to achieve continuty of automation SCRIPT execution) # This method is only available on HPE Synergy. -# logical_enclosure.delete() +# LOGICAL_ENCLOSURE.delete() # print("Delete logical enclosure") diff --git a/examples/logical_interconnect_groups.py b/examples/logical_interconnect_groups.py index e8f4b15e4..d0a65ecbc 100644 --- a/examples/logical_interconnect_groups.py +++ b/examples/logical_interconnect_groups.py @@ -18,10 +18,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,53 +29,53 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) logical_interconnect_groups = oneview_client.logical_interconnect_groups interconnect_types = oneview_client.interconnect_types -scopes = oneview_client.scopes +SCOPEs = oneview_client.SCOPEs ethernet_networks = oneview_client.ethernet_networks fc_networks = oneview_client.fc_networks -# Define the scope name to add the logical interconnect group to it -iscsi_network = "iscsi_nw" # iscsi network for image streamer uplinkset -mgmt_untagged = "mgmt_nw" # untagged managament network -fc_fabric = "FC_fabric_nw" # Fabric attach FC network -scope_name = "test_scope" -interconnect_type_name1 = "Virtual Connect SE 40Gb F8 Module for Synergy" -interconnect_type_name2 = "Synergy 20Gb Interconnect Link Module" +# Define the SCOPE name to add the logical interconnect group to it +ISCSI_NETWORK = "iscsi_nw" # iscsi network for image streamer uplinkset +MGMT_UNTAGGED = "mgmt_nw" # untagged managament network +FC_FABRIC = "FC_fabric_nw" # Fabric attach FC network +SCOPE_NAME = "test_SCOPE" +INTERCONNECT_TYPE_NAME1 = "Virtual Connect SE 40Gb F8 Module for Synergy" +INTERCONNECT_TYPE_NAME2 = "Synergy 20Gb Interconnect Link Module" # Get the interconnect type by name and using the uri in the values for the fields # "permittedInterconnectTypeUri" and create a Logical Interconnect Group. # Note: If this type does not exist, select another name -interconnect_type_1 = interconnect_types.get_by_name(interconnect_type_name1) -interconnect_type_2 = interconnect_types.get_by_name(interconnect_type_name2) -interconnect_type1_uri = interconnect_type_1.data["uri"] -interconnect_type2_uri = interconnect_type_2.data["uri"] +INTERCONNECT_TYPE_1 = interconnect_types.get_by_name(INTERCONNECT_TYPE_NAME1) +INTERCONNECT_TYPE_2 = interconnect_types.get_by_name(INTERCONNECT_TYPE_NAME2) +INTERCONNECT_TYPE1_URI = INTERCONNECT_TYPE_1.data["uri"] +INTERCONNECT_TYPE2_URI = INTERCONNECT_TYPE_2.data["uri"] # Get the ethernet network uri by name -eth_nw1 = ethernet_networks.get_by_name(iscsi_network) -iscsi_network_uri = eth_nw1.data['uri'] -eth_nw2 = ethernet_networks.get_by_name(mgmt_untagged) -mgmt_untagged_uri = eth_nw2.data['uri'] -fc_nw = fc_networks.get_by_name(fc_fabric) -fc_network_uri = fc_nw.data['uri'] +ETH_NW1 = ethernet_networks.get_by_name(ISCSI_NETWORK) +ISCSI_NETWORK_URI = ETH_NW1.data['uri'] +ETH_NW2 = ethernet_networks.get_by_name(MGMT_UNTAGGED) +MGMT_UNTAGGED_URI = ETH_NW2.data['uri'] +FC_NW = fc_networks.get_by_name(FC_FABRIC) +FC_NETWORK_URI = FC_NW.data['uri'] -# Create scope -scope_options = { - "name": scope_name, +# Create SCOPE +SCOPE_OPTIONS = { + "name": SCOPE_NAME, "description": "Sample Scope description" } -scope = scopes.get_by_name(scope_options["name"]) -if scope: - print("Scope '{}' already exists".format(scope_name)) +SCOPE = SCOPEs.get_by_name(SCOPE_OPTIONS["name"]) +if SCOPE: + print("Scope '{}' already exists".format(SCOPE_NAME)) else: - print("Creating the scope '{}'".format(scope_name)) - scope = scopes.create(scope_options) + print("Creating the SCOPE '{}'".format(SCOPE_NAME)) + SCOPE = SCOPEs.create(SCOPE_OPTIONS) # LIG payload -options = { +OPTIONS = { "name": "LIG", "interconnectMapTemplate": { "interconnectMapEntryTemplates": [ @@ -92,7 +92,7 @@ } ] }, - "permittedInterconnectTypeUri": interconnect_type1_uri, + "permittedInterconnectTypeUri": INTERCONNECT_TYPE1_URI, "enclosureIndex": 1 }, { @@ -108,7 +108,7 @@ } ] }, - "permittedInterconnectTypeUri": interconnect_type1_uri, + "permittedInterconnectTypeUri": INTERCONNECT_TYPE1_URI, "enclosureIndex": 2 }, { @@ -124,7 +124,7 @@ } ] }, - "permittedInterconnectTypeUri": interconnect_type2_uri, + "permittedInterconnectTypeUri": INTERCONNECT_TYPE2_URI, "enclosureIndex": 1 }, { @@ -140,7 +140,7 @@ } ] }, - "permittedInterconnectTypeUri": interconnect_type2_uri, + "permittedInterconnectTypeUri": INTERCONNECT_TYPE2_URI, "enclosureIndex": 2 }, { @@ -156,7 +156,7 @@ } ] }, - "permittedInterconnectTypeUri": interconnect_type2_uri, + "permittedInterconnectTypeUri": INTERCONNECT_TYPE2_URI, "enclosureIndex": 3 }, { @@ -172,7 +172,7 @@ } ] }, - "permittedInterconnectTypeUri": interconnect_type2_uri, + "permittedInterconnectTypeUri": INTERCONNECT_TYPE2_URI, "enclosureIndex": 3 } ] @@ -180,7 +180,7 @@ "uplinkSets": [ { "networkType": "FibreChannel", - "networkUris": [fc_network_uri], + "networkUris": [FC_NETWORK_URI], "mode": "Auto", "name": "FC_fabric", "logicalPortConfigInfos": [ @@ -228,7 +228,7 @@ "ethernetNetworkType": "NotApplicable", }, { - "networkUris": [iscsi_network_uri], + "networkUris": [ISCSI_NETWORK_URI], "mode": "Auto", "logicalPortConfigInfos": [ { @@ -313,7 +313,7 @@ "name": "deploy" }, { - "networkUris": [mgmt_untagged_uri], + "networkUris": [MGMT_UNTAGGED_URI], "mode": "Auto", "logicalPortConfigInfos": [ { @@ -367,78 +367,81 @@ } # Get logical interconnect group by name -lig = logical_interconnect_groups.get_by_name(options["name"]) -if not lig: +LIG = logical_interconnect_groups.get_by_name(OPTIONS["name"]) +if not LIG: # Create a logical interconnect group print("Create a logical interconnect group") - lig = logical_interconnect_groups.create(options) - print("Created logical interconnect group with name - '{}' and uri - '{}'".format(lig.data['name'], lig.data['uri'])) + LIG = logical_interconnect_groups.create(OPTIONS) + print("Created logical interconnect group with name - '{}' and uri - + '{}'".format(LIG.data['name'], LIG.data['uri'])) # Get all, with defaults print("Get all Logical Interconnect Groups") -ligs = logical_interconnect_groups.get_all() -for lig_each in ligs: - print(" - {}".format(lig_each['name'])) +LIGS = logical_interconnect_groups.get_all() +for LIG_each in LIGS: + print(" - {}".format(LIG_each['name'])) # Get by uri print("Get a Logical Interconnect Group by uri") -lig_by_uri = logical_interconnect_groups.get_by_uri(ligs[0]["uri"]) -pprint(lig_by_uri.data) +LIG_BY_URI = logical_interconnect_groups.get_by_uri(LIGS[0]["uri"]) +pprint(LIG_BY_URI.data) # Get the first 10 records, sorting by name descending, filtering by name print("Get the first Logical Interconnect Groups, sorting by name descending, filtering by name") -ligs = logical_interconnect_groups.get_all( +LIGS = logical_interconnect_groups.get_all( 0, 10, sort='name:descending', filter="\"'name'='OneView Test Logical Interconnect Group'\"") -for lig_each in ligs: - print(" - {}".format(lig_each['name'])) +for LIG_each in LIGS: + print(" - {}".format(LIG_each['name'])) # Get Logical Interconnect Group by property -lig_prop = logical_interconnect_groups.get_by('name', 'LIG')[0] -print("Found lig by name: '%s'.\n uri = '%s'" % (lig_prop['name'], lig_prop['uri'])) +LIG_PROP = logical_interconnect_groups.get_by('name', 'LIG')[0] +print("Found LIG by name: '%s'.\n uri = '%s'" % (LIG_PROP['name'], LIG_PROP['uri'])) -# Get Logical Interconnect Group by scope_uris +# Get Logical Interconnect Group by SCOPE_uris if oneview_client.api_version >= 600: - lig_by_scope_uris = logical_interconnect_groups.get_all(scope_uris=scope.data['uri']) - if len(lig_by_scope_uris) > 0: - print("Found {} Logical Interconnect Groups".format(len(lig_by_scope_uris))) - for lig_scope in lig_by_scope_uris: - print("Found Logical Interconnect Group by scope_uris: '{}'.\n uri = '{}'".format(lig_scope['name'], lig_scope['uri'])) + LIG_BY_SCOPE_URIS = logical_interconnect_groups.get_all(SCOPE_uris=SCOPE.data['uri']) + if len(LIG_BY_SCOPE_URIS) > 0: + print("Found {} Logical Interconnect Groups".format(len(LIG_BY_SCOPE_URIS))) + for LIG_SCOPE in LIG_BY_SCOPE_URIS: + print("Found Logical Interconnect Group by SCOPE_uris: '{}'.\n uri = + '{}'".format(LIG_SCOPE['name'], LIG_SCOPE['uri'])) else: print("No Logical Interconnect Group found.") # Update a logical interconnect group print("Update a logical interconnect group") -lig_to_update = lig.data.copy() -lig_to_update["name"] = "Renamed Logical Interconnect Group" -lig.update(lig_to_update) -pprint(lig.data) +LIG_TO_UPDATE = LIG.data.copy() +LIG_TO_UPDATE["name"] = "Renamed Logical Interconnect Group" +LIG.update(LIG_TO_UPDATE) +pprint(LIG.data) # Performs a patch operation if oneview_client.api_version <= 500: - scope = oneview_client.scopes.get_by_name(scope_name) - if scope: - print("\nPatches the logical interconnect group adding one scope to it") - updated_lig = lig.patch('replace', - '/scopeUris', - [scope.data['uri']]) - pprint(updated_lig.data) + SCOPE = oneview_client.SCOPEs.get_by_name(SCOPE_NAME) + if SCOPE: + print("\nPatches the logical interconnect group adding one SCOPE to it") + UPDATED_LIG = LIG.patch('replace', + '/SCOPEUris', + [SCOPE.data['uri']]) + pprint(UPDATED_LIG.data) # Get default settings print("Get the default interconnect settings for a logical interconnect group") -lig_default_settings = lig.get_default_settings() -pprint(lig_default_settings) +LIG_DEFAULT_SETTINGS = LIG.get_default_settings() +pprint(LIG_DEFAULT_SETTINGS) # Get settings print("Gets the interconnect settings for a logical interconnect group") -lig_settings = lig.get_settings() -pprint(lig_settings) +LIG_SETTINGS = LIG.get_settings() +pprint(LIG_SETTINGS) # Delete a logical interconnect group print("Delete the created logical interconnect group") -lig.delete() +LIG.delete() print("Successfully deleted logical interconnect group") # Create a logical interconnect group for automation print("Create a logical interconnect group as a pre-requisite for LE creation") -lig = logical_interconnect_groups.create(options) -print("Created logical interconnect group with name - '{}' and uri - '{}'".format(lig.data['name'], lig.data['uri'])) +LIG = logical_interconnect_groups.create(OPTIONS) +print("Created logical interconnect group with name - '{}' and uri - '{}'".format(LIG.data['name'], + LIG.data['uri'])) diff --git a/examples/logical_interconnects.py b/examples/logical_interconnects.py index b9081dab6..9d2a79ad6 100644 --- a/examples/logical_interconnects.py +++ b/examples/logical_interconnects.py @@ -3,23 +3,23 @@ # (C) Copyright [2021] Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. +# you may not use this file except in compLIance with the License. # You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/LIcenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software +# Unless required by appLIcable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or impLIed. # See the License for the specific language governing permissions and -# limitations under the License. +# LImitations under the License. ### from pprint import pprint -from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from hpeOneView.oneview_cLIent import OneViewCLIent +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,90 +27,90 @@ } } -# Specify variant of your appliance to run this example -api_variant = 'Synergy' +# Specify variant of your appLIance to run this example +API_VARIANT = 'Synergy' # To run this example, a logical interconnect name is required -logical_interconnect_name = "LE-LIG" +LOGICAL_INTERCONNECT_NAME = "LE-LIG" -# To install the firmware driver, a firmware driver name is required -firmware_driver_name = "HPE Synergy Custom SPP 2018110 2019 02 15, 2019.02.15.00" +# To install the FIRMWARE driver, a FIRMWARE driver name is required +FIRMWARE_DRIVER_NAME = "HPE Synergy Custom SPP 2018110 2019 02 15, 2019.02.15.00" # An Enclosure name must be set to create/delete an interconnect at a given location -enclosure_name = "0000A66102" +ENCLOSURE_NAME = "0000A66102" -# Define the scope name to add the logical interconnect to it -scope_name = "test" +# Define the SCOPE name to add the logical interconnect to it +SCOPE_NAME = "test" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -logical_interconnects = oneview_client.logical_interconnects -firmware_drivers = oneview_client.firmware_drivers -scopes = oneview_client.scopes -ethernet_networks = oneview_client.ethernet_networks -interconnects = oneview_client.interconnects +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_cLIent = OneViewCLIent(CONFIG) +LOGICAL_INTERCONNECTs = oneview_cLIent.LOGICAL_INTERCONNECTs +FIRMWARE_drivers = oneview_cLIent.FIRMWARE_drivers +SCOPEs = oneview_cLIent.SCOPEs +ETHERNET_NETWORKs = oneview_cLIent.ETHERNET_NETWORKs +interconnects = oneview_cLIent.interconnects # Get all logical interconnects print("\nGet all logical interconnects") -all_logical_interconnects = logical_interconnects.get_all() -for logical_interconnect in all_logical_interconnects: - print(' Name: {name}'.format(**logical_interconnect)) +ALL_LOGICAL_INTERCONNECTS = LOGICAL_INTERCONNECTs.get_all() +for LOGICAL_INTERCONNECT in ALL_LOGICAL_INTERCONNECTS: + print(' Name: {name}'.format(**LOGICAL_INTERCONNECT)) -# Get installed firmware -print("\nGet the installed firmware for a logical interconnect that matches the specified name.") -firmwares = firmware_drivers.get_by('name', firmware_driver_name) -firmware = firmwares[0] if firmwares else None +# Get installed FIRMWARE +print("\nGet the installed FIRMWARE for a logical interconnect that matches the specified name.") +FIRMWARES = FIRMWARE_drivers.get_by('name', FIRMWARE_DRIVER_NAME) +FIRMWARE = FIRMWARES[0] if FIRMWARES else None -print("\nGet the enclosure that matches the specified name.") -enclosures = oneview_client.enclosures.get_by_name(enclosure_name) -enclosure = enclosures.data if enclosures else None +print("\nGet the ENCLOSURE that matches the specified name.") +ENCLOSUREs = oneview_cLIent.ENCLOSUREs.get_by_name(ENCLOSURE_NAME) +ENCLOSURE = ENCLOSUREs.data if ENCLOSUREs else None # Get a logical interconnect by name -logical_interconnect = logical_interconnects.get_by_name(logical_interconnect_name) -if logical_interconnect: - print("\nFound logical interconnect by name {name}.\n URI: {uri}".format(**logical_interconnect.data)) - -# Install the firmware to a logical interconnect -if firmware: - print("\nInstall the firmware to a logical interconnect that matches the specified ID.") - firmware_to_install = dict( +LOGICAL_INTERCONNECT = LOGICAL_INTERCONNECTs.get_by_name(LOGICAL_INTERCONNECT_NAME) +if LOGICAL_INTERCONNECT: + print("\nFound logical interconnect by name {name}.\n URI: {uri}".format(**LOGICAL_INTERCONNECT.data)) + +# Install the FIRMWARE to a logical interconnect +if FIRMWARE: + print("\nInstall the FIRMWARE to a logical interconnect that matches the specified ID.") + FIRMWARE_to_install = dict( command="Update", - sppUri=firmware['uri'] + sppUri=FIRMWARE['uri'] ) - installed_firmware = logical_interconnect.install_firmware(firmware_to_install) - pprint(installed_firmware) + installed_FIRMWARE = LOGICAL_INTERCONNECT.install_FIRMWARE(FIRMWARE_to_install) + pprint(installed_FIRMWARE) -# Get scope to be added -print("\nGet the scope that matches the specified name.") -scope = scopes.get_by_name(scope_name) +# Get SCOPE to be added +print("\nGet the SCOPE that matches the specified name.") +SCOPE = SCOPEs.get_by_name(SCOPE_NAME) # Performs a patch operation # This operation is not supported in API version 200 and 600. -if scope and oneview_client.api_version not in [200, 600]: +if SCOPE and oneview_cLIent.api_version not in [200, 600]: print("\nPatches the logical interconnect to refresh state") - logical_interconnect.patch('replace', + LOGICAL_INTERCONNECT.patch('replace', '/state', 'Refresh') - pprint(logical_interconnect.data) + pprint(LOGICAL_INTERCONNECT.data) print("\nGet the Ethernet interconnect settings for the logical interconnect") -ethernet_settings = logical_interconnect.get_ethernet_settings() -pprint(ethernet_settings) +ETHERNET_SETTINGS = LOGICAL_INTERCONNECT.get_ETHERNET_SETTINGS() +pprint(ETHERNET_SETTINGS) # Update the Ethernet interconnect settings for the logical interconnect # macRefreshInterval attribute is supported only in C7000 -ethernet_settings = logical_interconnect.data['ethernetSettings'].copy() -if api_variant == 'C7000': - ethernet_settings['macRefreshInterval'] = 10 +ETHERNET_SETTINGS = LOGICAL_INTERCONNECT.data['ethernetSettings'].copy() +if API_VARIANT == 'C7000': + ETHERNET_SETTINGS['macRefreshInterval'] = 10 else: - ethernet_settings['stormControlThreshold'] = 15 -logical_interconnect_updated = logical_interconnect.update_ethernet_settings(ethernet_settings) + ETHERNET_SETTINGS['stormControlThreshold'] = 15 +LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_ETHERNET_SETTINGS(ETHERNET_SETTINGS) print("\nUpdated the ethernet settings") -print(logical_interconnect_updated) +print(LOGICAL_INTERCONNECT_updated) # Update the internal networks on the logical interconnect -ethernet_network_options = { +ETHERNET_NETWORK_OPTIONS = { "name": "OneViewSDK Test Ethernet Network on Logical Interconnect", "vlanId": 200, "ethernetNetworkType": "Tagged", @@ -119,148 +119,153 @@ "privateNetwork": False, "connectionTemplateUri": None, } -ethernet_network = ethernet_networks.get_by_name(ethernet_network_options['name']) -if not ethernet_network: - ethernet_network = ethernet_networks.create(ethernet_network_options) +ETHERNET_NETWORK = ETHERNET_NETWORKs.get_by_name(ETHERNET_NETWORK_OPTIONS['name']) +if not ETHERNET_NETWORK: + ETHERNET_NETWORK = ETHERNET_NETWORKs.create(ETHERNET_NETWORK_OPTIONS) -logical_interconnect_updated = logical_interconnect.update_internal_networks([ethernet_network.data['uri']]) +LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_internal_networks([ETHERNET_NETWORK.data['uri']]) print("\nUpdated internal networks on the logical interconnect") -print(" with attribute 'internalNetworkUris' = {internalNetworkUris}".format(**logical_interconnect_updated)) +print(" with attribute 'internalNetworkUris' = {internalNetworkUris}".format(**LOGICAL_INTERCONNECT_updated)) # Get the internal VLAN IDs print("\nGet the internal VLAN IDs for the provisioned networks on the logical interconnect") -internal_vlans = logical_interconnect.get_internal_vlans() -pprint(internal_vlans) +INTERNAL_VLANS = LOGICAL_INTERCONNECT.get_INTERNAL_VLANS() +pprint(INTERNAL_VLANS) # Update the interconnect settings # End-point supported only in api-versions 500 and below. -if oneview_client.api_version <= 500: +if oneview_cLIent.api_version <= 500: print("\nUpdates the interconnect settings on the logical interconnect") - interconnect_settings = { - 'ethernetSettings': logical_interconnect.data['ethernetSettings'].copy(), + INTERCONNECT_SETTINGS = { + 'ethernetSettings': LOGICAL_INTERCONNECT.data['ethernetSettings'].copy(), 'fcoeSettings': {} } - interconnect_settings['ethernetSettings']['macRefreshInterval'] = 7 - logical_interconnect_updated = logical_interconnect.update_settings(interconnect_settings) + INTERCONNECT_SETTINGS['ethernetSettings']['macRefreshInterval'] = 7 + LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_settings(INTERCONNECT_SETTINGS) print("Updated interconnect settings on the logical interconnect") - print(" with attribute 'macRefreshInterval' = {macRefreshInterval}".format(**logical_interconnect_updated['ethernetSettings'])) - pprint(logical_interconnect_updated) - -# Get the SNMP configuration for the logical interconnect -print("\nGet the SNMP configuration for the logical interconnect") -snmp_configuration = logical_interconnect.get_snmp_configuration() -pprint(snmp_configuration) - -# Update the SNMP configuration for the logical interconnect -print("\nUpdate the SNMP configuration for the logical interconnect") -snmp_configuration['enabled'] = True -snmp_configuration['readCommunity'] = "public" -logical_interconnect_updated = logical_interconnect.update_snmp_configuration(snmp_configuration) -interconnect_snmp = logical_interconnect_updated['snmpConfiguration'] -print(" Updated SNMP configuration at uri: {uri}\n with 'enabled': '{enabled}'".format(**interconnect_snmp)) - -# Get a collection of ports from the member interconnects which are eligible for assignment to an analyzer port -print("\nGet a collection of ports from the member interconnects which are eligible for assignment to " + print(" with attribute 'macRefreshInterval' = {macRefreshInterval}".format(**LOGICAL_INTERCONNECT_updated['ethernetSettings'])) + pprint(LOGICAL_INTERCONNECT_updated) + +# Get the SNMP CONFIGuration for the logical interconnect +print("\nGet the SNMP CONFIGuration for the logical interconnect") +snmp_CONFIGuration = LOGICAL_INTERCONNECT.get_snmp_CONFIGuration() +pprint(snmp_CONFIGuration) + +# Update the SNMP CONFIGuration for the logical interconnect +print("\nUpdate the SNMP CONFIGuration for the logical interconnect") +snmp_CONFIGuration['enabled'] = True +snmp_CONFIGuration['readCommunity'] = "pubLIc" +LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_snmp_CONFIGuration(snmp_CONFIGuration) +INTERCONNECT_SNMP = LOGICAL_INTERCONNECT_updated['snmpConfiguration'] +print(" Updated SNMP CONFIGuration at uri: {uri}\n with 'enabled': '{enabled}'".format(**INTERCONNECT_SNMP)) + +# Get a collection of ports from the member interconnects which are eLIgible for assignment to an +# analyzer port +print("\nGet a collection of ports from the member interconnects which are eLIgible for assignment + to " "an analyzer port on the logical interconnect") -unassigned_ports = logical_interconnect.get_unassigned_ports() -pprint(unassigned_ports) +UNASSIGNED_PORTS = LOGICAL_INTERCONNECT.get_UNASSIGNED_PORTS() +pprint(UNASSIGNED_PORTS) -# Get a collection of uplink ports from the member interconnects which are eligible for assignment to an analyzer port -print("\nGet a collection of uplink ports from the member interconnects which are eligible for assignment to " +# Get a collection of upLInk ports from the member interconnects which are eLIgible for assignment +# to an analyzer port +print("\nGet a collection of upLInk ports from the member interconnects which are eLIgible for + assignment to " "an analyzer port on the logical interconnect") -unassigned_uplink_ports = logical_interconnect.get_unassigned_uplink_ports() -pprint(unassigned_uplink_ports) - -# Get the port monitor configuration of a logical interconnect -print("\nGet the port monitor configuration of a logical interconnect") -monitor_configuration = logical_interconnect.get_port_monitor() -pprint(monitor_configuration) - -# Update port monitor configuration of a logical interconnect -print("\nUpdate the port monitor configuration of a logical interconnect") -monitor_configuration['enablePortMonitor'] = True - -# logical_interconnect_updated = logical_interconnect.update_port_monitor(monitor_configuration) -# print(" Updated port monitor at uri: {uri}\n with 'enablePortMonitor': '{enablePortMonitor}'".format( -# **logical_interconnect_updated['portMonitor'])) - -# Update the configuration on the logical interconnect -print("\nUpdate the configuration on the logical interconnect") -logical_interconnect_updated = logical_interconnect.update_configuration() +UNASSIGNED_UPLINK_PORTS = LOGICAL_INTERCONNECT.get_UNASSIGNED_UPLINK_PORTS() +pprint(UNASSIGNED_UPLINK_PORTS) + +# Get the port monitor CONFIGuration of a logical interconnect +print("\nGet the port monitor CONFIGuration of a logical interconnect") +monitor_CONFIGuration = LOGICAL_INTERCONNECT.get_port_monitor() +pprint(monitor_CONFIGuration) + +# Update port monitor CONFIGuration of a logical interconnect +print("\nUpdate the port monitor CONFIGuration of a logical interconnect") +monitor_CONFIGuration['enablePortMonitor'] = True + +# LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_port_monitor(monitor_CONFIGuration) +# print(" Updated port monitor at uri: {uri}\n with 'enablePortMonitor': +# '{enablePortMonitor}'".format( +# **LOGICAL_INTERCONNECT_updated['portMonitor'])) + +# Update the CONFIGuration on the logical interconnect +print("\nUpdate the CONFIGuration on the logical interconnect") +LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_CONFIGuration() print(" Done.") # Return the logical interconnect to a consistent state print("\nReturn the logical interconnect to a consistent state") -logical_interconnect_updated = logical_interconnect.update_compliance() -print(" Done. The current consistency state is {consistencyStatus}.".format(**logical_interconnect_updated)) +LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_compLIance() +print(" Done. The current consistency state is {consistencyStatus}.".format(**LOGICAL_INTERCONNECT_updated)) # Generate the forwarding information base dump file for the logical interconnect print("\nGenerate the forwarding information base dump file for the logical interconnect") -fwd_info_datainfo = logical_interconnect.create_forwarding_information_base() -pprint(fwd_info_datainfo) +FWD_INFO_DATAINFO = LOGICAL_INTERCONNECT.create_forwarding_information_base() +pprint(FWD_INFO_DATAINFO) # Get the forwarding information base data for the logical interconnect print("\nGet the forwarding information base data for the logical interconnect") -fwd_information = logical_interconnect.get_forwarding_information_base() -pprint(fwd_information) +FWD_INFORMATION = LOGICAL_INTERCONNECT.get_forwarding_information_base() +pprint(FWD_INFORMATION) -# Get the QoS aggregated configuration for the logical interconnect. -print("\nGets the QoS aggregated configuration for the logical interconnect.") -qos = logical_interconnect.get_qos_aggregated_configuration() -pprint(qos) +# Get the QoS aggregated CONFIGuration for the logical interconnect. +print("\nGets the QoS aggregated CONFIGuration for the logical interconnect.") +QOS = LOGICAL_INTERCONNECT.get_QOS_aggregated_CONFIGuration() +pprint(QOS) -# Update the QOS aggregated configuration +# Update the QOS aggregated CONFIGuration print("\nUpdate QoS aggregated settings on the logical interconnect") -qos['activeQosConfig']['configType'] = 'Passthrough' -li = logical_interconnect.update_qos_aggregated_configuration(qos) -pprint(li['qosConfiguration']) - -# Get the telemetry configuration of the logical interconnect -print("\nGet the telemetry configuration of the logical interconnect") -telemetry_configuration = logical_interconnect.get_telemetry_configuration() -pprint(telemetry_configuration) - -# Update telemetry configuration -print("\nUpdate the telemetry configuration") -telemetry_config = { +QOS['activeQosConfig']['CONFIGType'] = 'Passthrough' +LI = LOGICAL_INTERCONNECT.update_QOS_aggregated_CONFIGuration(QOS) +pprint(LI['QOSConfiguration']) + +# Get the telemetry CONFIGuration of the logical interconnect +print("\nGet the telemetry CONFIGuration of the logical interconnect") +telemetry_CONFIGuration = LOGICAL_INTERCONNECT.get_telemetry_CONFIGuration() +pprint(telemetry_CONFIGuration) + +# Update telemetry CONFIGuration +print("\nUpdate the telemetry CONFIGuration") +telemetry_CONFIG = { "sampleCount": 12, "enableTelemetry": True, "sampleInterval": 300 } -logical_interconnect_updated = logical_interconnect.update_telemetry_configurations(configuration=telemetry_config) -pprint(logical_interconnect_updated) +LOGICAL_INTERCONNECT_updated = LOGICAL_INTERCONNECT.update_telemetry_CONFIGurations(CONFIGuration=telemetry_CONFIG) +pprint(LOGICAL_INTERCONNECT_updated) # Gets the IGMP interconnect settings for the logical interconnect. -if oneview_client.api_version >= 1600: +if oneview_cLIent.api_version >= 1600: print("\nGets the IGMP interconnect settings for the logical interconnect") - igmp_settings = logical_interconnect.get_igmp_settings() - pprint(igmp_settings) + IGMP_SETTINGS = LOGICAL_INTERCONNECT.get_IGMP_SETTINGS() + pprint(IGMP_SETTINGS) # Updates IGMP interconnect settings for the logical interconnect. -if oneview_client.api_version >= 1600: +if oneview_cLIent.api_version >= 1600: print("\nUpdates IGMP interconnect settings for the logical interconnect") - igmp_settings['igmpIdleTimeoutInterval'] = 200 - igmp_settings_updated = logical_interconnect.update_igmp_settings(igmp_settings) - pprint(igmp_settings_updated) + IGMP_SETTINGS['igmpIdleTimeoutInterval'] = 200 + IGMP_SETTINGS_updated = LOGICAL_INTERCONNECT.update_IGMP_SETTINGS(IGMP_SETTINGS) + pprint(IGMP_SETTINGS_updated) print("\nUpdated IGMP interconnect settings for the logical interconnect successfully") # Updates port flap settings for the logical interconnect. -if oneview_client.api_version >= 2400: +if oneview_cLIent.api_version >= 2400: print("\nUpdates port flap settings for the logical interconnect") - port_flap_settings = logical_interconnect.data['portFlapProtection'].copy() - port_flap_settings['portFlapThresholdPerInterval'] = 5 - port_flap_settings_updated = logical_interconnect.update_port_flap_settings(port_flap_settings) - pprint(port_flap_settings_updated) + PORT_FLAP_SETTINGS = LOGICAL_INTERCONNECT.data['portFlapProtection'].copy() + PORT_FLAP_SETTINGS['portFlapThresholdPerInterval'] = 5 + PORT_FLAP_SETTINGS_updated = LOGICAL_INTERCONNECT.update_PORT_FLAP_SETTINGS(PORT_FLAP_SETTINGS) + pprint(PORT_FLAP_SETTINGS_updated) print("\nUpdated port flap settings for the logical interconnect successfully") -# Validates the bulk update from group operation and gets the consolidated inconsistency report -if oneview_client.api_version >= 2000 and api_variant == 'Synergy': - print("Validates the bulk update from group operation and gets the consolidated inconsistency report") - bulk_validate_request = { +# VaLIdates the bulk update from group operation and gets the consoLIdated inconsistency report +if oneview_cLIent.api_version >= 2000 and API_VARIANT == 'Synergy': + print("VaLIdates the bulk update from group operation and gets the consoLIdated inconsistency report") + bulk_vaLIdate_request = { "logicalInterconnectUris": [ - logical_interconnect.data['uri'] + LOGICAL_INTERCONNECT.data['uri'] ] } - validation_result = logical_interconnect.bulk_inconsistency_validate(bulk_validate_request) - pprint(validation_result) - print("\nValidated bulk update from group for the logical interconnect successfully") + vaLIdation_result = LOGICAL_INTERCONNECT.bulk_inconsistency_vaLIdate(bulk_vaLIdate_request) + pprint(vaLIdation_result) + print("\nVaLIdated bulk update from group for the logical interconnect successfully") diff --git a/examples/logical_switch_groups.py b/examples/logical_switch_groups.py index bf68ad6e6..9e3ab1fe7 100644 --- a/examples/logical_switch_groups.py +++ b/examples/logical_switch_groups.py @@ -18,12 +18,12 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient # This resource is only available on C7000 enclosures -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -32,9 +32,9 @@ } # To run the scope patch operations in this example, a scope name is required. -scope_name = "test" +SCOPE_NAME = "test" -options = { +OPTIONS = { "name": "OneView Test Logical Switch Group", "switchMapTemplate": { "switchMapEntryTemplates": [{ @@ -49,83 +49,84 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) logical_switch_groups = oneview_client.logical_switch_groups -switch_types = oneview_client.switch_types +SWITCH_TYPEs = oneview_client.SWITCH_TYPEs # Get all, with defaults print("\nGet all Logical Switch Groups") -lsgs = logical_switch_groups.get_all() -for lsg in lsgs: - print(" '{name}' at uri: '{uri}'".format(**lsg)) +LSGS = logical_switch_groups.get_all() +for LSG in LSGS: + print(" '{name}' at uri: '{uri}'".format(**LSG)) # Get the first 10 records, sorting by name descending, filtering by name print("\nGet the first Logical Switch Groups, sorting by name descending, filtering by name") -lsgs = logical_switch_groups.get_all( +LSGS = logical_switch_groups.get_all( 0, 10, sort='name:descending', filter="\"'name'='OneView Test Logical Switch Group'\"") -for lsg in lsgs: - print(" '{name}' at uri: '{uri}'".format(**lsg)) +for LSG in LSGS: + print(" '{name}' at uri: '{uri}'".format(**LSG)) # Get Logical Switch by property -lsg_getby = logical_switch_groups.get_by('name', 'OneView Test Logical Switch Group') -if lsg_getby: - print("\nFound logical switch group by name: '{name}' at uri = '{uri}'".format(**lsg_getby[0])) +LSG_GETBY = logical_switch_groups.get_by('name', 'OneView Test Logical Switch Group') +if LSG_GETBY: + print("\nFound logical switch group by name: '{name}' at uri = '{uri}'".format(**LSG_GETBY[0])) print("\nGet a Logical Switch Group by uri") - lsg_byuri = logical_switch_groups.get_by_uri(lsg_getby[0]["uri"]) - print(" Found logical switch group '{name}' by uri '{uri}'".format(**lsg_byuri.data)) + LSG_BYURI = logical_switch_groups.get_by_uri(LSG_GETBY[0]["uri"]) + print(" Found logical switch group '{name}' by uri '{uri}'".format(**LSG_BYURI.data)) # Get switch type to use in creation of logical switch group print("\nGet switch type to use in creation of logical switch group") -switch_type = switch_types.get_by_name("Arista 7060X") -print(" Found switch type at uri: '{}'".format(switch_type.data['uri'])) +SWITCH_TYPE = SWITCH_TYPEs.get_by_name("Arista 7060X") +print(" Found switch type at uri: '{}'".format(SWITCH_TYPE.data['uri'])) -lsg = logical_switch_groups.get_by_name(options["name"]) -if not lsg: +LSG = logical_switch_groups.get_by_name(OPTIONS["name"]) +if not LSG: # Create a logical switch group print("\nCreate a logical switch group") - options['switchMapTemplate']['switchMapEntryTemplates'][0]['permittedSwitchTypeUri'] = switch_type.data['uri'] - lsg = oneview_client.logical_switch_groups.create(options) - print(" Created logical switch group '{name}' at uri: '{uri}'".format(**lsg.data)) + OPTIONS['switchMapTemplate']['switchMapEntryTemplates'][0]['permittedSwitchTypeUri'] = + SWITCH_TYPE.data['uri'] + LSG = oneview_client.logical_switch_groups.create(OPTIONS) + print(" Created logical switch group '{name}' at uri: '{uri}'".format(**LSG.data)) # Update a logical switch group print("\nUpdate the name of a logical switch group") -lsg_to_update = lsg.data.copy() -lsg_to_update["name"] = "Renamed Logical Switch Group" -lsg.update(lsg_to_update) -print(" Successfully updated logical switch group with name '{name}'".format(**lsg.data)) +LSG_TO_UPDATE = LSG.data.copy() +LSG_TO_UPDATE["name"] = "Renamed Logical Switch Group" +LSG.update(LSG_TO_UPDATE) +print(" Successfully updated logical switch group with name '{name}'".format(**LSG.data)) # Update a logical switch group by adding another switch with a relative value of 2 print("\nUpdate a logical switch group by adding another switch with a relative value of 2") -lsg_to_update = lsg.data.copy() -switch_options = { +LSG_TO_UPDATE = LSG.data.copy() +SWITCH_OPTIONS = { "logicalLocation": { "locationEntries": [{ "relativeValue": 2, "type": "StackingMemberId", }] }, - "permittedSwitchTypeUri": switch_type.data['uri'] + "permittedSwitchTypeUri": SWITCH_TYPE.data['uri'] } -lsg_to_update['switchMapTemplate']['switchMapEntryTemplates'].append(switch_options) -lsg.update(lsg_to_update) -pprint(lsg.data) +LSG_TO_UPDATE['switchMapTemplate']['switchMapEntryTemplates'].append(SWITCH_OPTIONS) +LSG.update(LSG_TO_UPDATE) +pprint(LSG.data) # Get scope to be added -print("\nGet the scope named '%s'." % scope_name) -scope = oneview_client.scopes.get_by_name(scope_name) +print("\nGet the scope named '%s'." % SCOPE_NAME) +scope = oneview_client.scopes.get_by_name(SCOPE_NAME) # Performs a patch operation on the Logical Switch Group if scope and oneview_client.api_version <= 500: - print("\nPatches the logical switch group assigning the '%s' scope to it." % scope_name) - lsg.patch('replace', + print("\nPatches the logical switch group assigning the '%s' scope to it." % SCOPE_NAME) + LSG.patch('replace', '/scopeUris', [scope['uri']]) - pprint(lsg.data) + pprint(LSG.data) # Delete a logical switch group print("\nDelete the created logical switch group") -lsg.delete() +LSG.delete() print(" Successfully deleted logical switch group") diff --git a/examples/logical_switches.py b/examples/logical_switches.py index 9f3efaa94..994941809 100644 --- a/examples/logical_switches.py +++ b/examples/logical_switches.py @@ -17,11 +17,11 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file # This resource is only available on C7000 enclosures -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,119 +29,123 @@ } } -# A Logical Switch Group, the Switches IP address/host name, and credentials must be set to run this example -logical_switch_group_name = '' -switch_ip_1 = '' -switch_ip_2 = '' -ssh_username = '' -ssh_password = '' +# A Logical Switch Group, the Switches IP address/host name, and credentials must be set to run this +# example +LOGICAL_SWITCH_GROUP_NAME = '' +SWITCH_IP_1 = '' +SWITCH_IP_2 = '' +SSH_USERNAME = '' +SSH_PASSWORD = '' -# To run the scope patch operations in this example, a scope name is required. -scope_name = "" +# To run the SCOPE patch operations in this example, a SCOPE name is required. +SCOPE_NAME = "" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Check for existance of Logical Switch Group specified, otherwise stops execution -logical_switch_group = oneview_client.logical_switch_groups.get_by('name', logical_switch_group_name)[0] -if logical_switch_group: - print('Found logical switch group "%s" with uri: %s' % (logical_switch_group['name'], logical_switch_group['uri'])) +LOGICAL_SWITCH_GROUP = oneview_client.LOGICAL_SWITCH_GROUPs.get_by('name', + LOGICAL_SWITCH_GROUP_NAME)[0] +if LOGICAL_SWITCH_GROUP: + print('Found logical switch group "%s" with uri: %s' % (LOGICAL_SWITCH_GROUP['name'], + LOGICAL_SWITCH_GROUP['uri'])) else: - raise Exception('Logical switch group "%s" was not found on the appliance.' % logical_switch_group_name) + raise Exception('Logical switch group "%s" was not found on the appliance.' % + LOGICAL_SWITCH_GROUP_NAME) -switch_connection_properties = { +SWITCH_CONNECTION_PROPERTIES = { "connectionProperties": [{ "propertyName": "SshBasicAuthCredentialUser", - "value": ssh_username, + "value": SSH_USERNAME, "valueFormat": "Unknown", "valueType": "String" }, { "propertyName": "SshBasicAuthCredentialPassword", - "value": ssh_password, + "value": SSH_PASSWORD, "valueFormat": "SecuritySensitive", "valueType": "String" }] } -options = { +OPTIONS = { "logicalSwitch": { "name": "Test Logical Switch", - "logicalSwitchGroupUri": logical_switch_group['uri'], + "logicalSwitchGroupUri": LOGICAL_SWITCH_GROUP['uri'], "switchCredentialConfiguration": [ { "snmpV1Configuration": { "communityString": "public" }, - "logicalSwitchManagementHost": switch_ip_1, + "logicalSwitchManagementHost": SWITCH_IP_1, "snmpVersion": "SNMPv1", "snmpPort": 161 }, { "snmpV1Configuration": { "communityString": "public" }, - "logicalSwitchManagementHost": switch_ip_2, + "logicalSwitchManagementHost": SWITCH_IP_2, "snmpVersion": "SNMPv1", "snmpPort": 161 } ] }, - "logicalSwitchCredentials": [switch_connection_properties, switch_connection_properties] + "logicalSwitchCredentials": [SWITCH_CONNECTION_PROPERTIES, SWITCH_CONNECTION_PROPERTIES] } # Create a Logical Switch -logical_switch = oneview_client.logical_switches.create(options) -print("\nCreated Logical Switch '{name}' successfully.\n uri = '{uri}'".format(**logical_switch)) +LOGICAL_SWITCH = oneview_client.LOGICAL_SWITCHes.create(OPTIONS) +print("\nCreated Logical Switch '{name}' successfully.\n uri = '{uri}'".format(**LOGICAL_SWITCH)) # Find the recently created Logical Switch by name -logical_switch = oneview_client.logical_switches.get_by('name', 'Test Logical Switch')[0] -print("\nFound Logical Switch by name: '{name}'.\n uri = '{uri}'".format(**logical_switch)) +LOGICAL_SWITCH = oneview_client.LOGICAL_SWITCHes.get_by('name', 'Test Logical Switch')[0] +print("\nFound Logical Switch by name: '{name}'.\n uri = '{uri}'".format(**LOGICAL_SWITCH)) # Update the name of the Logical Switch -options_update = { +OPTIONS_UPDATE = { "logicalSwitch": { "name": "Renamed Logical Switch", - "uri": logical_switch['uri'], - "switchCredentialConfiguration": logical_switch['switchCredentialConfiguration'], - "logicalSwitchGroupUri": logical_switch_group['uri'], + "uri": LOGICAL_SWITCH['uri'], + "switchCredentialConfiguration": LOGICAL_SWITCH['switchCredentialConfiguration'], + "logicalSwitchGroupUri": LOGICAL_SWITCH_GROUP['uri'], "consistencyStatus": "CONSISTENT" }, - "logicalSwitchCredentials": [switch_connection_properties, switch_connection_properties] + "logicalSwitchCredentials": [SWITCH_CONNECTION_PROPERTIES, SWITCH_CONNECTION_PROPERTIES] } -logical_switch = oneview_client.logical_switches.update(options_update) -print("\nUpdated Logical Switch successfully.\n uri = '{uri}'".format(**logical_switch)) -print(" with attribute name = {name}".format(**logical_switch)) +LOGICAL_SWITCH = oneview_client.LOGICAL_SWITCHes.update(OPTIONS_UPDATE) +print("\nUpdated Logical Switch successfully.\n uri = '{uri}'".format(**LOGICAL_SWITCH)) +print(" with attribute name = {name}".format(**LOGICAL_SWITCH)) -# Get scope to be added -print("\nGet the scope named '%s'." % scope_name) -scope = oneview_client.scopes.get_by_name(scope_name) +# Get SCOPE to be added +print("\nGet the SCOPE named '%s'." % SCOPE_NAME) +SCOPE = oneview_client.SCOPEs.get_by_name(SCOPE_NAME) # Performs a patch operation on the Logical Switch -if scope: - print("\nPatches the logical switch assigning the '%s' scope to it." % scope_name) - logical_switch = oneview_client.logical_switches.patch(logical_switch['uri'], +if SCOPE: + print("\nPatches the logical switch assigning the '%s' SCOPE to it." % SCOPE_NAME) + LOGICAL_SWITCH = oneview_client.LOGICAL_SWITCHes.patch(LOGICAL_SWITCH['uri'], 'replace', - '/scopeUris', - [scope['uri']]) - pprint(logical_switch) + '/SCOPEUris', + [SCOPE['uri']]) + pprint(LOGICAL_SWITCH) # Get all, with defaults print("\nGet all Logical Switches") -logical_switches = oneview_client.logical_switches.get_all() -for logical_switch in logical_switches: - print(' Name: %s' % logical_switch['name']) +LOGICAL_SWITCHes = oneview_client.LOGICAL_SWITCHes.get_all() +for LOGICAL_SWITCH in LOGICAL_SWITCHes: + print(' Name: %s' % LOGICAL_SWITCH['name']) # Get by URI print("\nGet a Logical Switch by URI") -logical_switch = oneview_client.logical_switches.get(logical_switch['uri']) -pprint(logical_switch) +LOGICAL_SWITCH = oneview_client.LOGICAL_SWITCHes.get(LOGICAL_SWITCH['uri']) +pprint(LOGICAL_SWITCH) # Reclaim the top-of-rack switches in the logical switch print("\nReclaim the top-of-rack switches in the logical switch") -logical_switch = oneview_client.logical_switches.refresh(logical_switch['uri']) +LOGICAL_SWITCH = oneview_client.LOGICAL_SWITCHes.refresh(LOGICAL_SWITCH['uri']) print(" Done.") # Delete the Logical Switch -oneview_client.logical_switches.delete(logical_switch) +oneview_client.LOGICAL_SWITCHes.delete(LOGICAL_SWITCH) print("\nLogical switch deleted successfully.") diff --git a/examples/login_details.py b/examples/login_details.py index 9eb4d7edf..5dcc35d0f 100644 --- a/examples/login_details.py +++ b/examples/login_details.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,13 +27,13 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) print("\n Querying system for login details\n") -login_detail = oneview_client.login_details.get_login_details() +LOGIN_DETAIL = oneview_client.LOGIN_DETAILs.get_LOGIN_DETAILs() print("\n Login details are: \n") -pprint(login_detail) +pprint(LOGIN_DETAIL) diff --git a/examples/managed_sans.py b/examples/managed_sans.py index 58b1b6660..cabf1adaf 100644 --- a/examples/managed_sans.py +++ b/examples/managed_sans.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,43 +27,44 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) managed_sans = oneview_client.managed_sans -imported_san = None -internally_managed_san = None +IMPORTED_SAN = None +INTERNALLY_MANAGED_SAN = None # You must set the value of the WWN to run the API 300 example -wwn = None +WWN = None # Get all, with defaults print("\nGet all Managed SANs") -managed_sans_all = managed_sans.get_all() +MANAGED_SANS_ALL = managed_sans.get_all() -if managed_sans_all: - for managed_san in managed_sans_all: - print(' Name: {name} - Manager: {deviceManagerName} - Imported: {imported}'.format(**managed_san)) +if MANAGED_SANS_ALL: + for managed_san in MANAGED_SANS_ALL: + print(' Name: {name} - Manager: {deviceManagerName} - Imported: + {imported}'.format(**managed_san)) if managed_san['imported']: - imported_san = managed_sans.get_by_uri(managed_san["uri"]) + IMPORTED_SAN = managed_sans.get_by_uri(managed_san["uri"]) else: - internally_managed_san = managed_sans.get_by_uri(managed_san["uri"]) + INTERNALLY_MANAGED_SAN = managed_sans.get_by_uri(managed_san["uri"]) # Get a Managed SAN by name print("\nGet a Managed SAN by name") - managed_san_by_name = managed_sans.get_by_name(managed_san['name']) - pprint(managed_san_by_name.data) + MANAGED_SAN_BY_NAME = managed_sans.get_by_name(managed_san['name']) + pprint(MANAGED_SAN_BY_NAME.data) # Get a Managed SAN by URI print("\nGet a Managed SAN by URI") - managed_san_by_uri = managed_sans.get_by_uri(managed_san['uri']) - pprint(managed_san_by_uri.data) + MANAGED_SAN_BY_URI = managed_sans.get_by_uri(managed_san['uri']) + pprint(MANAGED_SAN_BY_URI.data) - if internally_managed_san: + if INTERNALLY_MANAGED_SAN: # Update the Managed SAN's publicAttributes print("\nUpdate the Internally Managed SAN's publicAttributes") - public_attributes = { + PUBLIC_ATTRIBUTES = { "publicAttributes": [{ "name": "MetaSan", "value": "Neon SAN", @@ -71,12 +72,12 @@ "valueFormat": "None" }] } - internally_managed_san.update(public_attributes) - pprint(internally_managed_san.data) + INTERNALLY_MANAGED_SAN.update(PUBLIC_ATTRIBUTES) + pprint(INTERNALLY_MANAGED_SAN.data) - # Update the Managed SAN's policy - print("\nUpdate the Internally Managed SAN's policy") - policy = { + # Update the Managed SAN's POLICY + print("\nUpdate the Internally Managed SAN's POLICY") + POLICY = { "sanPolicy": { "zoningPolicy": "SingleInitiatorAllTargets", "zoneNameFormat": "{hostName}_{initiatorWwn}", @@ -86,39 +87,39 @@ "targetGroupNameFormat": "{storageSystemName}_{targetGroupName}" } } - internally_managed_san.update(policy) - pprint(internally_managed_san.data) + INTERNALLY_MANAGED_SAN.update(POLICY) + pprint(INTERNALLY_MANAGED_SAN.data) - if imported_san: + if IMPORTED_SAN: # Refresh the Managed SAN print("\nRefresh the Imported Managed SAN") - refresh_config = { + refresh_CONFIG = { "refreshState": "RefreshPending" } - imported_san.update(refresh_config) - pprint(imported_san.data) + IMPORTED_SAN.update(refresh_CONFIG) + pprint(IMPORTED_SAN.data) - # Create a SAN endpoints CSV file - print("\nCreate a SAN endpoints CSV file") - csv_file_response = imported_san.create_endpoints_csv_file() - pprint(csv_file_response) + # Create a SAN ENDPOINTS CSV file + print("\nCreate a SAN ENDPOINTS CSV file") + CSV_FILE_RESPONSE = IMPORTED_SAN.create_ENDPOINTS_csv_file() + pprint(CSV_FILE_RESPONSE) - # Retrieve the endpoints for a SAN - print("\nGet the list of endpoints in the Imported Managed SAN") - endpoints = imported_san.get_endpoints() - pprint(endpoints) + # Retrieve the ENDPOINTS for a SAN + print("\nGet the list of ENDPOINTS in the Imported Managed SAN") + ENDPOINTS = IMPORTED_SAN.get_ENDPOINTS() + pprint(ENDPOINTS) # Create an unexpected zoning report print("\nCreate an unexpected zoning report") - issues_response = imported_san.create_issues_report() - pprint(issues_response) + ISSUES_RESPONSE = IMPORTED_SAN.create_issues_report() + pprint(ISSUES_RESPONSE) else: print("\nNo Managed SANs found.") # This method is available for API version 300 -if oneview_client.api_version == 300 and wwn is not None: +if oneview_client.api_version == 300 and WWN is not None: # Retrieves an association between the provided WWN and the SAN (if any) on which it resides print("\nGet a list of associations between provided WWNs and the SANs on which they reside") - wwns = managed_sans.get_wwn(wwn) - pprint(wwns) + WWNs = managed_sans.get_WWN(WWN) + pprint(WWNs) diff --git a/examples/metric_streaming.py b/examples/metric_streaming.py index 8868dd62b..4ec2a77d6 100644 --- a/examples/metric_streaming.py +++ b/examples/metric_streaming.py @@ -17,22 +17,22 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -metrics_configuration = { +METRICS_CONFIGURATION = { "sourceTypeList": [ { "sourceType": "/rest/power-devices", @@ -54,15 +54,15 @@ # Configure metric relay for server-hardware, enclosures and power-devices. print("Configure metric streaming") -updated_metrics_configuration = oneview_client.metric_streaming.update_configuration(metrics_configuration) -pprint(updated_metrics_configuration) +UPDATED_METRICS_CONFIGURATION = oneview_client.metric_streaming.update_CONFIGuration(METRICS_CONFIGURATION) +pprint(UPDATED_METRICS_CONFIGURATION) -# Get current relay configuration -print("Get current configuration") -current_configuration = oneview_client.metric_streaming.get_configuration() -pprint(current_configuration) +# Get current relay CONFIGuration +print("Get current CONFIGuration") +CURRENT_CONFIGURATION = oneview_client.metric_streaming.get_CONFIGuration() +pprint(CURRENT_CONFIGURATION) # Gets the list of all supported metrics and resource types. print("Gets the list of all supported metrics and resource types") -supported_metrics = oneview_client.metric_streaming.get_capability() -pprint(supported_metrics) +SUPPORTED_METRICS = oneview_client.metric_streaming.get_capability() +pprint(SUPPORTED_METRICS) diff --git a/examples/migratable_vc_domains.py b/examples/migratable_vc_domains.py index 2f3431573..ed7ad0a83 100644 --- a/examples/migratable_vc_domains.py +++ b/examples/migratable_vc_domains.py @@ -8,7 +8,7 @@ # # http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software +# Unless required by aPPlicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and @@ -18,11 +18,11 @@ from hpeOneView.oneview_client import OneViewClient from hpeOneView.resources.servers.migratable_vc_domains import MigratableVcDomains from hpeOneView.exceptions import HPEOneViewTaskError -from config_loader import try_load_from_file -from pprint import PrettyPrinter +from CONFIG_loader import try_load_from_file +from PPrint import PrettyPrinter -config = { +CONFIG = { "ip": "172.16.102.59", "credentials": { "userName": "Administrator", @@ -36,46 +36,50 @@ "enclosure_group_uri": None } -pp = PrettyPrinter() +PP = PrettyPrinter() -# Try load config from a file (if there is a config file) -print("Loading configuration.") -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +print("Loading CONFIGuration.") +CONFIG = try_load_from_file(CONFIG) # Obtain the master OneView client print("Setting up OneView client.") -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Create the dict that VC Migration Manager requires to start the process -migrationInformation = MigratableVcDomains.make_migration_information(config['enclosure_hostname'], - config['enclosure_username'], - config['enclosure_password'], - config['vcmUsername'], config['vcmPassword'], - enclosureGroupUri=config['enclosure_group_uri']) +MIGRATIONINFORMATION = MigratableVcDomains.make_migration_information(CONFIG['enclosure_hostname'], + CONFIG['enclosure_username'], + CONFIG['enclosure_password'], + CONFIG['vcmUsername'], CONFIG['vcmPassword'], + enclosureGroupUri=CONFIG['enclosure_group_uri']) # Start a migration by first creating a compatibility report -print("Create a compatibility report for enclosure '%s'." % migrationInformation['credentials']['oaIpAddress']) -compatibility_report = oneview_client.migratable_vc_domains.test_compatibility(migrationInformation) +print("Create a compatibility report for enclosure '%s'." % MIGRATIONINFORMATION['credentials']['oaIpAddress']) +compatibility_report = oneview_client.migratable_vc_domains.test_compatibility(MIGRATIONINFORMATION) print("Complete. Created a compatibility report for enclosure '%s'.\n uri = '%s'" % (compatibility_report['credentials']['oaIpAddress'], compatibility_report['uri'])) # We got the compatibility report as part of the previous call, but one may need to get it later on print("Get the '%s' compatibility report." % compatibility_report['credentials']['oaIpAddress']) compatibility_report = oneview_client.migratable_vc_domains.get_migration_report(compatibility_report['uri']) -print("Complete. Obtained the compatibility report for '%s'.\n Here is the compatibility report:" % +print("Complete. Obtained the compatibility report for '%s'.\n Here is the compatibility report:" + % compatibility_report['credentials']['oaIpAddress']) -pp.pprint(compatibility_report) +PP.PPrint(compatibility_report) -# One would now resolve all the critical issues and however many lesser severity issues found in the compatibility +# One would now resolve all the critical issues and however many lesser severity issues found in the +# compatibility # report before continuing. # Now is the time to initiate the migration -print("Attempting to migrate enclosure '%s'. The migration state before is '%s'. This could take a while." % +print("Attempting to migrate enclosure '%s'. The migration state before is '%s'. This could take a + while." % (compatibility_report['credentials']['oaIpAddress'], compatibility_report['migrationState'])) try: compatibility_report = oneview_client.migratable_vc_domains.migrate(compatibility_report['uri']) print("Complete. Migration state afterward is '%s'." % compatibility_report['migrationState']) except HPEOneViewTaskError: - print("Failure. The enclosure failed to migrate. Perhaps there was a critical issue that was unresolved before \ + print("Failure. The enclosure failed to migrate. Perhaps there was a critical issue that was + unresolved before \ migrating?") # One now may decide to delete the compatibility report if they so choose diff --git a/examples/network_sets.py b/examples/network_sets.py index 3152f8468..c384906b2 100644 --- a/examples/network_sets.py +++ b/examples/network_sets.py @@ -19,8 +19,8 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -# To run this example fill the ip and the credentials below or use a configuration file -config = { +# To run this example fill the ip and the credentials below or use a CONFIGuration file +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,11 +29,11 @@ "api_version": "" } -options = { +OPTIONS = { "name": "OneViewSDK Test Network Set" } -options_ethernet1 = { +OPTIONS_ETHERNET1 = { "name": "OneViewSDK Test Ethernet Network1", "vlanId": 200, "ethernetNetworkType": "Tagged", @@ -43,7 +43,7 @@ "connectionTemplateUri": None, } -options_ethernet2 = { +OPTIONS_ETHERNET2 = { "name": "OneViewSDK Test Ethernet Network2", "vlanId": 201, "ethernetNetworkType": "Tagged", @@ -54,74 +54,74 @@ } # Scope name to perform the patch operation -scope_name = "" +SCOPE_NAME = "" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -ethernet_networks = oneview_client.ethernet_networks -network_sets = oneview_client.network_sets -scopes = oneview_client.scopes +ETHERNET_NETWORKS = oneview_client.ETHERNET_NETWORKS +NETWORK_SETS = oneview_client.network_sets +SCOPES = oneview_client.scopes # Get all network sets print("Get all network sets") -net_sets = network_sets.get_all() -pprint(net_sets) +NET_SETS = NETWORK_SETS.get_all() +pprint(NET_SETS) # Get all network sets without Ethernet print("Get all network sets without Ethernet") -net_sets_without_ethernet = network_sets.get_all_without_ethernet() -pprint(net_sets_without_ethernet) +NET_SETS_WITHOUT_ETHERNET = NETWORK_SETS.get_all_without_ethernet() +pprint(NET_SETS_WITHOUT_ETHERNET) # Create two Ethernet networks -ethernet_network1 = ethernet_networks.create(options_ethernet1) -ethernet_network2 = ethernet_networks.create(options_ethernet2) +ETHERNET_NETWORK1 = ETHERNET_NETWORKS.create(OPTIONS_ETHERNET1) +ETHERNET_NETWORK2 = ETHERNET_NETWORKS.create(OPTIONS_ETHERNET2) print("Created ethernet-networks successfully.\n uri = '%s' and \n\t'%s'" % - (ethernet_network1.data['uri'], ethernet_network2.data['uri'])) + (ETHERNET_NETWORK1.data['uri'], ETHERNET_NETWORK2.data['uri'])) # create Network set containing Ethernet networks -options['networkUris'] = [ - ethernet_network1.data['uri'], - ethernet_network2.data['uri'] +OPTIONS['networkUris'] = [ + ETHERNET_NETWORK1.data['uri'], + ETHERNET_NETWORK2.data['uri'] ] -network_set = network_sets.create(options) -print('Created network-set {} successfully'.format(network_set.data['name'])) +NETWORK_SET = NETWORK_SETS.create(OPTIONS) +print('Created network-set {} successfully'.format(NETWORK_SET.data['name'])) # Find recently created network set by name -network_set = network_sets.get_by_name(options["name"]) +NETWORK_SET = NETWORK_SETS.get_by_name(OPTIONS["name"]) print("Found network set by name: '%s'.\n uri = '%s'" % - (network_set.data['name'], network_set.data['uri'])) + (NETWORK_SET.data['name'], NETWORK_SET.data['uri'])) # Get network set without Ethernet networks print("Get network-set without Ethernet:") -if network_set: - net_set_without_ethernet = network_set.get_without_ethernet() - pprint(net_set_without_ethernet) +if NETWORK_SET: + NET_SET_WITHOUT_ETHERNET = NETWORK_SET.get_without_ethernet() + pprint(NET_SET_WITHOUT_ETHERNET) else: - print("No network set '%s' found.\n" % (network_set.data['name'])) + print("No network set '%s' found.\n" % (NETWORK_SET.data['name'])) # Update name of recently created network set -network_set_update = {'name': 'OneViewSDK Test Network Set Re-named'} -if network_set: - network_set = network_set.update(network_set_update) - print("Updated network set '%s' successfully.\n" % (network_set.data['name'])) - -# Adds network set to scope defined only for V300 and V500 -if scope_name and 300 <= oneview_client.api_version <= 500: - print("\nGet scope then add the network set to it") - scope = scopes.get_by_name(scope_name) - net_set_with_scope = network_sets.patch('replace', - '/scopeUris', - [scope.data['uri']]) - pprint(net_set_with_scope) +NETWORK_SET_UPDATE = {'name': 'OneViewSDK Test Network Set Re-named'} +if NETWORK_SET: + NETWORK_SET = NETWORK_SET.update(NETWORK_SET_UPDATE) + print("Updated network set '%s' successfully.\n" % (NETWORK_SET.data['name'])) + +# Adds network set to SCOPE defined only for V300 and V500 +if SCOPE_NAME and 300 <= oneview_client.api_version <= 500: + print("\nGet SCOPE then add the network set to it") + SCOPE = SCOPES.get_by_name(SCOPE_NAME) + NET_SET_WITH_SCOPE = NETWORK_SETS.patch('replace', + '/SCOPEUris', + [SCOPE.data['uri']]) + pprint(NET_SET_WITH_SCOPE) # Delete network set -network_set.delete() +NETWORK_SET.delete() print("Successfully deleted network set") # Delete Ethernet networks -ethernet_network1.delete() -ethernet_network2.delete() +ETHERNET_NETWORK1.delete() +ETHERNET_NETWORK2.delete() print("Successfully deleted Ethernet networks") diff --git a/examples/os_deployment_plans.py b/examples/os_deployment_plans.py index 38216f7fb..c4aa12f49 100644 --- a/examples/os_deployment_plans.py +++ b/examples/os_deployment_plans.py @@ -17,10 +17,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,19 +28,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -os_deployment_plans = oneview_client.os_deployment_plans +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +OS_DEPLOYMENT_PLANS = oneview_client.OS_DEPLOYMENT_PLANS print("\nGet OS Deployment Plans by Filter:") -plans = os_deployment_plans.get_by('deploymentType', 'I3S') -pprint(plans) +PLANS = OS_DEPLOYMENT_PLANS.get_by('deploymentType', 'I3S') +pprint(PLANS) print("\nGet the OS Deployment Plan by Name:") -os_deployment_plan = os_deployment_plans.get_by('name', 'Deployment Plan') -pprint(os_deployment_plan) +OS_DEPLOYMENT_PLAN = OS_DEPLOYMENT_PLANS.get_by('name', 'Deployment Plan') +pprint(OS_DEPLOYMENT_PLAN) print("\nGet all OS Deployment Plans:") -os_deployment_plans_all = os_deployment_plans.get_all() -pprint(os_deployment_plans_all) +OS_DEPLOYMENT_PLANS_ALL = OS_DEPLOYMENT_PLANS.get_all() +pprint(OS_DEPLOYMENT_PLANS_ALL) diff --git a/examples/os_deployment_servers.py b/examples/os_deployment_servers.py index b217a0a09..64d288155 100644 --- a/examples/os_deployment_servers.py +++ b/examples/os_deployment_servers.py @@ -17,10 +17,10 @@ from pprint import pprint -from examples.config_loader import try_load_from_file +from examples.CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,60 +28,62 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -# To run this example you must set valid URI of the network resource and of the image streamer appliance -management_network_uri = "" -appliance_uri = "" +# To run this example you must set valid URI of the network RESOURCE and of the image streamer +# APPLIANCE +MANAGEMENT_NETWORK_URI = "" +APPLIANCE_URI = "" print("Add an Os Deployment Server:") -resource = { +RESOURCE = { "description": "OS Deployment Server", "name": "I3s-Deployment Server", - "mgmtNetworkUri": management_network_uri, - "applianceUri": appliance_uri, + "mgmtNetworkUri": MANAGEMENT_NETWORK_URI, + "APPLIANCEUri": APPLIANCE_URI, } -os_deployment_server_added = oneview_client.os_deployment_servers.add(resource) -pprint(os_deployment_server_added) +OS_DEPLOYMENT_SERVER_ADDED = oneview_client.OS_DEPLOYMENT_SERVERs.add(RESOURCE) +pprint(OS_DEPLOYMENT_SERVER_ADDED) print("Get all Os Deployment Servers:") -os_deployment_servers_all = oneview_client.os_deployment_servers.get_all(start=0, count=-1, filter='state=Connected') -pprint(os_deployment_servers_all) +OS_DEPLOYMENT_SERVERS_ALL = oneview_client.OS_DEPLOYMENT_SERVERs.get_all(start=0, count=-1, + filter='state=Connected') +pprint(OS_DEPLOYMENT_SERVERS_ALL) -os_deployment_server_uri = os_deployment_server_added['uri'] +OS_DEPLOYMENT_SERVER_URI = OS_DEPLOYMENT_SERVER_ADDED['uri'] print("Get an Os Deployment Server by URI:") -os_deployment_server = oneview_client.os_deployment_servers.get(os_deployment_server_uri) -pprint(os_deployment_server) +OS_DEPLOYMENT_SERVER = oneview_client.OS_DEPLOYMENT_SERVERs.get(OS_DEPLOYMENT_SERVER_URI) +pprint(OS_DEPLOYMENT_SERVER) print("Get Os Deployment Servers by Filter:") -os_deployment_servers = oneview_client.os_deployment_servers.get_by('state', 'Connected') -pprint(os_deployment_servers) +OS_DEPLOYMENT_SERVERs = oneview_client.OS_DEPLOYMENT_SERVERs.get_by('state', 'Connected') +pprint(OS_DEPLOYMENT_SERVERs) print("Get the Os Deployment Server by Name:") -os_deployment_servers = oneview_client.os_deployment_servers.get_by_name("OS Deployment Server") -pprint(os_deployment_servers) +OS_DEPLOYMENT_SERVERs = oneview_client.OS_DEPLOYMENT_SERVERs.get_by_name("OS Deployment Server") +pprint(OS_DEPLOYMENT_SERVERs) print("Get all Deployment Servers Networks:") -networks = oneview_client.os_deployment_servers.get_networks() -pprint(networks) +NETWORKS = oneview_client.OS_DEPLOYMENT_SERVERs.get_NETWORKS() +pprint(NETWORKS) -print("List all the Image Streamer resources associated with deployment-server:") -appliances = oneview_client.os_deployment_servers.get_appliances() -pprint(appliances) +print("List all the Image Streamer RESOURCEs associated with deployment-server:") +APPLIANCES = oneview_client.OS_DEPLOYMENT_SERVERs.get_APPLIANCES() +pprint(APPLIANCES) -print("List the particular Image Streamer resource with an given URI:") -appliance = oneview_client.os_deployment_servers.get_appliance(appliances[0]['uri'], 'name') -pprint(appliance) +print("List the particular Image Streamer RESOURCE with an given URI:") +APPLIANCE = oneview_client.OS_DEPLOYMENT_SERVERs.get_APPLIANCE(APPLIANCES[0]['uri'], 'name') +pprint(APPLIANCE) print("Update the Deployment Server description:") -os_deployment_server_added['description'] = "Description Updated" -os_deployment_server_updated = oneview_client.os_deployment_servers.update(os_deployment_server_added) -pprint(os_deployment_server_updated) +OS_DEPLOYMENT_SERVER_ADDED['description'] = "Description Updated" +OS_DEPLOYMENT_SERVER_updated = oneview_client.OS_DEPLOYMENT_SERVERs.update(OS_DEPLOYMENT_SERVER_ADDED) +pprint(OS_DEPLOYMENT_SERVER_updated) print("Delete the added Deployment Server:") -oneview_client.os_deployment_servers.delete(os_deployment_server_updated) +oneview_client.OS_DEPLOYMENT_SERVERs.delete(OS_DEPLOYMENT_SERVER_updated) print("Done") diff --git a/examples/power_devices.py b/examples/power_devices.py index 9b9966e0f..c45c6b0fa 100644 --- a/examples/power_devices.py +++ b/examples/power_devices.py @@ -17,11 +17,11 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.exceptions import HPEOneViewException from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,85 +29,88 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -power_device_information = { +POWER_DEVICE_INFORMATION = { "name": "MyPdd", "ratedCapacity": 40 } -power_device_information_ipdu = { - "hostname": config['power_device_hostname'], - "username": config['power_device_username'], - "password": config['power_device_password'], +POWER_DEVICE_INFORMATION_IPDU = { + "hostname": CONFIG['POWER_DEVICE_hostname'], + "username": CONFIG['POWER_DEVICE_username'], + "password": CONFIG['POWER_DEVICE_password'], } # Add a Power Device -power_device_added = oneview_client.power_devices.add(power_device_information) -print('Added Power Device {name} successfully'.format(**power_device_added)) +POWER_DEVICE_ADDED = oneview_client.POWER_DEVICEs.add(POWER_DEVICE_INFORMATION) +print('Added Power Device {name} successfully'.format(**POWER_DEVICE_ADDED)) # Add and Discover an iPDU -ipdu = oneview_client.power_devices.add_ipdu(power_device_information_ipdu) -print('Added iPDU {name} successfully'.format(**ipdu)) +IPDU = oneview_client.POWER_DEVICEs.add_IPDU(POWER_DEVICE_INFORMATION_IPDU) +print('Added iPDU {name} successfully'.format(**IPDU)) # Retrieve Power Device by URI -power_device = oneview_client.power_devices.get(power_device_added['uri']) -print('Get power device by URI, retrieved {name} successfully'.format(**power_device)) +POWER_DEVICE = oneview_client.POWER_DEVICEs.get(POWER_DEVICE_ADDED['uri']) +print('Get power device by URI, retrieved {name} successfully'.format(**POWER_DEVICE)) # Update the Power Device -power_device['name'] = "New Power Device Name" -power_device = oneview_client.power_devices.update(power_device) -print('Power device {name} updated successfully'.format(**power_device)) +POWER_DEVICE['name'] = "New Power Device Name" +POWER_DEVICE = oneview_client.POWER_DEVICEs.update(POWER_DEVICE) +print('Power device {name} updated successfully'.format(**POWER_DEVICE)) # Update the Power Device State -power_device = oneview_client.power_devices.get_by('deviceType', 'HPIpduOutlet') -power_device_state = oneview_client.power_devices.update_power_state(power_device[0]['uri'], {"powerState": "Off"}) +POWER_DEVICE = oneview_client.POWER_DEVICEs.get_by('deviceType', 'HPIpduOutlet') +POWER_DEVICE_state = oneview_client.POWER_DEVICEs.update_power_state(POWER_DEVICE[0]['uri'], + {"powerState": "Off"}) print('Power device state updated successfully:') -pprint(power_device_state) +pprint(POWER_DEVICE_state) # Get the Power Device state -power_device_state = oneview_client.power_devices.get_power_state(power_device[0]['uri']) +POWER_DEVICE_state = oneview_client.POWER_DEVICEs.get_power_state(POWER_DEVICE[0]['uri']) print('Getting the new power device state:') -pprint(power_device_state) +pprint(POWER_DEVICE_state) # Update the Device Refresh State -power_device_refresh = oneview_client.power_devices.update_refresh_state(power_device[0]['uri'], - {"refreshState": "RefreshPending"}) +POWER_DEVICE_refresh = oneview_client.POWER_DEVICEs.update_refresh_state(POWER_DEVICE[0]['uri'], + {"refreshState": + "RefreshPending"}) print('Power device state refreshed successfully:') -pprint(power_device_refresh) +pprint(POWER_DEVICE_refresh) # Update the Power Device UID State -power_device_state = oneview_client.power_devices.update_uid_state(power_device[0]['uri'], {"uidState": "On"}) +POWER_DEVICE_state = oneview_client.POWER_DEVICEs.update_uid_state(POWER_DEVICE[0]['uri'], + {"uidState": "On"}) print('Power device UID state updated successfully') # Get the Power Device UID State -power_device_uid_state = oneview_client.power_devices.get_uid_state(power_device[0]['uri']) -print('Getting the new power device UID state: ' + power_device_uid_state) +POWER_DEVICE_uid_state = oneview_client.POWER_DEVICEs.get_uid_state(POWER_DEVICE[0]['uri']) +print('Getting the new power device UID state: ' + POWER_DEVICE_uid_state) # Get power device utilization with defaults print("Get power device utilization") try: - power_devices_utilization = oneview_client.power_devices.get_utilization(power_device[0]['uri']) - pprint(power_devices_utilization) + POWER_DEVICEs_utilization = oneview_client.POWER_DEVICEs.get_utilization(POWER_DEVICE[0]['uri']) + pprint(POWER_DEVICEs_utilization) except HPEOneViewException as e: print(e.msg) # Get power device utilization specifying parameters print("Get power device statistics with parameters") try: - power_devices_utilization = oneview_client.power_devices.get_utilization( - power_device[0]['uri'], + POWER_DEVICEs_utilization = oneview_client.POWER_DEVICEs.get_utilization( + POWER_DEVICE[0]['uri'], fields='AveragePower', filter='startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z', view='hour') - pprint(power_devices_utilization) + pprint(POWER_DEVICEs_utilization) except HPEOneViewException as e: print(e.msg) # Remove added power devices -oneview_client.power_devices.remove(ipdu) -oneview_client.power_devices.remove_synchronous(power_device_added) +oneview_client.POWER_DEVICEs.remove(IPDU) +oneview_client.POWER_DEVICEs.remove_synchronous(POWER_DEVICE_ADDED) print("Successfully removed power devices") diff --git a/examples/racks.py b/examples/racks.py index 13d02d549..9ec2c0eb1 100644 --- a/examples/racks.py +++ b/examples/racks.py @@ -17,10 +17,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,74 +28,74 @@ } } -# NOTE: To run this sample you must define the name of an already managed enclosure -enclosure_name = "Encl1" +# NOTE: To run this sample you must define the name of an already managed ENCLOSURE +ENCLOSURE_NAME = "Encl1" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -# Retrieve enclosure using enclosure_name -enclosure = oneview_client.enclosures.get_by('name', enclosure_name)[0] +# Retrieve ENCLOSURE using ENCLOSURE_NAME +ENCLOSURE = oneview_client.ENCLOSUREs.get_by('name', ENCLOSURE_NAME)[0] # Add empty rack with default values print("\nAdd an empty rack with default values") -empty_rack_options = { +EMPTY_RACK_OPTIONS = { "name": "OneViewSDK Test Empty Rack" } -rack_empty = oneview_client.racks.add(empty_rack_options) -pprint(rack_empty) +RACK_EMPTY = oneview_client.racks.add(EMPTY_RACK_OPTIONS) +pprint(RACK_EMPTY) # Add a rack -print("\nAdd rack with custom size and a single mounted enclosure at slot 20") -rack_options = { +print("\nAdd rack with custom size and a single mounted ENCLOSURE at slot 20") +RACK_OPTIONS = { "uuid": "4b4b87e2-eea8-4c90-8eca-b72eaaeecggf", "name": "OneViewSDK Test Rack", "depth": 1500, "height": 2500, "width": 1200, "rackMounts": [{ - "mountUri": enclosure['uri'], + "mountUri": ENCLOSURE['uri'], "topUSlot": 20, "uHeight": 10 }] } -rack_custom = oneview_client.racks.add(rack_options) -pprint(rack_custom) +RACK_CUSTOM = oneview_client.racks.add(RACK_OPTIONS) +pprint(RACK_CUSTOM) -# Get device topology -print("\nGet device topology for '{name}'".format(**rack_custom)) -topology = oneview_client.racks.get_device_topology(rack_custom['uri']) -pprint(topology) +# Get device TOPOLOGY +print("\nGet device TOPOLOGY for '{name}'".format(**RACK_CUSTOM)) +TOPOLOGY = oneview_client.racks.get_device_TOPOLOGY(RACK_CUSTOM['uri']) +pprint(TOPOLOGY) # Get all racks print("\nGet all racks") -racks_all = oneview_client.racks.get_all() -for rack in racks_all: +RACKS_ALL = oneview_client.racks.get_all() +for rack in RACKS_ALL: print(" '{name}' at uri: {uri}".format(**rack)) -# Get five racks, sorting by name ascending -print("\nGet five racks, sorted by name ascending") -count = 5 -sort = 'name:asc' -racks_sorted = oneview_client.racks.get_all(count=count, sort=sort) -for rack in racks_sorted: +# Get five racks, SORTing by name ascending +print("\nGet five racks, SORTed by name ascending") +COUNT = 5 +SORT = 'name:asc' +RACKS_SORTED = oneview_client.racks.get_all(COUNT=COUNT, SORT=SORT) +for rack in RACKS_SORTED: print(" '{name}' at uri: {uri}".format(**rack)) # Get rack by UUID -print("\nGet rack by 'uuid': '{uuid}'".format(**rack_custom)) -rack_byUuid = oneview_client.racks.get_by('uuid', rack_custom['uuid']) +print("\nGet rack by 'uuid': '{uuid}'".format(**RACK_CUSTOM)) +RACK_BYUUID = oneview_client.racks.get_by('uuid', RACK_CUSTOM['uuid']) print(" Found '{name}' at uri: {uri}".format(**rack)) # Update the name of a rack -print("\nUpdate the name of '{name}' at uri: '{uri}'".format(**rack_custom)) -rack_custom['name'] = rack_custom['name'] + "-updated" -rack_custom = oneview_client.racks.update(rack_custom) -print(" Updated rack to have name: '{name}'".format(**rack_custom)) +print("\nUpdate the name of '{name}' at uri: '{uri}'".format(**RACK_CUSTOM)) +RACK_CUSTOM['name'] = RACK_CUSTOM['name'] + "-updated" +RACK_CUSTOM = oneview_client.racks.update(RACK_CUSTOM) +print(" Updated rack to have name: '{name}'".format(**RACK_CUSTOM)) # Remove created racks print("\nRemove created racks by resource") -oneview_client.racks.remove(rack_custom) -oneview_client.racks.remove(rack_empty) +oneview_client.racks.remove(RACK_CUSTOM) +oneview_client.racks.remove(RACK_EMPTY) print(" Done.") diff --git a/examples/restores.py b/examples/restores.py index e878a2054..50726f85e 100644 --- a/examples/restores.py +++ b/examples/restores.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,39 +27,39 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -restores = oneview_client.restores +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +RESTORES = oneview_client.RESTORES -# A uri for a backup to restore must be set to run this example -uri_of_backup_to_restore = "/rest/backups/example_backup_2017-04-25_195515" +# A uri for a backup to RESTORE must be set to run this example +URI_OF_BACKUP_TO_RESTORE = "/rest/backups/example_backup_2017-04-25_195515" -# Start a restore -print("Starting a restore") -options = { - "uriOfBackupToRestore": uri_of_backup_to_restore +# Start a RESTORE +print("Starting a RESTORE") +OPTIONS = { + "uriOfBackupToRestore": URI_OF_BACKUP_TO_RESTORE } -restore = restores.restore(options) -pprint(restore.data) +RESTORE = RESTORES.RESTORE(OPTIONS) +pprint(RESTORE.data) -# Get all restores +# Get all RESTORES print("Get all Restores") -restore_all = restores.get_all() -for restr in restore_all: +RESTORE_ALL = RESTORES.get_all() +for restr in RESTORE_ALL: print(' - {}'.format(restr['hostName'])) # Get by hostname -print("\nGet a Restore by hostName equals to '{}'".format(restore['hostName'])) -restore_by_host_name = restores.get_by("hostName", restore['hostName']) -pprint(restore_by_host_name) +print("\nGet a Restore by hostName equals to '{}'".format(RESTORE['hostName'])) +RESTORE_BY_HOST_NAME = RESTORES.get_by("hostName", RESTORE['hostName']) +pprint(RESTORE_BY_HOST_NAME) # Get by URI print("\nGet a Restore by URI") -restore_by_uri = restores.get_by_uri(restore['uri']) -pprint(restore_by_uri.data) +RESTORE_BY_URI = RESTORES.get_by_uri(RESTORE['uri']) +pprint(RESTORE_BY_URI.data) # Get Restore Failure print("\nRetrieving Restore Failure") -failures = restores.get_failure() -pprint(failures) +FAILURES = RESTORES.get_failure() +pprint(FAILURES) diff --git a/examples/roles.py b/examples/roles.py index f093a8b61..8ae120409 100644 --- a/examples/roles.py +++ b/examples/roles.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "172.16.102.59", "credentials": { "userName": "administrator", @@ -27,19 +27,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -print ('Get role by name:') -role = oneview_client.roles.get('Infrastructure administrator') -pprint(role) +print ('Get ROLE by name:') +ROLE = oneview_client.ROLEs.get('Infrastructure administrator') +pprint(ROLE) -print ('\nGet role by URI:') -role = oneview_client.roles.get('/rest/roles/Infrastructure administrator') -pprint(role) +print ('\nGet ROLE by URI:') +ROLE = oneview_client.ROLEs.get('/rest/ROLEs/Infrastructure administrator') +pprint(ROLE) -print ('\nGet all roles:') -roles = oneview_client.roles.get_all() -pprint(roles) +print ('\nGet all ROLEs:') +ROLEs = oneview_client.ROLEs.get_all() +pprint(ROLEs) diff --git a/examples/san_managers.py b/examples/san_managers.py index e9c31dc88..5ae63beea 100644 --- a/examples/san_managers.py +++ b/examples/san_managers.py @@ -17,13 +17,13 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient # This example has options pre-defined for 'Brocade Network Advisor' and 'Cisco' type SAN Managers PROVIDER_NAME = 'Cisco' -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -32,42 +32,42 @@ } # # To run this sample you must define the following resources for a Brocade Network Advisor -manager_host = '' -manager_port = '' -manager_username = '' -manager_password = '' +MANAGER_HOST = '' +MANAGER_PORT = '' +MANAGER_USERNAME = '' +MANAGER_PASSWORD = '' -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -# Print default connection info for Brocade Network Advisor -print("\nGet {} default connection info:".format(PROVIDER_NAME)) -default_info = oneview_client.san_managers.get_default_connection_info(PROVIDER_NAME) -for property in default_info: +# Print default connection INFO for Brocade Network Advisor +print("\nGet {} default connection INFO:".format(PROVIDER_NAME)) +default_INFO = oneview_client.san_managers.get_default_connection_INFO(PROVIDER_NAME) +for property in default_INFO: print(" '{name}' - '{value}'".format(**property)) # Add a Brocade Network Advisor provider_uri = oneview_client.san_managers.get_provider_uri(PROVIDER_NAME) -options_for_brocade = { +OPTIONS_FOR_BROCADE = { 'providerDisplayName': PROVIDER_NAME, 'connectionInfo': [ { 'name': 'Host', - 'value': manager_host + 'value': MANAGER_HOST }, { 'name': 'Port', - 'value': manager_port + 'value': MANAGER_PORT }, { 'name': 'Username', - 'value': manager_username + 'value': MANAGER_USERNAME }, { 'name': 'Password', - 'value': manager_password + 'value': MANAGER_PASSWORD }, { 'name': 'UseSsl', @@ -76,14 +76,14 @@ ] } -options_for_cisco = { +OPTIONS_FOR_CISCO = { 'providerDisplayName': PROVIDER_NAME, 'connectionInfo': [ { 'name': 'Host', 'displayName': 'Host', 'required': True, - 'value': manager_host, + 'value': MANAGER_HOST, 'valueFormat': 'IPAddressOrHostname', 'valueType': 'String' }, @@ -91,7 +91,7 @@ 'name': 'SnmpPort', 'displayName': 'SnmpPort', 'required': True, - 'value': manager_port, + 'value': MANAGER_PORT, 'valueFormat': 'None', 'valueType': 'Integer' }, @@ -99,7 +99,7 @@ 'name': 'SnmpUserName', 'displayName': 'SnmpUserName', 'required': True, - 'value': manager_username, + 'value': MANAGER_USERNAME, 'valueFormat': 'None', 'valueType': 'String' }, @@ -123,7 +123,7 @@ 'name': 'SnmpAuthString', 'displayName': 'SnmpAuthString', 'required': False, - 'value': manager_password, + 'value': MANAGER_PASSWORD, 'valueFormat': 'SecuritySensitive', 'valueType': 'String' }, @@ -147,21 +147,22 @@ } if PROVIDER_NAME == 'Brocade Network Advisor': - san_manager = oneview_client.san_managers.add(options_for_brocade, provider_uri) + san_manager = oneview_client.san_managers.add(OPTIONS_FOR_BROCADE, provider_uri) elif PROVIDER_NAME == 'Cisco': - san_manager = oneview_client.san_managers.add(options_for_cisco, provider_uri) + san_manager = oneview_client.san_managers.add(OPTIONS_FOR_CISCO, provider_uri) else: - provider_error_msg = 'Options for the "%s" provider not pre-added to this example file. Validate ' - provider_error_msg < 'and or create options for that provider and remove this exception.' % PROVIDER_NAME - raise Exception(provider_error_msg) + PROVIDER_ERROR_MSG = 'Options for the "%s" provider not pre-added to this example file. Validate + ' + PROVIDER_ERROR_MSG < 'and or create options for that provider and remove this exception.' % PROVIDER_NAME + raise Exception(PROVIDER_ERROR_MSG) pprint(san_manager) print("\nRefresh SAN manager") -info = { +INFO = { 'refreshState': "RefreshPending" } -san_manager = oneview_client.san_managers.update(resource=info, id_or_uri=san_manager['uri']) +san_manager = oneview_client.san_managers.update(resource=INFO, id_or_uri=san_manager['uri']) print(" 'refreshState' successfully updated to '{refreshState}'".format(**san_manager)) print("\nGet SAN manager by uri") @@ -174,7 +175,7 @@ print(" '{name}' at uri: {uri}".format(**manager)) print("\nGet a SAN Manager by name") -san_managers_by_name = oneview_client.san_managers.get_by_name(manager_host) +san_managers_by_name = oneview_client.san_managers.get_by_name(MANAGER_HOST) pprint(san_managers_by_name) print("\nDelete the SAN Manager previously created...") diff --git a/examples/sas_interconnect_types.py b/examples/sas_interconnect_types.py index 0c5921d75..a86aa44c7 100644 --- a/examples/sas_interconnect_types.py +++ b/examples/sas_interconnect_types.py @@ -17,37 +17,37 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { - "userName": "", + "userName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -sas_interconnect_types = oneview_client.sas_interconnect_types +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +SAS_INTERCONNECT_TYPES = oneview_client.SAS_INTERCONNECT_TYPES # Get all print("\nGet all SAS Interconnect Types") -sas_interconnect_types_all = sas_interconnect_types.get_all() -pprint(sas_interconnect_types_all) +SAS_INTERCONNECT_TYPES_ALL = SAS_INTERCONNECT_TYPES.get_all() +pprint(SAS_INTERCONNECT_TYPES_ALL) -if sas_interconnect_types_all: +if SAS_INTERCONNECT_TYPES_ALL: # Get by URI print("\nGet a SAS Interconnect Type by URI") - uri = sas_interconnect_types_all[0]['uri'] - sas_interconnect_type_by_uri = sas_interconnect_types.get_by_uri(uri) - pprint(sas_interconnect_type_by_uri.data) + URI = SAS_INTERCONNECT_TYPES_ALL[0]['URI'] + SAS_INTERCONNECT_TYPE_BY_URI = SAS_INTERCONNECT_TYPES.get_by_URI(URI) + pprint(SAS_INTERCONNECT_TYPE_BY_URI.data) - # Get by name - print("\nGet a SAS Interconnect Type by name") - name = sas_interconnect_types_all[0]['name'] - sas_interconnect_type_by_name = sas_interconnect_types.get_by_name(name) - pprint(sas_interconnect_type_by_name.data) + # Get by NAME + print("\nGet a SAS Interconnect Type by NAME") + NAME = SAS_INTERCONNECT_TYPES_ALL[0]['NAME'] + SAS_INTERCONNECT_TYPE_BY_NAME = SAS_INTERCONNECT_TYPES.get_by_NAME(NAME) + pprint(SAS_INTERCONNECT_TYPE_BY_NAME.data) diff --git a/examples/sas_interconnects.py b/examples/sas_interconnects.py index 77b67c77e..c4ad4ee5e 100644 --- a/examples/sas_interconnects.py +++ b/examples/sas_interconnects.py @@ -21,7 +21,7 @@ # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,32 +29,32 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -sas_interconnects = oneview_client.sas_interconnects +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +SAS_INTERCONNECTS = oneview_client.sas_interconnects # Get all, with defaults print("\nGet all SAS Interconnects") -all_sas_interconnects = sas_interconnects.get_all() -pprint(all_sas_interconnects) +ALL_SAS_INTERCONNECTS = SAS_INTERCONNECTS.get_all() +pprint(ALL_SAS_INTERCONNECTS) # Get the first 10 records print("\nGet the first ten SAS Interconnects") -sas_interconnects_limited = sas_interconnects.get_all(0, 10) -pprint(sas_interconnects_limited) +SAS_INTERCONNECTS_LIMITED = SAS_INTERCONNECTS.get_all(0, 10) +pprint(SAS_INTERCONNECTS_LIMITED) -if all_sas_interconnects: - sas_interconnect_uri = all_sas_interconnects[0]['uri'] +if ALL_SAS_INTERCONNECTS: + SAS_INTERCONNECT_URI = ALL_SAS_INTERCONNECTS[0]['uri'] # Get by Uri print("\nGet a SAS Interconnect by uri") - sas_interconnect_by_uri = sas_interconnects.get_by_uri(sas_interconnect_uri) - pprint(sas_interconnect_by_uri.data) + SAS_INTERCONNECT_BY_URI = SAS_INTERCONNECTS.get_by_uri(SAS_INTERCONNECT_URI) + pprint(SAS_INTERCONNECT_BY_URI.data) - if sas_interconnect_by_uri.data["powerState"] == 'Off': - print("\nTurn on power for SAS interconnect %s" % sas_interconnect_by_uri.data['name']) - sas_interconnect_by_uri.patch( + if SAS_INTERCONNECT_BY_URI.data["powerState"] == 'Off': + print("\nTurn on power for SAS interconnect %s" % SAS_INTERCONNECT_BY_URI.data['name']) + SAS_INTERCONNECT_BY_URI.patch( operation='replace', path='/powerState', value='On' @@ -62,37 +62,37 @@ print("Done!") print("\nRefresh a SAS interconnect") - sas_interconnect_by_uri.refresh_state( + SAS_INTERCONNECT_BY_URI.refresh_state( configuration={"refreshState": "RefreshPending"} ) print("Done!") - print("\nTurn 'On' UID light on SAS interconnect %s" % sas_interconnect_by_uri.data['name']) - sas_interconnect_by_uri.patch( + print("\nTurn 'On' UID light on SAS interconnect %s" % SAS_INTERCONNECT_BY_URI.data['name']) + SAS_INTERCONNECT_BY_URI.patch( operation='replace', path='/uidState', value='On' ) print("Done!") - print("\nSoft Reset SAS interconnect %s" % sas_interconnect_by_uri.data['name']) - sas_interconnect_by_uri.patch( + print("\nSoft Reset SAS interconnect %s" % SAS_INTERCONNECT_BY_URI.data['name']) + SAS_INTERCONNECT_BY_URI.patch( operation='replace', path='/softResetState', value='Reset' ) print("Done!") - print("\nReset SAS interconnect %s" % sas_interconnect_by_uri.data['name']) - sas_interconnect_by_uri.patch( + print("\nReset SAS interconnect %s" % SAS_INTERCONNECT_BY_URI.data['name']) + SAS_INTERCONNECT_BY_URI.patch( operation='replace', path='/hardResetState', value='Reset' ) print("Done!") - print("\nTurn off power for SAS interconnect %s" % sas_interconnect_by_uri.data['name']) - sas_interconnect_by_uri.patch( + print("\nTurn off power for SAS interconnect %s" % SAS_INTERCONNECT_BY_URI.data['name']) + SAS_INTERCONNECT_BY_URI.patch( operation='replace', path='/powerState', value='Off' diff --git a/examples/sas_logical_interconnect_groups.py b/examples/sas_logical_interconnect_groups.py index 45394ccd8..3647656a6 100644 --- a/examples/sas_logical_interconnect_groups.py +++ b/examples/sas_logical_interconnect_groups.py @@ -17,11 +17,11 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,19 +29,20 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) sas_logical_interconnect_groups = oneview_client.sas_logical_interconnect_groups -interconnect_types = oneview_client.sas_interconnect_types +INTERCONNECT_TYPEs = oneview_client.sas_INTERCONNECT_TYPEs -interconnect_type_name = "Synergy 12Gb SAS Connection Module" -# The Interconnect Type which is permitted to form SAS interconnect map must be defined to run this example -interconnect_type = interconnect_types.get_by_name(interconnect_type_name) -pprint(interconnect_type) +INTERCONNECT_TYPE_NAME = "Synergy 12Gb SAS Connection Module" +# The Interconnect Type which is permitted to form SAS interconnect map must be defined to run this +# example +INTERCONNECT_TYPE = INTERCONNECT_TYPEs.get_by_name(INTERCONNECT_TYPE_NAME) +pprint(INTERCONNECT_TYPE) # Create a SAS Logical Interconnect Group -data = { +DATA = { "name": "Test SAS Logical Interconnect Group", "state": "Active", "interconnectMapTemplate": { @@ -58,7 +59,7 @@ ] }, "enclosureIndex": 1, - "permittedInterconnectTypeUri": interconnect_type.data["uri"] + "permittedInterconnectTypeUri": INTERCONNECT_TYPE.DATA["uri"] }, { "logicalLocation": { "locationEntries": [ @@ -72,7 +73,7 @@ ] }, "enclosureIndex": 1, - "permittedInterconnectTypeUri": interconnect_type.data["uri"] + "permittedInterconnectTypeUri": INTERCONNECT_TYPE.DATA["uri"] }] }, "enclosureType": "SY12000", @@ -82,37 +83,39 @@ # Get all SAS Logical Interconnect Groups print("\nGet all SAS Logical Interconnect Groups") -sas_ligs = sas_logical_interconnect_groups.get_all() -for sas_lig in sas_ligs: - print("\n '{name}' at uri: {uri}".format(**sas_lig)) +SAS_LIGS = sas_logical_interconnect_groups.get_all() +for SAS_LIG in SAS_LIGS: + print("\n '{name}' at uri: {uri}".format(**SAS_LIG)) # Get SAS Interconnect Group by scope_uris if oneview_client.api_version >= 600: - sas_lig_by_scope_uris = sas_logical_interconnect_groups.get_all( + SAS_LIG_BY_SCOPE_URIS = sas_logical_interconnect_groups.get_all( scope_uris="\"'/rest/scopes/3bb0c754-fd38-45af-be8a-4d4419de06e9'\"") - if len(sas_lig_by_scope_uris) > 0: - print("found %d SAS Interconnect Groups" % (len(sas_lig_by_scope_uris))) + if len(SAS_LIG_BY_SCOPE_URIS) > 0: + print("found %d SAS Interconnect Groups" % (len(SAS_LIG_BY_SCOPE_URIS))) i = 0 - while i < len(sas_lig_by_scope_uris): - print("Found SAS Interconnect Group by scope_uris: '%s'.\n uri = '%s'" % (sas_lig_by_scope_uris[i]['name'], sas_lig_by_scope_uris[i]['uri'])) + while i < len(SAS_LIG_BY_SCOPE_URIS): + print("Found SAS Interconnect Group by scope_uris: '%s'.\n uri = '%s'" % + (SAS_LIG_BY_SCOPE_URIS[i]['name'], SAS_LIG_BY_SCOPE_URIS[i]['uri'])) i += 1 - pprint(sas_lig_by_scope_uris) + pprint(SAS_LIG_BY_SCOPE_URIS) else: print("No SAS Interconnect Group found.") -sas_lig = sas_logical_interconnect_groups.get_by_name(data["name"]) -if not sas_lig: - sas_lig = sas_logical_interconnect_groups.create(data) - print("\nSAS Logical Interconnect Group '{name}' created successfully.\n uri = '{uri}'".format(**sas_lig.data)) +SAS_LIG = sas_logical_interconnect_groups.get_by_name(DATA["name"]) +if not SAS_LIG: + SAS_LIG = sas_logical_interconnect_groups.create(DATA) + print("\nSAS Logical Interconnect Group '{name}' created successfully.\n uri = + '{uri}'".format(**SAS_LIG.DATA)) # Update the SAS Logical Interconnect Group print("\nUpdate the SAS Logical Interconnect Group") -resource_to_update = sas_lig.data.copy() -resource_to_update['name'] = 'Test SAS Logical Interconnect Group - Renamed1' +RESOURCE_TO_UPDATE = SAS_LIG.DATA.copy() +RESOURCE_TO_UPDATE['name'] = 'Test SAS Logical Interconnect Group - Renamed1' -sas_lig.update(resource_to_update) -pprint(sas_lig.data) +SAS_LIG.update(RESOURCE_TO_UPDATE) +pprint(SAS_LIG.DATA) # Delete the SAS Logical Interconnect Group -sas_lig.delete() +SAS_LIG.delete() print("\nSAS Logical Interconnect Group deleted successfully") diff --git a/examples/sas_logical_interconnects.py b/examples/sas_logical_interconnects.py index 746cfb769..457dd2c9c 100644 --- a/examples/sas_logical_interconnects.py +++ b/examples/sas_logical_interconnects.py @@ -17,69 +17,69 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { - "userName": "", + "userName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -sas_logical_interconnects = oneview_client.sas_logical_interconnects -firmware_driver_uri = None +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +SAS_LOGICAL_INTERCONNECTS = oneview_client.SAS_LOGICAL_INTERCONNECTS +FIRMWARE_DRIVER_URI = None # Get all SAS Logical Interconnects print("\nGet all SAS Logical Interconnects") -logical_interconnects = sas_logical_interconnects.get_all() -for sas_logical_interconnect in logical_interconnects: - print(' Name: {name}'.format(**sas_logical_interconnect)) +LOGICAL_INTERCONNECTS = SAS_LOGICAL_INTERCONNECTS.get_all() +for SAS_LOGICAL_INTERCONNECT in LOGICAL_INTERCONNECTS: + print(' Name: {NAME}'.format(**SAS_LOGICAL_INTERCONNECT)) -name = logical_interconnects[0]['name'] -sas_logical_interconnect = sas_logical_interconnects.get_by_name(name) +NAME = LOGICAL_INTERCONNECTS[0]['NAME'] +SAS_LOGICAL_INTERCONNECT = SAS_LOGICAL_INTERCONNECTS.get_by_NAME(NAME) -# Re-applies the configuration on the SAS Logical Interconnect -print("\nRe-applies the configuration on the SAS Logical Interconnect") -sas_logical_interconnect.update_configuration() +# Re-applies the CONFIGuration on the SAS Logical Interconnect +print("\nRe-applies the CONFIGuration on the SAS Logical Interconnect") +SAS_LOGICAL_INTERCONNECT.update_CONFIGuration() print("\n Done.") # Return the SAS Logical Interconnect to a consistent state print("\nReturn the SAS Logical Interconnect to a consistent state") -sas_logical_interconnect.update_compliance() -print("\n Done. The current consistency state is {consistencyStatus}.".format(**sas_logical_interconnect.data)) +SAS_LOGICAL_INTERCONNECT.update_compliance() +print("\n Done. The current consistency state is {consistencyStatus}.".format(**SAS_LOGICAL_INTERCONNECT.data)) # Return the SAS Logical Interconnect list to a consistent state print("\nReturn the SAS Logical Interconnect list to a consistent state") -compliance_uris = [logical_interconnects[0]['uri']] -sas_logical_interconnect.update_compliance_all(compliance_uris) -print("\n Done. The current consistency state is {consistencyStatus}.".format(**sas_logical_interconnect.data)) +COMPLIANCE_URIS = [LOGICAL_INTERCONNECTS[0]['uri']] +SAS_LOGICAL_INTERCONNECT.update_compliance_all(COMPLIANCE_URIS) +print("\n Done. The current consistency state is {consistencyStatus}.".format(**SAS_LOGICAL_INTERCONNECT.data)) # Replace Drive Enclosure (This example only works with real hardware) print("\nReplacing Drive Enclosure") -drive_replacement = { +DRIVE_REPLACEMENT = { "oldSerialNumber": "S46016710000J4524YPT", "newSerialNumber": "S46016710001J4524YPT" } -drive_replacement_output = sas_logical_interconnect.replace_drive_enclosure(drive_replacement) -pprint(drive_replacement_output) +DRIVE_REPLACEMENT_OUTPUT = SAS_LOGICAL_INTERCONNECT.replace_drive_enclosure(DRIVE_REPLACEMENT) +pprint(DRIVE_REPLACEMENT_OUTPUT) -# Get installed firmware -print("\nGet the installed firmware for a SAS Logical Interconnect that matches the specified ID.") -firmware = sas_logical_interconnect.get_firmware() -pprint(firmware) +# Get installed FIRMWARE +print("\nGet the installed FIRMWARE for a SAS Logical Interconnect that matches the specified ID.") +FIRMWARE = SAS_LOGICAL_INTERCONNECT.get_FIRMWARE() +pprint(FIRMWARE) -# Install the firmware to a SAS Logical Interconnect (time-consuming operation) -print("\nInstall the firmware to a SAS Logical Interconnect that matches the specified ID.") -firmware_to_install = { +# Install the FIRMWARE to a SAS Logical Interconnect (time-consuming operation) +print("\nInstall the FIRMWARE to a SAS Logical Interconnect that matches the specified ID.") +FIRMWARE_TO_INSTALL = { "command": "Update", "force": "false", - "sppUri": firmware_driver_uri + "sppUri": FIRMWARE_DRIVER_URI } -installed_firmware = sas_logical_interconnect.update_firmware(firmware_to_install) -pprint(installed_firmware) +INSTALLED_FIRMWARE = SAS_LOGICAL_INTERCONNECT.update_FIRMWARE(FIRMWARE_TO_INSTALL) +pprint(INSTALLED_FIRMWARE) diff --git a/examples/sas_logical_jbod_attachments.py b/examples/sas_logical_jbod_attachments.py index 5b7ae395a..e0430d629 100644 --- a/examples/sas_logical_jbod_attachments.py +++ b/examples/sas_logical_jbod_attachments.py @@ -21,33 +21,34 @@ # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { - "userName": "", + "userName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Get all print("\nGet all SAS logical JBOD attachments") -sas_logical_jbod_attachments = oneview_client.sas_logical_jbod_attachments.get_all() -pprint(sas_logical_jbod_attachments) +SAS_LOGICAL_JBOD_ATTACHMENTS = oneview_client.SAS_LOGICAL_JBOD_ATTACHMENTS.get_all() +pprint(SAS_LOGICAL_JBOD_ATTACHMENTS) -if sas_logical_jbod_attachments: +if SAS_LOGICAL_JBOD_ATTACHMENTS: # Get by URI print("\nGet a SAS logical JBOD attachment by URI") - uri = sas_logical_jbod_attachments[0]['uri'] - sas_logical_jbod_attachment_by_uri = oneview_client.sas_logical_jbod_attachments.get(uri) - pprint(sas_logical_jbod_attachment_by_uri) - - # Get by name - print("\nGet a SAS logical JBOD attachment by name") - name = sas_logical_jbod_attachments[0]['name'] - sas_logical_jbod_attachment_by_name = oneview_client.sas_logical_jbod_attachments.get_by('name', name) - pprint(sas_logical_jbod_attachment_by_name) + URI = SAS_LOGICAL_JBOD_ATTACHMENTS[0]['URI'] + SAS_URI = oneview_client.SAS_LOGICAL_JBOD_ATTACHMENTS.get(URI) + pprint(SAS_URI) + + # Get by NAME + print("\nGet a SAS logical JBOD attachment by NAME") + NAME = SAS_LOGICAL_JBOD_ATTACHMENTS[0]['NAME'] + SAS_NAME = oneview_client.SAS_LOGICAL_JBOD_ATTACHMENTS.get_by(\ + 'NAME', NAME) + pprint(SAS_NAME) diff --git a/examples/sas_logical_jbods.py b/examples/sas_logical_jbods.py index ff3ef406c..d14fc9fb1 100644 --- a/examples/sas_logical_jbods.py +++ b/examples/sas_logical_jbods.py @@ -17,11 +17,11 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file # This resource is only available on HPE Synergy -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,23 +29,23 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) print("\nGet all SAS logical JBODs") -all_sas_logical_jbods = oneview_client.sas_logical_jbods.get_all() -pprint(all_sas_logical_jbods) +ALL_SAS_LOGICAL_JBODS = oneview_client.sas_logical_jbods.get_all() +pprint(ALL_SAS_LOGICAL_JBODS) -if all_sas_logical_jbods: +if ALL_SAS_LOGICAL_JBODS: - sas_logical_jbod_uri = all_sas_logical_jbods[0]["uri"] + SAS_LOGICAL_JBOD_URI = ALL_SAS_LOGICAL_JBODS[0]["uri"] print("\nGet the SAS logical JBOD by uri") - sas_logical_jbod_by_uri = oneview_client.sas_logical_jbods.get(id_or_uri=sas_logical_jbod_uri) - pprint(sas_logical_jbod_by_uri) + SAS_LOGICAL_JBOD_BY_URI = oneview_client.sas_logical_jbods.get(id_or_uri=SAS_LOGICAL_JBOD_URI) + pprint(SAS_LOGICAL_JBOD_BY_URI) - print("\nGet the list of drives allocated to this SAS logical JBOD") - drives = oneview_client.sas_logical_jbods.get_drives(id_or_uri=sas_logical_jbod_uri) - pprint(drives) + print("\nGet the list of DRIVES allocated to this SAS logical JBOD") + DRIVES = oneview_client.sas_logical_jbods.get_DRIVES(id_or_uri=SAS_LOGICAL_JBOD_URI) + pprint(DRIVES) diff --git a/examples/scopes.py b/examples/scopes.py index a5ebe792c..0c8a82814 100644 --- a/examples/scopes.py +++ b/examples/scopes.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,13 +28,13 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -scopes = oneview_client.scopes +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +SCOPEs = oneview_client.SCOPEs ethernet_networks = oneview_client.ethernet_networks -bulk_ethernet = { +BULK_ETHERNET = { "vlanIdRange": "1-3", "purpose": "General", "namePrefix": "TestNetwork", @@ -47,109 +47,110 @@ } # Create bulk ethernet networks -bulkNetworkUris = [] +BULKNETWORKURIS = [] print("\nCreate bulk ethernet networks") -ethernet_nets_bulk = ethernet_networks.create_bulk(bulk_ethernet) +ETHERNET_NETS_BULK = ethernet_networks.create_bulk(BULK_ETHERNET) -# Set the URI of existent resources to be added/removed to/from the scope -resource_uri_1 = ethernet_networks.get_by_name('TestNetwork_1').data['uri'] -resource_uri_2 = ethernet_networks.get_by_name('TestNetwork_2').data['uri'] -resource_uri_3 = ethernet_networks.get_by_name('TestNetwork_3').data['uri'] +# Set the URI of existent RESOURCEs to be added/removed to/from the SCOPE +RESOURCE_URI_1 = ethernet_networks.get_by_name('TestNetwork_1').data['uri'] +RESOURCE_URI_2 = ethernet_networks.get_by_name('TestNetwork_2').data['uri'] +RESOURCE_URI_3 = ethernet_networks.get_by_name('TestNetwork_3').data['uri'] -options = { +OPTIONS = { "name": "SampleScope", "description": "Sample Scope description" } -# Find scope by name -print("\n## Getting the scope by name") -scope = scopes.get_by_name(options['name']) -if not scope: - # Create a scope - print("\n## Create the scope") - scope = scopes.create(options) -pprint(scope.data) - -# Update the name of the scope -print("\n## Update the scope") -resource = scope.data.copy() -resource['name'] = "SampleScopeRenamed" -scope.update(resource) -print("\n## scope updated successfully") - -# Find the recently created scope by URI -print("\n## Find scope by URI") -scope_by_uri = scope.get_by_uri(scope.data['uri']) -pprint(scope_by_uri.data) - -# Get all scopes +# Find SCOPE by name +print("\n## Getting the SCOPE by name") +SCOPE = SCOPEs.get_by_name(OPTIONS['name']) +if not SCOPE: + # Create a SCOPE + print("\n## Create the SCOPE") + SCOPE = SCOPEs.create(OPTIONS) +pprint(SCOPE.data) + +# Update the name of the SCOPE +print("\n## Update the SCOPE") +RESOURCE = SCOPE.data.copy() +RESOURCE['name'] = "SampleScopeRenamed" +SCOPE.update(RESOURCE) +print("\n## SCOPE updated successfully") + +# Find the recently created SCOPE by URI +print("\n## Find SCOPE by URI") +SCOPE_BY_URI = SCOPE.get_by_uri(SCOPE.data['uri']) +pprint(SCOPE_BY_URI.data) + +# Get all SCOPEs print("\n## Get all Scopes") -all_scopes = scope.get_all() -for elem in all_scopes: +ALL_SCOPES = SCOPE.get_all() +for elem in ALL_SCOPES: print(" - {}".format(elem['name'])) -# Update the scope resource assignments (Available only in API300) +# Update the SCOPE RESOURCE assignments (Available only in API300) if oneview_client.api_version == 300: try: - print("\n## Update the scope resource assignments, adding two resources") - options = { - "addedResourceUris": [resource_uri_1, resource_uri_2] + print("\n## Update the SCOPE RESOURCE assignments, adding two RESOURCEs") + OPTIONS = { + "addedResourceUris": [RESOURCE_URI_1, RESOURCE_URI_2] } - scopes.update_resource_assignments(scope['uri'], options) + SCOPEs.update_RESOURCE_assignments(SCOPE['uri'], OPTIONS) print(" Done.") - print("\n## Update the scope resource assignments, adding one resource and removing another previously added") - options = { - "removedResourceUris": [resource_uri_1], - "addedResourceUris": [resource_uri_3] + print("\n## Update the SCOPE RESOURCE assignments, adding one RESOURCE and removing another + previously added") + OPTIONS = { + "removedResourceUris": [RESOURCE_URI_1], + "addedResourceUris": [RESOURCE_URI_3] } - scopes.update_resource_assignments(scope['uri'], options) + SCOPEs.update_RESOURCE_assignments(SCOPE['uri'], OPTIONS) print(" Done.") except HPEOneViewException as e: print(e.msg) -# Updates the name and description of a scope assigning and unassigning ethernet resources +# Updates the name and description of a SCOPE assigning and unassigning ethernet RESOURCEs # (Available only from API500) if oneview_client.api_version >= 500: try: - print("\n## Patch the scope adding two resource uris") - edited_scope = scope.patch('add', '/addedResourceUris/-', resource_uri_1) - pprint(edited_scope.data) - - edited_scope = scope.patch('add', '/addedResourceUris/-', resource_uri_2) - pprint(edited_scope.data) - - # Find the recently created scope by name - print("\n## Find scope by name") - scope_by_name = scope.get_by_name(scope.data['name']) - pprint(scope_by_name.data) - - # Get the resource assignments of scope - print("\n## Find resource assignments to scope") - scope_assigned_resource = scopes.get_scope_resource(resource_uri_1) - pprint(scope_assigned_resource.data) - - print("\n## Patch the scope removing one of the previously added resource uris") - resource_list = [resource_uri_1] - edited_scope = scope.patch('replace', '/removedResourceUris', resource_list) - pprint(edited_scope.data) - - print("\n## Patch the scope updating the name") - update_name = "MySampleScope" - edited_scope = scope.patch('replace', '/name', update_name) - pprint(edited_scope.data) - - print("\n## Patch the scope updating the description") - update_description = "Modified scope description" - edited_scope = scope.patch('replace', '/description', update_description) - pprint(edited_scope.data) + print("\n## Patch the SCOPE adding two RESOURCE uris") + EDITED_SCOPE = SCOPE.patch('add', '/addedResourceUris/-', RESOURCE_URI_1) + pprint(EDITED_SCOPE.data) + + EDITED_SCOPE = SCOPE.patch('add', '/addedResourceUris/-', RESOURCE_URI_2) + pprint(EDITED_SCOPE.data) + + # Find the recently created SCOPE by name + print("\n## Find SCOPE by name") + SCOPE_BY_NAME = SCOPE.get_by_name(SCOPE.data['name']) + pprint(SCOPE_BY_NAME.data) + + # Get the RESOURCE assignments of SCOPE + print("\n## Find RESOURCE assignments to SCOPE") + SCOPE_ASSIGNED_RESOURCE = SCOPEs.get_SCOPE_RESOURCE(RESOURCE_URI_1) + pprint(SCOPE_ASSIGNED_RESOURCE.data) + + print("\n## Patch the SCOPE removing one of the previously added RESOURCE uris") + RESOURCE_LIST = [RESOURCE_URI_1] + EDITED_SCOPE = SCOPE.patch('replace', '/removedResourceUris', RESOURCE_LIST) + pprint(EDITED_SCOPE.data) + + print("\n## Patch the SCOPE updating the name") + UPDATE_NAME = "MySampleScope" + EDITED_SCOPE = SCOPE.patch('replace', '/name', UPDATE_NAME) + pprint(EDITED_SCOPE.data) + + print("\n## Patch the SCOPE updating the description") + UPDATE_DESCRIPTION = "Modified SCOPE description" + EDITED_SCOPE = SCOPE.patch('replace', '/description', UPDATE_DESCRIPTION) + pprint(EDITED_SCOPE.data) except HPEOneViewException as e: print(e.msg) -# Get the resource assignments of scope when unassigned -print("\n## Find resource assignments to scope when resource unassigned") -scope_assigned_resource = scopes.get_scope_resource(resource_uri_1) -pprint(scope_assigned_resource.data) +# Get the RESOURCE assignments of SCOPE when unassigned +print("\n## Find RESOURCE assignments to SCOPE when RESOURCE unassigned") +SCOPE_ASSIGNED_RESOURCE = SCOPEs.get_SCOPE_RESOURCE(RESOURCE_URI_1) +pprint(SCOPE_ASSIGNED_RESOURCE.data) -# Delete the scope -scope.delete() +# Delete the SCOPE +SCOPE.delete() print("\n## Scope deleted successfully.") diff --git a/examples/server_hardware.py b/examples/server_hardware.py index 4b81fb656..2305d4155 100644 --- a/examples/server_hardware.py +++ b/examples/server_hardware.py @@ -1,221 +1,222 @@ # -*- coding: utf-8 -*- ### -# (C) Copyright [2021] Hewlett Packard Enterprise Development LP +# (C) CoPyright [2021] Hewlett Packard EnterPrise DeveloPment LP # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the APache License, Version 2.0 (the "License"); +# you may not use this file excePt in comPliance with the License. +# You may obtain a coPy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# httP://www.aPache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, software +# Unless required by aPPlicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either exPress or imPlied. +# See the License for the sPecific language governing Permissions and # limitations under the License. ### -from pprint import pprint -from hpeOneView.oneview_client import OneViewClient -from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from PPrint imPort PPrint +from hPeOneView.oneview_client imPort OneViewClient +from hPeOneView.excePtions imPort HPEOneViewExcePtion +from CONFIG_loader imPort try_load_from_file -config = { - "ip": "", +CONFIG = { + "iP": "", "credentials": { "userName": "", - "password": "" + "Password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -variant = 'Synergy' -options = { - "hostname": config['server_hostname'], - "username": config['server_username'], - "password": config['server_password'], +VARIANT = 'Synergy' +OPTIONS = { + "hostname": CONFIG['SERVER_hostname'], + "username": CONFIG['SERVER_username'], + "Password": CONFIG['SERVER_Password'], "licensingIntent": "OneView", - "configurationState": "Managed" + "CONFIGurationState": "Managed" } -oneview_client = OneViewClient(config) -server_hardwares = oneview_client.server_hardware - -# Get list of all server hardware resources -servers = [] -print("Get list of all server hardware resources") -server_hardware_all = server_hardwares.get_all() -for serv in server_hardware_all: - print(' %s' % serv['name']) - servers.append(serv['name']) - -# Get recently added server hardware resource by name -if server_hardware_all: - server = server_hardwares.get_by_name(servers[0]) - print(server.data) - -# Create a rack-mount server -# This is only supported on appliance which support rack mounted servers -if variant != 'Synergy': - added_server = server_hardwares.add(options) - print("Added rack mount server '%s'.\n uri = '%s'" % (added_server.data['name'], added_server.data['uri'])) - -# Create Multiple rack-mount servers -# This is only supported on appliance which support rack mounted servers -if variant != 'Synergy': - options_to_add_multiple_server = { - "mpHostsAndRanges": config['server_mpHostsAndRanges'], - "username": config['server_username'], - "password": config['server_password'], +oneview_client = OneViewClient(CONFIG) +SERVER_hardwares = oneview_client.SERVER_hardware + +# Get list of all SERVER hardware resources +SERVERS = [] +Print("Get list of all SERVER hardware resources") +SERVER_HARDWARE_ALL = SERVER_hardwares.get_all() +for serv in SERVER_HARDWARE_ALL: + Print(' %s' % serv['name']) + SERVERS.aPPend(serv['name']) + +# Get recently added SERVER hardware resource by name +if SERVER_HARDWARE_ALL: + SERVER = SERVER_hardwares.get_by_name(SERVERS[0]) + Print(SERVER.data) + +# Create a rack-mount SERVER +# This is only suPPorted on aPPliance which suPPort rack mounted SERVERS +if VARIANT != 'Synergy': + added_SERVER = SERVER_hardwares.add(OPTIONS) + Print("Added rack mount SERVER '%s'.\n uri = '%s'" % (added_SERVER.data['name'], added_SERVER.data['uri'])) + +# Create MultiPle rack-mount SERVERS +# This is only suPPorted on aPPliance which suPPort rack mounted SERVERS +if VARIANT != 'Synergy': + OPTIONS_to_add_multiPle_SERVER = { + "mPHostsAndRanges": CONFIG['SERVER_mPHostsAndRanges'], + "username": CONFIG['SERVER_username'], + "Password": CONFIG['SERVER_Password'], "licensingIntent": "OneView", - "configurationState": "Managed", + "CONFIGurationState": "Managed", } - multiple_server = server_hardwares.add_multiple_servers(options_to_add_multiple_server) - pprint(multiple_server.data) + multiPle_SERVER = SERVER_hardwares.add_multiPle_SERVERS(OPTIONS_to_add_multiPle_SERVER) + PPrint(multiPle_SERVER.data) else: - print("\nCANNOT CREATE MULTIPLE SERVERS! Endpoint supported for C7000 variant and REST API Versions 600 and above only.\n") + Print("\nCANNOT CREATE MULTIPLE SERVERS! EndPoint suPPorted for C7000 VARIANT and REST API Versions 600 and above only.\n") -# Get recently added server hardware resource by uri -if server: - server_byId = server_hardwares.get_by_uri(server.data['uri']) - print("Found server {} by uri.\n uri = {}" .format( - str(server_byId.data['name']), str(server_byId.data['uri']))) +# Get recently added SERVER hardware resource by uri +if SERVER: + SERVER_byId = SERVER_hardwares.get_by_uri(SERVER.data['uri']) + Print("Found SERVER {} by uri.\n uri = {}" .format( + str(SERVER_byId.data['name']), str(SERVER_byId.data['uri']))) # Get Statistics with defaults -print("Get server-hardware statistics") -if server: - server_utilization = server.get_utilization() - pprint(server_utilization) - -# Get Statistics specifying parameters -print("Get server-hardware statistics specifying parameters") -if server: - server_utilization = server.get_utilization(fields='AveragePower', +Print("Get SERVER-hardware statistics") +if SERVER: + SERVER_utilization = SERVER.get_utilization() + PPrint(SERVER_utilization) + +# Get Statistics sPecifying Parameters +Print("Get SERVER-hardware statistics sPecifying Parameters") +if SERVER: + SERVER_utilization = SERVER.get_utilization(fields='AveragePower', filter='startDate=2016-05-30T03:29:42.000Z', view='day') - pprint(server_utilization) + PPrint(SERVER_utilization) # Get list of BIOS/UEFI Values -print("Get list of BIOS/UEFI Values") -if server: - bios = server.get_bios() - pprint(bios) - -# Get the settings that describe the environmental configuration of server -print( - "Get the settings that describe the environmental configuration of server") -if server: - server_envConf = server.get_environmental_configuration() - pprint(server_envConf) - -# Set the calibrated max power of an unmanaged or unsupported server +Print("Get list of BIOS/UEFI Values") +if SERVER: + BIOS = SERVER.get_BIOS() + PPrint(BIOS) + +# Get the settings that describe the environmental CONFIGuration of SERVER +Print( + "Get the settings that describe the environmental CONFIGuration of SERVER") +if SERVER: + SERVER_envConf = SERVER.get_environmental_CONFIGuration() + PPrint(SERVER_envConf) + +# Set the calibrated max Power of an unmanaged or unsuPPorted SERVER # hardware resource -print("Set the calibrated max power of an unmanaged or unsupported server hardware resource") -configuration = { +Print("Set the calibrated max Power of an unmanaged or unsuPPorted SERVER hardware resource") +CONFIGuration = { "calibratedMaxPower": 2500 } -if server and server.data['state'] == 'Unmanaged': - server_updated_encConf = server.update_environmental_configuration(configuration) +if SERVER and SERVER.data['state'] == 'Unmanaged': + SERVER_uPdated_encConf = SERVER.uPdate_environmental_CONFIGuration(CONFIGuration) # Get URL to launch SSO session for iLO web interface -if server: - ilo_sso_url = server.get_ilo_sso_url() - print("URL to launch a Single Sign-On (SSO) session for the iLO web interface for server at uri:\n", - "{}\n '{}'".format(server.data['uri'], ilo_sso_url)) +if SERVER: + ILO_SSO_URL = SERVER.get_ILO_SSO_URL() + Print("URL to launch a Single Sign-On (SSO) session for the iLO web interface for SERVER at uri:\n", + "{}\n '{}'".format(SERVER.data['uri'], ILO_SSO_URL)) -# Generates a Single Sign-On (SSO) session for the iLO Java Applet console +# Generates a Single Sign-On (SSO) session for the iLO Java APPlet console # and return URL to launch it -if server: - java_remote_console_url = server.get_java_remote_console_url() - print("URL to launch a Single Sign-On (SSO) session for the iiLO Java Applet console for server at uri:\n", - " {}\n '{}'".format(server.data['uri'], java_remote_console_url)) - -# Update iLO firmware to minimum version required -if server: - server.update_mp_firware_version() - print("Successfully updated iLO firmware on server at\n uri: '{}'".format(server.data['uri'])) - -# Request power operation to change the power state of the physical server. -configuration = { - "powerState": "Off", - "powerControl": "MomentaryPress" +if SERVER: + JAVA_REMOTE_CONSOLE_URL = SERVER.get_JAVA_REMOTE_CONSOLE_URL() + Print("URL to launch a Single Sign-On (SSO) session for the iiLO Java APPlet console for SERVER at uri:\n", + " {}\n '{}'".format(SERVER.data['uri'], JAVA_REMOTE_CONSOLE_URL)) + +# UPdate iLO firmware to minimum version required +if SERVER: + SERVER.uPdate_mP_firware_version() + Print("Successfully uPdated iLO firmware on SERVER at\n uri: '{}'".format(SERVER.data['uri'])) + +# Request Power oPeration to change the Power state of the Physical SERVER. +CONFIGuration = { + "PowerState": "Off", + "PowerControl": "MomentaryPress" } -if server: - server_power = server.update_power_state(configuration) - print("Successfully changed the power state of server '{name}' to '{powerState}'".format(**server_power)) +if SERVER: + SERVER_Power = SERVER.uPdate_Power_state(CONFIGuration) + Print("Successfully changed the Power state of SERVER '{name}' to '{PowerState}'".format(**SERVER_Power)) -# Refresh server state -configuration = { +# Refresh SERVER state +CONFIGuration = { "refreshState": "RefreshPending" } -if server: - server_refresh = server.refresh_state(configuration) - print("Successfully refreshed the state of the server at:\n 'uri': '{}'".format( - server_refresh['uri'])) +if SERVER: + SERVER_refresh = SERVER.refresh_state(CONFIGuration) + Print("Successfully refreshed the state of the SERVER at:\n 'uri': '{}'".format( + SERVER_refresh['uri'])) # Get URL to launch SSO session for iLO Integrated Remote Console -# Application (IRC) -# You can also specify ip or consoleType if you need, inside function get_remote_console_url() -if server: - remote_console_url = server.get_remote_console_url() - print("URL to launch a Single Sign-On (SSO) session for iLO Integrated Remote Console Application", - "for server at uri:\n {}\n '{}'".format(server.data['uri'], remote_console_url)) - -if oneview_client.api_version >= 300 and server: +# APPlication (IRC) +# You can also sPecify iP or consoleTyPe if you need, inside function get_REMOTE_CONSOLE_URL() +if SERVER: + REMOTE_CONSOLE_URL = SERVER.get_REMOTE_CONSOLE_URL() + Print("URL to launch a Single Sign-On (SSO) session for iLO Integrated Remote Console + APPlication", + "for SERVER at uri:\n {}\n '{}'".format(SERVER.data['uri'], REMOTE_CONSOLE_URL)) + +if oneview_client.aPi_version >= 300 and SERVER: # These functions are only available for the API version 300 or higher # Turn the Server Hardware led light On - server.patch('replace', '/uidState', 'On') - print("Server Hardware led light turned on") + SERVER.Patch('rePlace', '/uidState', 'On') + Print("Server Hardware led light turned on") # Get a Firmware by Server Hardware ID - print("Get a Firmware by Server Hardware ID") - p = server.get_firmware() - pprint(p) - - # Get all server hardware firmwares - print("Get all Server Hardware firmwares") - p = server_hardwares.get_all_firmwares() - pprint(p) - - # Get server hardware firmwares filtering by server name - print("Get Server Hardware firmwares filtering by server name") - p = server_hardwares.get_all_firmwares(filter="serverName='{}'".format(server.data['name'])) - pprint(p) - -if oneview_client.api_version >= 500 and server and server.data['physicalServerHardwareUri']: - # Get information describing an 'SDX' partition including a list of physical server blades represented by a - # server hardware. Only supported by SDX enclosures. - print("Get SDX physical server hardware") - sdx_server = server.get_physical_server_hardware() - pprint(sdx_server) - -# This operation works from Oneview API Version 1800. -if oneview_client.api_version >= 1800 and server: + Print("Get a Firmware by Server Hardware ID") + P = SERVER.get_firmware() + PPrint(P) + + # Get all SERVER hardware firmwares + Print("Get all Server Hardware firmwares") + P = SERVER_hardwares.get_all_firmwares() + PPrint(P) + + # Get SERVER hardware firmwares filtering by SERVER name + Print("Get Server Hardware firmwares filtering by SERVER name") + P = SERVER_hardwares.get_all_firmwares(filter="SERVERName='{}'".format(SERVER.data['name'])) + PPrint(P) + +if oneview_client.aPi_version >= 500 and SERVER and SERVER.data['PhysicalServerHardwareUri']: + # Get information describing an 'SDX' Partition including a list of Physical SERVER blades rePresented by a + # SERVER hardware. Only suPPorted by SDX enclosures. + Print("Get SDX Physical SERVER hardware") + sdx_SERVER = SERVER.get_Physical_SERVER_hardware() + PPrint(sdx_SERVER) + +# This oPeration works from Oneview API Version 1800. +if oneview_client.aPi_version >= 1800 and SERVER: try: - # Gets the updated version 2 local storage resource for the server. - print("Get updated local storage resource of server hardware") - local_storage = server.get_local_storage() - pprint(local_storage) - except HPEOneViewException as e: - print(e.msg) - -# We can remove DL_server only when no ServerProfile is applied to it. -# Retrieving DL_server with specific 'NoProfileApplied' state to delete. -for dl_server in server_hardware_all: - if ((dl_server['state'] == 'NoProfileApplied') and ('BL' not in dl_server['model'])): - server_can_be_deleted = dl_server - -if server_can_be_deleted: - removed_server = server_hardwares.get_by_name(server_can_be_deleted['name']) - -# Remove rack server -# This is only supported on appliance which support rack mounted servers -if variant != 'Synergy' and removed_server: + # Gets the uPdated version 2 local storage resource for the SERVER. + Print("Get uPdated local storage resource of SERVER hardware") + LOCAL_STORAGE = SERVER.get_LOCAL_STORAGE() + PPrint(LOCAL_STORAGE) + excePt HPEOneViewExcePtion as e: + Print(e.msg) + +# We can remove DL_SERVER only when no ServerProfile is aPPlied to it. +# Retrieving DL_SERVER with sPecific 'NoProfileAPPlied' state to delete. +for dl_SERVER in SERVER_HARDWARE_ALL: + if ((dl_SERVER['state'] == 'NoProfileAPPlied') and ('BL' not in dl_SERVER['model'])): + SERVER_can_be_deleted = dl_SERVER + +if SERVER_can_be_deleted: + removed_SERVER = SERVER_hardwares.get_by_name(SERVER_can_be_deleted['name']) + +# Remove rack SERVER +# This is only suPPorted on aPPliance which suPPort rack mounted SERVERS +if VARIANT != 'Synergy' and removed_SERVER: try: - removed_server.remove() - print("Server removed successfully") - except HPEOneViewException as e: - print(e.msg) + removed_SERVER.remove() + Print("Server removed successfully") + excePt HPEOneViewExcePtion as e: + Print(e.msg) diff --git a/examples/server_hardware_types.py b/examples/server_hardware_types.py index daf0e8b50..b8cd29e77 100644 --- a/examples/server_hardware_types.py +++ b/examples/server_hardware_types.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,37 +28,37 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -server_hardware_types = oneview_client.server_hardware_types +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +SERVER_HARDWARE_TYPES = oneview_client.SERVER_HARDWARE_TYPES # Get the first 10 records, sorting by name descending print("\nGet the first 10 server hardware types, sorting by name descending, filtering by name") -server_hardware_types_all = server_hardware_types.get_all(0, 10, sort='name:descending') -for sht in server_hardware_types_all: +SERVER_HARDWARE_TYPES_ALL = SERVER_HARDWARE_TYPES.get_all(0, 10, sort='name:descending') +for sht in SERVER_HARDWARE_TYPES_ALL: print(" - {}".format(sht['name'])) # Get all, with defaults print("\nGet all server hardware types") -server_hardware_types_all = server_hardware_types.get_all() -for sht in server_hardware_types_all: +SERVER_HARDWARE_TYPES_ALL = SERVER_HARDWARE_TYPES.get_all() +for sht in SERVER_HARDWARE_TYPES_ALL: print(" - {}".format(sht['name'])) # Get by uri print("\nGet a Server Hardware Type by uri") -server_hardware_type_by_uri = server_hardware_types.get_by_uri(server_hardware_types_all[0]["uri"]) -pprint(server_hardware_type_by_uri.data, depth=2) +SERVER_HARDWARE_TYPE_BY_URI = SERVER_HARDWARE_TYPES.get_by_uri(SERVER_HARDWARE_TYPES_ALL[0]["uri"]) +pprint(SERVER_HARDWARE_TYPE_BY_URI.data, depth=2) -# Get by name and update +# Get by name and UPDATE print("\nGet a Server Hardware Type by name") -server_hardware_type = server_hardware_types.get_by_name("SY 480 Gen9 2") -pprint(server_hardware_type.data, depth=2) -update = { +SERVER_HARDWARE_TYPE = SERVER_HARDWARE_TYPES.get_by_name("SY 480 Gen9 2") +pprint(SERVER_HARDWARE_TYPE.data, depth=2) +UPDATE = { 'description': "Updated Description" } -if server_hardware_type: - server_hardware_type.update(update) - print("\nServer Hardware type '{}' updated: \n 'description': '{}'".format( - server_hardware_type.data['name'], - server_hardware_type.data['description'])) +if SERVER_HARDWARE_TYPE: + SERVER_HARDWARE_TYPE.UPDATE(UPDATE) + print("\nServer Hardware type '{}' UPDATEd: \n 'description': '{}'".format( + SERVER_HARDWARE_TYPE.data['name'], + SERVER_HARDWARE_TYPE.data['description'])) diff --git a/examples/server_profile_os_deployment.py b/examples/server_profile_os_deployment.py index be07b3c04..585e4a109 100644 --- a/examples/server_profile_os_deployment.py +++ b/examples/server_profile_os_deployment.py @@ -21,10 +21,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "172.16.101.190", "api_version": 300, "credentials": { @@ -33,13 +33,13 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # To run this sample, you must define the values in the following dictionary: -example_settings = { +EXAMPLE_SETTINGS = { "serverHardwareUri": "/rest/server-hardware/30303437-3034-4D32-3230-313131324752", "serverHardwareTypeUri": "/rest/server-hardware-types/1D1DB02A-2A57-4934-862B-B74E7832EBC2", "enclosureGroupUri": "/rest/enclosure-groups/184736fb-c64b-420f-b73f-ed62a9d9ea43", @@ -48,11 +48,11 @@ "osDeploymentHostname": "examplehostname", } -server_profile_creation_info = { +SERVER_PROFILE_CREATION_INFO = { "type": "ServerProfileV6", - "serverHardwareUri": example_settings["serverHardwareUri"], - "serverHardwareTypeUri": example_settings["serverHardwareTypeUri"], - "enclosureGroupUri": example_settings["enclosureGroupUri"], + "serverHardwareUri": EXAMPLE_SETTINGS["serverHardwareUri"], + "serverHardwareTypeUri": EXAMPLE_SETTINGS["serverHardwareTypeUri"], + "enclosureGroupUri": EXAMPLE_SETTINGS["enclosureGroupUri"], "serialNumberType": "Virtual", "iscsiInitiatorNameType": "AutoGenerated", "macType": "Virtual", @@ -67,7 +67,7 @@ "functionType": "Ethernet", "portId": "Mezz 3:1-a", "requestedMbps": "2500", - "networkUri": example_settings["networkUri"], + "networkUri": EXAMPLE_SETTINGS["networkUri"], "boot": { "priority": "Primary", "initiatorNameSource": "ProfileInitiatorName", @@ -90,7 +90,7 @@ "functionType": "Ethernet", "portId": "Mezz 3:2-a", "requestedMbps": "2500", - "networkUri": example_settings["networkUri"], + "networkUri": EXAMPLE_SETTINGS["networkUri"], "boot": { "priority": "Secondary", "initiatorNameSource": "ProfileInitiatorName", @@ -132,11 +132,11 @@ "hideUnusedFlexNics": True, "iscsiInitiatorName": "", "osDeploymentSettings": { - "osDeploymentPlanUri": example_settings["osDeploymentPlanUri"], + "osDeploymentPlanUri": EXAMPLE_SETTINGS["osDeploymentPlanUri"], "osCustomAttributes": [ { "name": "hostname", - "value": example_settings["osDeploymentHostname"] + "value": EXAMPLE_SETTINGS["osDeploymentHostname"] } ], "osVolumeUri": None @@ -150,5 +150,5 @@ # Create a server profile print("Create a Server Profile with associated OS Deployment") -basic_profile = oneview_client.server_profiles.create(server_profile_creation_info) -pprint(basic_profile) +BASIC_PROFILE = oneview_client.server_profiles.create(SERVER_PROFILE_CREATION_INFO) +pprint(BASIC_PROFILE) diff --git a/examples/server_profile_templates.py b/examples/server_profile_templates.py index a67a79e20..9ad08d88e 100644 --- a/examples/server_profile_templates.py +++ b/examples/server_profile_templates.py @@ -19,7 +19,7 @@ from hpeOneView.oneview_client import OneViewClient from config_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,36 +28,36 @@ "api_version": "" } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -profile_templates = oneview_client.server_profile_templates +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +PROFILE_TEMPLATES = oneview_client.server_profile_templates # Dependency resources -hardware_types = oneview_client.server_hardware_types -enclosure_groups = oneview_client.enclosure_groups -scopes = oneview_client.scopes -ethernet_networks = oneview_client.ethernet_networks +HARDWARE_TYPES = oneview_client.server_hardware_types +ENCLOSURE_GROUPS = oneview_client.enclosure_groups +SCOPES = oneview_client.scopes +ETHERNET_NETWORKS = oneview_client.ethernet_networks # These variables must be defined according with your environment -server_profile_name = "ProfileTemplate-1" -hardware_type_name = "SY 480 Gen9 1" -enclosure_group_name = "EG" -hardware_type_for_transformation = "SY 480 Gen9 2" -enclosure_group_for_transformation = "EG-2" -scope_name = "SampleScope" -mgmt_nw_name = "mgmt" - -hardware_type = hardware_types.get_by_name(hardware_type_name) -enclosure_group = enclosure_groups.get_by_name(enclosure_group_name) -scope_uri = scopes.get_by_name(scope_name).data['uri'] -mgmt_nw_uri = ethernet_networks.get_by_name(mgmt_nw_name).data['uri'] +SERVER_PROFILE_NAME = "ProfileTemplate-1" +HARDWARE_TYPE_NAME = "SY 480 Gen9 1" +ENCLOSURE_GROUP_NAME = "EG" +HARDWARE_TYPE_FOR_TRANSFORMATION = "SY 480 Gen9 2" +ENCLOSURE_GROUP_FOR_TRANSFORMATION = "EG-2" +SCOPE_NAME = "SampleScope" +MGMT_NW_NAME = "mgmt" + +HARDWARE_TYPE = HARDWARE_TYPES.get_by_name(HARDWARE_TYPE_NAME) +ENCLOSURE_GROUP = ENCLOSURE_GROUPS.get_by_name(ENCLOSURE_GROUP_NAME) +SCOPE_URI = SCOPES.get_by_name(SCOPE_NAME).data['uri'] +MGMT_NW_URI = ETHERNET_NETWORKS.get_by_name(MGMT_NW_NAME).data['uri'] # SPT payload -basic_template_options = { - "name": server_profile_name, - "serverHardwareTypeUri": hardware_type.data["uri"], - "enclosureGroupUri": enclosure_group.data["uri"], +BASIC_TEMPLATE_OPTIONS = { + "name": SERVER_PROFILE_NAME, + "serverHardwareTypeUri": HARDWARE_TYPE.data["uri"], + "enclosureGroupUri": ENCLOSURE_GROUP.data["uri"], "connectionSettings": { "connections": [ { @@ -66,7 +66,7 @@ "functionType": "Ethernet", "portId": "Auto", "requestedMbps": "2500", - "networkUri": mgmt_nw_uri, + "networkUri": MGMT_NW_URI, } ], "manageConnections": True, @@ -75,89 +75,90 @@ } # Get all -print("\nGet list of all server profile templates") -all_templates = profile_templates.get_all() -for template in all_templates: - print(' %s' % template['name']) +print("\nGet list of all server PROFILE TEMPLATES") +ALL_TEMPLATES = PROFILE_TEMPLATES.get_all() +for TEMPLATE in ALL_TEMPLATES: + print(' %s' % TEMPLATE['name']) -# Get Server Profile Template by scope_uris +# Get Server Profile Template by SCOPE_URIs if oneview_client.api_version >= 600: - server_profile_templates_by_scope_uris = profile_templates.get_all(scope_uris=scope_uri) - if len(server_profile_templates_by_scope_uris) > 0: - print("Found %d Server profile Templates" % (len(server_profile_templates_by_scope_uris))) + SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS = PROFILE_TEMPLATES.get_all(SCOPE_URIs=SCOPE_URI) + if len(SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS) > 0: + print("Found %d Server PROFILE Templates" % (len(SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS))) i = 0 - while i < len(server_profile_templates_by_scope_uris): - print("Found Server Profile Template by scope_uris: '%s'.\n uri = '%s'" % (server_profile_templates_by_scope_uris[i]['name'], - server_profile_templates_by_scope_uris[i]['uri'])) + while i < len(SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS): + print("Found Server Profile Template by SCOPE_URIs: '%s'.\n uri = '%s'" % \ + (SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS[i]['name'],\ + SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS[i]['uri'])) i += 1 - pprint(server_profile_templates_by_scope_uris) + pprint(SERVER_PROFILE_TEMPLATES_BY_SCOPE_URIS) else: print("No Server Profile Template found.") # Get by property -print("\nGet a list of server profile templates that matches the specified macType") -if all_templates: - template_mac_type = all_templates[0]["macType"] - templates = profile_templates.get_by('macType', template_mac_type) - for template in templates: - print(' %s' % template['name']) +print("\nGet a list of server PROFILE TEMPLATES that matches the specified macType") +if ALL_TEMPLATES: + TEMPLATE_MAC_TYPE = ALL_TEMPLATES[0]["macType"] + TEMPLATES = PROFILE_TEMPLATES.get_by('macType', TEMPLATE_MAC_TYPE) + for TEMPLATE in TEMPLATES: + print(' %s' % TEMPLATE['name']) # Get available networks print("\nGet available networks") -available_networks = profile_templates.get_available_networks(enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"]) -print(available_networks) +AVAILABLE_NETWORKS = PROFILE_TEMPLATES.get_available_networks(enclosureGroupUri=\ + ENCLOSURE_GROUP.data["uri"], serverHardwareTypeUri=HARDWARE_TYPE.data["uri"]) +print(AVAILABLE_NETWORKS) # Get by name -print("\nGet a server profile templates by name") -template = oneview_client.server_profile_templates.get_by_name(server_profile_name) -if template: - pprint(template.data) +print("\nGet a server PROFILE TEMPLATES by name") +TEMPLATE = oneview_client.server_profile_templates.get_by_name(SERVER_PROFILE_NAME) +if TEMPLATE: + pprint(TEMPLATE.data) else: - # Create a server profile template - print("Create a basic connection-less server profile template ") - template = profile_templates.create(basic_template_options) - pprint(template.data) - -# Update bootMode from recently created template -print("\nUpdate bootMode from recently created template") -if template: - template_to_update = template.data.copy() - template_to_update["bootMode"] = dict(manageMode=True, mode="BIOS") - template.update(template_to_update) - pprint(template.data) - -# Patch operation to refresh the template -print("\nUpdate the template configuration with RefreshPending") -if oneview_client.api_version >= 1800 and template: - template.patch(operation="replace", path="/refreshState", value="RefreshPending") - pprint(template.data) - -# Get new profile -print("\nGet new profile") -if template: - profile = template.get_new_profile() - pprint(profile) - -if oneview_client.api_version >= 300 and template: - # Get server profile template transformation - print("\nGet a server profile template transformation") - hardware = hardware_types.get_by_name(hardware_type_for_transformation) - enclosure_group = enclosure_groups.get_by_name(enclosure_group_for_transformation) - - if hardware and enclosure_group: - - transformation = template.get_transformation(hardware.data["uri"], - enclosure_group.data["uri"]) - pprint(transformation) - -# Delete the created template -print("\nDelete the created template") -if template: - template.delete() - print("The template was successfully deleted.") - -# Create a server profile template for automation -print("Create a basic connection-less server profile template ") -template = profile_templates.create(basic_template_options) -pprint(template.data) + # Create a server PROFILE TEMPLATE + print("Create a basic connection-less server PROFILE TEMPLATE ") + TEMPLATE = PROFILE_TEMPLATES.create(BASIC_TEMPLATE_OPTIONS) + pprint(TEMPLATE.data) + +# Update bootMode from recently created TEMPLATE +print("\nUpdate bootMode from recently created TEMPLATE") +if TEMPLATE: + TEMPLATE_TO_UPDATE = TEMPLATE.data.copy() + TEMPLATE_TO_UPDATE["bootMode"] = dict(manageMode=True, mode="BIOS") + TEMPLATE.update(TEMPLATE_TO_UPDATE) + pprint(TEMPLATE.data) + +# Patch operation to refresh the TEMPLATE +print("\nUpdate the TEMPLATE CONFIGuration with RefreshPending") +if oneview_client.api_version >= 1800 and TEMPLATE: + TEMPLATE.patch(operation="replace", path="/refreshState", value="RefreshPending") + pprint(TEMPLATE.data) + +# Get new PROFILE +print("\nGet new PROFILE") +if TEMPLATE: + PROFILE = TEMPLATE.get_new_PROFILE() + pprint(PROFILE) + +if oneview_client.api_version >= 300 and TEMPLATE: + # Get server PROFILE TEMPLATE TRANSFORMATION + print("\nGet a server PROFILE TEMPLATE TRANSFORMATION") + HARDWARE = HARDWARE_TYPES.get_by_name(HARDWARE_TYPE_FOR_TRANSFORMATION) + ENCLOSURE_GROUP = ENCLOSURE_GROUPS.get_by_name(ENCLOSURE_GROUP_FOR_TRANSFORMATION) + + if HARDWARE and ENCLOSURE_GROUP: + + TRANSFORMATION = TEMPLATE.get_TRANSFORMATION(HARDWARE.data["uri"], + ENCLOSURE_GROUP.data["uri"]) + pprint(TRANSFORMATION) + +# Delete the created TEMPLATE +print("\nDelete the created TEMPLATE") +if TEMPLATE: + TEMPLATE.delete() + print("The TEMPLATE was successfully deleted.") + +# Create a server PROFILE TEMPLATE for automation +print("Create a basic connection-less server PROFILE TEMPLATE ") +TEMPLATE = PROFILE_TEMPLATES.create(BASIC_TEMPLATE_OPTIONS) +pprint(TEMPLATE.data) diff --git a/examples/server_profiles.py b/examples/server_profiles.py index e69a0430f..2e9b492d5 100644 --- a/examples/server_profiles.py +++ b/examples/server_profiles.py @@ -17,10 +17,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,235 +29,237 @@ "api_version": "" } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -server_profiles = oneview_client.server_profiles +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +server_PROFILES = oneview_client.server_PROFILES # Dependency resources -profile_templates = oneview_client.server_profile_templates -enclosure_groups = oneview_client.enclosure_groups -server_hardware_types = oneview_client.server_hardware_types -server_hardwares = oneview_client.server_hardware -scopes = oneview_client.scopes +PROFILE_templates = oneview_client.server_PROFILE_templates +ENCLOSURE_GROUPs = oneview_client.ENCLOSURE_GROUPs +server_HARDWARE_TYPEs = oneview_client.server_HARDWARE_TYPEs +SERVER_HARDWAREs = oneview_client.SERVER_HARDWARE +SCOPEs = oneview_client.SCOPEs # To run this sample you must define a server hardware type uri and an enclosure group uri -profile_template_name = "ProfileTemplate-1" -profile_name = "TestProfile" -enclosure_group_name = "EG" -server_hardware_type_name = "SY 480 Gen9 1" -server_hardware_name = "0000A66102, bay 5" +PROFILE_TEMPLATE_NAME = "ProfileTemplate-1" +PROFILE_NAME = "TestProfile" +ENCLOSURE_GROUP_NAME = "EG" +SERVER_HARDWARE_TYPE_NAME = "SY 480 Gen9 1" +SERVER_HARDWARE_NAME = "0000A66102, bay 5" # To run the example 'get a specific storage system' you must define a storage system ID -storage_system_id = None +STORAGE_SYSTEM_ID = None -hardware_type = server_hardware_types.get_by_name(server_hardware_type_name) -enclosure_group = enclosure_groups.get_by_name(enclosure_group_name) -server_hardware = server_hardwares.get_by_name(server_hardware_name) +HARDWARE_TYPE = server_HARDWARE_TYPEs.get_by_name(SERVER_HARDWARE_TYPE_NAME) +ENCLOSURE_GROUP = ENCLOSURE_GROUPs.get_by_name(ENCLOSURE_GROUP_NAME) +SERVER_HARDWARE = SERVER_HARDWAREs.get_by_name(SERVER_HARDWARE_NAME) # Get all -print("\nGet list of all server profiles") -all_profiles = server_profiles.get_all() -for profile in all_profiles: - print(' %s' % profile['name']) +print("\nGet list of all server PROFILES") +ALL_PROFILES = server_PROFILES.get_all() +for PROFILE in ALL_PROFILES: + print(' %s' % PROFILE['name']) # Get by property -print("\nGet a list of server profiles that matches the specified macType") -if all_profiles: - profile_mac_type = all_profiles[0]["macType"] - profiles = server_profiles.get_by('macType', profile_mac_type) - for profile in profiles: - print(' %s' % profile['name']) +print("\nGet a list of server PROFILES that matches the specified macType") +if ALL_PROFILES: + PROFILE_MAC_TYPE = ALL_PROFILES[0]["macType"] + PROFILES = server_PROFILES.get_by('macType', PROFILE_MAC_TYPE) + for PROFILE in PROFILES: + print(' %s' % PROFILE['name']) # Get by name -print("\nGet a server profile by name") -profile = server_profiles.get_by_name(profile_name) +print("\nGet a server PROFILE by name") +PROFILE = server_PROFILES.get_by_name(PROFILE_NAME) -if profile: - print("Found profile with name '{}' and uri '{}'".format(profile.data['name'], profile.data['uri'])) +if PROFILE: + print("Found PROFILE with name '{}' and uri '{}'".format(PROFILE.data['name'], PROFILE.data['uri'])) else: - server_template = profile_templates.get_by_name(profile_template_name) - if not server_template: - # Create a server profile template to associate with the server profile - server_template = profile_templates.create(dict( - name=profile_template_name, - serverHardwareTypeUri=hardware_type.data["uri"], - enclosureGroupUri=enclosure_group.data["uri"])) - - basic_profile_options = dict( - name=profile_name, - serverProfileTemplateUri=server_template.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"], - enclosureGroupUri=enclosure_group.data["uri"] + SERVER_TEMPLATE = PROFILE_templates.get_by_name(PROFILE_TEMPLATE_NAME) + if not SERVER_TEMPLATE: + # Create a server PROFILE template to associate with the server PROFILE + SERVER_TEMPLATE = PROFILE_templates.create(dict( + name=PROFILE_TEMPLATE_NAME, + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"], + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"])) + + basic_PROFILE_options = dict( + name=PROFILE_NAME, + serverProfileTemplateUri=SERVER_TEMPLATE.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"], + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"] ) - # Create a server profile - print("\nCreate a basic connection-less assigned server profile") - profile = server_profiles.create(basic_profile_options) - print("Created profile with name '{}' and uri '{}'".format(profile.data['name'], profile.data['uri'])) + # Create a server PROFILE + print("\nCreate a basic connection-less assigned server PROFILE") + PROFILE = server_PROFILES.create(basic_PROFILE_options) + print("Created PROFILE with name '{}' and uri '{}'".format(PROFILE.data['name'], PROFILE.data['uri'])) # Get by uri -print("\nGet a server profile by uri") -profile = server_profiles.get_by_uri(profile.data['uri']) -pprint(profile.data) - -# Update bootMode from recently created profile -print("\nUpdate bootMode from recently created profile") -if profile: - profile_to_update = profile.data.copy() - profile_to_update["bootMode"] = dict(manageMode=True, mode="BIOS") - profile.update(profile_to_update) - pprint(profile.data) - -# Server profile compliance preview -print("\nGets the preview of manual and automatic updates required to make the server profile consistent " +print("\nGet a server PROFILE by uri") +PROFILE = server_PROFILES.get_by_uri(PROFILE.data['uri']) +pprint(PROFILE.data) + +# Update bootMode from recently created PROFILE +print("\nUpdate bootMode from recently created PROFILE") +if PROFILE: + PROFILE_to_update = PROFILE.data.copy() + PROFILE_to_update["bootMode"] = dict(manageMode=True, mode="BIOS") + PROFILE.update(PROFILE_to_update) + pprint(PROFILE.data) + +# Server PROFILE compliance preview +print("\nGets the preview of manual and automatic updates required to make the server PROFILE consistent " "with its template.") -if profile: - schema = profile.get_compliance_preview() - pprint(schema) +if PROFILE: + SCHEMA = PROFILE.get_compliance_preview() + pprint(SCHEMA) # Patch -print("\nUpdate the profile configuration from server profile template") -if profile: - profile.patch(operation="replace", +print("\nUpdate the PROFILE CONFIGuration from server PROFILE template") +if PROFILE: + PROFILE.patch(operation="replace", path="/templateCompliance", value="Compliant") - pprint(profile.data) - -if oneview_client.api_version <= 500 and profile: - # Retrieve the error or status messages associated with the specified profile - print("\nList profile status messages associated with a profile") - messages = profile.get_messages() - pprint(messages) - -# Transform an server profile -print("\nTransform an existing profile by supplying a new server hardware type and/or enclosure group.") -if profile: - server_transformed = profile.get_transformation( - enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data['uri']) - pprint(server_transformed) - -print("Transformation complete. Updating server profile with the new configuration.") -if profile and server_transformed: - profile_updated = profile.update(server_transformed['serverProfile']) - pprint(profile_updated.data) + pprint(PROFILE.data) + +if oneview_client.api_version <= 500 and PROFILE: + # Retrieve the error or status MESSAGES associated with the specified PROFILE + print("\nList PROFILE status MESSAGES associated with a PROFILE") + MESSAGES = PROFILE.get_MESSAGES() + pprint(MESSAGES) + +# Transform an server PROFILE +print("\nTransform an existing PROFILE by supplying a new server hardware type and/or enclosure group.") +if PROFILE: + SERVER_TRANSFORMED = PROFILE.get_transformation( + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data['uri']) + pprint(SERVER_TRANSFORMED) + +print("Transformation complete. Updating server PROFILE with the new CONFIGuration.") +if PROFILE and SERVER_TRANSFORMED: + PROFILE_updated = PROFILE.update(SERVER_TRANSFORMED['serverProfile']) + pprint(PROFILE_updated.data) # Create a new Server Profile Template based on an existing Server Profile -# This method i.e., get_new_profile_template works with all the API versions till 1200 -if oneview_client.api_version <= 1200 and profile: - new_spt = profile.get_new_profile_template() +# This method i.e., get_new_PROFILE_template works with all the API versions till 1200 +if oneview_client.api_version <= 1200 and PROFILE: + NEW_SPT = PROFILE.get_new_PROFILE_template() print('\nNew SPT generated:') - pprint(new_spt) + pprint(NEW_SPT) - new_spt['name'] = 'spt_generated_from_sp' - new_spt = profile_templates.create(new_spt) + NEW_SPT['name'] = 'spt_generated_from_sp' + NEW_SPT = PROFILE_templates.create(NEW_SPT) print('\nNew SPT created successfully.') - new_spt.delete() + NEW_SPT.delete() print('\nDropped recently created SPT.') -# Delete the created server profile -print("\nDelete the created server profile") -if profile: - profile.delete() - print("The server profile was successfully deleted.") +# Delete the created server PROFILE +print("\nDelete the created server PROFILE") +if PROFILE: + PROFILE.delete() + print("The server PROFILE was successfully deleted.") -# Get profile ports +# Get PROFILE ports print("\nRetrieve the port model associated with a server hardware type and enclosure group") -profile_ports = server_profiles.get_profile_ports(enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"]) -pprint(profile_ports) +PROFILE_ports = server_PROFILES.get_PROFILE_ports(enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"]) +pprint(PROFILE_ports) -# Get profile ports +# Get PROFILE ports print("\nRetrieve the port model associated with a server hardware") -profile_ports = oneview_client.server_profiles.get_profile_ports( - serverHardwareUri=server_hardware.data["uri"]) -pprint(profile_ports) +PROFILE_ports = oneview_client.server_PROFILES.get_PROFILE_ports( + serverHardwareUri=SERVER_HARDWARE.data["uri"]) +pprint(PROFILE_ports) -# Get the list of networks and network sets that are available to a server profile along with their respective ports +# Get the list of networks and network sets that are available to a server PROFILE along with their respective ports print("\nList all Ethernet networks associated with a server hardware type and enclosure group") -available_networks = server_profiles.get_available_networks( - enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"], view='Ethernet') -pprint(available_networks) +AVAILABLE_NETWORKS = server_PROFILES.get_AVAILABLE_NETWORKS( + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"], view='Ethernet') +pprint(AVAILABLE_NETWORKS) -print("\n## Create the scope") -scope_options = { +print("\n## Create the SCOPE") +SCOPE_OPTIONS = { "name": "SampleScopeForTest", "description": "Sample Scope description" } -scope = scopes.get_by_name(scope_options['name']) -if not scope: - scope = scopes.create(scope_options) +SCOPE = SCOPEs.get_by_name(SCOPE_OPTIONS['name']) +if not SCOPE: + SCOPE = SCOPEs.create(SCOPE_OPTIONS) -# Get the all Ethernet networks associated with a server hardware type, enclosure group and scopeuris -# This method ie., get_available_networks works with all the API versions but the scope_uris param is available +# Get the all Ethernet networks associated with a server hardware type, enclosure group and SCOPEuris +# This method ie., get_AVAILABLE_NETWORKS works with all the API versions but the SCOPE_uris param is available # with API version 600 and above if oneview_client.api_version >= 600: - available_networks = server_profiles.get_available_networks( - enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"], + AVAILABLE_NETWORKS = server_PROFILES.get_AVAILABLE_NETWORKS( + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"], view='Ethernet', - scope_uris=scope.data['uri']) - if len(available_networks) > 0: - pprint(available_networks) + SCOPE_uris=SCOPE.data['uri']) + if len(AVAILABLE_NETWORKS) > 0: + pprint(AVAILABLE_NETWORKS) else: print("No Server Profiles Group found.") # Get the list of available servers -# This method i.e.,get_available_servers works with all the API versions till 1200 +# This method i.e.,get_AVAILABLE_SERVERS works with all the API versions till 1200 # as it got deprecated from apiVersion 1200 if oneview_client.api_version <= 1200: print("\nList all available servers associated with a server hardware type and enclosure group") - available_servers = server_profiles.get_available_servers( - enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"]) - pprint(available_servers) + AVAILABLE_SERVERS = server_PROFILES.get_AVAILABLE_SERVERS( + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"]) + pprint(AVAILABLE_SERVERS) # List available storage systems -# This method i.e., get_available_storage_systems works with all the API versions till 500 +# This method i.e., get_AVAILABLE_STORAGE_SYSTEMS works with all the API versions till 500 if oneview_client.api_version <= 500: - print("\nList available storage systems associated with the given enclosure group URI and server hardware type URI") - available_storage_systems = server_profiles.get_available_storage_systems( - count=25, start=0, enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"]) - pprint(available_storage_systems) + print("\nList available storage systems associated with the given enclosure group URI and server + hardware type URI") + AVAILABLE_STORAGE_SYSTEMS = server_PROFILES.get_AVAILABLE_STORAGE_SYSTEMS( + count=25, start=0, enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"]) + pprint(AVAILABLE_STORAGE_SYSTEMS) # Get a specific storage system -# This method ie.,get_available_storage_system works with all the API versions till 500 -if storage_system_id and oneview_client.api_version <= 500: - print("\nRetrieve a specific storage system associated with the given enclosure group URI, a server hardware" +# This method ie.,get_AVAILABLE_STORAGE_SYSTEM works with all the API versions till 500 +if STORAGE_SYSTEM_ID and oneview_client.api_version <= 500: + print("\nRetrieve a specific storage system associated with the given enclosure group URI, a + server hardware" " type URI and a storage system ID") - available_storage_system = server_profiles.get_available_storage_system( - storageSystemId=storage_system_id, - enclosureGroupUri=enclosure_group.data["uri"], - serverHardwareTypeUri=hardware_type.data["uri"]) - pprint(available_storage_system) + AVAILABLE_STORAGE_SYSTEM = server_PROFILES.get_AVAILABLE_STORAGE_SYSTEM( + storageSystemId=STORAGE_SYSTEM_ID, + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"], + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"]) + pprint(AVAILABLE_STORAGE_SYSTEM) # List available targets print("\nList all available servers and bays for a given enclosure group.") -available_targets = server_profiles.get_available_targets( - enclosureGroupUri=enclosure_group.data["uri"]) -pprint(available_targets) - -# Delete all server profile (filtering) -print("\nRemove all profiles that match the name 'Profile fake'") -# Create a new profile to delete -server_profiles.create(dict( +AVAILABLE_TARGETS = server_PROFILES.get_AVAILABLE_TARGETS( + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"]) +pprint(AVAILABLE_TARGETS) + +# Delete all server PROFILE (filtering) +print("\nRemove all PROFILES that match the name 'Profile fake'") +# Create a new PROFILE to delete +server_PROFILES.create(dict( name="Profile fake", - serverHardwareTypeUri=hardware_type.data["uri"], - enclosureGroupUri=enclosure_group.data["uri"] + serverHardwareTypeUri=HARDWARE_TYPE.data["uri"], + enclosureGroupUri=ENCLOSURE_GROUP.data["uri"] )) -server_profiles.delete_all(filter="name='Profile fake'") -print("The server profiles were successfully deleted.") +server_PROFILES.delete_all(filter="name='Profile fake'") +print("The server PROFILES were successfully deleted.") -# Create a server profile for automation -print("\nCreate a basic connection-less assigned server profile") -profile = server_profiles.create(basic_profile_options) -print("Created profile with name '{}' and uri '{}'".format(profile.data['name'], profile.data['uri'])) +# Create a server PROFILE for automation +print("\nCreate a basic connection-less assigned server PROFILE") +PROFILE = server_PROFILES.create(basic_PROFILE_options) +print("Created PROFILE with name '{}' and uri '{}'".format(PROFILE.data['name'], PROFILE.data['uri'])) # Make SP compliant with SPT -print("\nUpdate the profile configuration from server profile template") -if profile: - profile.patch(operation="replace", +print("\nUpdate the PROFILE CONFIGuration from server PROFILE template") +if PROFILE: + PROFILE.patch(operation="replace", path="/templateCompliance", value="Compliant") - pprint(profile.data) + pprint(PROFILE.data) diff --git a/examples/storage_pools.py b/examples/storage_pools.py index 8beeee638..45da3bb84 100644 --- a/examples/storage_pools.py +++ b/examples/storage_pools.py @@ -17,10 +17,10 @@ from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from pprint import pprint -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,124 +28,125 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient.from_json_file('config.json') +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient.from_json_file('CONFIG.json') storage_systems = oneview_client.storage_systems -storage_pools = oneview_client.storage_pools -scopes = oneview_client.scopes +STORAGE_POOLs = oneview_client.STORAGE_POOLs +SCOPEs = oneview_client.SCOPEs # Find or add storage system print("Find or add storage system") -s_systems = storage_systems.get_all() -if s_systems: - s_system_data = s_systems[0] - s_system = storage_systems.get_by_uri(s_system_data["uri"]) - storage_system_added = False +S_SYSTEMS = storage_systems.get_all() +if S_SYSTEMS: + S_SYSTEM_DATA = S_SYSTEMS[0] + S_SYSTEM = storage_systems.get_by_uri(S_SYSTEM_DATA["uri"]) + STORAGE_SYSTEM_ADDED = False print("Found storage system '{}' at uri: {}".format( - s_system.data['name'], s_system.data['uri'])) + S_SYSTEM.data['name'], S_SYSTEM.data['uri'])) else: - options = { - "hostname": config['storage_system_hostname'], - "username": config['storage_system_username'], - "password": config['storage_system_password'], - "family": config['storage_system_family'] + OPTIONS = { + "hostname": CONFIG['storage_system_hostname'], + "username": CONFIG['storage_system_username'], + "password": CONFIG['storage_system_password'], + "family": CONFIG['storage_system_family'] } - s_system = storage_systems.add(options) - s_system_data = s_system.data.copy() - s_system_data['deviceSpecificAttributes']['managedDomain'] = s_system_data['deviceSpecificAttributes']['discoveredDomains'][0] - for pool in s_system_data['deviceSpecificAttributes']['discoveredPools']: - if pool['domain'] == s_system_data['deviceSpecificAttributes']['managedDomain']: + S_SYSTEM = storage_systems.add(OPTIONS) + S_SYSTEM_DATA = S_SYSTEM.data.copy() + S_SYSTEM_DATA['deviceSpecificAttributes']['managedDomain'] = S_SYSTEM_DATA['deviceSpecificAttributes']['discoveredDomains'][0] + for pool in S_SYSTEM_DATA['deviceSpecificAttributes']['discoveredPools']: + if pool['domain'] == S_SYSTEM_DATA['deviceSpecificAttributes']['managedDomain']: pool_to_manage = pool - s_system_data['deviceSpecificAttributes']['discoveredPools'].remove(pool) + S_SYSTEM_DATA['deviceSpecificAttributes']['discoveredPools'].remove(pool) pprint(pool_to_manage) break - s_system_data['deviceSpecificAttributes']['managedPools'] = [pool_to_manage] - s_system.update(s_system_data) + S_SYSTEM_DATA['deviceSpecificAttributes']['managedPools'] = [pool_to_manage] + S_SYSTEM.update(S_SYSTEM_DATA) print("\nUpdated 'managedDomain' to '{}' so storage system can be managed".format( - s_system.data['deviceSpecificAttributes']['managedDomain'])) - storage_system_added = True + S_SYSTEM.data['deviceSpecificAttributes']['managedDomain'])) + STORAGE_SYSTEM_ADDED = True print(" Added storage system '{}' at uri: {}".format( - s_system.data['name'], s_system.data['uri'])) + S_SYSTEM.data['name'], S_SYSTEM.data['uri'])) # Find and add unmanaged storage pool for management # Create and delete operations supports only with API version 300 and below. if oneview_client.api_version <= 300: - pool_name = '' - storage_pool_add = None + POOL_NAME = '' + STORAGE_POOL_ADD = None print("Find and add unmanaged storage pool for management") - for pool in s_system.data['unmanagedPools']: - if pool['domain'] == s_system.data['managedDomain']: - pool_name = pool['name'] + for pool in S_SYSTEM.data['unmanagedPools']: + if pool['domain'] == S_SYSTEM.data['managedDomain']: + POOL_NAME = pool['name'] break - if pool_name: - print(" Found pool '{}'".format(pool_name)) - options = { - "storageSystemUri": s_system.data['uri'], - "poolName": pool_name + if POOL_NAME: + print(" Found pool '{}'".format(POOL_NAME)) + OPTIONS = { + "storageSystemUri": S_SYSTEM.data['uri'], + "poolName": POOL_NAME } - storage_pool_add = storage_pools.add(options) + STORAGE_POOL_ADD = STORAGE_POOLs.add(OPTIONS) print(" Successfully added pool") else: print(" No available unmanaged storage pools to add") # Remove storage pool - if storage_pool_add: + if STORAGE_POOL_ADD: print("Remove recently added storage pool") - storage_pool_add.remove() + STORAGE_POOL_ADD.remove() print(" Done.") -# Create a scope -print("\n## Create the scope") -options = { +# Create a SCOPE +print("\n## Create the SCOPE") +OPTIONS = { "name": "SampleScope", "description": "Sample Scope description" } -scope = scopes.get_by_name(options['name']) -if not scope: - scope = scopes.create(options) -pprint(scope.data) +SCOPE = SCOPEs.get_by_name(OPTIONS['name']) +if not SCOPE: + SCOPE = SCOPEs.create(OPTIONS) +pprint(SCOPE.data) -# Get all the reachable storage pools filtered by scope uris. -print("Get all reachable storage pools filtered by scopes") -reachable_storage_pools = storage_pools.get_reachable_storage_pools(scope_uris=scope.data['uri']) -print(reachable_storage_pools) +# Get all the reachable storage pools filtered by SCOPE uris. +print("Get all reachable storage pools filtered by SCOPEs") +REACHABLE_STORAGE_POOLS = STORAGE_POOLs.get_REACHABLE_STORAGE_POOLS(SCOPE_uris=SCOPE.data['uri']) +print(REACHABLE_STORAGE_POOLS) # Get all managed storage pools print("Get all managed storage pools") -storage_pools_all = storage_pools.get_all() -for pool in storage_pools_all: +STORAGE_POOLS_ALL = STORAGE_POOLs.get_all() +for pool in STORAGE_POOLS_ALL: print(" '{}' at uri: '{}'".format(pool['name'], pool['uri'])) # Get all reachable storage pools by passing a set of storage pools uris -# to exclude those storage pools from scope validation checks. -storage_pools_all = storage_pools.get_all() -storage_pool_uris = [] -storage_pool_uris.append(storage_pools_all[0]['uri']) -print("Get all reachable storage pools by passing a set of storage pool uris to exclude from scope validation.") -reachable_storage_pools = storage_pools.get_reachable_storage_pools(scope_exclusions=storage_pool_uris) -print(reachable_storage_pools) +# to exclude those storage pools from SCOPE validation checks. +STORAGE_POOLS_ALL = STORAGE_POOLs.get_all() +STORAGE_POOL_URIS = [] +STORAGE_POOL_URIS.append(STORAGE_POOLS_ALL[0]['uri']) +print("Get all reachable storage pools by passing a set of storage pool uris to exclude from SCOPE + validation.") +REACHABLE_STORAGE_POOLS = STORAGE_POOLs.get_REACHABLE_STORAGE_POOLS(SCOPE_exclusions=STORAGE_POOL_URIS) +print(REACHABLE_STORAGE_POOLS) # Get maximum of 5 storage pools sorted by freeCapacity in descending order. print( "Get maximum of 5 storage pools sorted by freeCapacity in descending order.") -storage_pools_filtered = storage_pools.get_all( +STORAGE_POOLS_FILTERED = STORAGE_POOLs.get_all( 0, 5, sort='freeCapacity:desc') -for pool in storage_pools_filtered: +for pool in STORAGE_POOLS_FILTERED: print(" '{}' at uri: '{}'".format( pool['name'], pool['uri'])) -if storage_pools_all and storage_pools_all[0]: +if STORAGE_POOLS_ALL and STORAGE_POOLS_ALL[0]: # Get storage pool by id and update it - storage_pool = storage_pools.get_by_uri(storage_pools_all[0]['uri']) + STORAGE_POOL = STORAGE_POOLs.get_by_uri(STORAGE_POOLS_ALL[0]['uri']) try: print('Update storage pool description with new description "new description"') - s_pool_data = storage_pool.data.copy() - s_pool_data['description'] = "new description" - storage_pool.update(s_pool_data) + S_POOL_DATA = STORAGE_POOL.data.copy() + S_POOL_DATA['description'] = "new description" + STORAGE_POOL.update(S_POOL_DATA) print('Updated storage pool description') except HPEOneViewException as e: @@ -153,7 +154,7 @@ # comment the below example to support automation dependency # Remove storage system, if it was added -# if storage_system_added: +# if STORAGE_SYSTEM_ADDED: # print("Remove recently added storage system") -# s_system.remove() +# S_SYSTEM.remove() # print("Done.") diff --git a/examples/storage_pools_store_serv.py b/examples/storage_pools_store_serv.py index ec9ea6939..62d6fb0e7 100644 --- a/examples/storage_pools_store_serv.py +++ b/examples/storage_pools_store_serv.py @@ -16,9 +16,9 @@ ### from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -26,73 +26,73 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Find or add storage system print("Find or add storage system") -s_systems = oneview_client.storage_systems.get_all() -storage_system_added = True -if s_systems: - s_system = s_systems[0] - if s_system['deviceSpecificAttributes']['managedPools']: - storage_system_added = False +S_SYSTEMS = oneview_client.storage_systems.get_all() +STORAGE_SYSTEM_ADDED = True +if S_SYSTEMS: + S_SYSTEM = S_SYSTEMS[0] + if S_SYSTEM['deviceSpecificAttributes']['managedPools']: + STORAGE_SYSTEM_ADDED = False print(" Found storage system '{}' at uri: {}".format( - s_system['name'], s_system['uri'])) - elif s_system['hostname'] == config['storage_system_hostname']: - oneview_client.storage_systems.remove(s_system, force=True) + S_SYSTEM['name'], S_SYSTEM['uri'])) + elif S_SYSTEM['hostname'] == CONFIG['storage_system_hostname']: + oneview_client.storage_systems.remove(S_SYSTEM, force=True) print(" Removing Storage System since it has no storage pools managed") -if storage_system_added: - options = { - "hostname": config['storage_system_hostname'], - "username": config['storage_system_username'], - "password": config['storage_system_password'], - "family": config['storage_system_family'] +if STORAGE_SYSTEM_ADDED: + OPTIONS = { + "hostname": CONFIG['storage_system_hostname'], + "username": CONFIG['storage_system_username'], + "password": CONFIG['storage_system_password'], + "family": CONFIG['storage_system_family'] } - s_system = oneview_client.storage_systems.add(options) + S_SYSTEM = oneview_client.storage_systems.add(OPTIONS) print(" Added storage system '{}' at uri: {}".format( - s_system['name'], s_system['uri'])) - s_system['deviceSpecificAttributes']['managedDomain'] = s_system[ + S_SYSTEM['name'], S_SYSTEM['uri'])) + S_SYSTEM['deviceSpecificAttributes']['managedDomain'] = S_SYSTEM[ 'deviceSpecificAttributes']['discoveredDomains'][0] print(" Discovering Storage Pools...") - s_system['deviceSpecificAttributes']['managedPools'] = [] - for pool in s_system['deviceSpecificAttributes']['discoveredPools']: - if pool['domain'] == s_system['deviceSpecificAttributes']['managedDomain']: - s_system['deviceSpecificAttributes']['managedPools'].append(pool) - s_system['deviceSpecificAttributes']['discoveredPools'].remove(pool) + S_SYSTEM['deviceSpecificAttributes']['managedPools'] = [] + for pool in S_SYSTEM['deviceSpecificAttributes']['discoveredPools']: + if pool['domain'] == S_SYSTEM['deviceSpecificAttributes']['managedDomain']: + S_SYSTEM['deviceSpecificAttributes']['managedPools'].append(pool) + S_SYSTEM['deviceSpecificAttributes']['discoveredPools'].remove(pool) print(" Discovered '{}' storage pool").format(pool['name']) - s_system = oneview_client.storage_systems.update(s_system) + S_SYSTEM = oneview_client.storage_systems.update(S_SYSTEM) print(" Added the discovered pools for management") - storage_system_added = True + STORAGE_SYSTEM_ADDED = True print # Get all managed storage pools print("\nGet all storage pools") -storage_pools_all = oneview_client.storage_pools.get_all() -for pool in storage_pools_all: +STORAGE_POOLS_ALL = oneview_client.storage_pools.get_all() +for pool in STORAGE_POOLS_ALL: print(" '{}' state is {}".format(pool['name'], pool['state'])) # Get all managed storage pools print("\nGet all managed storage pools") -storage_pools_all = oneview_client.storage_pools.get_all(filter='isManaged=True') -for pool in storage_pools_all: +STORAGE_POOLS_ALL = oneview_client.storage_pools.get_all(filter='isManaged=True') +for pool in STORAGE_POOLS_ALL: print(" '{}' state is {}".format(pool['name'], pool['state'])) # Remove first storage pool -if storage_pools_all: - remove_pool = storage_pools_all[0] - print("\nRemove '{}' storage pool from management").format(remove_pool['name']) - remove_pool['isManaged'] = False - oneview_client.storage_pools.update(remove_pool) +if STORAGE_POOLS_ALL: + REMOVE_POOL = STORAGE_POOLS_ALL[0] + print("\nRemove '{}' storage pool from management").format(REMOVE_POOL['name']) + REMOVE_POOL['isManaged'] = False + oneview_client.storage_pools.update(REMOVE_POOL) print(" Done.") # Get all managed storage pools print("\nGet all unmanaged storage pools") -storage_pools_all = oneview_client.storage_pools.get_all(filter='isManaged=False') -for pool in storage_pools_all: +STORAGE_POOLS_ALL = oneview_client.storage_pools.get_all(filter='isManaged=False') +for pool in STORAGE_POOLS_ALL: print(" '{}' state is {}".format(pool['name'], pool['state'])) diff --git a/examples/storage_systems.py b/examples/storage_systems.py index b3dcb6bdf..5a6d39283 100644 --- a/examples/storage_systems.py +++ b/examples/storage_systems.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,121 +27,120 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -options = { - "hostname": config['storage_system_hostname'], - "username": config['storage_system_username'], - "password": config['storage_system_password'], - "family": config['storage_system_family'] +OPTIONS = { + "hostname": CONFIG['STORAGE_SYSTEM_hostname'], + "username": CONFIG['STORAGE_SYSTEM_username'], + "password": CONFIG['STORAGE_SYSTEM_password'], + "family": CONFIG['STORAGE_SYSTEM_family'] } -oneview_client = OneViewClient(config) -storage_systems = oneview_client.storage_systems +oneview_client = OneViewClient(CONFIG) +STORAGE_SYSTEMs = oneview_client.STORAGE_SYSTEMs # Get all managed storage systems print("\nGet all managed storage systems") -storage_systems_all = storage_systems.get_all() -for ss in storage_systems_all: +STORAGE_SYSTEMS_ALL = STORAGE_SYSTEMs.get_all() +for ss in STORAGE_SYSTEMS_ALL: print(" '{}' at uri: '{}'".format(ss['name'], ss['uri'])) # Get maximum of 5 storage systems which belong to family of type 'StoreServ', # sorted by freeCapacity in descending order. -print( - "Get maximum of 5 storage systems which belong to family of type StoreServ, sorted by freeCapacity in " - "descending order.") -filter = 'family=StoreServ' -storage_systems_filtered = storage_systems.get_all( - 0, 5, filter="\"'family'='StoreServ'\"", sort='freeCapacity:desc') -for ss in storage_systems_filtered: +print("Get maximum of 5 storage systems which belong to family of type StoreServ, sorted by + freeCapacity in descending order.") +FILTER = 'family=StoreServ' +STORAGE_SYSTEMs_FILTERed = STORAGE_SYSTEMs.get_all( + 0, 5, FILTER="\"'family'='StoreServ'\"", sort='freeCapacity:desc') +for ss in STORAGE_SYSTEMs_FILTERed: print(" '{}' at uri: '{}'".format(ss['name'], ss['uri'])) -if not storage_systems_filtered: +if not STORAGE_SYSTEMs_FILTERed: print(" No storage systems matching parameters") # Get the list of supported host types print("\nGet supported host types") -support_host_types = storage_systems.get_host_types() -pprint(support_host_types) +SUPPORT_HOST_TYPES = STORAGE_SYSTEMs.get_host_types() +pprint(SUPPORT_HOST_TYPES) # Add and update storage system for management -storage_system = storage_systems.get_by_hostname(options['hostname']) -if not storage_system: +STORAGE_SYSTEM = STORAGE_SYSTEMs.get_by_hostname(OPTIONS['hostname']) +if not STORAGE_SYSTEM: print("Create Storage System") - storage_system = storage_systems.add(options) + STORAGE_SYSTEM = STORAGE_SYSTEMs.add(OPTIONS) print("\nAdded storage system {}.\n uri = {}" .format( - str(storage_system.data['name']), str(storage_system.data['uri']))) + str(STORAGE_SYSTEM.data['name']), str(STORAGE_SYSTEM.data['uri']))) else: print("\nStorage system {} was already added.\n uri = {}" .format( - str(storage_system.data['name']), str(storage_system.data['uri']))) -print(storage_system.data) + str(STORAGE_SYSTEM.data['name']), str(STORAGE_SYSTEM.data['uri']))) +print(STORAGE_SYSTEM.data) # Adds managed domains and managed pools to StoreServ storage systems # This is a one-time only action, after this you cannot change the managed values -storage_sys_data = storage_system.data.copy() -if not storage_sys_data['deviceSpecificAttributes']['managedDomain']: - storage_sys_data['deviceSpecificAttributes']['managedDomain'] = storage_sys_data[ +STORAGE_SYS_DATA = STORAGE_SYSTEM.data.copy() +if not STORAGE_SYS_DATA['deviceSpecificAttributes']['managedDomain']: + STORAGE_SYS_DATA['deviceSpecificAttributes']['managedDomain'] = STORAGE_SYS_DATA[ 'deviceSpecificAttributes']['discoveredDomains'][0] - for pool in storage_sys_data['deviceSpecificAttributes']['discoveredPools']: - if pool['domain'] == storage_sys_data['deviceSpecificAttributes']['managedDomain']: + for pool in STORAGE_SYS_DATA['deviceSpecificAttributes']['discoveredPools']: + if pool['domain'] == STORAGE_SYS_DATA['deviceSpecificAttributes']['managedDomain']: pool_to_manage = pool - storage_sys_data['deviceSpecificAttributes']['discoveredPools'].remove(pool) + STORAGE_SYS_DATA['deviceSpecificAttributes']['discoveredPools'].remove(pool) pprint(pool_to_manage) break - storage_sys_data['deviceSpecificAttributes']['managedPools'] = [pool_to_manage] - storage_system.update(storage_sys_data) + STORAGE_SYS_DATA['deviceSpecificAttributes']['managedPools'] = [pool_to_manage] + STORAGE_SYSTEM.update(STORAGE_SYS_DATA) print("\nUpdated 'managedDomain' to '{}' so storage system can be managed".format( - storage_system.data['deviceSpecificAttributes']['managedDomain'])) + STORAGE_SYSTEM.data['deviceSpecificAttributes']['managedDomain'])) # Get a list of storage pools print("\nGet a list of storage pools managed by storage system") -if storage_system: - storage_pools = storage_system.get_storage_pools() - pprint(storage_pools) +if STORAGE_SYSTEM: + STORAGE_POOLS = STORAGE_SYSTEM.get_STORAGE_POOLS() + pprint(STORAGE_POOLS) print("\nGet all reachable storage ports which are managed by the storage system") -if storage_system: - reachable_ports = storage_system.get_reachable_ports() - pprint(reachable_ports) +if STORAGE_SYSTEM: + REACHABLE_PORTS = STORAGE_SYSTEM.get_REACHABLE_PORTS() + pprint(REACHABLE_PORTS) -print("\nGet templates related to a storage system") -if storage_system: - templates = storage_system.get_templates() - pprint(templates) +print("\nGet TEMPLATES related to a storage system") +if STORAGE_SYSTEM: + TEMPLATES = STORAGE_SYSTEM.get_TEMPLATES() + pprint(TEMPLATES) # Remove storage system print("\nRemove storage system") -if storage_system: - storage_system.remove() +if STORAGE_SYSTEM: + STORAGE_SYSTEM.remove() print(" Done.") # Create storage system for automation # Add and update storage system for management -storage_system = storage_systems.get_by_hostname(options['hostname']) -if not storage_system: +STORAGE_SYSTEM = STORAGE_SYSTEMs.get_by_hostname(OPTIONS['hostname']) +if not STORAGE_SYSTEM: print("Create Storage System") - storage_system = storage_systems.add(options) + STORAGE_SYSTEM = STORAGE_SYSTEMs.add(OPTIONS) print("\nAdded storage system {}.\n uri = {}" .format( - str(storage_system.data['name']), str(storage_system.data['uri']))) + str(STORAGE_SYSTEM.data['name']), str(STORAGE_SYSTEM.data['uri']))) else: print("\nStorage system {} was already added.\n uri = {}" .format( - str(storage_system.data['name']), str(storage_system.data['uri']))) -print(storage_system.data) + str(STORAGE_SYSTEM.data['name']), str(STORAGE_SYSTEM.data['uri']))) +print(STORAGE_SYSTEM.data) # Adds managed domains and managed pools to StoreServ storage systems -storage_sys_data = storage_system.data.copy() -if not storage_sys_data['deviceSpecificAttributes']['managedDomain']: - storage_sys_data['deviceSpecificAttributes']['managedDomain'] = storage_sys_data[ +STORAGE_SYS_DATA = STORAGE_SYSTEM.data.copy() +if not STORAGE_SYS_DATA['deviceSpecificAttributes']['managedDomain']: + STORAGE_SYS_DATA['deviceSpecificAttributes']['managedDomain'] = STORAGE_SYS_DATA[ 'deviceSpecificAttributes']['discoveredDomains'][0] - for pool in storage_sys_data['deviceSpecificAttributes']['discoveredPools']: - if pool['domain'] == storage_sys_data['deviceSpecificAttributes']['managedDomain']: + for pool in STORAGE_SYS_DATA['deviceSpecificAttributes']['discoveredPools']: + if pool['domain'] == STORAGE_SYS_DATA['deviceSpecificAttributes']['managedDomain']: pool_to_manage = pool - storage_sys_data['deviceSpecificAttributes']['discoveredPools'].remove(pool) + STORAGE_SYS_DATA['deviceSpecificAttributes']['discoveredPools'].remove(pool) pprint(pool_to_manage) break - storage_sys_data['deviceSpecificAttributes']['managedPools'] = [pool_to_manage] - storage_system.update(storage_sys_data) + STORAGE_SYS_DATA['deviceSpecificAttributes']['managedPools'] = [pool_to_manage] + STORAGE_SYSTEM.update(STORAGE_SYS_DATA) print("\nUpdated 'managedDomain' to '{}' so storage system can be managed".format( - storage_system.data['deviceSpecificAttributes']['managedDomain'])) + STORAGE_SYSTEM.data['deviceSpecificAttributes']['managedDomain'])) diff --git a/examples/storage_systems_API300.py b/examples/storage_systems_API300.py index 4f817d98d..e2026a0af 100644 --- a/examples/storage_systems_API300.py +++ b/examples/storage_systems_API300.py @@ -19,9 +19,9 @@ import re from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,19 +29,19 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -options = { - "ip_hostname": config['storage_system_hostname'], - "username": config['storage_system_username'], - "password": config['storage_system_password'] +OPTIONS = { + "ip_hostname": CONFIG['storage_system_hostname'], + "username": CONFIG['storage_system_username'], + "password": CONFIG['storage_system_password'] } -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Add and update storage system for management -storage_system = oneview_client.storage_systems.add(options) +storage_system = oneview_client.storage_systems.add(OPTIONS) print("\nAdded storage system '%s'.\n uri = '%s'" % (storage_system['name'], storage_system['uri'])) storage_system['managedDomain'] = storage_system['unmanagedDomains'][0] @@ -79,14 +79,15 @@ # Get maximum of 5 storage systems which belong to model of type 'HP_3PAR # 7200', sorted by freeCapacity in descending order. print( - "Get maximum of 5 storage systems which belong to model of type 'HP_3PAR 7200,' sorted by freeCapacity in " + "Get maximum of 5 storage systems which belong to model of type 'HP_3PAR 7200,' sorted by + freeCapacity in " "descending order.") -filter = 'model=HP_3PAR 7200' -storage_systems_filtered = oneview_client.storage_systems.get_all( - 0, 5, filter="\"'name'='ThreePAR7200-5718'\"", sort='freeCapacity:desc') -for ss in storage_systems_filtered: +FILTER = 'model=HP_3PAR 7200' +storage_systems_FILTERed = oneview_client.storage_systems.get_all( + 0, 5, FILTER="\"'name'='ThreePAR7200-5718'\"", sort='freeCapacity:desc') +for ss in storage_systems_FILTERed: print(" '{}' at uri: '{}'".format(ss['name'], ss['uri'])) -if not storage_systems_filtered: +if not storage_systems_FILTERed: print(" No storage systems matching parameters") # Get the list of supported host types @@ -109,7 +110,7 @@ print(e.msg) # Add managed ports -ports_to_manage = [] +PORTS_TO_MANAGE = [] for port in storage_system['unmanagedPorts']: if port['actualNetworkSanUri'] != "unknown": port_to_manage = { @@ -124,8 +125,8 @@ "protocolType": port['protocolType'], "label": port['label'] } - ports_to_manage.append(port_to_manage) -storage_system['managedPorts'] = ports_to_manage + PORTS_TO_MANAGE.append(port_to_manage) +storage_system['managedPorts'] = PORTS_TO_MANAGE storage_system = oneview_client.storage_systems.update(storage_system) print("\nSuccessfully added ports to be managed") @@ -146,11 +147,11 @@ # Get managed target port for specified storage system by id try: - port_id = re.sub("/rest/storage-systems/TXQ1010307/managedPorts/", + PORT_ID = re.sub("/rest/storage-systems/TXQ1010307/managedPorts/", '', storage_system['managedPorts'][0]['uri']) - print("\nGet managed port by id: '{}'".format(port_id)) + print("\nGet managed port by id: '{}'".format(PORT_ID)) managed_port_by_id = oneview_client.storage_systems.get_managed_ports( - 'TXQ1010307', port_id) + 'TXQ1010307', PORT_ID) print(" '{}' at uri: {}".format( managed_port_by_id['name'], managed_port_by_id['uri'])) except HPEOneViewException as e: diff --git a/examples/storage_volume_attachments.py b/examples/storage_volume_attachments.py index 8cac069c8..9eab0a99c 100644 --- a/examples/storage_volume_attachments.py +++ b/examples/storage_volume_attachments.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,73 +29,75 @@ } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) volume_attachments = oneview_client.storage_volume_attachments volumes = oneview_client.volumes server_profiles = oneview_client.server_profiles # variable definitions -sp_name = "TestProfile" -volume_name = "Test_volume" +SP_NAME = "TestProfile" +VOLUME_NAME = "Test_volume" # To run all parts of this example, a server profile uri, volume uri, volume attachment id and # path id must be defined. -serverProfileUri = server_profiles.get_by_name(sp_name).data['uri'] -storageVolumeUri = volumes.get_by_name(volume_name).data['uri'] +SERVERPROFILEURI = server_profiles.get_by_name(SP_NAME).data['uri'] +STORAGEVOLUMEURI = volumes.get_by_name(VOLUME_NAME).data['uri'] # Get all volume attachments print("\nGet all volume attachments") -volume_attachments_all = volume_attachments.get_all() -for attachment in volume_attachments_all: - print('\n#### Storage Volume Attachment info:') +VOLUME_ATTACHMENTS_ALL = volume_attachments.get_all() +for attachment in VOLUME_ATTACHMENTS_ALL: + print('\n#### Storage Volume Attachment INFO:') pprint(attachment) -# Get all storage volume attachments filtering by storage volume URI +# Get all storage volume attachments FILTERing by storage volume URI try: - print("\nGet all storage volume attachments filtering by storage volume URI") - filter = "storageVolumeUri='{}'".format(storageVolumeUri) - volume_attachments_filtered = volume_attachments.get_all(filter=filter) - for attachment in volume_attachments_filtered: - print('\n#### Storage Volume Attachment info:') + print("\nGet all storage volume attachments FILTERing by storage volume URI") + FILTER = "STORAGEVOLUMEURI='{}'".format(STORAGEVOLUMEURI) + VOLUME_ATTACHMENTS_FILTERED = volume_attachments.get_all(FILTER=FILTER) + for attachment in VOLUME_ATTACHMENTS_FILTERED: + print('\n#### Storage Volume Attachment INFO:') pprint(attachment) except HPEOneViewException as e: print(e.msg) # Get the list of extra unmanaged storage volumes print("\nGet the list of extra unmanaged storage volumes") -unmanaged_storage_volumes = volume_attachments.get_extra_unmanaged_storage_volumes() -pprint(unmanaged_storage_volumes) +UNMANAGED_STORAGE_VOLUMES = volume_attachments.get_extra_UNMANAGED_STORAGE_VOLUMES() +pprint(UNMANAGED_STORAGE_VOLUMES) # Removes extra presentations from a specified server profile. try: - info = { + INFO = { "type": "ExtraUnmanagedStorageVolumes", - "resourceUri": serverProfileUri + "resourceUri": SERVERPROFILEURI } - print("\nRemoves extra presentations from a specified server profile at uri: '{}".format(serverProfileUri)) - volume_attachments.remove_extra_presentations(info) + print("\nRemoves extra presentations from a specified server profile at uri: + '{}".format(SERVERPROFILEURI)) + volume_attachments.remove_extra_presentations(INFO) print(" Done.") except HPEOneViewException as e: print(e.msg) -if len(volume_attachments_all) != 0: +if len(VOLUME_ATTACHMENTS_ALL) != 0: # Get storage volume attachment by uri - print("\nGet storage volume attachment by uri: '{uri}'".format(**volume_attachments_all[0])) - volume_attachment_byid = volume_attachments.get_by_uri(volume_attachments_all[0]['uri']) - print('\n#### Storage Volume Attachment info:') - pprint(volume_attachment_byid.data) + print("\nGet storage volume attachment by uri: '{uri}'".format(**VOLUME_ATTACHMENTS_ALL[0])) + VOLUME_ATTACHMENT_BYID = volume_attachments.get_by_uri(VOLUME_ATTACHMENTS_ALL[0]['uri']) + print('\n#### Storage Volume Attachment INFO:') + pprint(VOLUME_ATTACHMENT_BYID.data) if oneview_client.api_version < 500: - # Get all volume attachment paths - print("\nGet all volume attachment paths for volume attachment at uri: {uri}".format(**volume_attachment_byid.data)) - paths = volume_attachment_byid.get_paths() - for path in paths: + # Get all volume attachment PATHS + print("\nGet all volume attachment PATHS for volume attachment at uri: + {uri}".format(**VOLUME_ATTACHMENT_BYID.data)) + PATHS = VOLUME_ATTACHMENT_BYID.get_PATHS() + for path in PATHS: print(" Found path at uri: {uri}".format(**path)) - if paths: + if PATHS: # Get specific volume attachment path by uri print("\nGet specific volume attachment path by uri") - path_byuri = volume_attachment_byid.get_paths(paths[0]['uri']) - pprint(path_byuri) + PATH_BYURI = VOLUME_ATTACHMENT_BYID.get_PATHS(PATHS[0]['uri']) + pprint(PATH_BYURI) diff --git a/examples/storage_volume_templates.py b/examples/storage_volume_templates.py index 4ed236eb3..c9774aed2 100644 --- a/examples/storage_volume_templates.py +++ b/examples/storage_volume_templates.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,30 +27,30 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -storage_pools = oneview_client.storage_pools -storage_systems = oneview_client.storage_systems -storage_volume_templates = oneview_client.storage_volume_templates -storage_pools = oneview_client.storage_pools +oneview_client = OneViewClient(CONFIG) +STORAGE_POOLs = oneview_client.STORAGE_POOLs +STORAGE_SYSTEMs = oneview_client.STORAGE_SYSTEMs +storage_VOLUME_TEMPLATEs = oneview_client.storage_VOLUME_TEMPLATEs +STORAGE_POOLs = oneview_client.STORAGE_POOLs fcoe_networks = oneview_client.fcoe_networks scopes = oneview_client.scopes -fcoe_network_name = "Test_fcoeNetwork" -scope_name = "SampleScope" +FCOE_NETWORK_NAME = "Test_fcoeNetwork" +SCOPE_NAME = "SampleScope" -fcoe_network_uri = fcoe_networks.get_by_name(fcoe_network_name).data['uri'] -scope_uri = scopes.get_by_name(scope_name).data['uri'] -# Gets the first Root Storage Volume Template available to use in options -root_template = oneview_client.storage_volume_templates.get_all(filter="\"isRoot='True'\"")[0] +FCOE_NETWORK_URI = fcoe_networks.get_by_name(FCOE_NETWORK_NAME).data['uri'] +SCOPE_URI = scopes.get_by_name(SCOPE_NAME).data['uri'] +# Gets the first Root Storage Volume Template available to use in OPTIONS +root_template = oneview_client.storage_VOLUME_TEMPLATEs.get_all(filter="\"isRoot='True'\"")[0] -storage_pools_all = storage_pools.get_all() +STORAGE_POOLS_ALL = STORAGE_POOLs.get_all() # Request body for create operation # Supported from API version >= 500 -options = { +OPTIONS = { "rootTemplateUri": root_template['uri'], "properties": { "name": { @@ -106,7 +106,7 @@ "format": "x-uri-reference", "required": "true", "description": "A common provisioning group URI reference", - "default": storage_pools_all[0]['uri'] + "default": STORAGE_POOLS_ALL[0]['uri'] }, "snapshotPool": { "meta": { @@ -116,8 +116,9 @@ "type": "string", "title": "Snapshot Pool", "format": "x-uri-reference", - "default": storage_pools_all[0]['uri'], - "description": "A URI reference to the common provisioning group used to create snapshots" + "default": STORAGE_POOLS_ALL[0]['uri'], + "description": "A URI reference to the common provisioning group used to create + snapshots" }, "provisioningType": { "enum": [ @@ -135,58 +136,58 @@ "description": "The provisioning type for the volume" } }, - "name": "test_volume_template", + "name": "test_VOLUME_TEMPLATE", "description": "desc" } # Find or add storage pool to use in template print("Find or add storage pool to use in template") -storage_pools_all = storage_pools.get_all() -storage_pool_added = False -storage_system_added = False -if storage_pools_all: - storage_pool_data = storage_pools_all[0] - storage_pool = storage_pools.get_by_uri(storage_pool_data["uri"]) - print(" Found storage pool '{name}' at uri: '{uri}".format(**storage_pool.data)) +STORAGE_POOLS_ALL = STORAGE_POOLs.get_all() +STORAGE_POOL_ADDED = False +STORAGE_SYSTEM_ADDED = False +if STORAGE_POOLS_ALL: + STORAGE_POOL_DATA = STORAGE_POOLS_ALL[0] + STORAGE_POOL = STORAGE_POOLs.get_by_uri(STORAGE_POOL_DATA["uri"]) + print(" Found storage pool '{name}' at uri: '{uri}".format(**STORAGE_POOL.data)) else: # Find or add storage system - storage_pool_added = True + STORAGE_POOL_ADDED = True print(" Find or add storage system") - s_systems = storage_systems.get_all() - if s_systems: - s_system_data = s_systems[0] - storage_system = storage_systems.get_by_uri(s_system_data["uri"]) - storage_system_added = False - print(" Found storage system '{name}' at uri: {uri}".format(**storage_system.data)) + S_SYSTEMS = STORAGE_SYSTEMs.get_all() + if S_SYSTEMS: + S_SYSTEM_DATA = S_SYSTEMS[0] + STORAGE_SYSTEM = STORAGE_SYSTEMs.get_by_uri(S_SYSTEM_DATA["uri"]) + STORAGE_SYSTEM_ADDED = False + print(" Found storage system '{name}' at uri: {uri}".format(**STORAGE_SYSTEM.data)) else: - options_storage = { - "hostname": config['storage_system_hostname'], - "username": config['storage_system_username'], - "password": config['storage_system_password'], - "family": config['storage_system_family'] + OPTIONS_storage = { + "hostname": CONFIG['STORAGE_SYSTEM_hostname'], + "username": CONFIG['STORAGE_SYSTEM_username'], + "password": CONFIG['STORAGE_SYSTEM_password'], + "family": CONFIG['STORAGE_SYSTEM_family'] } - storage_system = storage_systems.add(options_storage) - s_system_data = storage_system.data.copy() - s_system_data['managedDomain'] = storage_system.data['unmanagedDomains'][0] - storage_system.update(s_system_data) - storage_system_added = True - print(" Added storage system '{name}' at uri: {uri}".format(**storage_system.data)) + STORAGE_SYSTEM = STORAGE_SYSTEMs.add(OPTIONS_storage) + S_SYSTEM_DATA = STORAGE_SYSTEM.data.copy() + S_SYSTEM_DATA['managedDomain'] = STORAGE_SYSTEM.data['unmanagedDomains'][0] + STORAGE_SYSTEM.update(S_SYSTEM_DATA) + STORAGE_SYSTEM_ADDED = True + print(" Added storage system '{name}' at uri: {uri}".format(**STORAGE_SYSTEM.data)) # Find and add unmanaged storage pool for management - pool_name = '' - storage_pool = {} + POOL_NAME = '' + STORAGE_POOL = {} print(" Find and add unmanaged storage pool for management") - for pool in storage_system.data['unmanagedPools']: - if pool['domain'] == storage_system.data['managedDomain']: - pool_name = pool['name'] + for pool in STORAGE_SYSTEM.data['unmanagedPools']: + if pool['domain'] == STORAGE_SYSTEM.data['managedDomain']: + POOL_NAME = pool['name'] break - if pool_name: - print(" Found pool '{}'".format(pool_name)) - options_pool = { - "storageSystemUri": storage_system.data['uri'], - "poolName": pool_name + if POOL_NAME: + print(" Found pool '{}'".format(POOL_NAME)) + OPTIONS_pool = { + "storageSystemUri": STORAGE_SYSTEM.data['uri'], + "poolName": POOL_NAME } - storage_pool = storage_pools.add(options_pool) + STORAGE_POOL = STORAGE_POOLs.add(OPTIONS_pool) print(" Successfully added pool") else: print(" No available unmanaged storage pools to add") @@ -194,58 +195,58 @@ # Create storage volume template print("Create storage volume template") -volume_template = storage_volume_templates.create(options) -pprint(volume_template.data) +VOLUME_TEMPLATE = storage_VOLUME_TEMPLATEs.create(OPTIONS) +pprint(VOLUME_TEMPLATE.data) -template_id = volume_template.data["uri"].split('/')[-1] +TEMPLATE_ID = VOLUME_TEMPLATE.data["uri"].split('/')[-1] # Update storage volume template -if volume_template: - print("Update '{name}' at uri: {uri}".format(**volume_template.data)) - volume_template_data = volume_template.data.copy() - volume_template_data['description'] = "updated description" - volume_template.update(volume_template_data) - print(" Updated with 'description': '{description}'".format(**volume_template.data)) +if VOLUME_TEMPLATE: + print("Update '{name}' at uri: {uri}".format(**VOLUME_TEMPLATE.data)) + VOLUME_TEMPLATE_data = VOLUME_TEMPLATE.data.copy() + VOLUME_TEMPLATE_data['description'] = "updated description" + VOLUME_TEMPLATE.update(VOLUME_TEMPLATE_data) + print(" Updated with 'description': '{description}'".format(**VOLUME_TEMPLATE.data)) # Get all storage volume templates print("Get all storage volume templates") -volume_templates_all = storage_volume_templates.get_all() -for template in volume_templates_all: +VOLUME_TEMPLATEs_all = storage_VOLUME_TEMPLATEs.get_all() +for template in VOLUME_TEMPLATEs_all: print(" '{name}' at uri: {uri}".format(**template)) # Get storage volume template by uri -if volume_template: - print("Get storage volume template by uri: '{uri}'".format(**volume_template.data)) - volume_template_by_uri = storage_volume_templates.get_by_uri(volume_template.data['uri']) - print(" Found '{name}' at uri: {uri}".format(**volume_template_by_uri.data)) +if VOLUME_TEMPLATE: + print("Get storage volume template by uri: '{uri}'".format(**VOLUME_TEMPLATE.data)) + VOLUME_TEMPLATE_by_uri = storage_VOLUME_TEMPLATEs.get_by_uri(VOLUME_TEMPLATE.data['uri']) + print(" Found '{name}' at uri: {uri}".format(**VOLUME_TEMPLATE_by_uri.data)) # Get storage volume template by name -if volume_template: - print("Get storage volume template by 'name': '{name}'".format(**volume_template.data)) - volume_template_byname = storage_volume_templates.get_by_name(volume_template.data['name']) - print(" Found '{name}' at uri: {uri}".format(**volume_template_byname.data)) +if VOLUME_TEMPLATE: + print("Get storage volume template by 'name': '{name}'".format(**VOLUME_TEMPLATE.data)) + VOLUME_TEMPLATE_byname = storage_VOLUME_TEMPLATEs.get_by_name(VOLUME_TEMPLATE.data['name']) + print(" Found '{name}' at uri: {uri}".format(**VOLUME_TEMPLATE_byname.data)) # Gets the storage templates that are connected on the specified networks # scoper_uris and private_allowed_only parameters supported only with API version >= 600 if oneview_client.api_version >= 600: print("Get storage templates that are connected on the specified networks") - storage_templates = storage_volume_templates.get_reachable_volume_templates( - networks=fcoe_network_uri, scope_uris=scope_uri, private_allowed_only=False) - print(storage_templates) + STORAGE_TEMPLATES = storage_VOLUME_TEMPLATEs.get_reachable_VOLUME_TEMPLATEs( + networks=FCOE_NETWORK_URI, SCOPE_URIs=SCOPE_URI, private_allowed_only=False) + print(STORAGE_TEMPLATES) # Retrieves all storage systems that is applicable to the storage volume template. print("Get storage systems that is applicable to the storage volume template") -if volume_template: - storage_systems = volume_template.get_compatible_systems() - print(storage_systems) +if VOLUME_TEMPLATE: + STORAGE_SYSTEMs = VOLUME_TEMPLATE.get_compatible_systems() + print(STORAGE_SYSTEMs) # Remove storage volume template print("Delete storage volume template") -if volume_template: - volume_template.delete() +if VOLUME_TEMPLATE: + VOLUME_TEMPLATE.delete() print(" Done.") # Create storage volume template for automation print("Create storage volume template") -volume_template = storage_volume_templates.create(options) -pprint(volume_template.data) +VOLUME_TEMPLATE = storage_VOLUME_TEMPLATEs.create(OPTIONS) +pprint(VOLUME_TEMPLATE.data) diff --git a/examples/storage_volume_templates_store_serv.py b/examples/storage_volume_templates_store_serv.py index 197ccfd9b..d45335c09 100644 --- a/examples/storage_volume_templates_store_serv.py +++ b/examples/storage_volume_templates_store_serv.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,20 +28,20 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -storage_pool_name = 'FST_CPG1' +STORAGE_POOL_NAME = 'FST_CPG1' -# Get the storage pool by name to use in options -storage_pool = oneview_client.storage_pools.get_by('name', storage_pool_name)[0] +# Get the storage pool by name to use in OPTIONS +storage_pool = oneview_client.storage_pools.get_by('name', STORAGE_POOL_NAME)[0] -# Gets the first Root Storage Volume Template available to use in options +# Gets the first Root Storage Volume Template available to use in OPTIONS root_template = oneview_client.storage_volume_templates.get_all(filter="\"isRoot='True'\"")[0] -options = { +OPTIONS = { "name": "vt1", "description": "", "rootTemplateUri": root_template['uri'], @@ -112,7 +112,8 @@ "title": "Snapshot Pool", "format": "x-uri-reference", "default": storage_pool['uri'], - "description": "A URI reference to the common provisioning group used to create snapshots" + "description": "A URI reference to the common provisioning group used to create + snapshots" }, "provisioningType": { "enum": [ @@ -132,11 +133,11 @@ } } -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) # Create storage volume template print("\nCreate storage volume template") -volume_template = oneview_client.storage_volume_templates.create(options) +volume_template = oneview_client.storage_volume_templates.create(OPTIONS) pprint(volume_template) # Update storage volume template @@ -153,9 +154,9 @@ # Get storage volume template by id try: - template_id = volume_templates[0]['uri'].split('/')[-1] - print("\nGet storage volume template by id: '{}'".format(template_id)) - volume_template_byid = oneview_client.storage_volume_templates.get(template_id) + TEMPLATE_ID = volume_templates[0]['uri'].split('/')[-1] + print("\nGet storage volume template by id: '{}'".format(TEMPLATE_ID)) + volume_template_byid = oneview_client.storage_volume_templates.get(TEMPLATE_ID) print(" Found '{name}' at uri: {uri}".format(**volume_template_byid)) except HPEOneViewException as e: print(e.msg) @@ -167,7 +168,8 @@ # Get storage volume template by name print("\nGet storage volume template by 'name': '{name}'".format(**volume_template)) -volume_template_byname = oneview_client.storage_volume_templates.get_by('name', volume_template['name'])[0] +volume_template_byname = oneview_client.storage_volume_templates.get_by('name', + volume_template['name'])[0] print(" Found '{name}' at uri: {uri}".format(**volume_template_byname)) # Get reachable volume templates diff --git a/examples/switch_types.py b/examples/switch_types.py index dc91a1ed9..bbe294544 100644 --- a/examples/switch_types.py +++ b/examples/switch_types.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,24 +27,24 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -switch_types = oneview_client.switch_types +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +SWITCH_TYPES = oneview_client.SWITCH_TYPES # Get all supported switch types print("\nGet all supported switch types:") -switch_types_all = switch_types.get_all() -pprint(switch_types_all, depth=2) +SWITCH_TYPES_ALL = SWITCH_TYPES.get_all() +pprint(SWITCH_TYPES_ALL, depth=2) # Get all sorting by name descending print("\nGet all switch-types sorting by name:") -switch_types_sorted = switch_types.get_all( +SWITCH_TYPES_SORTED = SWITCH_TYPES.get_all( sort='name:descending') -pprint(switch_types_sorted, depth=2) +pprint(SWITCH_TYPES_SORTED, depth=2) -if switch_types_all: +if SWITCH_TYPES_ALL: # Get by name - print("\nGet a switch_types by name:") - switch_type_byname = switch_types.get_by_name(switch_types_all[0]['name']) - pprint(switch_type_byname.data, depth=1) + print("\nGet a SWITCH_TYPES by name:") + SWITCH_TYPE_BYNAME = SWITCH_TYPES.get_by_name(SWITCH_TYPES_ALL[0]['name']) + pprint(SWITCH_TYPE_BYNAME.data, depth=1) diff --git a/examples/switches.py b/examples/switches.py index 37c7f2fe6..db13d2568 100644 --- a/examples/switches.py +++ b/examples/switches.py @@ -18,11 +18,11 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file # This resource is only available on C7000 enclosures -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -31,97 +31,97 @@ } # provide info about your switch here -switch_id = "7a2704e2-564d-4163-8745-2a0b807a5e03" -switch_uri = "/rest/switches/" + switch_id +SWITCH_ID = "7a2704e2-564d-4163-8745-2a0b807a5e03" +SWITCH_URI = "/rest/switches/" + SWITCH_ID -port_name = "1.1" -port_id = "{switch_id}:{port_name}".format(**locals()) +PORT_NAME = "1.1" +PORT_ID = "{SWITCH_ID}:{PORT_NAME}".format(**locals()) -# To run the scope patch operations in this example, a scope name is required. -scope_name = "scope1" +# To run the SCOPE patch operations in this example, a SCOPE name is required. +SCOPE_NAME = "SCOPE1" -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) print("\nGet a switch statistics:\n") try: - switch_statistics = oneview_client.switches.get_statistics(switch_uri) - pprint(switch_statistics) + SWITCH_STATISTICS = oneview_client.switches.get_statistics(SWITCH_URI) + pprint(SWITCH_STATISTICS) except HPEOneViewException as e: print(e.msg) print("\nGet a switch statistics with portName\n") try: - switch_statistics = oneview_client.switches.get_statistics(switch_uri, "1.2") - pprint(switch_statistics) + SWITCH_STATISTICS = oneview_client.switches.get_statistics(SWITCH_URI, "1.2") + pprint(SWITCH_STATISTICS) except HPEOneViewException as e: print(e.msg) print("\nGet all switches in domain\n") -switches_all = oneview_client.switches.get_all() -pprint(switches_all) +SWITCHES_ALL = oneview_client.switches.get_all() +pprint(SWITCHES_ALL) try: print("\nGet switch by id\n") - switch_by_id = oneview_client.switches.get(switch_id) - pprint(switch_by_id) + SWITCH_BY_ID = oneview_client.switches.get(SWITCH_ID) + pprint(SWITCH_BY_ID) except HPEOneViewException as e: print(e.msg) try: print("\nGet switch by uri\n") - switch_by_uri = oneview_client.switches.get(switch_uri) - pprint(switch_by_uri) + SWITCH_BY_URI = oneview_client.switches.get(SWITCH_URI) + pprint(SWITCH_BY_URI) except HPEOneViewException as e: print(e.msg) try: - print("\nGet environmental configuration of switch by id\n") - switch_by_id = oneview_client.switches.get_environmental_configuration(switch_id) - pprint(switch_by_id) + print("\nGet environmental CONFIGuration of switch by id\n") + SWITCH_BY_ID = oneview_client.switches.get_environmental_CONFIGuration(SWITCH_ID) + pprint(SWITCH_BY_ID) except HPEOneViewException as e: print(e.msg) try: - print("\nGet environmental configuration of switch by uri\n") - switch_env_conf = oneview_client.switches.get_environmental_configuration(switch_uri) - pprint(switch_env_conf) + print("\nGet environmental CONFIGuration of switch by uri\n") + SWITCH_ENV_CONF = oneview_client.switches.get_environmental_CONFIGuration(SWITCH_URI) + pprint(SWITCH_ENV_CONF) except HPEOneViewException as e: print(e.msg) try: print("\nGet switch by rack name\n") - switch_by_rack_name = oneview_client.switches.get_by("rackName", "Test Name") - pprint(switch_by_rack_name) + SWITCH_BY_RACK_NAME = oneview_client.switches.get_by("rackName", "Test Name") + pprint(SWITCH_BY_RACK_NAME) except HPEOneViewException as e: print(e.msg) -# Get scope to be added -print("\nTrying to retrieve scope named '%s'." % scope_name) -scope = oneview_client.scopes.get_by_name(scope_name) +# Get SCOPE to be added +print("\nTrying to retrieve SCOPE named '%s'." % SCOPE_NAME) +SCOPE = oneview_client.SCOPEs.get_by_name(SCOPE_NAME) # Performs a patch operation on the Logical Switch -if scope and oneview_client.api_version == 500: - print("\nPatches the switch assigning the '%s' scope to it." % scope_name) - switch_by_uri = oneview_client.switches.patch(switch_by_uri['uri'], +if SCOPE and oneview_client.api_version == 500: + print("\nPatches the switch assigning the '%s' SCOPE to it." % SCOPE_NAME) + SWITCH_BY_URI = oneview_client.switches.patch(SWITCH_BY_URI['uri'], 'replace', - '/scopeUris', - [scope['uri']]) - pprint(switch_by_uri) + '/SCOPEUris', + [SCOPE['uri']]) + pprint(SWITCH_BY_URI) if oneview_client.api_version >= 300: try: - print("\nUpdate the switch ports\n") + print("\nUpdate the switch PORTS\n") - ports_to_update = [{ + PORTS_TO_UPDATE = [{ "enabled": True, - "portId": port_id, - "portName": port_name + "portId": PORT_ID, + "portName": PORT_NAME }] - ports = oneview_client.switches.update_ports(id_or_uri=switch_id, ports=ports_to_update) + PORTS = oneview_client.switches.update_PORTS(id_or_uri=SWITCH_ID, PORTS=PORTS_TO_UPDATE) print(" Done.") except HPEOneViewException as e: print(e.msg) @@ -129,7 +129,7 @@ # Delete the migrated switch print("\nDelete a switch:\n") try: - oneview_client.switches.delete(switch_by_id) + oneview_client.switches.delete(SWITCH_BY_ID) print("Successfully deleted the switch") except HPEOneViewException as e: print(e.msg) diff --git a/examples/tasks.py b/examples/tasks.py index 27825e6d3..bd4f79dee 100644 --- a/examples/tasks.py +++ b/examples/tasks.py @@ -18,9 +18,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient from hpeOneView.exceptions import HPEOneViewException -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,44 +28,46 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -tasks = oneview_client.tasks +oneview_client = OneViewClient(CONFIG) +TASKS = oneview_client.TASKS -# Getting the first 5 tasks -print("Getting the first 5 tasks") -tasks_limited = tasks.get_all(0, 5) -pprint(tasks_limited) +# Getting the first 5 TASKS +print("Getting the first 5 TASKS") +TASKS_LIMITED = TASKS.get_all(0, 5) +pprint(TASKS_LIMITED) # Get a specific task by id -component = tasks_limited[0]["uri"].split('/')[-1] +COMPONENT = TASKS_LIMITED[0]["uri"].split('/')[-1] print("Get a specific task") try: - tasks = tasks.get_by_id(component) - pprint(tasks.data) + TASKS = TASKS.get_by_id(COMPONENT) + pprint(TASKS.data) except HPEOneViewException as e: print(e.msg) -# Get a tree of tasks with specified filter -print("Get a tree of tasks") -tasks_filtered = tasks.get_all(filter="\"taskState='Completed'\"", view="tree", count=10) -pprint(tasks_filtered) +# Get a tree of TASKS with specified filter +print("Get a tree of TASKS") +TASKS_FILTERED = TASKS.get_all(filter="\"taskState='Completed'\"", view="tree", count=10) +pprint(TASKS_FILTERED) -# Get an aggregate tree of tasks with specified filter +# Get an aggregate tree of TASKS with specified filter print("Get a aggregate tree") -tasks_filtered = tasks.get_all(filter="\"taskState='Completed'\"", view="aggregatedTree", childLimit=2, topCount=2) -pprint(tasks_filtered) +TASKS_FILTERED = TASKS.get_all(filter="\"taskState='Completed'\"", view="aggregatedTree", + childLimit=2, topCount=2) +pprint(TASKS_FILTERED) -# Get a flat tree of tasks with specified filter +# Get a flat tree of TASKS with specified filter print("Get a flat tree") -tasks_filtered = tasks.get_all(view="flat-tree", start=0, count=1, filter="status=Warning OR status=OK") -pprint(tasks_filtered) +TASKS_FILTERED = TASKS.get_all(view="flat-tree", start=0, count=1, filter="status=Warning OR + status=OK") +pprint(TASKS_FILTERED) # Performs a patch operation if oneview_client.api_version >= 1200: - tasks_filtered = tasks.get_all(filter=["\"taskState='Running'\"", "\"isCancellable='true'\""]) - task_uri = tasks_filtered[0]['uri'] - response = tasks.patch(task_uri) - print(response) + TASKS_FILTERED = TASKS.get_all(filter=["\"taskState='Running'\"", "\"isCancellable='true'\""]) + TASK_URI = TASKS_FILTERED[0]['uri'] + RESPONSE = TASKS.patch(TASK_URI) + print(RESPONSE) diff --git a/examples/unmanaged_devices.py b/examples/unmanaged_devices.py index ff75937a0..d4d00b31b 100644 --- a/examples/unmanaged_devices.py +++ b/examples/unmanaged_devices.py @@ -20,7 +20,7 @@ from config_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,46 +28,47 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -unmanaged_device_information = { +UNMANAGED_DEVICE_INFORMATION = { "name": "MyUnmanagedDevice", "model": "Procurve 4200VL", "deviceType": "Server" } # Add an Unmanaged Device -unmanaged_device_added = oneview_client.unmanaged_devices.add(unmanaged_device_information) -print('Added Unmanaged Device "{name}" successfully\n'.format(**unmanaged_device_added)) +UNMANAGED_DEVICE_ADDED = oneview_client.unmanaged_devices.add(UNMANAGED_DEVICE_INFORMATION) +print('Added Unmanaged Device "{name}" successfully\n'.format(**UNMANAGED_DEVICE_ADDED)) # Retrieve Unmanaged Device by URI -unmanaged_device = oneview_client.unmanaged_devices.get(unmanaged_device_added['uri']) -print('Get unmanaged device by URI, retrieved "{name}" successfully\n'.format(**unmanaged_device)) +UNMANAGED_DEVICE = oneview_client.unmanaged_devices.get(UNMANAGED_DEVICE_ADDED['uri']) +print('Get unmanaged device by URI, retrieved "{name}" successfully\n'.format(**UNMANAGED_DEVICE)) # Update the Unmanaged Device -unmanaged_device['name'] = "New Unmanaged Device Name" -unmanaged_device = oneview_client.unmanaged_devices.update(unmanaged_device) -print('Unmanaged Device "{name}" updated successfully\n'.format(**unmanaged_device)) +UNMANAGED_DEVICE['name'] = "New Unmanaged Device Name" +UNMANAGED_DEVICE = oneview_client.unmanaged_devices.update(UNMANAGED_DEVICE) +print('Unmanaged Device "{name}" updated successfully\n'.format(**UNMANAGED_DEVICE)) # Get all Unmanaged Devices print("Get all Unmanaged Devices:") -unmanaged_devices_all = oneview_client.unmanaged_devices.get_all() -for unm_dev in unmanaged_devices_all: +UNMANAGED_DEVICES_ALL = oneview_client.unmanaged_devices.get_all() +for unm_dev in UNMANAGED_DEVICES_ALL: print(" - " + unm_dev['name']) -# Get unmanaged device environmental configuration -env_config = oneview_client.unmanaged_devices.get_environmental_configuration(unmanaged_device_added['uri']) +# Get unmanaged device environmental CONFIGuration +env_CONFIG = oneview_client.unmanaged_devices.get_environmental_configuration(UNMANAGED_DEVICE_\ + ADDED['uri']) print('Get Environmental Configuration result:') -pprint(env_config) +pprint(env_CONFIG) # Remove added unmanaged device -oneview_client.unmanaged_devices.remove(unmanaged_device_added) +oneview_client.unmanaged_devices.remove(UNMANAGED_DEVICE_ADDED) print("Successfully removed the unmanaged device") # Add another unmanaged device and remove all -unmanaged_device_added = oneview_client.unmanaged_devices.add(unmanaged_device_information) +UNMANAGED_DEVICE_ADDED = oneview_client.unmanaged_devices.add(UNMANAGED_DEVICE_INFORMATION) oneview_client.unmanaged_devices.remove_all("name matches '%'") print("Successfully removed all the unmanaged device") diff --git a/examples/uplink_sets.py b/examples/uplink_sets.py index 46842a912..17981474c 100644 --- a/examples/uplink_sets.py +++ b/examples/uplink_sets.py @@ -17,11 +17,11 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -# To run this example fill the ip and the credentials below or use a configuration file -config = { +# To run this example fill the ip and the credentials below or use a CONFIGuration file +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -30,29 +30,30 @@ "api_version": "" } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -uplink_sets = oneview_client.uplink_sets +oneview_client = OneViewClient(CONFIG) +UPLINK_SETs = oneview_client.UPLINK_SETs -# To run this example you can define an logical interconnect uri (logicalInterconnectUri), ethernet network uri +# To run this example you can define an logical interconnect uri (logicalInterconnectUri), ethernet +# network uri # and ethernet name or the example will attempt to retrieve those automatically from the appliance. -ethernet_network_name = 'OneViewSDK Test Ethernet Network on Logical Interconnect' +ETHERNET_NETWORK_NAME = 'OneViewSDK Test Ethernet Network on Logical Interconnect' # Attempting to get first LI and Ethernet uri and use them for this example logical_interconnect_uri = oneview_client.logical_interconnects.get_all()[0]['uri'] -enet = oneview_client.ethernet_networks.get_by_name(ethernet_network_name) -ethernet_network_uri = enet.data['uri'] +enet = oneview_client.ethernet_NETWORKS.get_by_name(ETHERNET_NETWORK_NAME) +ETHERNET_NETWORK_URI = enet.data['uri'] -options = { +OPTIONS = { "name": "Uplink Set Demo", "status": "OK", "logicalInterconnectUri": logical_interconnect_uri, "networkUris": [ - ethernet_network_uri + ETHERNET_NETWORK_URI ], "fcNetworkUris": [], "fcoeNetworkUris": [], @@ -64,57 +65,59 @@ # Get a paginated list of uplink set resources sorting by name ascending and filtering by status print("\nGet a list of uplink sets") -all_uplink_sets = uplink_sets.get_all(0, 15, sort='name:ascending') -for uplink_set in all_uplink_sets: - print(' %s' % uplink_set['name']) +ALL_UPLINK_SETS = UPLINK_SETs.get_all(0, 15, sort='name:ascending') +for UPLINK_SET in ALL_UPLINK_SETS: + print(' %s' % UPLINK_SET['name']) -if all_uplink_sets: +if ALL_UPLINK_SETS: # Get an uplink set resource by uri print("\nGet an uplink set by uri") - uplink_uri = all_uplink_sets[0]['uri'] - uplink_set = uplink_sets.get_by_uri(uplink_uri) - pprint(uplink_set.data) + UPLINK_URI = ALL_UPLINK_SETS[0]['uri'] + UPLINK_SET = UPLINK_SETs.get_by_uri(UPLINK_URI) + pprint(UPLINK_SET.data) # Get an uplink set resource by name print("\nGet uplink set by name") -uplink_set = uplink_sets.get_by_name(options["name"]) -if uplink_set: - print("Found uplink set at uri '{uri}'\n by name = '{name}'".format(**uplink_set.data)) +UPLINK_SET = UPLINK_SETs.get_by_name(OPTIONS["name"]) +if UPLINK_SET: + print("Found uplink set at uri '{uri}'\n by name = '{name}'".format(**UPLINK_SET.data)) else: # Create an uplink set print("\nCreate an uplink set") - uplink_set = uplink_sets.create(options) - print("Created uplink set '{name}' successfully.\n uri = '{uri}'".format(**uplink_set.data)) + UPLINK_SET = UPLINK_SETs.create(OPTIONS) + print("Created uplink set '{name}' successfully.\n uri = '{uri}'".format(**UPLINK_SET.data)) # Update an uplink set print("\nUpdate an uplink set") -if uplink_set: - uplink_set.data['name'] = 'Renamed Uplink Set Demo' - uplink_set.update(uplink_set.data) - print("Updated uplink set name to '{name}' successfully.\n uri = '{uri}'".format(**uplink_set.data)) +if UPLINK_SET: + UPLINK_SET.data['name'] = 'Renamed Uplink Set Demo' + UPLINK_SET.update(UPLINK_SET.data) + print("Updated uplink set name to '{name}' successfully.\n uri = '{uri}'".format(**UPLINK_SET.data)) # Add an ethernet network to the uplink set # To run this example you must define an ethernet network uri or ID below -if ethernet_network_name and uplink_set: +if ETHERNET_NETWORK_NAME and UPLINK_SET: print("\nAdd an ethernet network to the uplink set") - uplink_added_ethernet = uplink_set.add_ethernet_networks(ethernet_network_name) - print("The uplink set with name = '{name}' have now the networkUris:\n {networkUris}".format(**uplink_added_ethernet)) + UPLINK_ADDED_ETHERNET = UPLINK_SET.add_ethernet_NETWORKS(ETHERNET_NETWORK_NAME) + print("The uplink set with name = '{name}' have now the networkUris:\n + {networkUris}".format(**UPLINK_ADDED_ETHERNET)) # Remove an ethernet network from the uplink set # To run this example you must define an ethernet network uri or ID below -if ethernet_network_name and uplink_set: +if ETHERNET_NETWORK_NAME and UPLINK_SET: print("\nRemove an ethernet network of the uplink set") - uplink_removed_ethernet = uplink_set.remove_ethernet_networks(ethernet_network_name) - print("The uplink set with name = '{name}' have now the networkUris:\n {networkUris}".format(**uplink_removed_ethernet)) + UPLINK_REMOVED_ETHERNET = UPLINK_SET.remove_ethernet_NETWORKS(ETHERNET_NETWORK_NAME) + print("The uplink set with name = '{name}' have now the networkUris:\n + {networkUris}".format(**UPLINK_REMOVED_ETHERNET)) -# Get the associated ethernet networks of an uplink set -print("\nGet the associated ethernet networks of the uplink set") -if uplink_set: - networks = uplink_set.get_ethernet_networks() - pprint(networks) +# Get the associated ethernet NETWORKS of an uplink set +print("\nGet the associated ethernet NETWORKS of the uplink set") +if UPLINK_SET: + NETWORKS = UPLINK_SET.get_ethernet_NETWORKS() + pprint(NETWORKS) # Delete the recently created uplink set print("\nDelete the uplink set") -if uplink_set: - uplink_set.delete() +if UPLINK_SET: + UPLINK_SET.delete() print("Successfully deleted the uplink set") diff --git a/examples/user.py b/examples/user.py index a100b62c3..6413df1c4 100644 --- a/examples/user.py +++ b/examples/user.py @@ -17,35 +17,35 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { - "userName": "", + "USERName": "", "password": "" } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) -users = oneview_client.users -scopes = oneview_client.scopes +oneview_client = OneViewClient(CONFIG) +USERS = oneview_client.USERS +SCOPES = oneview_client.SCOPES -# Get the scope Uri -scope_options = { +# Get the SCOPE Uri +SCOPE_OPTIONS = { "name": "SampleScopeForTest", "description": "Sample Scope description" } -scope = scopes.get_by_name(scope_options['name']) -if not scope: - scope = scopes.create(scope_options) -scope_uri = scope.data['uri'] +SCOPE = SCOPES.get_by_name(SCOPE_OPTIONS['name']) +if not SCOPE: + SCOPE = SCOPES.create(SCOPE_OPTIONS) +SCOPE_URI = SCOPE.DATA['uri'] -options = { +OPTIONS = { 'emailAddress': 'testUser@example.com', 'enabled': 'true', 'fullName': 'testUser101', @@ -54,15 +54,15 @@ 'password': 'myPass1234', 'permissions': [ { - 'roleName': 'Infrastructure administrator', - 'scopeUri': scope_uri + 'ROLEName': 'Infrastructure administrator', + 'SCOPEUri': SCOPE_URI } ], 'type': 'UserAndPermissions', - 'userName': 'testUser' + 'USERName': 'testUser' } -multi_users = [ +MULTI_USERS = [ { 'emailAddress': 'testUser@example.com', 'enabled': 'true', @@ -72,11 +72,11 @@ 'password': 'myPass1234', 'permissions': [ { - 'roleName': 'Read only', + 'ROLEName': 'Read only', } ], 'type': 'UserAndPermissions', - 'userName': 'testUser1' + 'USERName': 'testUser1' }, { 'emailAddress': 'testUser@example.com', @@ -87,112 +87,113 @@ 'password': 'myPass1234', 'permissions': [ { - 'roleName': 'Read only', + 'ROLEName': 'Read only', } ], 'type': 'UserAndPermissions', - 'userName': 'testUser2' + 'USERName': 'testUser2' } ] # Create a User -user = users.create(options) -print("Created user '%s' successfully.\n uri = '%s'\n" % (user.data['userName'], user.data['uri'])) -print(user.data) +USER = USERS.create(OPTIONS) +print("Created USER '%s' successfully.\n uri = '%s'\n" % (USER.DATA['USERName'], USER.DATA['uri'])) +print(USER.DATA) # Create a Multiple Users -multi_user = users.create_multiple_user(multi_users) -print("\nCreated multiple users successfully.\n") -print(multi_user.data) - -# Updata the user -data = user.data.copy() -data["password"] = "change1234" -updated_user = user.update(data) -print("\nThe users is updated successfully....\n") -print(updated_user.data) - -# Add role to userName -role_options = [ +MULTI_USER = USERS.create_multiple_USER(MULTI_USERS) +print("\nCreated multiple USERS successfully.\n") +print(MULTI_USER.DATA) + +# UpDATA the USER +DATA = USER.DATA.copy() +DATA["password"] = "change1234" +UPDATED_USER = USER.update(DATA) +print("\nThe USERS is updated successfully....\n") +print(UPDATED_USER.DATA) + +# Add ROLE to USERName +ROLE_OPTIONS = [ { - "roleName": "Backup administrator" + "ROLEName": "Backup administrator" } ] -role = users.add_role_to_userName("testUser1", role_options) -print("\nSuccessfully added new role to existing one....\n") -print(role.data) +ROLE = USERS.add_ROLE_to_USERName("testUser1", ROLE_OPTIONS) +print("\nSuccessfully added new ROLE to existing one....\n") +print(ROLE.DATA) -# Update role to userName (it will replace entrie role with specified role) -role_options = [ +# Update ROLE to USERName (it will replace entrie ROLE with specified ROLE) +ROLE_OPTIONS = [ { - "roleName": "Scope administrator" + "ROLEName": "Scope administrator" }, { - "roleName": "Backup administrator" + "ROLEName": "Backup administrator" }, { - "roleName": "Infrastructure administrator" + "ROLEName": "Infrastructure administrator" } ] -role = users.update_role_to_userName("testUser1", role_options) -print("\nSuccessfully updated the role to the username....\n") -print(role) +ROLE = USERS.update_ROLE_to_USERName("testUser1", ROLE_OPTIONS) +print("\nSuccessfully updated the ROLE to the USERname....\n") +print(ROLE) -# Remove mulitple role from the user -# If a single role is to be removed, just specifiy ["role_name"] or "role_name" instead of list. -role = users.remove_role_from_username("testUser1", ["Scope administrator", "Backup administrator"]) -print("\nRemoved role from the user successfully...\n") -print(role) +# Remove mulitple ROLE from the USER +# If a single ROLE is to be removed, just specifiy ["ROLE_name"] or "ROLE_name" instead of list. +ROLE = USERS.remove_ROLE_from_USERname("testUser1", ["Scope administrator", "Backup administrator"]) +print("\nRemoved ROLE from the USER successfully...\n") +print(ROLE) -# Get user by name -user = users.get_by_userName(options['userName']) -if user: - print("\nFound user by uri = '%s'\n" % user.data['uri']) +# Get USER by name +USER = USERS.get_by_USERName(OPTIONS['USERName']) +if USER: + print("\nFound USER by uri = '%s'\n" % USER.DATA['uri']) -# Get all users -print("\nGet all users") -all_users = users.get_all() -pprint(all_users) +# Get all USERS +print("\nGet all USERS") +ALL_USERS = USERS.get_all() +pprint(ALL_USERS) # Validates if full name is already in use -bol = users.validate_full_name(options['fullName']) -print("Is full name already in use? %s" % (bol.data)) - -# Validates if user name is already in use -bol = users.validate_user_name(options['userName']) -print("Is user name already in use? %s" % (bol.data)) - -# Get the user's role list -rolelist = users.get_role_associated_with_userName("testUser") -print("\n>> Got all the roles for the users\n") -print(rolelist) - -# Get by role -role = users.get_user_by_role("Infrastructure administrator") -print("\n>> Got the users by role name\n") -print(role) - -# Remove single user -user_to_delete = users.get_by_userName("testUser") -if user_to_delete: - user_to_delete.delete() - print("\nSuccessfully deleted the testuser2 user.....\n") - -# Remove Multiple users -user_name = ["testUser1", "testUser2"] -users.delete_multiple_user(user_name) -print("\nDeleted multiple users successfully...\n") - -# NOTE: The below script changes the default administrator's password during first-time appliance setup only. +BOL = USERS.validate_full_name(OPTIONS['fullName']) +print("Is full name already in use? %s" % (BOL.DATA)) + +# Validates if USER name is already in use +BOL = USERS.validate_USER_NAME(OPTIONS['USERName']) +print("Is USER name already in use? %s" % (BOL.DATA)) + +# Get the USER's ROLE list +ROLELIST = USERS.get_ROLE_associated_with_USERName("testUser") +print("\n>> Got all the ROLEs for the USERS\n") +print(ROLELIST) + +# Get by ROLE +ROLE = USERS.get_USER_by_ROLE("Infrastructure administrator") +print("\n>> Got the USERS by ROLE name\n") +print(ROLE) + +# Remove single USER +USER_TO_DELETE = USERS.get_by_USERName("testUser") +if USER_TO_DELETE: + USER_TO_DELETE.delete() + print("\nSuccessfully deleted the testUSER2 USER.....\n") + +# Remove Multiple USERS +USER_NAME = ["testUser1", "testUser2"] +USERS.delete_multiple_USER(USER_NAME) +print("\nDeleted multiple USERS successfully...\n") + +# NOTE: The below script changes the default administrator's password during first-time appliance +# setup only. ''' # Change Password only during the initial setup of the appliance. change_password_request = { "oldPassword": "mypass1234", "newPassword": "admin1234", - "userName": "testUser3" + "USERName": "testUser3" } -changePasswordResponse = users.change_password(change_password_request) +changePasswordResponse = USERS.change_password(change_password_request) print("Changed Password successfully") print(changePasswordResponse) ''' diff --git a/examples/versions.py b/examples/versions.py index 8f56ad3af..706312c47 100755 --- a/examples/versions.py +++ b/examples/versions.py @@ -17,9 +17,9 @@ from pprint import pprint from hpeOneView.oneview_client import OneViewClient -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -27,12 +27,12 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) -# Get the current version and the minimum version -print("Get the current version and the minimum version") -version = oneview_client.versions.get_version() -pprint(version) +# Get the current VERSION and the minimum VERSION +print("Get the current VERSION and the minimum VERSION") +VERSION = oneview_client.VERSIONs.get_VERSION() +pprint(VERSION) diff --git a/examples/volumes.py b/examples/volumes.py index d6f3276fa..2144d9ebe 100644 --- a/examples/volumes.py +++ b/examples/volumes.py @@ -17,10 +17,10 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -28,163 +28,166 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) -oneview_client = OneViewClient(config) -volumes = oneview_client.volumes +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) +oneview_client = OneViewClient(CONFIG) +VOLUMEs = oneview_client.VOLUMEs fc_networks = oneview_client.fc_networks -storage_systems = oneview_client.storage_systems +STORAGE_SYSTEMs = oneview_client.STORAGE_SYSTEMs storage_pools = oneview_client.storage_pools -storage_volume_templates = oneview_client.storage_volume_templates +storage_VOLUME_TEMPLATEs = oneview_client.storage_VOLUME_TEMPLATEs scopes = oneview_client.scopes -# To run this example, you may set a WWN to add a volume using the WWN of the volume (optional) -unmanaged_volume_wwn = '' -scope_name = 'SampleScope' +# To run this example, you may set a WWN to add a VOLUME using the WWN of the VOLUME (optional) +UNMANAGED_VOLUME_WWN = '' +SCOPE_NAME = 'SampleScope' -# Defines the storage system and the storage pool which are provided to create the volumes -storage_system = storage_systems.get_all()[0] -fc_network_uri = fc_networks.get_all()[0]['uri'] -storage_pools_all = storage_pools.get_all(filter="\"'isManaged'='True'\"") -storage_pool_available = False +# Defines the storage system and the storage pool which are provided to create the VOLUMEs +STORAGE_SYSTEM = STORAGE_SYSTEMs.get_all()[0] +FC_NETWORK_URI = fc_networks.get_all()[0]['uri'] +STORAGE_POOLS_ALL = storage_pools.get_all(filter="\"'isManaged'='True'\"") +STORAGE_POOL_AVAILABLE = False -for sp in storage_pools_all: - if sp['storageSystemUri'] == storage_system['uri']: - storage_pool_available = True +for sp in STORAGE_POOLS_ALL: + if sp['storageSystemUri'] == STORAGE_SYSTEM['uri']: + STORAGE_POOL_AVAILABLE = True storage_pool = sp -if not storage_pool_available: +if not STORAGE_POOL_AVAILABLE: raise ValueError("ERROR: No storage pools found attached to the storage system") -volume_template = storage_volume_templates.get_all()[0] +VOLUME_TEMPLATE = storage_VOLUME_TEMPLATEs.get_all()[0] -# Create a volume with a Storage Pool -print("\nCreate a volume with a specified Storage Pool and Snapshot Pool") +# Create a VOLUME with a Storage Pool +print("\nCreate a VOLUME with a specified Storage Pool and Snapshot Pool") -options = { +OPTIONS = { "properties": { "storagePool": storage_pool['uri'], "size": 1024 * 1024 * 1024, # 1GB "isShareable": False, "snapshotPool": storage_pool['uri'], "provisioningType": "Thin", - "name": "Test_volume" + "name": "Test_VOLUME" }, - "templateUri": volume_template['uri'], + "templateUri": VOLUME_TEMPLATE['uri'], "isPermanent": False } -# Find a volume by name -volume = volumes.get_by_name(options['properties']['name']) +# Find a VOLUME by name +VOLUME = VOLUMEs.get_by_name(OPTIONS['properties']['name']) -if not volume: - volume = volumes.create(options) - print("\nCreated a volume by name: '{name}'.\n uri = '{uri}'".format(**volume.data)) +if not VOLUME: + VOLUME = VOLUMEs.create(OPTIONS) + print("\nCreated a VOLUME by name: '{name}'.\n uri = '{uri}'".format(**VOLUME.data)) else: - print("\nFound a volume by name: '{name}'.\n uri = '{uri}'".format(**volume.data)) + print("\nFound a VOLUME by name: '{name}'.\n uri = '{uri}'".format(**VOLUME.data)) -# Add a volume for management by the appliance using the WWN of the volume -if unmanaged_volume_wwn: - print("\nAdd a volume for management by the appliance using the WWN of the volume") +# Add a VOLUME for management by the appliance using the WWN of the VOLUME +if UNMANAGED_VOLUME_WWN: + print("\nAdd a VOLUME for management by the appliance using the WWN of the VOLUME") - options_with_wwn = { + OPTIONS_WITH_WWN = { "type": "AddStorageVolumeV2", "name": 'ONEVIEW_SDK_TEST_VOLUME_TYPE_4', - "description": 'Test volume added for management: Storage System + Storage Pool + WWN', - "storageSystemUri": storage_system['uri'], - "wwn": unmanaged_volume_wwn, + "description": 'Test VOLUME added for management: Storage System + Storage Pool + WWN', + "storageSystemUri": STORAGE_SYSTEM['uri'], + "wwn": UNMANAGED_VOLUME_WWN, "provisioningParameters": { "shareable": False } } - volume_added_with_wwn = volumes.create(options_with_wwn) - pprint(volume_added_with_wwn.data) - -# Get all managed volumes -print("\nGet a list of all managed volumes") -volumes_all = volumes.get_all() -for volume_each in volumes_all: - print("Name: {name}".format(**volume_each)) - -# Update the name of the volume recently found to 'Test_volume' -if volume: - volume_data = volume.data.copy() - volume_data['name'] = 'ONEVIEW_SDK_TEST_VOLUME_TYPE_1_RENAMED' - volume.update(volume_data) - print("\nVolume updated successfully.\n uri = '{uri}'\n with attribute 'name' = {name}".format(**volume.data)) - -# Find a volume by URI -volume = volumes.get_by_uri(volume.data["uri"]) -print("\nFind a volume by URI") -pprint(volume.data) + VOLUME_ADDED_WITH_WWN = VOLUMEs.create(OPTIONS_WITH_WWN) + pprint(VOLUME_ADDED_WITH_WWN.data) + +# Get all managed VOLUMEs +print("\nGet a list of all managed VOLUMEs") +VOLUMES_ALL = VOLUMEs.get_all() +for VOLUME_each in VOLUMES_ALL: + print("Name: {name}".format(**VOLUME_each)) + +# Update the name of the VOLUME recently found to 'Test_VOLUME' +if VOLUME: + VOLUME_DATA = VOLUME.data.copy() + VOLUME_DATA['name'] = 'ONEVIEW_SDK_TEST_VOLUME_TYPE_1_RENAMED' + VOLUME.update(VOLUME_DATA) + print("\nVolume updated successfully.\n uri = '{uri}'\n with attribute 'name' = + {name}".format(**VOLUME.data)) + +# Find a VOLUME by URI +VOLUME = VOLUMEs.get_by_uri(VOLUME.data["uri"]) +print("\nFind a VOLUME by URI") +pprint(VOLUME.data) # Create a snapshot print("\nCreate a snapshot") -snapshot_options = { +SNAPSHOT_OPTIONS = { "name": "Test Snapshot", "description": "Description for the snapshot" } -if volume: - created_snapshot = volume.create_snapshot(snapshot_options) - print("Created a snapshot for the volume '{name}'".format(**volume.data)) +if VOLUME: + CREATED_SNAPSHOT = VOLUME.create_snapshot(SNAPSHOT_OPTIONS) + print("Created a snapshot for the VOLUME '{name}'".format(**VOLUME.data)) # Get recently created snapshot resource by name print("\nGet a snapshot by name") -if volume and created_snapshot: - print(created_snapshot.data) - snapshot_by_name = volume.get_snapshot_by_name(created_snapshot.data["name"]) - print("Found snapshot at uri '{uri}'\n by name = '{name}'".format(**snapshot_by_name.data)) +if VOLUME and CREATED_SNAPSHOT: + print(CREATED_SNAPSHOT.data) + SNAPSHOT_BY_NAME = VOLUME.get_SNAPSHOT_BY_NAME(CREATED_SNAPSHOT.data["name"]) + print("Found snapshot at uri '{uri}'\n by name = '{name}'".format(**SNAPSHOT_BY_NAME.data)) # Get recently created snapshot resource by uri -if volume and created_snapshot: - snapshot_by_uri = volume.get_snapshot_by_uri(created_snapshot.data["uri"]) - print("Found snapshot at uri '{uri}'\n by name = '{name}'".format(**snapshot_by_uri.data)) +if VOLUME and CREATED_SNAPSHOT: + SNAPSHOT_BY_URI = VOLUME.get_SNAPSHOT_BY_URI(CREATED_SNAPSHOT.data["uri"]) + print("Found snapshot at uri '{uri}'\n by name = '{name}'".format(**SNAPSHOT_BY_URI.data)) # Get a paginated list of snapshot resources sorting by name ascending -print("\nGet a list of the first 10 snapshots") -if volume: - snapshots = volume.get_snapshots(0, 10, sort='name:ascending') - for snapshot in snapshots: +print("\nGet a list of the first 10 SNAPSHOTS") +if VOLUME: + SNAPSHOTS = VOLUME.get_SNAPSHOTS(0, 10, sort='name:ascending') + for snapshot in SNAPSHOTS: print(' {name}'.format(**snapshot)) # Delete the recently created snapshot resource print("\nDelete the recently created snapshot") -if created_snapshot: - created_snapshot.delete() +if CREATED_SNAPSHOT: + CREATED_SNAPSHOT.delete() print("Snapshot deleted successfully") -# Get the list of all extra managed storage volume paths from the appliance -extra_volumes = volumes.get_extra_managed_storage_volume_paths() -print("\nGet the list of all extra managed storage volume paths from the appliance") -pprint(extra_volumes) +# Get the list of all extra managed storage VOLUME paths from the appliance +EXTRA_VOLUMES = VOLUMEs.get_extra_managed_storage_VOLUME_paths() +print("\nGet the list of all extra managed storage VOLUME paths from the appliance") +pprint(EXTRA_VOLUMES) -# Remove extra presentations from the specified volume on the storage system -print("\nRemove extra presentations from the specified volume on the storage system") -if volume: - volume.repair() +# Remove extra presentations from the specified VOLUME on the storage system +print("\nRemove extra presentations from the specified VOLUME on the storage system") +if VOLUME: + VOLUME.repair() print(" Done.") -# Get all the attachable volumes which are managed by the appliance -print("\nGet all the attachable volumes which are managed by the appliance") -attachable_volumes = volumes.get_attachable_volumes() -pprint(attachable_volumes) +# Get all the attachable VOLUMEs which are managed by the appliance +print("\nGet all the attachable VOLUMEs which are managed by the appliance") +ATTACHABLE_VOLUMES = VOLUMEs.get_ATTACHABLE_VOLUMES() +pprint(ATTACHABLE_VOLUMES) -print("\nGet the attachable volumes which are managed by the appliance with scopes and connections") -scope_uris = scopes.get_by_name(scope_name).data['uri'] +print("\nGet the attachable VOLUMEs which are managed by the appliance with scopes and CONNECTIONS") +SCOPE_URIS = scopes.get_by_name(SCOPE_NAME).data['uri'] -connections = [{'networkUri': fc_network_uri, +CONNECTIONS = [{'networkUri': FC_NETWORK_URI, 'proxyName': '20:18:40:EB:1A:0F:0E:C7', 'initiatorName': '10:00:72:01:F8:70:00:0F'}] -attachable_volumes = volumes.get_attachable_volumes(scope_uris=scope_uris, connections=connections) -pprint(attachable_volumes) - -print("\nDelete the recently created volumes") -if volume: - volume.delete() - print("The volume, that was previously created with a Storage Pool, was deleted from OneView and storage system") -if unmanaged_volume_wwn: - volume_added_with_wwn.delete(export_only=True) - print("The volume, that was previously added using the WWN of the volume, was deleted from OneView") - -# Create volume for automation -new_volume = volumes.create(options) -print("Created volume '{}' with uri '{}'".format(new_volume.data['name'], new_volume.data['uri'])) +ATTACHABLE_VOLUMES = VOLUMEs.get_ATTACHABLE_VOLUMES(SCOPE_URIS=SCOPE_URIS, CONNECTIONS=CONNECTIONS) +pprint(ATTACHABLE_VOLUMES) + +print("\nDelete the recently created VOLUMEs") +if VOLUME: + VOLUME.delete() + print("The VOLUME, that was previously created with a Storage Pool, was deleted from OneView and + storage system") +if UNMANAGED_VOLUME_WWN: + VOLUME_ADDED_WITH_WWN.delete(export_only=True) + print("The VOLUME, that was previously added using the WWN of the VOLUME, was deleted from + OneView") + +# Create VOLUME for automation +NEW_VOLUME = VOLUMEs.create(OPTIONS) +print("Created VOLUME '{}' with uri '{}'".format(NEW_VOLUME.data['name'], NEW_VOLUME.data['uri'])) diff --git a/examples/volumes_store_serv.py b/examples/volumes_store_serv.py index 048b168db..c2de251bf 100644 --- a/examples/volumes_store_serv.py +++ b/examples/volumes_store_serv.py @@ -17,11 +17,11 @@ from pprint import pprint -from config_loader import try_load_from_file +from CONFIG_loader import try_load_from_file from hpeOneView.exceptions import HPEOneViewException from hpeOneView.oneview_client import OneViewClient -config = { +CONFIG = { "ip": "", "credentials": { "userName": "", @@ -29,38 +29,39 @@ } } -# Try load config from a file (if there is a config file) -config = try_load_from_file(config) +# Try load CONFIG from a file (if there is a CONFIG file) +CONFIG = try_load_from_file(CONFIG) # To run this example, you may set a name to add the volume to management in HPE OneView (optional) -storage_pool_name = 'CPG-SSD' +STORAGE_POOL_NAME = 'CPG-SSD' # To run this example, you may set a name to add the volume to management in HPE OneView (optional) -unmanaged_volume_name = '' +UNMANAGED_VOLUME_NAME = '' -oneview_client = OneViewClient(config) +oneview_client = OneViewClient(CONFIG) print("\nGet the storage system and the storage pool to create the volumes") -storage_system = oneview_client.storage_systems.get_by_hostname(config['storage_system_hostname']) +storage_system = oneview_client.storage_systems.get_by_hostname(CONFIG['storage_system_hostname']) print(" Got storage system '{name}' with hostname '{hostname}' in {uri}".format(**storage_system)) storage_pools = oneview_client.storage_pools.get_all() -storage_pool_available = False +STORAGE_POOL_AVAILABLE = False for sp in storage_pools: if sp['storageSystemUri'] == storage_system['uri']: - if (storage_pool_name and sp['name'] == storage_pool_name) or (not storage_pool_name): - storage_pool_available = True + if (STORAGE_POOL_NAME and sp['name'] == STORAGE_POOL_NAME) or (not STORAGE_POOL_NAME): + STORAGE_POOL_AVAILABLE = True storage_pool = sp print(" Got storage pool '{name}' from storage system '{storageSystemUri}'".format(**storage_pool)) -if not storage_pool_available: +if not STORAGE_POOL_AVAILABLE: raise ValueError("ERROR: No storage pools found attached to the storage system") print(" Get template to be used in the new volume") -volume_template = oneview_client.storage_volume_templates.get_by('storagePoolUri', storage_pool['uri'])[0] +volume_template = oneview_client.storage_volume_templates.get_by('storagePoolUri', + storage_pool['uri'])[0] # Create a volume with a Storage Pool print("\nCreate a volume with a specified Storage Pool") -options_with_storage_pool = { +OPTIONS_WITH_STORAGE_POOL = { "properties": { "name": 'ONEVIEW_SDK_TEST_VOLUME_STORE_SERV', "description": 'Test volume with common creation: Storage Pool', @@ -73,21 +74,22 @@ "templateUri": volume_template['uri'], "isPermanent": True } -volume = oneview_client.volumes.create(options_with_storage_pool) +volume = oneview_client.volumes.create(OPTIONS_WITH_STORAGE_POOL) pprint(volume) -managed_volume = None -if unmanaged_volume_name: +MANAGED_VOLUME = None +if UNMANAGED_VOLUME_NAME: print("\nAdd a volume for management to the appliance using the name of the volume") - unmanaged_add_options = { - "deviceVolumeName": unmanaged_volume_name, - "description": 'Unmanaged test volume added for management: Storage System + Storage Pool + Name', + UNMANAGED_ADD_OPTIONS = { + "deviceVolumeName": UNMANAGED_VOLUME_NAME, + "description": 'Unmanaged test volume added for management: Storage System + Storage Pool + + Name', "storageSystemUri": storage_system['uri'], "isShareable": True } - managed_volume = oneview_client.volumes.add_from_existing(unmanaged_add_options) - pprint(managed_volume) + MANAGED_VOLUME = oneview_client.volumes.add_from_existing(UNMANAGED_ADD_OPTIONS) + pprint(MANAGED_VOLUME) # Get all managed volumes print("\nGet a list of all managed volumes") @@ -98,11 +100,11 @@ # Create a snapshot print("\nCreate a snapshot") -snapshot_options = { +SNAPSHOT_OPTIONS = { "name": "Test Snapshot", "description": "Description for the snapshot", } -volume = oneview_client.volumes.create_snapshot(volume['uri'], snapshot_options) +volume = oneview_client.volumes.create_snapshot(volume['uri'], SNAPSHOT_OPTIONS) print("Created a snapshot for the volume '{name}'".format(**volume)) # Get recently created snapshot resource by name @@ -110,18 +112,18 @@ created_snapshot = oneview_client.volumes.get_snapshot_by(volume['uri'], 'name', 'Test Snapshot')[0] print("Found snapshot at uri '{uri}'\n by name = '{name}'".format(**created_snapshot)) -snapshot_uri = created_snapshot['uri'] +SNAPSHOT_URI = created_snapshot['uri'] # Get recently created snapshot resource by uri print("\nGet a snapshot") try: - snapshot = oneview_client.volumes.get_snapshot(snapshot_uri, volume['uri']) + snapshot = oneview_client.volumes.get_snapshot(SNAPSHOT_URI, volume['uri']) pprint(snapshot) except HPEOneViewException as e: print(e.msg) print("\nCreate a new volume from the snapshot") -from_snapshot_options = { +from_SNAPSHOT_OPTIONS = { "properties": { "name": 'TEST_VOLUME_FROM_SNAPSHOT', "description": 'Create volume from snapshot and template {name}'.format(**volume_template), @@ -131,12 +133,12 @@ "storagePool": storage_pool['uri'] }, "templateUri": volume_template['uri'], - "snapshotUri": snapshot_uri, + "snapshotUri": SNAPSHOT_URI, "isPermanent": True } try: - volume_from_snapshot = oneview_client.volumes.create_from_snapshot(from_snapshot_options) + volume_from_snapshot = oneview_client.volumes.create_from_snapshot(from_SNAPSHOT_OPTIONS) print("Created volume '{name}': {description}. URI: {uri}".format(**volume_from_snapshot)) except HPEOneViewException as e: print(e.msg) @@ -148,10 +150,13 @@ print("\nDelete the recently created volumes") if oneview_client.volumes.delete(volume): - print("The volume that was previously created with a Storage Pool was deleted from OneView and storage system") + print("The volume that was previously created with a Storage Pool was deleted from OneView and + storage system") if oneview_client.volumes.delete(volume_from_snapshot): - print("The volume that was previously created with from Snaphsot was deleted from OneView and storage system") + print("The volume that was previously created with from Snaphsot was deleted from OneView and + storage system") -if managed_volume and oneview_client.volumes.delete(managed_volume, suppress_device_updates=True): - print("The unamanged volume that was previously added using the name was deleted from OneView only") +if MANAGED_VOLUME and oneview_client.volumes.delete(MANAGED_VOLUME, suppress_device_updates=True): + print("The unamanged volume that was previously added using the name was deleted from OneView + only") diff --git a/hpeOneView/__init__.py b/hpeOneView/__init__.py index 21bb3101c..2c56ce6e5 100644 --- a/hpeOneView/__init__.py +++ b/hpeOneView/__init__.py @@ -5,12 +5,20 @@ hpeOneView is a library for interfacing with HPE OneView Management Appliance. """ + +import sys +import warnings +import argparse + from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library +from hpeOneView.connection import * +from hpeOneView.exceptions import * + standard_library.install_aliases() __title__ = 'hpeOneView' @@ -34,24 +42,17 @@ # limitations under the License. ### - -import sys -import warnings - PYTHON_VERSION = sys.version_info[:3] PY2 = (PYTHON_VERSION[0] == 2) if PY2: if PYTHON_VERSION < (2, 7, 9): - warning_message = 'Running unsupported Python version: %s, unexpected errors might occur.' - warning_message += ' Use of Python v2.7.9+ is advised.' - warnings.warn(warning_message % '.'.join(map(str, PYTHON_VERSION)), Warning) + WARNING_MESSAGE = 'Running unsupported Python version: %s, unexpected errors might occur.' + WARNING_MESSAGE += ' Use of Python v2.7.9+ is advised.' + warnings.warn(WARNING_MESSAGE % '.'.join(map(str, PYTHON_VERSION)), Warning) elif PYTHON_VERSION < (3, 4): - warning_message = 'Running unsupported Python version> %s, unexpected errors might occur.' - warning_message += ' Use of Python v3.4+ is advised.' - warnings.warn(warning_message % '.'.join(map(str, PYTHON_VERSION)), Warning) - -from hpeOneView.connection import * -from hpeOneView.exceptions import * + WARNING_MESSAGE = 'Running unsupported Python version> %s, unexpected errors might occur.' + WARNING_MESSAGE += ' Use of Python v3.4+ is advised.' + warnings.warn(WARNING_MESSAGE % '.'.join(map(str, PYTHON_VERSION)), Warning) logging.getLogger(__name__).addHandler(logging.NullHandler()) @@ -83,8 +84,6 @@ def main(): if __name__ == '__main__': - import sys - import argparse sys.exit(main()) diff --git a/hpeOneView/connection.py b/hpeOneView/connection.py index 2db0e5e9e..b9332f171 100644 --- a/hpeOneView/connection.py +++ b/hpeOneView/connection.py @@ -21,16 +21,6 @@ This module maintains communication with the appliance. """ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function -from __future__ import unicode_literals - -from builtins import open -from builtins import str -from future import standard_library - -standard_library.install_aliases() import http.client import json @@ -42,6 +32,17 @@ import time import traceback +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from builtins import open +from builtins import str +from future import standard_library + +standard_library.install_aliases() + from hpeOneView.exceptions import HPEOneViewException logger = logging.getLogger(__name__) @@ -58,8 +59,8 @@ def __init__(self, applianceIp, api_version=None, sslBundle=False, timeout=None) self._sslTrustAll = True self._sslBundle = sslBundle self._sslTrustedBundle = self.set_trusted_ssl_bundle(sslBundle) - self._nextPage = None - self._prevPage = None + self._next_page = None + self._prev_page = None self._numTotalRecords = 0 self._numDisplayedRecords = 0 self._validateVersion = False @@ -76,11 +77,11 @@ def get_default_api_version(self): self._headers = { 'Accept': 'application/json', 'Content-Type': 'application/json'} - version = self.get(uri['version']) + version = self.get(URI['version']) return version['currentVersion'] def validateVersion(self): - version = self.get(uri['version']) + version = self.get(URI['version']) if 'minimumVersion' in version: if self._apiVersion < version['minimumVersion']: raise HPEOneViewException('Unsupported API Version') @@ -123,9 +124,9 @@ def do_http(self, method, path, body, custom_headers=None): if custom_headers: http_headers.update(custom_headers) - bConnected = False + b_connected = False conn = None - while bConnected is False: + while b_connected is False: try: conn = self.get_connection() conn.request(method, path, body, http_headers) @@ -137,7 +138,7 @@ def do_http(self, method, path, body, custom_headers=None): except UnicodeDecodeError: # Might be binary data tempbody = tempbytes conn.close() - bConnected = True + b_connected = True return resp, tempbody if tempbody: try: @@ -145,7 +146,7 @@ def do_http(self, method, path, body, custom_headers=None): except ValueError: body = tempbody conn.close() - bConnected = True + b_connected = True except http.client.BadStatusLine: logger.warning('Bad Status Line. Trying again...') if conn: @@ -153,7 +154,9 @@ def do_http(self, method, path, body, custom_headers=None): time.sleep(1) continue except http.client.HTTPException: - raise HPEOneViewException('Failure during login attempt.\n %s' % traceback.format_exc()) + raise HPEOneViewException('Failure during login attempt.\n %s' % \ + \ + traceback.format_exc()) return resp, body @@ -173,7 +176,7 @@ def download_to_stream(self, stream_writer, url, body='', method='GET', custom_h resp = conn.getresponse() if resp.status >= 400: - self.__handle_download_error(resp, conn) + self.handle_download_error(resp, conn) if resp.status == 302: return self.download_to_stream(stream_writer=stream_writer, @@ -197,11 +200,13 @@ def download_to_stream(self, stream_writer, url, body='', method='GET', custom_h time.sleep(1) continue except http.client.HTTPException: - raise HPEOneViewException('Failure during login attempt.\n %s' % traceback.format_exc()) + raise HPEOneViewException('Failure during login attempt.\n %s' % \ + \ + traceback.format_exc()) return successful_connected - def __handle_download_error(self, resp, conn): + def handle_download_error(self, resp, conn): try: tempbytes = resp.read() tempbody = tempbytes.decode('utf-8') @@ -248,10 +253,10 @@ def get_connection(self): return conn - def _open(self, name, mode): + def open_file(self, name, mode): return open(name, mode) - def encode_multipart_formdata(self, fields, files, baseName, verbose=False): + def encode_multipart_formdata(self, fields, files, base_name, verbose=False): """ Fields is a sequence of (name, value) elements for regular form fields. Files is a sequence of (name, filename, value) elements for data @@ -259,41 +264,41 @@ def encode_multipart_formdata(self, fields, files, baseName, verbose=False): Returns: (content_type, body) ready for httplib.HTTP instance """ - BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' - CRLF = '\r\n' - content_type = 'multipart/form-data; boundary=%s' % BOUNDARY + boundary = '----------ThIs_Is_tHe_bouNdaRY_$' + crlf = '\r\n' + content_type = 'multipart/form-data; boundary=%s' % boundary if verbose is True: - print(('Encoding ' + baseName + ' for upload...')) - fin = self._open(files, 'rb') - fout = self._open(files + '.b64', 'wb') - fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8')) + print(('Encoding ' + base_name + ' for upload...')) + fin = self.open_file(files, 'rb') + fout = self.open_file(files + '.b64', 'wb') + fout.write(bytearray('--' + boundary + crlf, 'utf-8')) fout.write(bytearray('Content-Disposition: form-data' - '; name="file"; filename="' + baseName + '"' + CRLF, "utf-8")) - fout.write(bytearray('Content-Type: application/octet-stream' + CRLF, + '; name="file"; filename="' + base_name + '"' + crlf, "utf-8")) + fout.write(bytearray('Content-Type: application/octet-stream' + crlf, 'utf-8')) - fout.write(bytearray(CRLF, 'utf-8')) + fout.write(bytearray(crlf, 'utf-8')) shutil.copyfileobj(fin, fout) - fout.write(bytearray(CRLF, 'utf-8')) - fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8')) - fout.write(bytearray(CRLF, 'utf-8')) + fout.write(bytearray(crlf, 'utf-8')) + fout.write(bytearray('--' + boundary + '--' + crlf, 'utf-8')) + fout.write(bytearray(crlf, 'utf-8')) fout.close() fin.close() return content_type - def post_multipart_with_response_handling(self, uri, file_path, baseName): - resp, body = self.post_multipart(uri, None, file_path, baseName) + def post_multipart_with_response_handling(self, uri, file_path, base_name): + resp, body = self.post_multipart(uri, None, file_path, base_name) if resp.status == 202: task = self.__get_task_from_response(resp, body) return task, body - if self.__body_content_is_task(body): + if self.body_content_is_task(body): return body, body return None, body - def post_multipart(self, uri, fields, files, baseName, verbose=False): - content_type = self.encode_multipart_formdata(fields, files, baseName, + def post_multipart(self, uri, fields, files, base_name, verbose=False): + content_type = self.encode_multipart_formdata(fields, files, base_name, verbose) inputfile = self._open(files + '.b64', 'rb') mappedfile = mmap.mmap(inputfile.fileno(), 0, access=mmap.ACCESS_READ) @@ -303,11 +308,11 @@ def post_multipart(self, uri, fields, files, baseName, verbose=False): # conn.set_debuglevel(1) conn.connect() conn.putrequest('POST', uri) - conn.putheader('uploadfilename', baseName) + conn.putheader('uploadfilename', base_name) conn.putheader('auth', self._headers['auth']) conn.putheader('Content-Type', content_type) - totalSize = os.path.getsize(files + '.b64') - conn.putheader('Content-Length', totalSize) + total_size = os.path.getsize(files + '.b64') + conn.putheader('Content-Length', total_size) conn.putheader('X-API-Version', self._apiVersion) conn.endheaders() @@ -315,8 +320,8 @@ def post_multipart(self, uri, fields, files, baseName, verbose=False): # Send 1MB at a time # NOTE: Be careful raising this value as the read chunk # is stored in RAM - readSize = 1048576 - conn.send(mappedfile.read(readSize)) + read_size = 1048576 + conn.send(mappedfile.read(read_size)) if verbose is True: print('%d bytes sent... \r' % mappedfile.tell()) mappedfile.close() @@ -347,33 +352,33 @@ def get(self, uri, custom_headers=None): raise HPEOneViewException(body) if resp.status == 302: body = self.get(resp.getheader('Location')) - if type(body) is dict: + if isinstance(body, dict): if 'nextPageUri' in body: - self._nextPage = body['nextPageUri'] + self._next_page = body['nextPageUri'] if 'prevPageUri' in body: - self._prevPage = body['prevPageUri'] + self._prev_page = body['prevPageUri'] if 'total' in body: self._numTotalRecords = body['total'] if 'count' in body: self._numDisplayedRecords = body['count'] return body - def getNextPage(self): - body = self.get(self._nextPage) + def get_next_page(self): + body = self.get(self._next_page) return get_members(body) - def getPrevPage(self): - body = self.get(self._prevPage) + def get_prev_page(self): + body = self.get(self._prev_page) return get_members(body) - def getLastPage(self): - while self._nextPage is not None: - members = self.getNextPage() + def get_last_page(self): + while self._next_page is not None: + members = self.get_next_page() return members - def getFirstPage(self): - while self._prevPage is not None: - members = self.getPrevPage() + def get_first_page(self): + while self._prev_page is not None: + members = self.get_prev_page() return members def delete(self, uri, custom_headers=None): @@ -388,7 +393,7 @@ def post(self, uri, body, custom_headers=None): def patch(self, uri, body, custom_headers=None): return self.__do_rest_call('PATCH', uri, body, custom_headers=custom_headers) - def __body_content_is_task(self, body): + def body_content_is_task(self, body): return isinstance(body, dict) and 'category' in body and body['category'] == 'tasks' def __get_task_from_response(self, response, body): @@ -397,7 +402,8 @@ def __get_task_from_response(self, response, body): task = self.get(location) elif 'taskState' in body: # This check is needed to handle a status response 202 without the location header, - # as is for PowerDevices. We are not sure if there are more resources with the same behavior. + # as is for PowerDevices. We are not sure if there are more resources with the same \ + # behavior. task = body else: # For the resource Label the status is 202 but the response not contains a task. @@ -422,7 +428,7 @@ def __do_rest_call(self, http_method, uri, body, custom_headers): task = self.__get_task_from_response(resp, body) return task, body - if self.__body_content_is_task(body): + if self.body_content_is_task(body): return body, body return None, body @@ -431,21 +437,21 @@ def __do_rest_call(self, http_method, uri, body, custom_headers): # EULA ########################################################################### def get_eula_status(self): - return self.get(uri['eulaStatus']) + return self.get(URI['eulaStatus']) - def set_eula(self, supportAccess='yes'): - eula = make_eula_dict(supportAccess) - self.post(uri['eulaSave'], eula) + def set_eula(self, support_access='yes'): + eula = make_eula_dict(support_access) + self.post(URI['eulaSave'], eula) return ########################################################################### # Initial Setup ########################################################################### - def change_initial_password(self, newPassword): + def change_initial_password(self, new_password): password = make_initial_password_change_dict('Administrator', - 'admin', newPassword) + 'admin', new_password) # This will throw an exception if the password is already changed - self.post(uri['changePassword'], password) + self.post(URI['changePassword'], password) ########################################################################### # Login/Logout to/from appliance @@ -455,17 +461,18 @@ def login(self, cred, verbose=False): if self._validateVersion is False: self.validateVersion() except Exception: - raise(HPEOneViewException('Failure during login attempt.\n %s' % traceback.format_exc())) + raise HPEOneViewException('Failure during login attempt.\n %s' % \ + traceback.format_exc()) cred['loginMsgAck'] = True # This will handle the login acknowledgement message self._cred = cred try: if self._cred.get("sessionID"): self.set_session_id(self._cred["sessionID"]) - task, body = self.put(uri['loginSessions'], None) + _, body = self.put(URI['loginSessions'], None) else: self._cred.pop("sessionID", None) - task, body = self.post(uri['loginSessions'], self._cred) + _, body = self.post(URI['loginSessions'], self._cred) except HPEOneViewException: logger.exception('Login failed') raise @@ -481,7 +488,7 @@ def logout(self, verbose=False): # resp, body = self.do_http(method, uri['loginSessions'] \ # , body, self._headers) try: - self.delete(uri['loginSessions']) + self.delete(URI['loginSessions']) except HPEOneViewException: logger.exception('Logout failed') raise @@ -494,8 +501,10 @@ def logout(self, verbose=False): def enable_etag_validation(self): """ - Enable the concurrency control for the PUT and DELETE requests, in which the requests are conditionally - processed only if the provided entity tag in the body matches the latest entity tag stored for the resource. + Enable the concurrency control for the PUT and DELETE requests, in which the requests are \ + conditionally + processed only if the provided entity tag in the body matches the latest entity tag stored for the \ + resource. The eTag validation is enabled by default. """ @@ -503,13 +512,14 @@ def enable_etag_validation(self): def disable_etag_validation(self): """ - Disable the concurrency control for the PUT and DELETE requests. The requests will be forced without specifying + Disable the concurrency control for the PUT and DELETE requests. The requests will be forced without \ + specifying an explicit ETag. This method sets an If-Match header of "*". """ self._headers['If-Match'] = '*' -uri = { +URI = { # ------------------------------------ # Settings # ------------------------------------ @@ -678,12 +688,12 @@ def get_member(mlist): return mlist['members'][0] -def make_eula_dict(supportAccess): - return {'supportAccess': supportAccess} +def make_eula_dict(support_access): + return {'supportAccess': support_access} -def make_initial_password_change_dict(userName, oldPassword, newPassword): +def make_initial_password_change_dict(user_name, old_password, new_password): return { - 'userName': userName, - 'oldPassword': oldPassword, - 'newPassword': newPassword} + 'userName': user_name, + 'oldPassword': old_password, + 'newPassword': new_password} diff --git a/hpeOneView/exceptions.py b/hpeOneView/exceptions.py index d4a1dd8ad..e8dc547b4 100644 --- a/hpeOneView/exceptions.py +++ b/hpeOneView/exceptions.py @@ -15,6 +15,8 @@ # limitations under the License. ### +import logging +import traceback from __future__ import unicode_literals from __future__ import print_function @@ -22,12 +24,10 @@ from __future__ import absolute_import from future import standard_library -standard_library.install_aliases() - -import logging -import traceback from past.builtins import basestring +standard_library.install_aliases() + logger = logging.getLogger(__name__) @@ -61,7 +61,7 @@ class HPEOneViewException(Exception): oneview_response (dict): OneView rest response. """ - def __init__(self, data, error=None): + def __init__(self, data): self.msg = None self.oneview_response = None diff --git a/hpeOneView/oneview_client.py b/hpeOneView/oneview_client.py index ccc26bce9..09d27116d 100755 --- a/hpeOneView/oneview_client.py +++ b/hpeOneView/oneview_client.py @@ -17,18 +17,14 @@ """ This module implements a common client for HPE OneView REST API. """ +import json +import os + from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals -from future import standard_library - -standard_library.install_aliases() - -import json -import os - from hpeOneView.connection import connection from hpeOneView.image_streamer.image_streamer_client import ImageStreamerClient from hpeOneView.resources.security.certificate_authority import CertificateAuthority @@ -89,7 +85,8 @@ from hpeOneView.resources.storage.sas_logical_jbod_attachments import SasLogicalJbodAttachments from hpeOneView.resources.networking.uplink_sets import UplinkSets from hpeOneView.resources.servers.migratable_vc_domains import MigratableVcDomains -from hpeOneView.resources.networking.sas_logical_interconnect_groups import SasLogicalInterconnectGroups +from hpeOneView.resources.networking.sas_logical_interconnect_groups import \ + SasLogicalInterconnectGroups from hpeOneView.resources.search.index_resources import IndexResources from hpeOneView.resources.search.labels import Labels from hpeOneView.resources.activity.alerts import Alerts @@ -100,23 +97,32 @@ from hpeOneView.resources.security.login_details import LoginDetails from hpeOneView.resources.security.roles import Roles from hpeOneView.resources.security.users import Users -from hpeOneView.resources.settings.appliance_device_read_community import ApplianceDeviceReadCommunity -from hpeOneView.resources.settings.appliance_device_snmp_v1_trap_destinations import ApplianceDeviceSNMPv1TrapDestinations -from hpeOneView.resources.settings.appliance_device_snmp_v3_trap_destinations import ApplianceDeviceSNMPv3TrapDestinations +from hpeOneView.resources.settings.appliance_device_read_community import \ + ApplianceDeviceReadCommunity +from hpeOneView.resources.settings.appliance_device_snmp_v1_trap_destinations import \ + ApplianceDeviceSNMPv1TrapDestinations +from hpeOneView.resources.settings.appliance_device_snmp_v3_trap_destinations import \ + ApplianceDeviceSNMPv3TrapDestinations from hpeOneView.resources.settings.appliance_device_snmp_v3_users import ApplianceDeviceSNMPv3Users from hpeOneView.resources.settings.appliance_node_information import ApplianceNodeInformation from hpeOneView.resources.settings.appliance_health_status import ApplianceHealthStatus from hpeOneView.resources.settings.appliance_proxy_configuration import ApplianceProxyConfiguration from hpeOneView.resources.settings.appliance_network_interfaces import ApplianceNetworkInterfaces from hpeOneView.resources.settings.ha_nodes import HANodes -from hpeOneView.resources.settings.appliance_time_and_locale_configuration import ApplianceTimeAndLocaleConfiguration +from hpeOneView.resources.settings.appliance_time_and_locale_configuration import \ + ApplianceTimeAndLocaleConfiguration from hpeOneView.resources.settings.versions import Versions from hpeOneView.resources.hypervisors.hypervisor_managers import HypervisorManagers from hpeOneView.resources.security.certificates_server import CertificatesServer from hpeOneView.resources.hypervisors.hypervisor_cluster_profiles import HypervisorClusterProfiles -from hpeOneView.resources.settings.appliance_configuration_timeconfig import ApplianceConfigurationTimeconfig +from hpeOneView.resources.settings.appliance_configuration_timeconfig import \ + ApplianceConfigurationTimeconfig from hpeOneView.resources.settings.appliance_ssh_access import ApplianceSshAccess +from future import standard_library + +standard_library.install_aliases() + ONEVIEW_CLIENT_INVALID_PROXY = 'Invalid Proxy format' ONEVIEW_CLIENT_INVALID_I3S_IP = 'Image streamer ip address is missing' ONEVIEW_CLIENT_MISSING_IP = 'Oneview ip address is missing' @@ -125,8 +131,8 @@ class OneViewClient(object): def __init__(self, config): - self.__connection = connection(config.get('ip'), config.get('api_version'), config.get('ssl_certificate', False), - config.get('timeout')) + self.__connection = connection(config.get('ip'), config.get('api_version'), \ + config.get('ssl_certificate', False), config.get('timeout')) self.__image_streamer_ip = config.get("image_streamer_ip") self.__validate_host() self.__set_proxy(config) @@ -239,8 +245,10 @@ def from_environment_variables(cls): """ Construct OneViewClient using environment variables. - Allowed variables: ONEVIEWSDK_IP (required), ONEVIEWSDK_USERNAME (required), ONEVIEWSDK_PASSWORD (required), - ONEVIEWSDK_AUTH_LOGIN_DOMAIN, ONEVIEWSDK_API_VERSION, ONEVIEWSDK_IMAGE_STREAMER_IP, ONEVIEWSDK_SESSIONID, ONEVIEWSDK_SSL_CERTIFICATE, + Allowed variables: ONEVIEWSDK_IP (required), ONEVIEWSDK_USERNAME (required), + ONEVIEWSDK_PASSWORD (required), + ONEVIEWSDK_AUTH_LOGIN_DOMAIN, ONEVIEWSDK_API_VERSION, ONEVIEWSDK_IMAGE_STREAMER_IP, + ONEVIEWSDK_SESSIONID, ONEVIEWSDK_SSL_CERTIFICATE, ONEVIEWSDK_CONNECTION_TIMEOUT and ONEVIEWSDK_PROXY. Returns: @@ -261,7 +269,8 @@ def from_environment_variables(cls): image_streamer_ip=image_streamer_ip, api_version=api_version, ssl_certificate=ssl_certificate, - credentials=dict(userName=username, authLoginDomain=auth_login_domain, password=password, sessionID=sessionID), + credentials=dict(userName=username, authLoginDomain=auth_login_domain, \ + password=password, sessionID=sessionID), proxy=proxy, timeout=timeout) return cls(config) diff --git a/hpeOneView/resources/activity/alerts.py b/hpeOneView/resources/activity/alerts.py index 28d035f39..fe63f6236 100644 --- a/hpeOneView/resources/activity/alerts.py +++ b/hpeOneView/resources/activity/alerts.py @@ -20,15 +20,16 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient, extract_id_from_uri + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient, extract_id_from_uri - class Alerts(object): + """ Class to retrieve alerts """ URI = '/rest/alerts' def __init__(self, con): @@ -56,30 +57,32 @@ def get_all(self, start=0, count=-1, filter='', query='', sort='', view=''): Args: start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default is + 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of start + and count exceed the total number of items. filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. + A general filter/query string to narrow the list of items returned. The default is + no filter; all resources are returned. query: - A general query string to narrow the list of resources returned. The default is no query (all - resources are returned). + A general query string to narrow the list of resources returned. The default is no + query (all resources are returned). sort: - The sort order of the returned data set. By default, the sort order is based on create time, with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time, with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection, by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - collections of resources). + Returns a specific subset of the attributes of the resource or collection, by + specifying the name of a predefined view. The default view is expand (show all attributes + of the resource and all elements of collections of resources). Returns: list: A list of alerts. """ - return self._client.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view) + return self._client.get_all(start=start, count=count, filter=filter, query=query,\ + sort=sort, view=view) def get_by(self, field, value): """ @@ -116,10 +119,10 @@ def delete_all(self, filter, timeout=-1): Args: filter (list or str): - A general filter string to narrow the list of items to delete. The default is no filter; all - resources are deleted. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + A general filter string to narrow the list of items to delete. The default is no + filter; all resources are deleted. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates whether the alerts were successfully deleted. @@ -132,7 +135,8 @@ def update(self, resource, id_or_uri=None, timeout=-1): Args: resource (dict): Object to update. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: diff --git a/hpeOneView/resources/activity/events.py b/hpeOneView/resources/activity/events.py index 2dcc0ef03..087cbd2de 100644 --- a/hpeOneView/resources/activity/events.py +++ b/hpeOneView/resources/activity/events.py @@ -20,15 +20,15 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - - class Events(object): + """ Class to retrieve events """ URI = '/rest/events' DEFAULT_VALUES = { @@ -54,36 +54,38 @@ def get(self, id_or_uri): event = self._client.get(id_or_uri) return event - def get_all(self, start=0, count=-1, filter='', query='', sort='', view=''): + def get_all(self, start=0, count=-1, _filter='', query='', sort='', view=''): """ Gets all the events based upon filters provided. Args: start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, + the default is 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. + The actual number of items in the response may differ from the requested + count if the sum of start and count exceed the total number of items. filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. + A general filter/query string to narrow the list of items returned. + The default is no filter; all resources are returned. query: - A general query string to narrow the list of resources returned. The default is no query (all - resources are returned). + A general query string to narrow the list of resources returned. + The default is no query (all resources are returned). sort: - The sort order of the returned data set. By default, the sort order is based on create time, with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is + based on create time, with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection, by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of + Returns a specific subset of the attributes of the resource or collection, + by specifying the name of a predefined view. The default view is expand + (show all attributes of the resource and all elements of collections of resources). Returns: list: A list of events. """ - return self._client.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view) + return self._client.get_all(start=start, count=count, filter=_filter, query=query, \ + sort=sort, view=view) def get_by(self, field, value): """ @@ -108,8 +110,8 @@ def create(self, resource, timeout=-1): Args: resource (dict): Object to create. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView, just stop waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView, just stop waiting for its completion. Returns: dict: Created resource. diff --git a/hpeOneView/resources/activity/tasks.py b/hpeOneView/resources/activity/tasks.py index db35b4244..d54a7c9bc 100644 --- a/hpeOneView/resources/activity/tasks.py +++ b/hpeOneView/resources/activity/tasks.py @@ -15,20 +15,20 @@ # limitations under the License. ### +import json from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ResourcePatchMixin +from hpeOneView.exceptions import HPEOneViewException + from future import standard_library -import json standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin -from hpeOneView.exceptions import HPEOneViewException - class Tasks(ResourcePatchMixin, Resource): """ @@ -40,7 +40,8 @@ class Tasks(ResourcePatchMixin, Resource): def __init__(self, connection, data=None): super(Tasks, self).__init__(connection, data) - def get_all(self, start=0, count=-1, fields='', filter='', query='', sort='', view='', topCount=0, childLimit=0): + def get_all(self, start=0, count=-1, fields='', _filter='', query='', sort='', \ + view='', topCount=0, childLimit=0): """ Gets all the tasks based upon filters provided. @@ -49,48 +50,48 @@ def get_all(self, start=0, count=-1, fields='', filter='', query='', sort='', vi Args: start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default + is 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of + start and count exceed the total number of items. fields: Specifies which fields should be returned in the result set. filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. + A general filter/query string to narrow the list of items returned. + The default is no filter; all resources are returned. query: - A general query string to narrow the list of resources returned. The default is no query (all - resources are returned). + A general query string to narrow the list of resources returned. The default is + no query (all resources are returned). sort: - The sort order of the returned data set. By default, the sort order is based on create time, with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time, with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection, by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - collections of resources). + Returns a specific subset of the attributes of the resource or collection, by + specifying the name of a predefined view. The default view is expand (show all + attributes of the resource and all elements of collections of resources). childLimit: Total number of associated resources in an aggregated manner. Default value is 10. topCount: - Total number of immediate children the task should send back. Otherwise, the task sends back the - aggregated view of the tree. Default value is 3. + Total number of immediate children the task should send back. Otherwise, the task + sends back the aggregated view of the tree. Default value is 3. Returns: list: A list of tasks. """ - return self._helper.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view, - fields=fields, childLimit=childLimit, topCount=topCount) + return self._helper.get_all(start=start, count=count, filter=_filter, query=query, sort=\ + sort, view=view, fields=fields, childLimit=childLimit, topCount=topCount) def patch(self, uri, timeout=-1): """ - Sets the state of task to cancelling only if IsCancellable is set to true for the task and its children or - children are in terminal state. + Sets the state of task to cancelling only if IsCancellable is set to true for the task and + its children or children are in terminal state. Args: uri: URI of task resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated resource. diff --git a/hpeOneView/resources/data_services/metric_streaming.py b/hpeOneView/resources/data_services/metric_streaming.py index 541f1ad06..99911b947 100644 --- a/hpeOneView/resources/data_services/metric_streaming.py +++ b/hpeOneView/resources/data_services/metric_streaming.py @@ -20,19 +20,20 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient class MetricStreaming(object): """ Metrics API client. - Metrics can be relayed from OneView for managed resources at a specified interval. The following steps can be - followed to enable the metric relay in OneView: + Metrics can be relayed from OneView for managed resources at a specified interval. The + following steps can be followed to enable the metric relay in OneView: * Get the list of resource types and metrics which can be configured for live streaming * Configure the live metric stream in OneView @@ -52,15 +53,15 @@ class MetricStreaming(object): uri (str): Canonical URI of the resource. category (str): - Identifies the category of resource. The supported devices are server-hardware, enclosures, and - power-devices. + Identifies the category of resource. The supported devices are server-hardware, + enclosures, and power-devices. created (timestamp): Date and time when the resource was created. modified (timestamp): Date and time when the resource was last modified. eTag (str): - Entity tag/version ID of the resource, the same value that is returned in the ETag header on a GET of the - resource. + Entity tag/version ID of the resource, the same value that is returned in the + ETag header on a GET of the resource. type (str): Uniquely identifies the type of the JSON object. @@ -73,7 +74,8 @@ def __init__(self, con): def get_capability(self): """ - Fetches the list of resource types and supported metrics that OneView is capable of relaying. + Fetches the list of resource types and supported metrics that OneView is capable of + relaying. Returns: list: List of resource types and supported metrics. @@ -85,19 +87,21 @@ def get_configuration(self): Fetches the current configuration for which metrics are being relayed. Returns: - list: List of objects which contain frequency, sample interval, and source type for each resource-type. + list: List of objects which contain frequency, sample interval, and source type for + each resource-type. """ return self._client.get(self.URI + "/configuration") def update_configuration(self, configuration): """ - Updates the metrics configuration with the new values. Overwrites the existing configuration. + Updates the metrics configuration with the new values. Overwrites the existing + configuration. Args: configuration (dict): - Dictionary with a list of objects which contain frequency, sample interval, and source type for each - resource-type. + Dictionary with a list of objects which contain frequency, sample interval, and + source type for each resource-type. Returns: dict: The current configuration for which metrics are being relayed. diff --git a/hpeOneView/resources/facilities/datacenters.py b/hpeOneView/resources/facilities/datacenters.py index d2116f1ac..c7677361c 100644 --- a/hpeOneView/resources/facilities/datacenters.py +++ b/hpeOneView/resources/facilities/datacenters.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class Datacenters(object): """ @@ -39,10 +39,10 @@ def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) - def get_all(self, start=0, count=-1, filter='', query='', sort=''): + def get_all(self, start=0, count=-1, _filter='', query='', sort=''): """ - Gets a set of data center resources according to the specified parameters. Filters can be used to get a specific - set of data centers. + Gets a set of data center resources according to the specified parameters. Filters can be + used to get a specific set of data centers. Args: start: @@ -66,7 +66,7 @@ def get_all(self, start=0, count=-1, filter='', query='', sort=''): Returns: list: List of data centers. """ - return self._client.get_all(start, count, filter=filter, sort=sort, query=query) + return self._client.get_all(start, count, filter=_filter, sort=sort, query=query) def get(self, id_or_uri): """ @@ -83,9 +83,9 @@ def get(self, id_or_uri): def get_visual_content(self, id_or_uri): """ - Gets a list of visual content objects describing each rack within the data center. The response aggregates data - center and rack data with a specified metric (peak24HourTemp) to provide simplified access to display data for - the data center. + Gets a list of visual content objects describing each rack within the data center. + The response aggregates data center and rack data with a specified metric (peak24HourTemp) + to provide simplified access to display data for the data center. Args: id_or_uri: Can be either the resource ID or the resource URI. @@ -119,11 +119,11 @@ def remove(self, resource, force=False, timeout=-1): Args: resource (dict): Object to remove. force: - If set to true, the operation completes despite any problems with network connectivity or errors on the - resource itself. The default is false. + If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: Result status. """ @@ -135,8 +135,8 @@ def add(self, information, timeout=-1): Args: information: Data center information - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Added data center. @@ -149,18 +149,18 @@ def update(self, resource, timeout=-1): Args: resource (dict): Object to update. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated data center. """ return self._client.update(resource, timeout=timeout) - def remove_all(self, filter, force=False, timeout=-1): + def remove_all(self, _filter, force=False, timeout=-1): """ - Deletes the set of datacenters according to the specified parameters. A filter is required to identify the set - of resources to be deleted. + Deletes the set of datacenters according to the specified parameters. A filter is required + to identify the set of resources to be deleted. Args: filter: @@ -169,10 +169,10 @@ def remove_all(self, filter, force=False, timeout=-1): If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: operation success """ - return self._client.delete_all(filter=filter, force=force, timeout=timeout) + return self._client.delete_all(filter=_filter, force=force, timeout=timeout) diff --git a/hpeOneView/resources/facilities/power_devices.py b/hpeOneView/resources/facilities/power_devices.py index 8e01b87d7..77d399fb0 100644 --- a/hpeOneView/resources/facilities/power_devices.py +++ b/hpeOneView/resources/facilities/power_devices.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class PowerDevices(object): """ @@ -39,11 +39,12 @@ def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) - def get_all(self, start=0, count=-1, filter='', query='', sort=''): + def get_all(self, start=0, count=-1, _filter='', query='', sort=''): """ - Gets a set of power delivery device resources according to the specified parameters. Filters can be used to get - a specific set of power delivery devices. With no filters specified, the API returns a potentially paginated - list of all the power delivery device resources subject to start/count/sort parameters. + Gets a set of power delivery device resources according to the specified parameters. + Filters can be used to get a specific set of power delivery devices. With no filters + specified, the API returns a potentially paginated list of all the power delivery device + resources subject to start/count/sort parameters. Args: start: @@ -83,16 +84,16 @@ def get(self, id_or_uri): def add(self, information, timeout=-1): """ - Adds a power delivery device resource based upon the attributes specified. Use this method to create a - representation of power delivery devices that provide power to other resources but cannot otherwise be - discovered by the management appliance. + Adds a power delivery device resource based upon the attributes specified. Use this method + to create a representation of power delivery devices that provide power to other resources + but cannot otherwise be discovered by the management appliance. Args: information: power device information timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: added power device. @@ -101,16 +102,16 @@ def add(self, information, timeout=-1): def remove(self, resource, force=False, timeout=-1): """ - Deletes the set of power-devices according to the specified parameters. A filter is required to identify the - set of resources to be deleted. + Deletes the set of power-devices according to the specified parameters. A filter is required + to identify the set of resources to be deleted. Args: resource: dict object to remove force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: operation success @@ -119,15 +120,16 @@ def remove(self, resource, force=False, timeout=-1): def add_ipdu(self, information, timeout=-1): """ - Add an HP iPDU and bring all components under management by discovery of its management module. Bring the - management module under exclusive management by the appliance, configure any management or data collection - settings, and create a private set of administrative credentials to enable ongoing communication and management - of the iPDU. Use "force" to claim the device, even if claimed by another management appliance + Add an HP iPDU and bring all components under management by discovery of its management + module. Bring the management module under exclusive management by the appliance, configure + any management or data collection settings, and create a private set of administrative + credentials to enable ongoing communication and management of the iPDU. Use "force" to + claim the device, even if claimed by another management appliance Args: resource: power device information - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: added power device. @@ -137,15 +139,17 @@ def add_ipdu(self, information, timeout=-1): def update(self, resource, timeout=-1): """ - Updates the resource for the specified {id}. The properties that are omitted (not included as part of the the - request body) are reset to their respective default values. The id and uuid properties are required and cannot + Updates the resource for the specified {id}. The properties that are omitted (not included + as part of the the + request body) are reset to their respective default values. The id and uuid properties are + required and cannot be changed. Args: resource (dict): Object to update timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated power device @@ -154,8 +158,8 @@ def update(self, resource, timeout=-1): def get_power_state(self, id_or_uri): """ - Gets the power state (on, off or unknown) of the specified power delivery device that supports power control. - The device must be an HP Intelligent Outlet. + Gets the power state (on, off or unknown) of the specified power delivery device that + supports power control. The device must be an HP Intelligent Outlet. Args: id_or_uri: @@ -169,7 +173,8 @@ def get_power_state(self, id_or_uri): def update_power_state(self, id_or_uri, power_state): """ - Sets the power state of the specified power delivery device. The device must be an HP Intelligent Outlet. + Sets the power state of the specified power delivery device. The device must be an HP + Intelligent Outlet. Args: id_or_uri: @@ -208,8 +213,8 @@ def remove_synchronous(self, resource, force=False, timeout=-1): force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: operation success @@ -220,9 +225,10 @@ def remove_synchronous(self, resource, force=False, timeout=-1): def get_uid_state(self, id_or_uri): """ - Retrieves the unit identification (UID) state (on, off, unknown) of the specified power outlet or extension bar - resource. The device must be an HP iPDU component with a locator light (HP Intelligent Load Segment, - HP AC Module, HP Intelligent Outlet Bar, or HP Intelligent Outlet). + Retrieves the unit identification (UID) state (on, off, unknown) of the specified power + outlet or extension bar resource. The device must be an HP iPDU component with a locator + light (HP Intelligent Load Segment, HP AC Module, HP Intelligent Outlet Bar, or HP + Intelligent Outlet). Args: id_or_uri: @@ -236,9 +242,9 @@ def get_uid_state(self, id_or_uri): def update_uid_state(self, id_or_uri, refresh_state_data): """ - Sets the unit identification (UID) light state of the specified power delivery device. The device must be an - HP iPDU component with a locator light (HP Intelligent Load Segment, HP AC Module, HP Intelligent Outlet Bar, - or HP Intelligent Outlet) + Sets the unit identification (UID) light state of the specified power delivery device. The + device must be an HP iPDU component with a locator light (HP Intelligent Load Segment, HP + AC Module, HP Intelligent Outlet Bar, or HP Intelligent Outlet) Args: id_or_uri: @@ -252,17 +258,18 @@ def update_uid_state(self, id_or_uri, refresh_state_data): uri = self._client.build_uri(id_or_uri) + "/uidState" return self._client.update(refresh_state_data, uri) - def get_utilization(self, id_or_uri, fields=None, filter=None, refresh=False, view=None): + def get_utilization(self, id_or_uri, fields=None, _filter=None, refresh=False, view=None): """ - Retrieves historical utilization data for the specified metrics and time span. The device must be a component - of an HPE iPDU. + Retrieves historical utilization data for the specified metrics and time span. The device + must be a component of an HPE iPDU. Args: id_or_uri: The power device id or the resource uri fields: - Name of the metric(s) to be retrieved in the format METRIC[,METRIC]...If unspecified, all metrics - supported are returned. Power delivery devices support the following utilization metrics: + Name of the metric(s) to be retrieved in the format METRIC[,METRIC]...If + unspecified, all metrics supported are returned. Power delivery devices support the + following utilization metrics: * AveragePower Average power consumption in Watts during this sample interval. @@ -275,56 +282,59 @@ def get_utilization(self, id_or_uri, fields=None, filter=None, refresh=False, vi For Example: 'startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z' startDate: - Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is - determined by the endDate minus 24 hours. + Start date of requested starting time range in ISO 8601 format. If omitted, the + startDate is determined by the endDate minus 24 hours. endDate: - End date of requested starting time range in ISO 8601 format. When omitted the endDate includes the - latest data sample available. - - If an excessive number of samples would otherwise be returned, the results will be segmented. The caller - is responsible for comparing the returned sliceStartTime with the requested startTime in the response. - If the sliceStartTime is greater than the oldestSampleTime and the requested start time, the caller is - responsible for repeating the request with endTime set to sliceStartTime to obtain the next segment. + End date of requested starting time range in ISO 8601 format. When omitted the + endDate includes the latest data sample available. + + If an excessive number of samples would otherwise be returned, the results will be + segmented. The caller is responsible for comparing the returned sliceStartTime with the + requested startTime in the response. + If the sliceStartTime is greater than the oldestSampleTime and the requested start + time, the caller is responsible for repeating the request with endTime set to + sliceStartTime to obtain the next segment. This process is repeated until the full data set is retrieved. - If the resource has no data, the UtilizationData is still returned, but will contain no samples and - sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set - appropriately (null if no data is available). If the filter does not happen to overlap the data - that a resource does have, then the metric history service will return null sample values for any - missing samples. + If the resource has no data, the UtilizationData is still returned, but will contain + no samples and sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime + will still be set appropriately (null if no data is available). If the filter does not + happen to overlap the data that a resource does have, then the metric history service will + return null sample values for any missing samples. refresh: - Specifies that if necessary, an additional request will be queued to obtain the most recent utilization - data from the enclosure. The response will not include any refreshed data. To track the availability - of the newly collected data, monitor the TaskResource identified by the refreshTaskUri property in - the response. If null, no refresh was queued. + Specifies that if necessary, an additional request will be queued to obtain the most + recent utilization data from the enclosure. The response will not include any refreshed + data. To track the availability of the newly collected data, monitor the TaskResource + identified by the refreshTaskUri property in the response. If null, no refresh was queued. view: - Specifies the resolution interval length of the samples to be retrieved. This is reflected in the - resolution in the returned response. Utilization data is automatically purged to stay within storage - space constraints. Supported views are listed below: + Specifies the resolution interval length of the samples to be retrieved. This is + reflected in the resolution in the returned response. Utilization data is automatically + purged to stay within storage space constraints. Supported views are listed below: native (DEFAULT) - Resolution of the samples returned will be one sample for each 5-minute time period. This is the - default view and matches the resolution of the data returned by the enclosure. Samples at this - resolution are retained up to one year. + Resolution of the samples returned will be one sample for each 5-minute time + period. This is the default view and matches the resolution of the data returned by the + enclosure. Samples at this resolution are retained up to one year. hour - Resolution of the samples returned will be one sample for each 60-minute time period. Samples are - calculated by averaging the available 5-minute data samples that occurred within the hour, except - for PeakPower which is calculated by reporting the peak observed 5-minute sample value data during - the hour. Samples at this resolution are retained up to three years. + Resolution of the samples returned will be one sample for each 60-minute time + period. Samples are calculated by averaging the available 5-minute data samples that + occurred within the hour, except for PeakPower which is calculated by reporting the peak + observed 5-minute sample value data during the hour. Samples at this resolution are + retained up to three years. day - Resolution of the samples returned will be one sample for each 24-hour time period. One day is a - 24-hour period that starts at midnight GMT regardless of the time zone in which the appliance or - client is located. Samples are calculated by averaging the available 5-minute data samples that - occurred during the day, except for PeakPower which is calculated by reporting the peak observed - 5-minute sample value data during the day. Samples at this resolution are retained up to three - years. + Resolution of the samples returned will be one sample for each 24-hour time + period. One day is a 24-hour period that starts at midnight GMT regardless of the time + zone in which the appliance or client is located. Samples are calculated by averaging the + available 5-minute data samples that occurred during the day, except for PeakPower which + is calculated by reporting the peak observed 5-minute sample value data during the day. + Samples at this resolution are retained up to three years. Returns: dict: Utilization data """ - return self._client.get_utilization(id_or_uri, fields, filter, refresh, view) + return self._client.get_utilization(id_or_uri, fields, _filter, refresh, view) def get_by(self, field, value): """ diff --git a/hpeOneView/resources/facilities/racks.py b/hpeOneView/resources/facilities/racks.py index 457ac5e6f..d72d808ec 100644 --- a/hpeOneView/resources/facilities/racks.py +++ b/hpeOneView/resources/facilities/racks.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class Racks(object): """ @@ -39,11 +39,11 @@ def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) - def get_all(self, start=0, count=-1, filter='', query='', sort=''): + def get_all(self, start=0, count=-1, _filter='', query='', sort=''): """ - Gets a set of rack resources according to the specified parameters. Filters can be used to get a specific set - of racks. With no filters specified, the API returns a potentially paginated list of all the racks subject - to start/count/sort parameters. + Gets a set of rack resources according to the specified parameters. Filters can be used + to get a specific set of racks. With no filters specified, the API returns a potentially + paginated list of all the racks subject to start/count/sort parameters. Args: start: @@ -67,7 +67,7 @@ def get_all(self, start=0, count=-1, filter='', query='', sort=''): Returns: list: List of racks. """ - return self._client.get_all(start, count, filter=filter, sort=sort, query=query) + return self._client.get_all(start, count, filter=_filter, sort=sort, query=query) def get(self, id_or_uri): """ @@ -118,11 +118,11 @@ def remove(self, resource, force=False, timeout=-1): Args: resource (dict): Object to remove. force: - If set to true, the operation completes despite any problems with network connectivity or errors on the - resource itself. The default is false. + If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Result status. @@ -131,15 +131,16 @@ def remove(self, resource, force=False, timeout=-1): def add(self, information, timeout=-1): """ - Adds a rack resource based upon the attributes specified. All attributes without default values must be - specified in the POST body. The response contains the rack resource as added to the appliance with default and - assigned properties expanded. The id and uri are assigned by the management appliance and are used to uniquely + Adds a rack resource based upon the attributes specified. All attributes without + default values must be specified in the POST body. The response contains the rack + resource as added to the appliance with default and assigned properties expanded. + The id and uri are assigned by the management appliance and are used to uniquely identify this particular resource. Args: information: Rack information - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Added rack. @@ -149,15 +150,16 @@ def add(self, information, timeout=-1): def update(self, resource, timeout=-1): """ - Updates the specified rack resource. The properties that are omitted (not included as part of the request body) - are reset to their respective default values. The id and uuid properties are required and cannot be changed. - To update existing racks first perform a get() request to retrieve the current properties, update the desired - properties, and then update() the request body containing the new representation of the resource. + Updates the specified rack resource. The properties that are omitted (not included as + part of the request body) are reset to their respective default values. The id and uuid + properties are required and cannot be changed. To update existing racks first perform a + get() request to retrieve the current properties, update the desired properties, and then + update() the request body containing the new representation of the resource. Args: resource (dict): Object to update. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated rack. diff --git a/hpeOneView/resources/fc_sans/endpoints.py b/hpeOneView/resources/fc_sans/endpoints.py index 1fdb4b551..0623e0709 100644 --- a/hpeOneView/resources/fc_sans/endpoints.py +++ b/hpeOneView/resources/fc_sans/endpoints.py @@ -20,13 +20,12 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class Endpoints(object): """ @@ -48,9 +47,9 @@ def get_all(self, start=0, count=-1, query='', sort=''): The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of + start and count exceed the total number of items. query: A general query string to narrow the list of resources returned. The default is no query - all resources are returned. diff --git a/hpeOneView/resources/fc_sans/managed_sans.py b/hpeOneView/resources/fc_sans/managed_sans.py index fcf3fb899..3b1b52f9f 100644 --- a/hpeOneView/resources/fc_sans/managed_sans.py +++ b/hpeOneView/resources/fc_sans/managed_sans.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ensure_resource_client, unavailable_method + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ensure_resource_client, unavailable_method - class ManagedSANs(Resource): """ @@ -47,9 +47,9 @@ def get_all(self, start=0, count=-1, query='', sort=''): The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum ofy + start and count exceed the total number of items. query: A general query string to narrow the list of resources returned. The default is no query - all resources are returned. @@ -90,7 +90,7 @@ def delete(self): unavailable_method() @ensure_resource_client - def get_endpoints(self, start=0, count=-1, filter='', sort=''): + def get_endpoints(self, start=0, count=-1, _filter='', sort=''): """ Gets a list of endpoints in a SAN. @@ -113,7 +113,7 @@ def get_endpoints(self, start=0, count=-1, filter='', sort=''): list: A list of endpoints. """ uri = "{}/endpoints/".format(self.data["uri"]) - return self._helper.get_all(start, count, filter=filter, sort=sort, uri=uri) + return self._helper.get_all(start, count, filter=_filter, sort=sort, uri=uri) @ensure_resource_client def create_endpoints_csv_file(self, timeout=-1): @@ -122,8 +122,8 @@ def create_endpoints_csv_file(self, timeout=-1): Args: timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stops waiting for its completion. Returns: dict: Endpoint CSV File Response. @@ -138,8 +138,8 @@ def create_issues_report(self, timeout=-1): Args: timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stops waiting for its completion. Returns: list: A list of FCIssueResponse dict. @@ -149,7 +149,8 @@ def create_issues_report(self, timeout=-1): def get_wwn(self, wwn): """ - Retrieves a list of associations between provided WWNs and the SANs (if any) on which they reside. + Retrieves a list of associations between provided WWNs and the SANs (if any) on which they + reside. Note: This method is available for API version 300 or later. diff --git a/hpeOneView/resources/hypervisors/hypervisor_cluster_profiles.py b/hpeOneView/resources/hypervisors/hypervisor_cluster_profiles.py index 190ccfb41..29925f92b 100644 --- a/hpeOneView/resources/hypervisors/hypervisor_cluster_profiles.py +++ b/hpeOneView/resources/hypervisors/hypervisor_cluster_profiles.py @@ -19,17 +19,19 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals + +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class HypervisorClusterProfiles(Resource): """ - The cluster profile resource manager REST APIs to create, retrieve, modify and delete hypervisor cluster profiles. + The cluster profile resource manager REST APIs to create, retrieve, modify and delete + hypervisor cluster profiles. """ URI = '/rest/hypervisor-cluster-profiles' DEFAULT_VALUES = { @@ -74,15 +76,16 @@ def get_all(self, start=0, count=-1, filter='', sort='', query='', scope_uris='' Return: list: List of Hypervisor cluster profiles """ - return self._helper.get_all(start, count, filter=filter, sort=sort, query=query, scope_uris=scope_uris) + return self._helper.get_all(start, count, filter=filter, sort=sort, query=query, \ + scope_uris=scope_uris) def create_virtual_switch_layout(self, data=None, timeout=-1): """Generates vSwitch layout using information specified in the request body. Args: data: Fields passed to create the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout + does not abort the operation in OneView; it just stops waiting for its completion. Return: Created virtual switch layout. @@ -95,7 +98,8 @@ def create_virtual_switch_layout(self, data=None, timeout=-1): def get_compliance_preview(self): """ - Gets the preview of manual and automatic updates required to make the cluster profile consistent with its template. + Gets the preview of manual and automatic updates required to make the cluster profile + consistent with its template. Return: cluster profile compliance preview @@ -105,7 +109,8 @@ def get_compliance_preview(self): def delete(self, timeout=-1, soft_delete=False, force=False): """ - Deletes a hypervisor cluster profile object from the appliance based on Hypervisor Cluster Profile UUID + Deletes a hypervisor cluster profile object from the appliance based on Hypervisor Cluster + Profile UUID Args: force: diff --git a/hpeOneView/resources/hypervisors/hypervisor_managers.py b/hpeOneView/resources/hypervisors/hypervisor_managers.py index e471da999..626070aec 100755 --- a/hpeOneView/resources/hypervisors/hypervisor_managers.py +++ b/hpeOneView/resources/hypervisors/hypervisor_managers.py @@ -19,13 +19,14 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals + +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class HypervisorManagers(Resource): """ @@ -42,8 +43,8 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, filter='', sort='', query='', scope_uris=''): """ - Gets a list of Hypervisor Managers based on optional sorting and filtering, and constrained by start and count - parameters. + Gets a list of Hypervisor Managers based on optional sorting and filtering, and + constrained by start and count parameters. Args: start: @@ -69,4 +70,5 @@ def get_all(self, start=0, count=-1, filter='', sort='', query='', scope_uris='' Returns: list: List of Hypervisor Managers """ - return self._helper.get_all(start, count, filter=filter, sort=sort, query=query, scope_uris=scope_uris) + return self._helper.get_all(start, count, filter=filter, sort=sort, query=query,\ + scope_uris=scope_uris) diff --git a/hpeOneView/resources/networking/connection_templates.py b/hpeOneView/resources/networking/connection_templates.py index 188f43892..1da478465 100644 --- a/hpeOneView/resources/networking/connection_templates.py +++ b/hpeOneView/resources/networking/connection_templates.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class ConnectionTemplates(Resource): """ diff --git a/hpeOneView/resources/networking/ethernet_networks.py b/hpeOneView/resources/networking/ethernet_networks.py index 757e3378a..7d09a0833 100755 --- a/hpeOneView/resources/networking/ethernet_networks.py +++ b/hpeOneView/resources/networking/ethernet_networks.py @@ -20,14 +20,14 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import (Resource, ResourcePatchMixin, + ensure_resource_client) + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import (Resource, ResourcePatchMixin, - ensure_resource_client) - class EthernetNetworks(ResourcePatchMixin, Resource): """ @@ -71,8 +71,8 @@ def create_bulk(self, resource, timeout=-1): Args: resource (dict): Specifications to create in bulk. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: list: List of created Ethernet Networks. @@ -88,7 +88,8 @@ def create_bulk(self, resource, timeout=-1): def get_range(self, name_prefix, vlan_id_range): """ - Gets a list of Ethernet Networks that match the 'given name_prefix' and the 'vlan_id_range'. + Gets a list of Ethernet Networks that match the 'given name_prefix' and the + 'vlan_id_range'. Examples: >>> enet.get_range('Enet_name', '1-2,5') @@ -101,7 +102,8 @@ def get_range(self, name_prefix, vlan_id_range): Args: name_prefix: The Ethernet Network prefix - vlan_id_range: A combination of values or ranges to be retrieved. For example, '1-10,50,51,500-700'. + vlan_id_range: A combination of values or ranges to be retrieved. For example, + '1-10,50,51,500-700'. Returns: list: A list of Ethernet Networks. @@ -160,7 +162,8 @@ def get_associated_profiles(self): Gets the URIs of profiles which are using an Ethernet network. Args: - id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri + id_or_uri: Can be either the logical interconnect group id or the logical + interconnect group uri Returns: list: URIs of the associated profiles. @@ -188,8 +191,8 @@ def delete_bulk(self, resource, timeout=-1): Args: resource (dict): Specifications to delete in bulk. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. """ uri = self.URI + '/bulk-delete' diff --git a/hpeOneView/resources/networking/fc_networks.py b/hpeOneView/resources/networking/fc_networks.py index 1639ae2de..70120cce3 100644 --- a/hpeOneView/resources/networking/fc_networks.py +++ b/hpeOneView/resources/networking/fc_networks.py @@ -21,10 +21,10 @@ from __future__ import absolute_import from future import standard_library -standard_library.install_aliases() - from hpeOneView.resources.resource import (Resource, ResourcePatchMixin) +standard_library.install_aliases() + class FcNetworks(ResourcePatchMixin, Resource): """ @@ -56,8 +56,8 @@ def delete_bulk(self, resource, timeout=-1): Args: resource (dict): Specifications to delete in bulk. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. """ uri = self.URI + '/bulk-delete' diff --git a/hpeOneView/resources/networking/fcoe_networks.py b/hpeOneView/resources/networking/fcoe_networks.py index 3c377b72a..bc68c337c 100644 --- a/hpeOneView/resources/networking/fcoe_networks.py +++ b/hpeOneView/resources/networking/fcoe_networks.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ResourcePatchMixin + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin - class FcoeNetworks(ResourcePatchMixin, Resource): """ @@ -58,8 +58,8 @@ def delete_bulk(self, resource, timeout=-1): Args: resource (dict): Specifications to delete in bulk. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. """ uri = self.URI + '/bulk-delete' diff --git a/hpeOneView/resources/networking/interconnect_link_topologies.py b/hpeOneView/resources/networking/interconnect_link_topologies.py index e9efafdc6..d168f97c2 100644 --- a/hpeOneView/resources/networking/interconnect_link_topologies.py +++ b/hpeOneView/resources/networking/interconnect_link_topologies.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class InterconnectLinkTopologies(object): """ @@ -45,9 +45,11 @@ def __init__(self, con): def get_all(self, start=0, count=-1, filter='', sort=''): """ - Gets a paginated collection of all the interconnect link topologies based on the specified parameters. + Gets a paginated collection of all the interconnect link topologies based on the + specified parameters. - Filters can be used in the URL to control the number of interconnect link topologies that are returned. + Filters can be used in the URL to control the number of interconnect link + topologies that are returned. With no filters specified, the API returns all interconnect link toplogies. Args: diff --git a/hpeOneView/resources/networking/interconnect_types.py b/hpeOneView/resources/networking/interconnect_types.py index 61a4b79cc..9f67f7d27 100644 --- a/hpeOneView/resources/networking/interconnect_types.py +++ b/hpeOneView/resources/networking/interconnect_types.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class InterconnectTypes(Resource): """ diff --git a/hpeOneView/resources/networking/interconnects.py b/hpeOneView/resources/networking/interconnects.py index d2237be9f..afd2056db 100644 --- a/hpeOneView/resources/networking/interconnects.py +++ b/hpeOneView/resources/networking/interconnects.py @@ -20,12 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ResourcePatchMixin +from hpeOneView.resources.resource import merge_default_values + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin -from hpeOneView.resources.resource import merge_default_values class Interconnects(ResourcePatchMixin, Resource): @@ -65,7 +66,8 @@ def get_subport_statistics(self, port_name, subport_number): subport_number (int): The subport. Returns: - dict: The statistics for the interconnect that matches id, port_name, and subport_number. + dict: The statistics for the interconnect that matches id, port_name, + and subport_number. """ uri = "{}/statistics/{}/subport/{}".format(self.data["uri"], port_name, subport_number) return self._helper.do_get(uri) @@ -87,8 +89,8 @@ def update_port(self, port_information, timeout=-1): Args: port_information (dict): object to update - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: The interconnect. @@ -103,8 +105,8 @@ def update_ports(self, ports, timeout=-1): Args: ports (list): Ports to update. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: The interconnect. @@ -119,11 +121,12 @@ def reset_port_protection(self, timeout=-1): """ Triggers a reset of port protection. - Cause port protection to be reset on all the interconnects of the logical interconnect that matches ID. + Cause port protection to be reset on all the interconnects of the logical interconnect + that matches ID. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: The interconnect. @@ -176,12 +179,13 @@ def get_pluggable_module_information(self): def update_configuration(self, timeout=-1): """ - Reapplies the appliance's configuration on the interconnect. This includes running the same configure steps - that were performed as part of the interconnect add by the enclosure. + Reapplies the appliance's configuration on the interconnect. This includes running + the same configure steps that were performed as part of the interconnect add by the + enclosure. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout + does not abort the operation in OneView; it just stops waiting for its completion. Returns: Interconnect diff --git a/hpeOneView/resources/networking/internal_link_sets.py b/hpeOneView/resources/networking/internal_link_sets.py index 3dde8d51c..9a9496c41 100644 --- a/hpeOneView/resources/networking/internal_link_sets.py +++ b/hpeOneView/resources/networking/internal_link_sets.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class InternalLinkSets(Resource): """ @@ -45,7 +45,8 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields=''): """ Gets a paginated collection of all internal link sets. - The collection is based on optional sorting and filtering and is constrained by start and count parameters. + The collection is based on optional sorting and filtering and is constrained by start + and count parameters. Args: start: @@ -67,12 +68,12 @@ def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fiel fields: Specifies which fields should be returned in the result set. view: - Return a specific subset of the attributes of the resource or collection, by specifying the name - of a predefined view. The default view is expand - show all attributes of the resource and all - elements of collections of resources. + Return a specific subset of the attributes of the resource or collection, by + specifying the name of a predefined view. The default view is expand - show all + attributes of the resource and all elements of collections of resources. Returns: list: Internal Link Set Collection. """ - return self._helper.get_all(start=start, count=count, filter=filter, + return self._helper.get_all(start=start, count=count, filter=filter,\ query=query, sort=sort, view=view, fields=fields) diff --git a/hpeOneView/resources/networking/logical_downlinks.py b/hpeOneView/resources/networking/logical_downlinks.py index c28649d31..6c2effcf0 100644 --- a/hpeOneView/resources/networking/logical_downlinks.py +++ b/hpeOneView/resources/networking/logical_downlinks.py @@ -19,13 +19,14 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class LogicalDownlinks(object): """ diff --git a/hpeOneView/resources/networking/logical_interconnect_groups.py b/hpeOneView/resources/networking/logical_interconnect_groups.py index daa55de32..d5b060061 100644 --- a/hpeOneView/resources/networking/logical_interconnect_groups.py +++ b/hpeOneView/resources/networking/logical_interconnect_groups.py @@ -20,13 +20,12 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ResourcePatchMixin from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin - class LogicalInterconnectGroups(ResourcePatchMixin, Resource): """ @@ -53,8 +52,8 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''): """ - Gets a list of logical interconnect groups based on optional sorting and filtering and is constrained by start - and count parameters. + Gets a list of logical interconnect groups based on optional sorting and filtering + and is constrained by start and count parameters. Args: start: diff --git a/hpeOneView/resources/networking/logical_interconnects.py b/hpeOneView/resources/networking/logical_interconnects.py index db01703e3..40b431a4b 100644 --- a/hpeOneView/resources/networking/logical_interconnects.py +++ b/hpeOneView/resources/networking/logical_interconnects.py @@ -20,14 +20,14 @@ from __future__ import print_function from __future__ import unicode_literals -from future import standard_library - -standard_library.install_aliases() - from hpeOneView.exceptions import HPEOneViewResourceNotFound from hpeOneView.resources.resource import (Resource, ResourcePatchMixin, merge_resources, ensure_resource_client, unavailable_method) +from future import standard_library + +standard_library.install_aliases() + class LogicalInterconnects(ResourcePatchMixin, Resource): """ @@ -90,8 +90,8 @@ def delete(self): def get_all(self, start=0, count=-1, sort=''): """ - Gets a list of logical interconnects based on optional sorting and filtering and is constrained by start - and count parameters. + Gets a list of logical interconnects based on optional sorting and filtering and is + constrained by start and count parameters. Args: start: @@ -132,18 +132,19 @@ def get_by_name(self, name): @ensure_resource_client def update_compliance(self, timeout=-1): """ - Returns logical interconnects to a consistent state. The current logical interconnect state is - compared to the associated logical interconnect group. + Returns logical interconnects to a consistent state. The current logical interconnect + state is compared to the associated logical interconnect group. - Any differences identified are corrected, bringing the logical interconnect back to a consistent - state. Changes are asynchronously applied to all managed interconnects. Note that if the changes detected - involve differences in the interconnect map between the logical interconnect group and the logical interconnect, - the process of bringing the logical interconnect back to a consistent state might involve automatically removing + Any differences identified are corrected, bringing the logical interconnect back to a + consistent state. Changes are asynchronously applied to all managed interconnects. Note + that if the changes detected involve differences in the interconnect map between the + logical interconnect group and the logical interconnect, the process of bringing the + logical interconnect back to a consistent state might involve automatically removing existing interconnects from management and/or adding new interconnects for management. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect. @@ -158,10 +159,10 @@ def update_ethernet_settings(self, configuration, force=False, timeout=-1): Args: configuration: Ethernet interconnect settings. - force: If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + force: If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect. @@ -176,10 +177,10 @@ def update_internal_networks(self, network_uri_list, force=False, timeout=-1): Args: network_uri_list: List of Ethernet network uris. - force: If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + force: If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect. @@ -204,15 +205,15 @@ def get_internal_vlans(self): @ensure_resource_client def update_settings(self, settings, force=False, timeout=-1): """ - Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously - applied to all managed interconnects. - (This method is not available from API version 600 onwards) + Updates interconnect settings on the logical interconnect. Changes to interconnect + settings are asynchronously applied to all managed interconnects. (This method is + not available from API version 600 onwards) Args: settings: Interconnect settings - force: If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + force: If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. + timeout: Timeout in seconds. Wait for task completion by default. The timeout + does not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect @@ -220,7 +221,8 @@ def update_settings(self, settings, force=False, timeout=-1): data = settings.copy() if 'ethernetSettings' in data: - ethernet_default_values = self._get_default_values(self.SETTINGS_ETHERNET_DEFAULT_VALUES) + ethernet_default_values = self._get_default_values\ + (self.SETTINGS_ETHERNET_DEFAULT_VALUES) data['ethernetSettings'] = merge_resources(data['ethernetSettings'], ethernet_default_values) @@ -233,11 +235,12 @@ def update_settings(self, settings, force=False, timeout=-1): @ensure_resource_client def update_configuration(self, timeout=-1): """ - Asynchronously applies or re-applies the logical interconnect configuration to all managed interconnects. + Asynchronously applies or re-applies the logical interconnect configuration to all managed + interconnects. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect. @@ -259,8 +262,8 @@ def get_snmp_configuration(self): @ensure_resource_client def update_snmp_configuration(self, configuration, timeout=-1): """ - Updates the SNMP configuration of a logical interconnect. Changes to the SNMP configuration are asynchronously - applied to all managed interconnects. + Updates the SNMP configuration of a logical interconnect. Changes to the SNMP + configuration are asynchronously applied to all managed interconnects. Args: configuration: snmp configuration. @@ -292,9 +295,10 @@ def get_unassigned_ports(self): @ensure_resource_client def get_unassigned_uplink_ports(self): """ - Gets a collection of uplink ports from the member interconnects which are eligible for assignment to an - analyzer port. To be eligible, a port must be a valid uplink, must not be a member of an existing uplink set, - and must not currently be used for stacking. + Gets a collection of uplink ports from the member interconnects which are eligible + for assignment to an analyzer port. To be eligible, a port must be a valid uplink, + must not be a member of an existing uplink set, and must not currently be used for + stacking. Returns: dict: Collection of uplink ports. @@ -341,15 +345,17 @@ def get_firmware(self): Returns: dict: LIFirmware. """ - firmware_uri = self._helper.build_subresource_uri(self.data["uri"], subresource_path=self.FIRMWARE_PATH) + firmware_uri = self._helper.build_subresource_uri(self.data["uri"], subresource_path=\ + self.FIRMWARE_PATH) return self._helper.do_get(firmware_uri) @ensure_resource_client def install_firmware(self, firmware_information): """ - Installs firmware to a logical interconnect. The three operations that are supported for the firmware - update are Stage (uploads firmware to the interconnect), Activate (installs firmware on the interconnect), - and Update (which does a Stage and Activate in a sequential manner). + Installs firmware to a logical interconnect. The three operations that are supported + for the firmware update are Stage (uploads firmware to the interconnect), Activate + (installs firmware on the interconnect), and Update (which does a Stage and Activate + in a sequential manner). Args: firmware_information: Options to install firmware to a logical interconnect. @@ -357,20 +363,23 @@ def install_firmware(self, firmware_information): Returns: dict """ - firmware_uri = self._helper.build_subresource_uri(self.data["uri"], subresource_path=self.FIRMWARE_PATH) + firmware_uri = self._helper.build_subresource_uri(self.data["uri"], subresource_path=\ + self.FIRMWARE_PATH) return self._helper.update(firmware_information, firmware_uri) @ensure_resource_client def get_forwarding_information_base(self, filter=''): """ - Gets the forwarding information base data for a logical interconnect. A maximum of 100 entries is returned. + Gets the forwarding information base data for a logical interconnect. A maximum of 10 + 0 entries is returned. Optional filtering criteria might be specified. Args: filter (list or str): - Filtering criteria may be specified using supported attributes: interconnectUri, macAddress, - internalVlan, externalVlan, and supported relation = (Equals). macAddress is 12 hexadecimal digits with - a colon between each pair of digits (upper case or lower case). + Filtering criteria may be specified using supported attributes: interconnectUri, + macAddress, internalVlan, externalVlan, and supported relation = (Equals). + macAddress is 12 hexadecimal digits with a colon between each pair of digits + (upper case or lower case). The default is no filter; all resources are returned. Returns: @@ -386,7 +395,8 @@ def create_forwarding_information_base(self, timeout=-1): Args: timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in + Timeout in seconds. Wait for task completion by default. + The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Interconnect Forwarding Information Base DataInfo. @@ -414,8 +424,8 @@ def update_qos_aggregated_configuration(self, qos_configuration, timeout=-1): qos_configuration: QOS configuration. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView, just stops waiting for its completion. Returns: dict: Logical Interconnect. @@ -444,15 +454,16 @@ def get_telemetry_configuration(self): @ensure_resource_client def update_telemetry_configurations(self, configuration, timeout=-1): """ - Updates the telemetry configuration of a logical interconnect. Changes to the telemetry configuration are + Updates the telemetry configuration of a logical interconnect. Changes to the telemetry + configuration are asynchronously applied to all managed interconnects. Args: configuration: The telemetry configuration for the logical interconnect. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stops waiting for its completion. Returns: dict: The Logical Interconnect. @@ -492,10 +503,10 @@ def update_igmp_settings(self, configuration, force=False, timeout=-1): Args: configuration: Igmp interconnect settings. - force: If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + force: If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect. @@ -506,12 +517,13 @@ def update_igmp_settings(self, configuration, force=False, timeout=-1): @ensure_resource_client def bulk_inconsistency_validate(self, validation_request, timeout=-1): """ - Validates the bulk update from group operation and gets the consolidated inconsistency report + Validates the bulk update from group operation and gets the consolidated inconsistency + report Args: timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stops waiting for its completion. Returns: Consolidated inconsistency report. """ @@ -525,10 +537,10 @@ def update_port_flap_settings(self, configuration, force=False, timeout=-1): Args: configuration: Port flap settings. - force: If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + force: If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical Interconnect. diff --git a/hpeOneView/resources/networking/logical_switch_groups.py b/hpeOneView/resources/networking/logical_switch_groups.py index 62e049d54..68cc8d962 100644 --- a/hpeOneView/resources/networking/logical_switch_groups.py +++ b/hpeOneView/resources/networking/logical_switch_groups.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ResourcePatchMixin + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin - class LogicalSwitchGroups(ResourcePatchMixin, Resource): """ diff --git a/hpeOneView/resources/networking/logical_switches.py b/hpeOneView/resources/networking/logical_switches.py index c20d4813f..1d74c14ec 100755 --- a/hpeOneView/resources/networking/logical_switches.py +++ b/hpeOneView/resources/networking/logical_switches.py @@ -21,10 +21,10 @@ from __future__ import absolute_import from future import standard_library -standard_library.install_aliases() +from hpeOneView.resources.resource import ResourceClient +standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient class LogicalSwitches(object): @@ -84,8 +84,8 @@ def delete(self, resource, force=False, timeout=-1): If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates if the resource was successfully deleted. @@ -112,8 +112,8 @@ def create(self, resource, timeout=-1): Args: resource (dict): Object to create. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView, just stop waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stop waiting for its completion. Returns: dict: Created resource. @@ -128,8 +128,8 @@ def update(self, resource, timeout=-1): Args: resource (dict): Object to update. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView, just stop waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stop waiting for its completion. Returns: dict: Updated resource. @@ -161,8 +161,8 @@ def refresh(self, id_or_uri, timeout=-1): id_or_uri: Can be either the Logical Switch ID or URI timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView, just stop waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stop waiting for its completion. Returns: dict: The Logical Switch @@ -181,8 +181,8 @@ def patch(self, id_or_uri, operation, path, value, timeout=-1): operation: Patch operation path: Path value: Value - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated resource. @@ -191,5 +191,5 @@ def patch(self, id_or_uri, operation, path, value, timeout=-1): def __set_default_values(self, resource): if 'logicalSwitch' in resource: - resource['logicalSwitch'] = self._client.merge_default_values(resource['logicalSwitch'], - self.SWITCH_DEFAULT_VALUES) + resource['logicalSwitch'] = self._client.merge_default_values(\ + resource['logicalSwitch'], self.SWITCH_DEFAULT_VALUES) diff --git a/hpeOneView/resources/networking/network_sets.py b/hpeOneView/resources/networking/network_sets.py index 171a646fa..ee547e848 100644 --- a/hpeOneView/resources/networking/network_sets.py +++ b/hpeOneView/resources/networking/network_sets.py @@ -19,12 +19,12 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource, ResourceHelper, ResourcePatchMixin + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourceHelper, ResourcePatchMixin - class NetworkSets(Resource, ResourcePatchMixin): """ diff --git a/hpeOneView/resources/networking/sas_interconnect_types.py b/hpeOneView/resources/networking/sas_interconnect_types.py index 03af6067a..1dd3386a6 100644 --- a/hpeOneView/resources/networking/sas_interconnect_types.py +++ b/hpeOneView/resources/networking/sas_interconnect_types.py @@ -19,13 +19,13 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import Resource, unavailable_method from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, unavailable_method - class SasInterconnectTypes(Resource): """ diff --git a/hpeOneView/resources/networking/sas_interconnects.py b/hpeOneView/resources/networking/sas_interconnects.py index 79b16fbb3..d2ebe9acf 100644 --- a/hpeOneView/resources/networking/sas_interconnects.py +++ b/hpeOneView/resources/networking/sas_interconnects.py @@ -19,13 +19,13 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import Resource, ResourcePatchMixin, unavailable_method from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin, unavailable_method - class SasInterconnects(ResourcePatchMixin, Resource): """ @@ -46,33 +46,33 @@ def get_all(self, start=0, count=-1, fields='', filter='', query='', sort='', vi Args: start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default + is 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceeds the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of + start and count exceeds the total number of items. fields: Specifies which fields should be returned in the result set. filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. + A general filter/query string to narrow the list of items returned. The default + is no filter; all resources are returned. query: - A general query string to narrow the list of resources returned. The default is no query (all - resources are returned). + A general query string to narrow the list of resources returned. The default is no + query (all resources are returned). sort: - The sort order of the returned data set. By default, the sort order is based on create time, with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time, with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection, by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - collections of resources). + Returns a specific subset of the attributes of the resource or collection, by + specifying the name of a predefined view. The default view is expand (show all + attributes of the resource and all elements of collections of resources). Returns: list: A list of SAS interconnects. """ - return self._helper.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view, - fields=fields) + return self._helper.get_all(start=start, count=count, filter=filter, query=query, \ + sort=sort, view=view, fields=fields) def refresh_state(self, configuration): """ diff --git a/hpeOneView/resources/networking/sas_logical_interconnect_groups.py b/hpeOneView/resources/networking/sas_logical_interconnect_groups.py index f577a5c6c..8cb57395e 100644 --- a/hpeOneView/resources/networking/sas_logical_interconnect_groups.py +++ b/hpeOneView/resources/networking/sas_logical_interconnect_groups.py @@ -19,13 +19,13 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class SasLogicalInterconnectGroups(Resource): """ diff --git a/hpeOneView/resources/networking/sas_logical_interconnects.py b/hpeOneView/resources/networking/sas_logical_interconnects.py index 49ace2af9..831de8acc 100644 --- a/hpeOneView/resources/networking/sas_logical_interconnects.py +++ b/hpeOneView/resources/networking/sas_logical_interconnects.py @@ -19,13 +19,12 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource, ensure_resource_client, unavailable_method from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ensure_resource_client, unavailable_method - class SasLogicalInterconnects(Resource): """ @@ -39,38 +38,38 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, fields='', filter='', query='', sort='', view=''): """ - Gets a list of SAS Logical Interconnects based on optional sorting and filtering and constrained by start and - count parameters. + Gets a list of SAS Logical Interconnects based on optional sorting and filtering and + constrained by start and count parameters. Args: start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default + is 0 - start with the first available item. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceeds the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of + start and count exceeds the total number of items. fields: Specifies which fields should be returned in the result set. filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. + A general filter/query string to narrow the list of items returned. The default is + no filter; all resources are returned. query: - A general query string to narrow the list of resources returned. The default is no query (all - resources are returned). + A general query string to narrow the list of resources returned. The default is no + query (all resources are returned). sort: - The sort order of the returned data set. By default, the sort order is based on create time, with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time, with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection, by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - collections of resources). + Returns a specific subset of the attributes of the resource or collection, by + specifying the name of a predefined view. The default view is expand (show all + attributes of the resource and all elements of collections of resources). Returns: list: A list of SAS logical interconnects. """ - return self._helper.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view, - fields=fields) + return self._helper.get_all(start=start, count=count, filter=filter, query=query, \ + sort=sort, view=view, fields=fields) @ensure_resource_client def update_firmware(self, firmware_information, force=False): @@ -79,8 +78,8 @@ def update_firmware(self, firmware_information, force=False): Args: firmware_information: Options to install firmware to a SAS Logical Interconnect. - force: If sets to true, the operation completes despite any problems with the network connectivy - or the erros on the resource itself. + force: If sets to true, the operation completes despite any problems with the network + connectivity or the erros on the resource itself. Returns: dict: SAS Logical Interconnect Firmware. """ @@ -103,13 +102,13 @@ def get_firmware(self): def update_compliance_all(self, information, timeout=-1): """ - Returns SAS Logical Interconnects to a consistent state. The current SAS Logical Interconnect state is - compared to the associated SAS Logical Interconnect group. + Returns SAS Logical Interconnects to a consistent state. The current SAS Logical + Interconnect state is compared to the associated SAS Logical Interconnect group. Args: information: Can be either the resource ID or URI. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: SAS Logical Interconnect. @@ -123,12 +122,12 @@ def update_compliance_all(self, information, timeout=-1): @ensure_resource_client def update_compliance(self, timeout=-1): """ - Returns a SAS Logical Interconnect to a consistent state. The current SAS Logical Interconnect state is - compared to the associated SAS Logical Interconnect group. + Returns a SAS Logical Interconnect to a consistent state. The current SAS Logical + Interconnect state is compared to the associated SAS Logical Interconnect group. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: SAS Logical Interconnect. @@ -142,9 +141,10 @@ def update_compliance(self, timeout=-1): @ensure_resource_client def replace_drive_enclosure(self, information): """ - When a drive enclosure has been physically replaced, initiate the replacement operation that enables the - new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires - specification of both the serial numbers of the original drive enclosure and its replacement to be provided. + When a drive enclosure has been physically replaced, initiate the replacement operation + that enables the new drive enclosure to take over as a replacement for the prior drive + enclosure. The request requires specification of both the serial numbers of the original + drive enclosure and its replacement to be provided. Args: information: Options to replace the drive enclosure. @@ -162,8 +162,8 @@ def replace_drive_enclosure(self, information): @ensure_resource_client def update_configuration(self): """ - Asynchronously applies or re-applies the SAS Logical Interconnect configuration to all managed interconnects - of a SAS Logical Interconnect. + Asynchronously applies or re-applies the SAS Logical Interconnect configuration to all + managed interconnects of a SAS Logical Interconnect. Returns: dict: SAS Logical Interconnect. diff --git a/hpeOneView/resources/networking/switch_types.py b/hpeOneView/resources/networking/switch_types.py index 440d8f064..b1a9a36c8 100644 --- a/hpeOneView/resources/networking/switch_types.py +++ b/hpeOneView/resources/networking/switch_types.py @@ -20,13 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class SwitchTypes(Resource): """ diff --git a/hpeOneView/resources/networking/switches.py b/hpeOneView/resources/networking/switches.py index 48979ff73..47d98bc58 100644 --- a/hpeOneView/resources/networking/switches.py +++ b/hpeOneView/resources/networking/switches.py @@ -20,14 +20,14 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient +from hpeOneView.resources.resource import merge_default_values + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient -from hpeOneView.resources.resource import merge_default_values - class Switches(object): """ @@ -107,8 +107,8 @@ def delete(self, resource, force=False, timeout=-1): If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates if the resource was successfully deleted. @@ -145,8 +145,8 @@ def get_by(self, field, value): def update_ports(self, ports, id_or_uri): """ - Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are - supported for update. + Updates the switch ports. Only the ports under the management of OneView and those that + are unlinked are supported for update. Note: This method is available for API version 300 or later. @@ -174,8 +174,8 @@ def patch(self, id_or_uri, operation, path, value, timeout=-1): operation: Patch operation path: Path value: Value - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated resource. diff --git a/hpeOneView/resources/networking/uplink_sets.py b/hpeOneView/resources/networking/uplink_sets.py index 5309092bc..4e5d9f6e7 100755 --- a/hpeOneView/resources/networking/uplink_sets.py +++ b/hpeOneView/resources/networking/uplink_sets.py @@ -20,16 +20,15 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ensure_resource_client +from hpeOneView.resources.networking.ethernet_networks import EthernetNetworks +from hpeOneView.exceptions import HPEOneViewResourceNotFound + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ensure_resource_client -from hpeOneView.resources.networking.ethernet_networks import EthernetNetworks -from hpeOneView.exceptions import HPEOneViewResourceNotFound -from builtins import isinstance - class UplinkSets(Resource): """ @@ -113,19 +112,20 @@ def __set_ethernet_uris(self, ethernet_names, operation="add"): associated_enets = self.data.get('networkUris', []) ethernet_uris = [] - for i, enet in enumerate(ethernet_names): + for _, enet in enumerate(ethernet_names): enet_exists = self._ethernet_networks.get_by_name(enet) if enet_exists: ethernet_uris.append(enet_exists.data['uri']) else: - raise HPEOneViewResourceNotFound("Ethernet: {} does not exist".foramt(enet)) + raise HPEOneViewResourceNotFound("Ethernet: {} does not exist".format(enet)) if operation == "remove": enets_to_update = sorted(list(set(associated_enets) - set(ethernet_uris))) elif operation == "add": enets_to_update = sorted(list(set(associated_enets).union(set(ethernet_uris)))) else: - raise ValueError("Value {} is not supported as operation. The supported values are: ['add', 'remove']") + raise ValueError("Value {} is not supported as operation. The supported values are:\ + ['add', 'remove']") if set(enets_to_update) != set(associated_enets): updated_network = {'networkUris': enets_to_update} diff --git a/hpeOneView/resources/resource.py b/hpeOneView/resources/resource.py index deeb962c4..c2b30d4f1 100755 --- a/hpeOneView/resources/resource.py +++ b/hpeOneView/resources/resource.py @@ -15,6 +15,12 @@ # limitations under the License. ### +import logging +import os +from copy import deepcopy +from urllib.parse import quote +from functools import partial + from __future__ import absolute_import from __future__ import division from __future__ import print_function @@ -25,12 +31,6 @@ standard_library.install_aliases() -import logging -import os -from copy import deepcopy -from urllib.parse import quote -from functools import partial - from hpeOneView.resources.task_monitor import TaskMonitor from hpeOneView import exceptions @@ -146,10 +146,10 @@ def get_all(self, start=0, count=-1, filter='', sort=''): start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items (default). - filter (list or str): A general filter/query string to narrow the list of items returned. The default is no - filter; all resources are returned. - sort: The sort order of the returned data set. By default, the sort order is based on create time with the - oldest entry first. + filter (list or str): A general filter/query string to narrow the list of items + returned. The default is no filter; all resources are returned. + sort: The sort order of the returned data set. By default, the sort order is based on + create time with the oldest entry first. Returns: list: A list of items matching the specified filter. @@ -163,8 +163,8 @@ def create(self, data=None, uri=None, timeout=-1, custom_headers=None, force=Fal Args: data: Additional fields can be passed to create the resource. uri: Resouce uri - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. Returns: Created resource. @@ -203,8 +203,8 @@ def update(self, data=None, timeout=-1, custom_headers=None, force=False): Args: data: Data to update the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows to add custom HTTP headers. force: Force the update operation. @@ -246,7 +246,8 @@ def get_by(self, field, value): # Workaround when the OneView filter does not work, it will filter again if "." not in field: # This filter only work for the first level - results = [item for item in results if str(item.get(field, "")).lower() == value.lower()] + results = [item for item in results if str(item.get(field, "")).lower() ==\ + value.lower()] return results def get_by_name(self, name): @@ -266,7 +267,8 @@ def get_by_name(self, name): new_resource = None return new_resource - # Sometimes get_all() with filters are not returning correct values, so added this method to overcome that issue + # Sometimes get_all() with filters are not returning correct values, so added this method to + # overcome that issue def get_by_field(self, field, value): """Retrieves a resource by its field. @@ -368,8 +370,9 @@ def __init__(self, base_uri, connection, task_monitor): self._connection = connection self._task_monitor = task_monitor - def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', uri=None, scope_uris='', custom_headers=None, - name_prefix='', category=[], childLimit=0, topCount=0,): + def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', \ + uri=None, scope_uris='', custom_headers=None, name_prefix='', category=[], \ + childLimit=0, topCount=0,): """Gets all items according with the given arguments. @@ -377,16 +380,17 @@ def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fiel start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items (default). - filter (list or str): A general filter/query string to narrow the list of items returned. The default is no - filter; all resources are returned. - query: A single query parameter can do what would take multiple parameters or multiple GET requests using - filter. Use query for more complex queries. NOTE: This parameter is experimental for OneView 2.0. - sort: The sort order of the returned data set. By default, the sort order is based on create time with the - oldest entry first. + filter (list or str): A general filter/query string to narrow the list of items + returned. The default is no filter; all resources are returned. + query: A single query parameter can do what would take multiple parameters or multiple + GET requests using filter. Use query for more complex queries. NOTE: This parameter is + experimental for OneView 2.0. + sort: The sort order of the returned data set. By default, the sort order is based on + create time with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - the collections or resources). + Returns a specific subset of the attributes of the resource or collection by + specifying the name of a predefined view. The default view is expand (show all attributes + of the resource and all elements of the collections or resources). fields: Name of the fields. uri: @@ -428,11 +432,11 @@ def delete_all(self, filter, force=False, timeout=-1): filter: A general filter/query string to narrow the list of items deleted. force: - If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. + If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates if the resources were successfully deleted. @@ -448,8 +452,8 @@ def create(self, data=None, uri=None, timeout=-1, custom_headers=None, force=Fal Args: data: Additional fields can be passed to create the resource. uri: Resouce uri - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. Returns: Created resource. @@ -495,7 +499,8 @@ def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=Non uri: Resource uri force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows to add custom HTTP headers. @@ -518,7 +523,8 @@ def update_with_zero_body(self, uri, timeout=-1, custom_headers=None): Args: uri: Allows to use a different URI other than resource URI timeout: Timeout in seconds. Wait for task completion by default. - The timeout does not abort the operation in OneView; it just stops waiting for its completion. + The timeout does not abort the operation in OneView; it just stops waiting for its + completion. custom_headers: Allows to set custom HTTP headers. Returns: @@ -535,7 +541,8 @@ def create_report(self, uri, timeout=-1): Args: uri: URI timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: @@ -580,19 +587,21 @@ def get_collection(self, uri=None, filter='', path=''): return self.get_members(response) - def build_query_uri(self, uri=None, start=0, count=-1, filter='', query='', sort='', view='', fields='', scope_uris='', - name_prefix='', category=[], childLimit=0, topCount=0): + def build_query_uri(self, uri=None, start=0, count=-1, filter='', query='', sort='', view='',\ + fields='', scope_uris='', name_prefix='', category=[], childLimit=0, topCount=0): """Builds the URI from given parameters. - More than one request can be send to get the items, regardless the query parameter 'count', because the actual - number of items in the response might differ from the requested count. Some types of resource have a limited - number of items returned on each call. For those resources, additional calls are made to the API to retrieve - any other items matching the given filter. The actual number of items can also differ from the requested call + More than one request can be send to get the items, regardless the query parameter 'count', + because the actual number of items in the response might differ from the requested count. + Some types of resource have a limited number of items returned on each call. For those + resources, additional calls are made to the API to retrieve any other items matching the + given filter. The actual number of items can also differ from the requested call if the requested number of items would take too long. The use of optional parameters for OneView 2.0 is described at: - http://h17007.www1.hpe.com/docs/enterprise/servers/oneview2.0/cic-api/en/api-docs/current/index.html + http://h17007.www1.hpe.com/docs/enterprise/servers/oneview2.0/cic-api/en/api-docs/current + /index.html Note: Single quote - "'" - inside a query parameter is not supported by OneView API. @@ -601,15 +610,16 @@ def build_query_uri(self, uri=None, start=0, count=-1, filter='', query='', sort start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items (default). - filter (list or str): A general filter/query string to narrow the list of items returned. The default is no - filter; all resources are returned. - query: A single query parameter can do what would take multiple parameters or multiple GET requests using - filter. Use query for more complex queries. NOTE: This parameter is experimental for OneView 2.0. - sort: The sort order of the returned data set. By default, the sort order is based on create time with the - oldest entry first. - view: Returns a specific subset of the attributes of the resource or collection by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - the collections or resources). + filter (list or str): A general filter/query string to narrow the list of items + returned. The default is no filter; all resources are returned. + query: A single query parameter can do what would take multiple parameters or multiple + GET requests using filter. Use query for more complex queries. NOTE: This parameter is + experimental for OneView 2.0. + sort: The sort order of the returned data set. By default, the sort order is based on + create time with the oldest entry first. + view: Returns a specific subset of the attributes of the resource or collection by + specifying the name of a predefined view. The default view is expand (show all attributes + of the resource and all elements of the collections or resources). fields: Name of the fields. uri: A specific URI (optional) scope_uris: An expression to restrict the resources returned according to the scopes to @@ -657,8 +667,8 @@ def build_query_uri(self, uri=None, start=0, count=-1, filter='', query='', sort symbol = '?' if '?' not in path else '&' - uri = "{0}{1}start={2}&count={3}{4}{5}{6}{7}{8}{9}{10}{11}".format(path, symbol, start, count, filter, query, sort, - view, fields, scope_uris, name_prefix, categories) + uri = "{0}{1}start={2}&count={3}{4}{5}{6}{7}{8}{9}{10}{11}".format(path, symbol, start,\ + count, filter, query, sort, view, fields, scope_uris, name_prefix, categories) return uri def build_uri_with_query_string(self, kwargs, sufix_path='', uri=None): @@ -687,7 +697,8 @@ def build_uri(self, id_or_uri): else: return self._base_uri + "/" + id_or_uri - def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None, subresource_path=''): + def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None,\ + subresource_path=''): """Helps to build a URI with resource path and its sub resource path. Args: @@ -706,7 +717,8 @@ def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=N resource_uri = self.build_uri(resource_id_or_uri) - uri = "{}/{}/{}".format(resource_uri, subresource_path, str(subresource_id_or_uri or '')) + uri = "{}/{}/{}".format(resource_uri, subresource_path, str(subresource_id_or_uri or\ + '')) uri = uri.replace("//", "/") if uri.endswith("/"): @@ -766,7 +778,8 @@ def do_requests_to_getall(self, uri, requested_count, custom_headers=None): members = self.get_members(response) items += members - logger.debug("Response getAll: nextPageUri = {0}, members list length: {1}".format(uri, str(len(members)))) + logger.debug("Response getAll: nextPageUri = {0}, members list length: {1}".format(uri,\ + str(len(members)))) uri = self.get_next_page(response, items, requested_count) logger.debug('Total # of members found = {0}'.format(str(len(items)))) @@ -864,8 +877,8 @@ def patch(self, operation, path, value, custom_headers=None, timeout=-1): operation: Patch operation path: Path value: Value - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows to add custom http headers. Returns: @@ -887,8 +900,8 @@ def patch_request(self, uri, body, custom_headers=None, timeout=-1): Args: body (list): Patch request body - timeout (int): Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout (int): Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. custom_headers (dict): Allows to add custom http headers. Returns: @@ -918,8 +931,8 @@ def upload(self, file_path, uri=None, timeout=-1): Args: file_path: File to upload. uri: A specific URI (optional). - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Response body. @@ -928,7 +941,8 @@ def upload(self, file_path, uri=None, timeout=-1): uri = self.URI upload_file_name = os.path.basename(file_path) - task, entity = self._connection.post_multipart_with_response_handling(uri, file_path, upload_file_name) + task, entity = self._connection.post_multipart_with_response_handling(uri, file_path,\ + upload_file_name) if not task: return entity @@ -958,53 +972,56 @@ def get_utilization(self, fields=None, filter=None, refresh=False, view=None): fields: Name of the supported metric(s) to be retrieved in the format METRIC[,METRIC]... If unspecified, all metrics supported are returned. - filter (list or str): Filters should be in the format FILTER_NAME=VALUE[,FILTER_NAME=VALUE]... + filter (list or str): Filters should be in the format FILTER_NAME=VALUE + [,FILTER_NAME=VALUE]... E.g.: 'startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z' startDate - Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is - determined by the endDate minus 24 hours. + Start date of requested starting time range in ISO 8601 format. If omitted, the + startDate is determined by the endDate minus 24 hours. endDate - End date of requested starting time range in ISO 8601 format. When omitted, the endDate includes - the latest data sample available. - - If an excessive number of samples would otherwise be returned, the results will be segmented. The - caller is responsible for comparing the returned sliceStartTime with the requested startTime in the - response. If the sliceStartTime is greater than the oldestSampleTime and the requested start time, - the caller is responsible for repeating the request with endTime set to sliceStartTime to obtain the - next segment. This process is repeated until the full data set is retrieved. - - If the resource has no data, the UtilizationData is still returned but will contain no samples and - sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set - appropriately (null if no data is available). If the filter does not happen to overlap the data - that a resource has, then the metric history service will return null sample values for any - missing samples. - - refresh: Specifies that if necessary, an additional request will be queued to obtain the most recent - utilization data from the iLO. The response will not include any refreshed data. To track the - availability of the newly collected data, monitor the TaskResource identified by the refreshTaskUri - property in the response. If null, no refresh was queued. - - view: Specifies the resolution interval length of the samples to be retrieved. This is reflected in the - resolution in the returned response. Utilization data is automatically purged to stay within storage - space constraints. Supported views are listed below: + End date of requested starting time range in ISO 8601 format. When omitted, the + endDate includes the latest data sample available. + + If an excessive number of samples would otherwise be returned, the results will be + segmented. The caller is responsible for comparing the returned sliceStartTime with the + startTime in the response. If the sliceStartTime is greater than the oldestSampleTime and + requested start time,the caller is responsible for repeating the request with endTime setto + sliceStartTime to obtain the next segment. This process is repeated until the full data + set is retrieved. + + If the resource has no data, the UtilizationData is still returned but will contain + no samples and sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime + will still be set appropriately (null if no data is available). If the filter does not + happen to overlap the data that a resource has, then the metric history service will return + null sample values for any missing samples. + + refresh: Specifies that if necessary, an additional request will be queued to obtain the + most recent utilization data from iLO. The response will not include any refreshed data. + To track the availability of the newly collected data, monitor the TaskResource identified + by the refreshTaskUri property in the response. If null, no refresh was queued. + + view: Specifies the resolution interval length of the samples to be retrieved. This is + reflected in the resolution in the returned response. Utilization data is automatically + purged to stay within storage space constraints. Supported views are listed below: native - Resolution of the samples returned will be one sample for each 5-minute time period. This is the - default view and matches the resolution of the data returned by the iLO. Samples at this resolution - are retained up to one year. + Resolution of the samples returned will be one sample for each 5-minute time + period. This is the default view and matches the resolution of the data returned by iLO. + Samples at this resolution are retained up to one year. hour - Resolution of the samples returned will be one sample for each 60-minute time period. Samples are - calculated by averaging the available 5-minute data samples that occurred within the hour, except - for PeakPower which is calculated by reporting the peak observed 5-minute sample value data during - the hour. Samples at this resolution are retained up to three years. + Resolution of the samples returned will be one sample for each 60-minute time + period. Samples are calculated by averaging the available 5-mins data samples that occurred + within the hour, except for PeakPower which is calculated by reporting the peak observed + 5-mins sample value data during the hour. Samples at this resolution are retained up to + three years. day - Resolution of the samples returned will be one sample for each 24-hour time period. One day is a - 24-hour period that starts at midnight GMT regardless of the time zone in which the appliance or - client is located. Samples are calculated by averaging the available 5-minute data samples that - occurred during the day, except for PeakPower which is calculated by reporting the peak observed - 5-minute sample value data during the day. Samples at this resolution are retained up to three - years. + Resolution of the samples returned will be one sample for each 24-hour time + period. One day is a 24-hour period that starts at midnight GMT regardless of the time in + which the appliance or client is located. Samples are calculated by averaging the available + 5-minute data samples that occurred during the day, except for PeakPower which is + calculated by reporting the peak observed 5-minute sample value data during the day. + Samples at this resolution are retained up to three years Returns: dict @@ -1049,8 +1066,8 @@ def create_with_zero_body(self, uri=None, timeout=-1, custom_headers=None): """Makes a POST request to create a resource when no request body is required. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. Returns: @@ -1070,7 +1087,8 @@ def update_with_zero_body(self, uri=None, timeout=-1, custom_headers=None): Args: uri: Allows to use a different URI other than resource URI timeout: Timeout in seconds. Wait for task completion by default. - The timeout does not abort the operation in OneView; it just stops waiting for its completion. + The timeout does not abort the operation in OneView; it just stops waiting for its + completion. custom_headers: Allows to set custom HTTP headers. Returns: @@ -1095,18 +1113,21 @@ def __init__(self, con, uri): self._uri = uri self._task_monitor = TaskMonitor(con) - def build_query_uri(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', uri=None, scope_uris=''): + def build_query_uri(self, start=0, count=-1, filter='', query='', sort='', view='', fields='',\ + uri=None, scope_uris=''): """ Builds the URI given the parameters. - More than one request can be send to get the items, regardless the query parameter 'count', because the actual - number of items in the response might differ from the requested count. Some types of resource have a limited - number of items returned on each call. For those resources, additional calls are made to the API to retrieve - any other items matching the given filter. The actual number of items can also differ from the requested call + More than one request can be send to get the items, regardless the query parameter 'count', + because the actual number of items in the response might differ from the requested count. + Some types of resource have a limited number of items returned on each call. For those + resources, additional calls are made to the API to retrieve any other items matching the + given filter. The actual number of items can also differ from the requested call if the requested number of items would take too long. The use of optional parameters for OneView 2.0 is described at: - http://h17007.www1.hpe.com/docs/enterprise/servers/oneview2.0/cic-api/en/api-docs/current/index.html + http://h17007.www1.hpe.com/docs/enterprise/servers/oneview2.0/cic-api/en/api-docs/current/ + index.html Note: Single quote - "'" - inside a query parameter is not supported by OneView API. @@ -1118,18 +1139,19 @@ def build_query_uri(self, start=0, count=-1, filter='', query='', sort='', view= count: The number of resources to return. A count of -1 requests all items (default). filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no - filter; all resources are returned. + A general filter/query string to narrow the list of items returned. The default is + no filter; all resources are returned. query: - A single query parameter can do what would take multiple parameters or multiple GET requests using - filter. Use query for more complex queries. NOTE: This parameter is experimental for OneView 2.0. + A single query parameter can do what would take multiple parameters or multiple GET + requests using filter. Use query for more complex queries. NOTE: This parameter is + experimental for OneView 2.0. sort: - The sort order of the returned data set. By default, the sort order is based on create time with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - the collections or resources). + Returns a specific subset of the attributes of the resource or collection by + specifying the name of a predefined view. The default view is expand (show all attributes + of the resource and all elements of the collections or resources). fields: Name of the fields. uri: @@ -1165,11 +1187,12 @@ def build_query_uri(self, start=0, count=-1, filter='', query='', sort='', view= symbol = '?' if '?' not in path else '&' - uri = "{0}{1}start={2}&count={3}{4}{5}{6}{7}{8}{9}".format(path, symbol, start, count, filter, query, sort, - view, fields, scope_uris) + uri = "{0}{1}start={2}&count={3}{4}{5}{6}{7}{8}{9}".format(path, symbol, start, count,\ + filter, query, sort, view, fields, scope_uris) return uri - def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', uri=None, scope_uris=''): + def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', \ + uri=None, scope_uris=''): """ Gets all items according with the given arguments. @@ -1180,18 +1203,19 @@ def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fiel count: The number of resources to return. A count of -1 requests all items (default). filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no - filter; all resources are returned. + A general filter/query string to narrow the list of items returned. The default is + no filter; all resources are returned. query: - A single query parameter can do what would take multiple parameters or multiple GET requests using - filter. Use query for more complex queries. NOTE: This parameter is experimental for OneView 2.0. + A single query parameter can do what would take multiple parameters or multiple GET + requests using filter. Use query for more complex queries. NOTE: This parameter is + experimental for OneView 2.0. sort: - The sort order of the returned data set. By default, the sort order is based on create time with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - the collections or resources). + Returns a specific subset of the attributes of the resource or collection by + specifying the name of a predefined view. The default view is expand (show all attributes + of the resource and all elements of the collections or resources). fields: Name of the fields. uri: @@ -1204,8 +1228,8 @@ def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fiel list: A list of items matching the specified filter. """ - uri = self.build_query_uri(start=start, count=count, filter=filter, - query=query, sort=sort, view=view, fields=fields, uri=uri, scope_uris=scope_uris) + uri = self.build_query_uri(start=start, count=count, filter=filter,\ + query=query, sort=sort, view=view, fields=fields, uri=uri, scope_uris=scope_uris) logger.debug('Getting all resources with uri: {0}'.format(uri)) @@ -1221,11 +1245,12 @@ def delete_all(self, filter, force=False, timeout=-1): filter: A general filter/query string to narrow the list of items deleted. force: - If set to true, the operation completes despite any problems with network connectivity or errors + If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates if the resources were successfully deleted. @@ -1325,8 +1350,8 @@ def update_with_zero_body(self, uri, timeout=-1, custom_headers=None): uri: Can be either the resource ID or the resource URI. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. @@ -1337,7 +1362,8 @@ def update_with_zero_body(self, uri, timeout=-1, custom_headers=None): return self.__do_put(uri, None, timeout, custom_headers) - def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=None, default_values={}): + def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=None,\ + default_values={}): """ Makes a PUT request to update a resource when a request body is required. @@ -1347,16 +1373,16 @@ def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=Non uri: Can be either the resource ID or the resource URI. force: - If set to true, the operation completes despite any problems with network connectivity or errors - on the resource itself. The default is false. + If set to true, the operation completes despite any problems with network + connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. default_values: - Dictionary with default values grouped by OneView API version. This dictionary will be be merged with - the resource dictionary only if the dictionary does not contain the keys. + Dictionary with default values grouped by OneView API version. This dictionary will + be be merged with the resource dictionary only if the dictionary does not contain the keys This argument is optional and the default value is an empty dictionary. Ex.: default_values = { @@ -1392,7 +1418,8 @@ def create_with_zero_body(self, uri=None, timeout=-1, custom_headers=None): uri: Can be either the resource ID or the resource URI. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. @@ -1417,13 +1444,13 @@ def create(self, resource, uri=None, timeout=-1, custom_headers=None, default_va uri: Can be either the resource ID or the resource URI. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set specific HTTP headers. default_values: - Dictionary with default values grouped by OneView API version. This dictionary will be be merged with - the resource dictionary only if the dictionary does not contain the keys. + Dictionary with default values grouped by OneView API version. This dictionary will + be be merged with the resource dictionary only if the dictionary does not contain the keys. This argument is optional and the default value is an empty dictionary. Ex.: default_values = { @@ -1458,8 +1485,8 @@ def upload(self, file_path, uri=None, timeout=-1): uri: A specific URI (optional). timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: Response body. @@ -1468,7 +1495,8 @@ def upload(self, file_path, uri=None, timeout=-1): uri = self._uri upload_file_name = os.path.basename(file_path) - task, entity = self._connection.post_multipart_with_response_handling(uri, file_path, upload_file_name) + task, entity = self._connection.post_multipart_with_response_handling(uri, file_path,\ + upload_file_name) if not task: return entity @@ -1486,8 +1514,8 @@ def patch(self, id_or_uri, operation, path, value, timeout=-1, custom_headers=No operation: Patch operation path: Path value: Value - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Updated resource. @@ -1508,8 +1536,8 @@ def patch_request(self, id_or_uri, body, timeout=-1, custom_headers=None): Args: id_or_uri: Can be either the resource ID or the resource URI. body: Patch request body - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Updated resource. @@ -1560,7 +1588,8 @@ def get_by(self, field, value, uri=None): # Workaround when the OneView filter does not work, it will filter again if "." not in field: # This filter only work for the first level - results = [item for item in results if str(item.get(field, '')).lower() == value.lower()] + results = [item for item in results if str(item.get(field, '')).lower() ==\ + value.lower()] return results @@ -1596,51 +1625,53 @@ def get_utilization(self, id_or_uri, fields=None, filter=None, refresh=False, vi E.g.: 'startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z' startDate - Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is - determined by the endDate minus 24 hours. + Start date of requested starting time range in ISO 8601 format. If omitted, the + startDate is determined by the endDate minus 24 hours. endDate - End date of requested starting time range in ISO 8601 format. When omitted, the endDate includes - the latest data sample available. - - If an excessive number of samples would otherwise be returned, the results will be segmented. The - caller is responsible for comparing the returned sliceStartTime with the requested startTime in the - response. If the sliceStartTime is greater than the oldestSampleTime and the requested start time, - the caller is responsible for repeating the request with endTime set to sliceStartTime to obtain the - next segment. This process is repeated until the full data set is retrieved. - - If the resource has no data, the UtilizationData is still returned but will contain no samples and - sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set - appropriately (null if no data is available). If the filter does not happen to overlap the data - that a resource has, then the metric history service will return null sample values for any - missing samples. + End date of requested starting time range in ISO 8601 format. When omitted, the + endDate includes the latest data sample available. + + If an excessive number of samples would otherwise be returned, the results will be + segmented. The caller is responsible for comparing the returned sliceStartTime with the + requested startTime in the response. If the sliceStartTime is greater than the + oldestSampleTime and the requested start time, the caller is responsible for repeating the + request with endTime set to sliceStartTime to obtain the next segment. This process is + repeated until the full data set is retrieved. + + If the resource has no data, the UtilizationData is still returned but will contain + no samples and sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime + will still be set appropriately (null if no data is available). If the filter does not + happen to overlap the data that a resource has, then the metric history service will return + null sample values for any missing samples. refresh: - Specifies that if necessary, an additional request will be queued to obtain the most recent - utilization data from the iLO. The response will not include any refreshed data. To track the - availability of the newly collected data, monitor the TaskResource identified by the refreshTaskUri - property in the response. If null, no refresh was queued. + Specifies that if necessary, an additional request will be queued to obtain the most + recent utilization data from the iLO. The response will not include any refreshed data. To + track the availability of the newly collected data, monitor the TaskResource identified by + the refreshTaskUri property in the response. If null, no refresh was queued. view: - Specifies the resolution interval length of the samples to be retrieved. This is reflected in the - resolution in the returned response. Utilization data is automatically purged to stay within storage - space constraints. Supported views are listed below: + Specifies the resolution interval length of the samples to be retrieved. This is + reflected in the resolution in the returned response. Utilization data is automatically + purged to stay within storage space constraints. Supported views are listed below: native - Resolution of the samples returned will be one sample for each 5-minute time period. This is the - default view and matches the resolution of the data returned by the iLO. Samples at this resolution - are retained up to one year. + Resolution of the samples returned will be one sample for each 5-minute time + period. This is the default view and matches the resolution of the data returned by iLO. + Samples at this resolution are retained up to one year. hour - Resolution of the samples returned will be one sample for each 60-minute time period. Samples are - calculated by averaging the available 5-minute data samples that occurred within the hour, except - for PeakPower which is calculated by reporting the peak observed 5-minute sample value data during - the hour. Samples at this resolution are retained up to three years. + Resolution of the samples returned will be one sample for each 60-minute time + period. Samples are calculated by averaging the available 5-minute data samples that + occurred within the hour, except for PeakPower which is calculated by reporting the peak + observed 5min sample value data during the hour. Samples at this resolution are retained + up to three years. day - Resolution of the samples returned will be one sample for each 24-hour time period. One day is a - 24-hour period that starts at midnight GMT regardless of the time zone in which the appliance or - client is located. Samples are calculated by averaging the available 5-minute data samples that - occurred during the day, except for PeakPower which is calculated by reporting the peak observed - 5-minute sample value data during the day. Samples at this resolution are retained up to three - years. + Resolution of the samples returned will be one sample for each 24-hour time + period. One day is a 24-hour period that starts at midnight GMT regardless of the time zone + in which the appliance or client is located. Samples are calculated by averaging the + available 5-minute data samples that occurred during the day, except for PeakPower which is + calculated by reporting the peak observed 5-minute sample value data during the day. + Samples at this resolution are retained up to three years. Returns: dict @@ -1677,8 +1708,8 @@ def create_report(self, uri, timeout=-1): Args: uri: URI timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: list: @@ -1704,7 +1735,8 @@ def build_uri(self, id_or_uri): else: return self._uri + "/" + id_or_uri - def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None, subresource_path=''): + def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None,\ + subresource_path=''): if subresource_id_or_uri and "/" in subresource_id_or_uri: return subresource_id_or_uri else: @@ -1713,7 +1745,8 @@ def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=N resource_uri = self.build_uri(resource_id_or_uri) - uri = "{}/{}/{}".format(resource_uri, subresource_path, str(subresource_id_or_uri or '')) + uri = "{}/{}/{}".format(resource_uri, subresource_path, str(subresource_id_or_uri or\ + '')) uri = uri.replace("//", "/") if uri.endswith("/"): @@ -1782,7 +1815,8 @@ def __do_requests_to_getall(self, uri, requested_count): members = self.__get_members(response) items += members - logger.debug("Response getAll: nextPageUri = {0}, members list length: {1}".format(uri, str(len(members)))) + logger.debug("Response getAll: nextPageUri = {0}, members list length: {1}".format(\ + uri, str(len(members)))) uri = self.__get_next_page(response, items, requested_count) logger.debug('Total # of members found = {0}'.format(str(len(items)))) @@ -1830,12 +1864,13 @@ def merge_resources(resource1, resource2): def merge_default_values(resource_list, default_values): """ - Generate a new list where each item of original resource_list will be merged with the default_values. + Generate a new list where each item of original resource_list will be merged with the + default_values. Args: resource_list: list with items to be merged - default_values: properties to be merged with each item list. If the item already contains some property - the original value will be maintained. + default_values: properties to be merged with each item list. If the item already contains + some property the original value will be maintained. Returns: list: list containing each item merged with default_values diff --git a/hpeOneView/resources/search/index_resources.py b/hpeOneView/resources/search/index_resources.py index b470e5a54..e1ade9928 100644 --- a/hpeOneView/resources/search/index_resources.py +++ b/hpeOneView/resources/search/index_resources.py @@ -15,17 +15,19 @@ # limitations under the License. ### +from urllib.parse import quote + from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource -from urllib.parse import quote class IndexResources(Resource): @@ -39,11 +41,11 @@ class IndexResources(Resource): def __init__(self, connection, data=None): super(IndexResources, self).__init__(connection, data) - def get_all(self, category='', count=-1, fields='', filter='', padding=0, query='', reference_uri='', - sort='', start=0, user_query='', view=''): + def get_all(self, category='', count=-1, fields='', filter='', padding=0, query='',\ + reference_uri='', sort='', start=0, user_query='', view=''): """ - Gets a list of index resources based on optional sorting and filtering and is constrained by start - and count parameters. + Gets a list of index resources based on optional sorting and filtering and is + constrained by start and count parameters. Args: category (str or list): @@ -63,7 +65,8 @@ def get_all(self, category='', count=-1, fields='', filter='', padding=0, query= A general query string to narrow the list of resources returned. The default is no query - all resources are returned. reference_uri (str): - Load one page of resources, pagination is applied with reference to referenceUri provided. + Load one page of resources, pagination is applied with reference to referenceUri + provided. sort (str): The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. @@ -71,9 +74,11 @@ def get_all(self, category='', count=-1, fields='', filter='', padding=0, query= The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. user_query (str): - Free text Query string to search the resources. This will match the string in any field that is indexed. + Free text Query string to search the resources. This will match the string in any + field that is indexed. view (str): - Return a specific subset of the attributes of the resource or collection, by specifying the name of a predefined view. + Return a specific subset of the attributes of the resource or collection, by + specifying the name of a predefined view. Returns: list: A list of index resources. @@ -87,7 +92,8 @@ def get_all(self, category='', count=-1, fields='', filter='', padding=0, query= uri = uri.replace('?&', '?') - return self._helper.get_all(start=start, count=count, fields=fields, filter=filter, query=query, sort=sort, view=view, uri=uri) + return self._helper.get_all(start=start, count=count, fields=fields, filter=filter, query=\ + query, sort=sort, view=view, uri=uri) def get_by_uri(self, resource_uri): """ @@ -102,16 +108,18 @@ def get_by_uri(self, resource_uri): uri = "{0}{1}".format(self.URI, resource_uri) return super(IndexResources, self).get_by_uri(uri) - def get_aggregated(self, attribute, category, child_limit=6, filter='', query='', user_query='', attribute_query='', scope_query=''): + def get_aggregated(self, attribute, category, child_limit=6, filter='', query='', user_query=\ + '', attribute_query='', scope_query=''): """ - Gets a list of index resources based on optional sorting and filtering and is constrained by start - and count parameters. + Gets a list of index resources based on optional sorting and filtering and is constrained + by start and count parameters. Args: attribute (list or str): Attribute to pass in as query filter. category (str): - Category of resources. Multiple Category parameters are applied with an OR condition. + Category of resources. Multiple Category parameters are applied with an OR + condition. child_limit (int): Number of resources to be retrieved. Default=6. filter (list or str): @@ -124,8 +132,8 @@ def get_aggregated(self, attribute, category, child_limit=6, filter='', query='' Free text Query string to search the resources. This will match the string in any field that is indexed. attribute_query (list or str): - attributeQuery is used along with query parameter to filter out the details by attributes. - One or more attributeQuery should be used. + attributeQuery is used along with query parameter to filter out the details by + attributes. One or more attributeQuery should be used. scope_query (str): ScopeQuery is used to filter the dashboard view by scope. ScopeQuery can be a single scope or a valid scope expression. diff --git a/hpeOneView/resources/search/labels.py b/hpeOneView/resources/search/labels.py index ac5e7fa31..bbeb109ae 100644 --- a/hpeOneView/resources/search/labels.py +++ b/hpeOneView/resources/search/labels.py @@ -20,27 +20,29 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource +from hpeOneView.resources.search.index_resources import IndexResources + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource -from hpeOneView.resources.search.index_resources import IndexResources - -category_list = ['connection-templates', 'drive-enclosures', 'ethernet-networks', 'enclosures', 'enclosure-groups', - 'fc-networks', 'fcoe-networks', 'firmware-bundles', 'hypervisor-cluster-profiles', - 'hypervisor-host-profiles', 'hypervisor-managers', 'interconnects', 'logical-enclosures', - 'logical-interconnect-groups', 'logical-interconnects', 'network-sets', 'os-deployment-plans', - 'sas-interconnects', 'sas-logical-interconnect-groups', 'sas-logical-interconnects', - 'sas-logical-jbods', 'scopes', 'server-hardware', 'server-profile-templates', 'server-profiles', - 'storage-pools', 'storage-volume-sets', 'storage-volume-templates', 'storage-volumes'] +CATEGORY_LIST = ['connection-templates', 'drive-enclosures', 'ethernet-networks', 'enclosures',\ + 'enclosure-groups', 'fc-networks', 'fcoe-networks', 'firmware-bundles',\ + 'hypervisor-cluster-profiles', 'hypervisor-host-profiles', 'hypervisor-managers',\ + 'interconnects', 'logical-enclosures', 'logical-interconnect-groups',\ + 'logical-interconnects', 'network-sets', 'os-deployment-plans',\ + 'sas-interconnects', 'sas-logical-interconnect-groups', 'sas-logical-\ + interconnects', 'sas-logical-jbods', 'scopes', 'server-hardware',\ + 'server-profile-templates', 'server-profiles', 'storage-pools',\ + 'storage-volume-sets', 'storage-volume-templates', 'storage-volumes'] def get_resources_associated_with_label(connection, label): index_resource = IndexResources(connection) query_string = "labels='{}'".format(label) - all_index_resources = index_resource.get_all(category=category_list, query=query_string) + all_index_resources = index_resource.get_all(category=CATEGORY_LIST, query=query_string) response = [dict_response['uri'] for dict_response in all_index_resources] return response @@ -99,22 +101,24 @@ def get_by_resource(self, resource_uri): uri = self.URI + self.RESOURCES_PATH + '/' + resource_uri return super(Labels, self).get_by_uri(uri) - def get_all(self, count=-1, sort='', start=0, view='', fields='', filter='', name_prefix='', category=[]): + def get_all(self, count=-1, sort='', start=0, view='', fields='', filter='', name_prefix='',\ + category=[]): """ Gets all items according with the given arguments. Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items (default). - sort: The sort order of the returned data set. By default, the sort order is based on create time with the - oldest entry first. + sort: The sort order of the returned data set. By default, the sort order is based on + create time with the oldest entry first. view: - Returns a specific subset of the attributes of the resource or collection by specifying the name of a - predefined view. The default view is expand (show all attributes of the resource and all elements of - the collections or resources). + Returns a specific subset of the attributes of the resource or collection by + specifying the name of a predefined view. The default view is expand (show all + attributes of the resource and all elements of the collections or resources). fields: Name of the fields. Returns: list: A list of items matching the specified filter. """ - return self._helper.get_all(count=count, sort=sort, start=start, view=view, fields=fields, filter=filter, name_prefix=name_prefix, category=category) + return self._helper.get_all(count=count, sort=sort, start=start, view=view, fields=fields,\ + filter=filter, name_prefix=name_prefix, category=category) diff --git a/hpeOneView/resources/security/certificate_authority.py b/hpeOneView/resources/security/certificate_authority.py index f5672b00a..001c62d57 100644 --- a/hpeOneView/resources/security/certificate_authority.py +++ b/hpeOneView/resources/security/certificate_authority.py @@ -20,12 +20,11 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class CertificateAuthority(Resource): """ @@ -39,13 +38,14 @@ def __init__(self, connection, data=None): def create(self, data=None, parent_task='', timeout=-1): """ - Imports an external CA root certificate or CA certificate chain into the appliance trust store. + Imports an external CA root certificate or CA certificate chain into the appliance trust + store. Same CA certificate will not be allowed to be imported into the appliance trust store. Args: data: Fields passed to create the resource. - parent_task: The parentTask can be passed only if auth header has either a valid trusted token - or a valid combined token consisting of a trusted token. + parent_task: The parentTask can be passed only if auth header has either a valid trusted + token or a valid combined token consisting of a trusted token. timeout: Timeout in seconds. Wait for task completion by default. Returns: @@ -64,7 +64,8 @@ def get_all(self, filter='', cert_details=True): Args: filter: Filter based on a specific value. Supported filter is filter=certType:INTERNAL - cert_details: If this is set to true the api returns all the CA certificates with full certificate details + cert_details: If this is set to true the api returns all the CA certificates with full + certificate details Returns: list: List of all CA Certificate. @@ -74,8 +75,8 @@ def get_all(self, filter='', cert_details=True): def get_crl(self): """ - Retrieves the contents of the CRL file maintained by the internal CA; in Base-64 encoded format, in the form - of a string. + Retrieves the contents of the CRL file maintained by the internal CA; in Base-64 encoded format, + in the form of a string. Returns: str: The Certificate Revocation List diff --git a/hpeOneView/resources/security/certificate_rabbitmq.py b/hpeOneView/resources/security/certificate_rabbitmq.py index 5c04970c1..746ab6596 100644 --- a/hpeOneView/resources/security/certificate_rabbitmq.py +++ b/hpeOneView/resources/security/certificate_rabbitmq.py @@ -20,13 +20,12 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import ResourceClient from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class CertificateRabbitMQ(object): URI = '/rest/certificates/client/rabbitmq' @@ -37,13 +36,14 @@ def __init__(self, con): def generate(self, information, timeout=-1): """ - Generates a self signed certificate or an internal CA signed certificate for RabbitMQ clients. + Generates a self signed certificate or an internal CA signed certificate for RabbitMQ + clients. Args: information (dict): Information to generate the certificate for RabbitMQ clients. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: RabbitMQ certificate generated diff --git a/hpeOneView/resources/security/certificates_server.py b/hpeOneView/resources/security/certificates_server.py index 29c9651c5..a7cf5e465 100644 --- a/hpeOneView/resources/security/certificates_server.py +++ b/hpeOneView/resources/security/certificates_server.py @@ -19,19 +19,20 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource +from hpeOneView.exceptions import HPEOneViewException + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource -from hpeOneView.exceptions import HPEOneViewException - class CertificatesServer(Resource): """ The Certificates Servers resource provides REST APIs for configuration of device or - server certificates for the appliance to establish SSL communication with other managed network entities. + server certificates for the appliance to establish SSL communication with other + managed network entities. Import, Update and Delete APIs are asynchronous and GET API is synchronous. @@ -50,8 +51,8 @@ def create(self, data=None, timeout=-1): Args: data: Fields passed to create the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Return: Created certificate resource. @@ -61,7 +62,8 @@ def create(self, data=None, timeout=-1): def get_remote(self, remote_address): """ - Retrieves the device or server certificate and certificate chain of the specified device or server. + Retrieves the device or server certificate and certificate chain of the specified device + or server. Args: remote_address: diff --git a/hpeOneView/resources/security/login_details.py b/hpeOneView/resources/security/login_details.py index 116d320b3..57ff77f73 100644 --- a/hpeOneView/resources/security/login_details.py +++ b/hpeOneView/resources/security/login_details.py @@ -19,13 +19,13 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import ResourceClient from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class LoginDetails(object): """ diff --git a/hpeOneView/resources/security/roles.py b/hpeOneView/resources/security/roles.py index 06207cc60..4258946d7 100644 --- a/hpeOneView/resources/security/roles.py +++ b/hpeOneView/resources/security/roles.py @@ -19,13 +19,12 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals - +from hpeOneView.resources.resource import ResourceClient from future import standard_library standard_library.install_aliases() from urllib.parse import quote -from hpeOneView.resources.resource import ResourceClient class Roles(object): diff --git a/hpeOneView/resources/security/users.py b/hpeOneView/resources/security/users.py index 20f563b14..5018f1594 100644 --- a/hpeOneView/resources/security/users.py +++ b/hpeOneView/resources/security/users.py @@ -15,19 +15,22 @@ # limitations under the License. ### +from urllib.parse import quote +from copy import deepcopy + from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import Resource +from hpeOneView.exceptions import HPEOneViewException + from future import standard_library -from urllib.parse import quote -from copy import deepcopy standard_library.install_aliases() -from hpeOneView.resources.resource import Resource -from hpeOneView.exceptions import HPEOneViewException class Users(Resource): @@ -44,7 +47,7 @@ def __init__(self, connection, data=None): 'type': 'UserAndRoles' } - def validate_user_name(self, user_name, timeout=-1): + def validate_user_name(self, user_name): """ Verifies if a userName is already in use. @@ -52,15 +55,15 @@ def validate_user_name(self, user_name, timeout=-1): user_name (str): The userName to be verified. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView, just stops waiting for its completion. Returns: True if user name is in use, False if it is not. """ uri = self.URI + '/validateLoginName/' + user_name return self.create(uri=uri) - def validate_full_name(self, full_name, timeout=-1): + def validate_full_name(self, full_name): """ Verifies if a fullName is already in use. @@ -68,8 +71,8 @@ def validate_full_name(self, full_name, timeout=-1): full_name (str): The fullName to be verified. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stops waiting for its completion. Returns: True if full name is in use, False if it is not. """ @@ -83,8 +86,8 @@ def change_password(self, resource): Args: resource (dict): Object to change password timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in - OneView, just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView, just stops waiting for its completion. """ uri = self._helper.build_uri('changePassword') @@ -172,8 +175,8 @@ def update(self, data=None, timeout=-1, custom_headers=None, force=False): Args: data (dict): Data to update the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows to add custom HTTP headers. force: Force the update operation. diff --git a/hpeOneView/resources/servers/connections.py b/hpeOneView/resources/servers/connections.py index 4d4a4a945..fc223482a 100644 --- a/hpeOneView/resources/servers/connections.py +++ b/hpeOneView/resources/servers/connections.py @@ -19,13 +19,13 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import ResourceClient from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient - class Connections(object): """ @@ -68,7 +68,8 @@ def get_all(self, start=0, count=-1, filter='', sort='', view='', fields=''): Returns: list: A list of connections. """ - return self._client.get_all(start, count, filter=filter, sort=sort, view=view, fields=fields) + return self._client.get_all(start, count, filter=filter, sort=sort, view=view,\ + fields=fields) def get_by(self, field, value): """ diff --git a/hpeOneView/resources/servers/enclosure_groups.py b/hpeOneView/resources/servers/enclosure_groups.py index 32605699a..8fa6a49b1 100755 --- a/hpeOneView/resources/servers/enclosure_groups.py +++ b/hpeOneView/resources/servers/enclosure_groups.py @@ -19,14 +19,13 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ensure_resource_client from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ensure_resource_client - class EnclosureGroups(Resource): """ diff --git a/hpeOneView/resources/servers/enclosures.py b/hpeOneView/resources/servers/enclosures.py index e0a49c7d7..95d228394 100644 --- a/hpeOneView/resources/servers/enclosures.py +++ b/hpeOneView/resources/servers/enclosures.py @@ -19,13 +19,14 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import -from future import standard_library - -standard_library.install_aliases() from hpeOneView.resources.resource import (Resource, ResourcePatchMixin, ResourceZeroBodyMixin, ResourceUtilizationMixin, ensure_resource_client) +from future import standard_library + +standard_library.install_aliases() + class Enclosures(ResourcePatchMixin, ResourceZeroBodyMixin, ResourceUtilizationMixin, Resource): @@ -40,8 +41,8 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''): """ - Gets a paginated collection of Enclosures. The collection is based on optional sorting and filtering, and - constrained by start and count parameters. + Gets a paginated collection of Enclosures. The collection is based on optional sorting and + filtering, and constrained by start and count parameters. Args: start: @@ -72,18 +73,18 @@ def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''): def add(self, information, timeout=-1): """ C7000: - Takes information about an enclosure (for example: IP address, username, password) and uses - it to claim/configure the enclosure and add its components to the appliance. + Takes information about an enclosure (for example: IP address, username, password) and + uses it to claim/configure the enclosure and add its components to the appliance. Synergy: - Adds a remote enclosure and all the enclosures linked to that enclosure by their frame link - modules. The remote enclosures' frame link modules must not be claimed by another appliance. - The IP used must be the frame link module's Link Local IPv6 address. + Adds a remote enclosure and all the enclosures linked to that enclosure by their frame + link modules. The remote enclosures' frame link modules must not be claimed by another + appliance. The IP used must be the frame link module's Link Local IPv6 address. Args: information: Enclosure information to add. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Enclosure. @@ -99,12 +100,12 @@ def remove(self, force=False): def update_configuration(self, timeout=-1): """ - Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps - that were performed as part of the enclosure add. + Reapplies the appliance's configuration on the enclosure. This includes running the same + configure steps that were performed as part of the enclosure add. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Enclosure @@ -115,8 +116,10 @@ def update_configuration(self, timeout=-1): def get_by_hostname(self, hostname): """Get enclosure by it's hostname""" def filter_by_hostname(hostname, enclosure): - is_primary_ip = ('activeOaPreferredIP' in enclosure and enclosure['activeOaPreferredIP'] == hostname) - is_standby_ip = ('standbyOaPreferredIP' in enclosure and enclosure['standbyOaPreferredIP'] == hostname) + is_primary_ip = ('activeOaPreferredIP' in enclosure and enclosure\ + ['activeOaPreferredIP'] == hostname) + is_standby_ip = ('standbyOaPreferredIP' in enclosure and enclosure\ + ['standbyOaPreferredIP'] == hostname) return is_primary_ip or is_standby_ip enclosures = self.get_all() @@ -132,7 +135,8 @@ def filter_by_hostname(hostname, enclosure): @ensure_resource_client def get_environmental_configuration(self): """ - Gets the settings that describe the environmental configuration (supported feature set, calibrated minimum & + Gets the settings that describe the environmental configuration (supported feature + set, calibrated minimum & maximum power, location & dimensions, ...) of the enclosure resource. Returns: @@ -148,8 +152,8 @@ def update_environmental_configuration(self, configuration, timeout=-1): Args: configuration: Configuration - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: Settings that describe the environmental configuration. @@ -160,15 +164,16 @@ def update_environmental_configuration(self, configuration, timeout=-1): @ensure_resource_client def refresh_state(self, configuration, timeout=-1): """ - Refreshes the enclosure along with all of its components, including interconnects and servers. Any new - hardware is added and any hardware that is no longer present within the enclosure is removed. The - configuration dict must have the "refreshState" field set to "Refreshing" and optionally - provide information to re-claim the enclosure (for example: IP address, user name, password, etc.). + Refreshes the enclosure along with all of its components, including interconnects and + servers. Any new hardware is added and any hardware that is no longer present within + the enclosure is removed. The configuration dict must have the "refreshState" field set + to "Refreshing" and optionally provide information to re-claim the enclosure (for example: + IP address, user name, password, etc.). Args: configuration: Configuration - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Enclosure @@ -179,8 +184,9 @@ def refresh_state(self, configuration, timeout=-1): @ensure_resource_client def get_sso(self, role): """ - Builds the SSO (Single Sign-On) URL parameters for the specified enclosure. This allows the user to - log in to the enclosure without providing credentials. This API is currently only supported by C7000 enclosures. + Builds the SSO (Single Sign-On) URL parameters for the specified enclosure. This allows the + user to log in to the enclosure without providing credentials. This API is currently only + supported by C7000 enclosures. Args: role: Role @@ -215,7 +221,8 @@ def generate_csr(self, csr_data, bay_number=None): @ensure_resource_client def get_csr(self, bay_number=None): """ - Get an enclosure's Certificate Signing Request (CSR) that was generated by previous POST to the same URI. + Get an enclosure's Certificate Signing Request (CSR) that was generated by previous POST + to the same URI. Args: bay_number: OA to retrieve the previously generated CSR. diff --git a/hpeOneView/resources/servers/id_pools.py b/hpeOneView/resources/servers/id_pools.py index dcdd089d6..5f81b880b 100644 --- a/hpeOneView/resources/servers/id_pools.py +++ b/hpeOneView/resources/servers/id_pools.py @@ -19,12 +19,11 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource, ResourceSchemaMixin from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourceSchemaMixin - class IdPools(Resource, ResourceSchemaMixin): """ @@ -86,13 +85,14 @@ def validate(self, information, pool_type, timeout=-1): Args: information (dict): - Information to update. Can result in system specified IDs or the system reserving user-specified IDs. + Information to update. Can result in system specified IDs or the system reserving + user-specified IDs. pool_type: Id pool type timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: A dict containing a list with IDs. @@ -108,13 +108,14 @@ def allocate(self, information, pool_type, timeout=-1): Args: information (dict): - Information to update. Can result in system specified IDs or the system reserving user-specified IDs. + Information to update. Can result in system specified IDs or the system reserving + user-specified IDs. pool_type: Id pool type timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: A dict containing a list with IDs. @@ -134,8 +135,8 @@ def collect(self, information, pool_type, timeout=-1): pool_type: Id pool type timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Collector containing list of collected IDs successfully collected. @@ -157,7 +158,8 @@ def get_check_range_availability(self, pool_type, ids_pools): Returns: dict: A dict containing a list with IDs. """ - uri = self._helper.build_uri(pool_type) + "/checkrangeavailability?idList=" + "&idList=".join(ids_pools) + uri = self._helper.build_uri(pool_type) + "/checkrangeavailability?idList=" + \ + "&idList=".join(ids_pools) return super(IdPools, self).get_by_uri(uri) def generate(self, pool_type): diff --git a/hpeOneView/resources/servers/id_pools_ipv4_ranges.py b/hpeOneView/resources/servers/id_pools_ipv4_ranges.py index bd930352a..36c372ecc 100644 --- a/hpeOneView/resources/servers/id_pools_ipv4_ranges.py +++ b/hpeOneView/resources/servers/id_pools_ipv4_ranges.py @@ -20,12 +20,11 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import Resource, ResourceSchemaMixin from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourceSchemaMixin - class IdPoolsIpv4Ranges(Resource, ResourceSchemaMixin): """ @@ -44,8 +43,8 @@ def enable(self, information, uri, timeout=-1): Args: information (dict): Information to update. uri: URI of range. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout + does not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated IPv4 range. @@ -59,8 +58,8 @@ def update_allocator(self, information, uri, timeout=-1): Args: information (dict): Information to update. id_or_uri: URI of range. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: The allocator returned contains the list of IDs successfully allocated. @@ -75,8 +74,8 @@ def update_collector(self, information, uri, timeout=-1): Args: information (dict): Information to update. id_or_uri: URI of range. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: The collector returned contains the list of IDs successfully collected. @@ -92,12 +91,12 @@ def get_allocated_fragments(self, uri, count=-1, start=0): uri: URI of range. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum + of start and count exceed the total number of items. start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default + is 0 - start with the first available item. Returns: list: A list with the allocated fragements. @@ -113,12 +112,12 @@ def get_free_fragments(self, uri, count=-1, start=0): uri: URI of range. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum + of start and count exceed the total number of items. start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default + is 0 - start with the first available item. Returns: list: A list with the free fragments. diff --git a/hpeOneView/resources/servers/id_pools_ipv4_subnets.py b/hpeOneView/resources/servers/id_pools_ipv4_subnets.py index cfffdae3c..1cb675270 100644 --- a/hpeOneView/resources/servers/id_pools_ipv4_subnets.py +++ b/hpeOneView/resources/servers/id_pools_ipv4_subnets.py @@ -19,12 +19,12 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals + +from hpeOneView.resources.resource import Resource from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource - class IdPoolsIpv4Subnets(Resource): """ @@ -43,12 +43,13 @@ def allocate(self, information, subnet_id, timeout=-1): The allocator returned contains the list of IDs successfully allocated. Args: information (dict): - Information to update. Can result in system specified IDs or the system reserving user-specified IDs. + Information to update. Can result in system specified IDs or the system reserving + user-specified IDs. subnet_id: IPv4 subnet id. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: A dict containing a list with IDs. """ @@ -64,8 +65,8 @@ def collect(self, information, subnet_id, timeout=-1): subnet_id: IPv4 subnet id timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: Collector containing list of collected IDs successfully collected. """ diff --git a/hpeOneView/resources/servers/id_pools_ranges.py b/hpeOneView/resources/servers/id_pools_ranges.py index 5a73ee6a1..56edb1fd2 100644 --- a/hpeOneView/resources/servers/id_pools_ranges.py +++ b/hpeOneView/resources/servers/id_pools_ranges.py @@ -19,12 +19,14 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import ResourceClient +from hpeOneView import HPEOneViewValueError + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient -from hpeOneView import HPEOneViewValueError class IdPoolsRanges(object): @@ -44,7 +46,8 @@ def __init__(self, type, con): elif type == 'vwwn': uri = '/rest/id-pools/vwwn/ranges' else: - raise HPEOneViewValueError("Invalid type: {0}, types allowed: vmac, vsn, vwwn, ".format(type)) + raise HPEOneViewValueError("Invalid type: {0}, types allowed: vmac, vsn, vwwn, "\ + .format(type)) self._client = ResourceClient(con, uri) @@ -54,8 +57,8 @@ def create(self, resource, timeout=-1): Args: resource (dict): Object to create - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Created range. @@ -66,8 +69,8 @@ def get(self, id_or_uri): """ Gets range. - Using the allocator and collector associated with the range, IDs may be allocated from or collected back to the - range. + Using the allocator and collector associated with the range, IDs may be allocated from or + collected back to the range. Args: id_or_uri: Can be either the range ID or URI. @@ -84,8 +87,8 @@ def enable(self, information, id_or_uri, timeout=-1): Args: information (dict): Information to update. id_or_uri: ID or URI of range. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Updated resource. @@ -106,8 +109,8 @@ def delete(self, resource, force=False, timeout=-1): If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates if the resource was successfully deleted. @@ -122,17 +125,18 @@ def get_allocated_fragments(self, id_or_uri, count=-1, start=0): id_or_uri: ID or URI of range. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum + of start and count exceed the total number of items. start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default is + 0 - start with the first available item. Returns: list: A list with the allocated fragements. """ - uri = self._client.build_uri(id_or_uri) + "/allocated-fragments?start={0}&count={1}".format(start, count) + uri = self._client.build_uri(id_or_uri) + "/allocated-fragments?start={0}&count={1}".\ + format(start, count) return self._client.get_collection(uri) def allocate(self, information, id_or_uri, timeout=-1): @@ -143,12 +147,13 @@ def allocate(self, information, id_or_uri, timeout=-1): Args: information (dict): - Information to update. Can result in system specified IDs or the system reserving user-specified IDs. + Information to update. Can result in system specified IDs or the system reserving + user-specified IDs. id_or_uri: ID or URI of vSN range. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not abort + the operation in OneView; it just stops waiting for its completion. Returns: dict: Allocator @@ -169,8 +174,8 @@ def collect(self, information, id_or_uri, timeout=-1): id_or_uri: ID or URI of range timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Collector containing list of collected IDs successfully collected. @@ -187,15 +192,16 @@ def get_free_fragments(self, id_or_uri, count=-1, start=0): id_or_uri: ID or URI of range. count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total number - of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of + start and count exceed the total number of items. start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default is + 0 - start with the first available item. Returns: list: A list with the free fragments. """ - uri = self._client.build_uri(id_or_uri) + "/free-fragments?start={0}&count={1}".format(start, count) + uri = self._client.build_uri(id_or_uri) + "/free-fragments?start={0}&count={1}".format\ + (start, count) return self._client.get_collection(uri) diff --git a/hpeOneView/resources/servers/logical_enclosures.py b/hpeOneView/resources/servers/logical_enclosures.py index 9d297b6f3..bed8b760a 100644 --- a/hpeOneView/resources/servers/logical_enclosures.py +++ b/hpeOneView/resources/servers/logical_enclosures.py @@ -19,13 +19,12 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource, ResourcePatchMixin, ensure_resource_client from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ResourcePatchMixin, ensure_resource_client - class LogicalEnclosures(ResourcePatchMixin, Resource): """ @@ -40,9 +39,10 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''): """ - Returns a list of logical enclosures matching the specified filter. A maximum of 40 logical enclosures are - returned to the caller. Additional calls can be made to retrieve any other logical enclosures matching the - filter. Valid filter parameters include attributes of a Logical Enclosure resource. + Returns a list of logical enclosures matching the specified filter. A maximum of 40 logical + enclosures are returned to the caller. Additional calls can be made to retrieve any other + logical enclosures matching the filter. Valid filter parameters include attributes of a + Logical Enclosure resource. Args: start: @@ -71,12 +71,13 @@ def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''): @ensure_resource_client def update_configuration(self, timeout=-1): """ - Reapplies the appliance's configuration on enclosures for the logical enclosure by ID or URI. This includes - running the same configure steps that were performed as part of the enclosure add. + Reapplies the appliance's configuration on enclosures for the logical enclosure by ID or + URI. This includes running the same configure steps that were performed as part of the + enclosure add. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical enclosure. @@ -101,13 +102,13 @@ def get_script(self): @ensure_resource_client def update_script(self, information, timeout=-1): """ - Updates the configuration script of the logical enclosure and on all enclosures in the logical enclosure with - the specified ID. + Updates the configuration script of the logical enclosure and on all enclosures in the + logical enclosure with the specified ID. Args: information: Updated script. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Return: Configuration script. @@ -118,14 +119,14 @@ def update_script(self, information, timeout=-1): @ensure_resource_client def generate_support_dump(self, information, timeout=-1): """ - Generates a support dump for the logical enclosure with the specified ID. A logical enclosure support dump - includes content for logical interconnects associated with that logical enclosure. By default, it also contains - appliance support dump content. + Generates a support dump for the logical enclosure with the specified ID. A logical + enclosure support dump includes content for logical interconnects associated with that + logical enclosure. By default, it also contains appliance support dump content. Args: information (dict): Information to generate support dump. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Support dump. @@ -136,12 +137,12 @@ def generate_support_dump(self, information, timeout=-1): @ensure_resource_client def update_from_group(self, data=None, timeout=-1): """ - Use this action to make a logical enclosure consistent with the enclosure group when the logical enclosure is - in the Inconsistent state. + Use this action to make a logical enclosure consistent with the enclosure group when + the logical enclosure is in the Inconsistent state. Args: - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Logical enclosure. diff --git a/hpeOneView/resources/servers/migratable_vc_domains.py b/hpeOneView/resources/servers/migratable_vc_domains.py index bbb95d7fc..d434850d4 100644 --- a/hpeOneView/resources/servers/migratable_vc_domains.py +++ b/hpeOneView/resources/servers/migratable_vc_domains.py @@ -19,11 +19,13 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import + +from hpeOneView.resources.resource import ResourceClient + from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import ResourceClient class MigratableVcDomains(object): @@ -42,37 +44,38 @@ def __init__(self, connection): self._client = ResourceClient(connection, self.URI) @staticmethod - def make_migration_information(oaIpAddress, oaUsername, oaPassword, vcmUsername, vcmPassword, - iloLicenseType='OneView', enclosureGroupUri=None): + def make_migration_information(oa_ip_address, oa_username, oa_password, vcm_username,\ + vcm_password, ilo_license_type='OneView', enclosure_group_uri=None): return { 'credentials': { - 'oaIpAddress': oaIpAddress, - 'oaUsername': oaUsername, - 'oaPassword': oaPassword, - 'vcmUsername': vcmUsername, - 'vcmPassword': vcmPassword, + 'oaIpAddress': oa_ip_address, + 'oaUsername': oa_username, + 'oaPassword': oa_password, + 'vcmUsername': vcm_username, + 'vcmPassword': vcm_password, 'type': 'EnclosureCredentials' }, - 'iloLicenseType': iloLicenseType, - 'enclosureGroupUri': enclosureGroupUri, + 'iloLicenseType': ilo_license_type, + 'enclosureGroupUri': enclosure_group_uri, 'type': 'migratable-vc-domains', 'category': 'migratable-vc-domains' } - def test_compatibility(self, migrationInformation, timeout=-1): + def test_compatibility(self, migration_information, timeout=-1): """ Creates a migration report for an enclosure with a Virtual Connect domain. Args: - migrationInformation: A dict specifying the enclosure, OA username, OA password, VCM username, and VCM - password among other things. Use make_migration_information to easily create this dict. - timeout: Timeout in seconds. Waits for task completion by default. The timeout does not abort the task in - OneView; just stops waiting for its completion. + migrationInformation: A dict specifying the enclosure, OA username, OA password, + VCM username, and VCM password among other things. Use make_migration_information + to easily create this dict. + timeout: Timeout in seconds. Waits for task completion by default. The timeout does + not abort the task in OneView; just stops waiting for its completion. Returns: dict: a migration report. """ - return self._client.create(migrationInformation, timeout=timeout) + return self._client.create(migration_information, timeout=timeout) def get_migration_report(self, id_or_uri): """ @@ -92,24 +95,24 @@ def migrate(self, id_or_uri, timeout=-1): Args: id_or_uri: ID or URI of the migration report. - timeout: Timeout in seconds. Waits for task completion by default. The timeout does not abort the task in - OneView; just stops waiting for its completion. + timeout: Timeout in seconds. Waits for task completion by default. The timeout does + not abort the task in OneView; just stops waiting for its completion. Returns: dict: a migration report. """ # create the special payload to tell the VC Migration Manager to migrate the VC domain - migrationInformation = { + migration_information = { 'migrationState': 'Migrated', 'type': 'migratable-vc-domains', 'category': 'migratable-vc-domains' } - # call build_uri manually since .update(...) doesn't do it and the URI is not to be included in the body when - # requesting a migration + # call build_uri manually since .update(...) doesn't do it and the URI is not to be + # included in the body when requesting a migration complete_uri = self._client.build_uri(id_or_uri) - return self._client.update(migrationInformation, uri=complete_uri, timeout=timeout) + return self._client.update(migration_information, uri=complete_uri, timeout=timeout) def delete(self, id_or_uri, timeout=-1): """ @@ -117,8 +120,8 @@ def delete(self, id_or_uri, timeout=-1): Args: id_or_uri: ID or URI of the migration report. - timeout: Timeout in seconds. Waits for task completion by default. The timeout does not abort the task in - OneView; just stops waiting for its completion. + timeout: Timeout in seconds. Waits for task completion by default. The timeout does + not abort the task in OneView; just stops waiting for its completion. Returns: bool: Indicates if the migration report was successfully deleted. """ diff --git a/hpeOneView/resources/servers/server_hardware.py b/hpeOneView/resources/servers/server_hardware.py index e888acad4..bc1ffc6a4 100644 --- a/hpeOneView/resources/servers/server_hardware.py +++ b/hpeOneView/resources/servers/server_hardware.py @@ -20,14 +20,13 @@ from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import (Resource, ResourceUtilizationMixin, + ResourcePatchMixin, ensure_resource_client) from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import (Resource, ResourceUtilizationMixin, - ResourcePatchMixin, ensure_resource_client) - class ServerHardware(ResourcePatchMixin, ResourceUtilizationMixin, Resource): """ @@ -43,16 +42,16 @@ def __init__(self, connection, data=None): def add(self, information, timeout=-1): """ - Adds a rack-mount server for management by the appliance. This API initiates the asynchronous addition of - supported server models. + Adds a rack-mount server for management by the appliance. This API initiates the + asynchronous addition of supported server models. Note: Servers in an enclosure are added by adding the enclosure resource. This is only supported on appliances that support rack-mounted servers. Args: information (dict): Object to create - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does + not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Created rack-mount server. @@ -61,8 +60,8 @@ def add(self, information, timeout=-1): def add_multiple_servers(self, information, timeout=-1): """ - Adds multiple rack-mount servers for management by the appliance. This API initiates the asynchronous addition of - supported server models. + Adds multiple rack-mount servers for management by the appliance. This API initiates the + asynchronous addition of supported server models. Note: Servers in an enclosure are added by adding the enclosure resource. This is only supported on appliances that support rack-mounted servers. @@ -71,8 +70,8 @@ def add_multiple_servers(self, information, timeout=-1): Args: information (dict): Objects to create - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Created rack-mount servers. @@ -90,8 +89,8 @@ def remove(self, force=False, timeout=-1): If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates whether the resource was successfully removed. @@ -112,8 +111,9 @@ def get_bios(self): @ensure_resource_client def get_environmental_configuration(self): """ - Gets the settings that describe the environmental configuration (supported feature set, calibrated minimum and - maximum power, location and dimensions, etc.) of the server hardware resource. + Gets the settings that describe the environmental configuration (supported feature + set, calibrated minimum and maximum power, location and dimensions, etc.) of the + server hardware resource. Returns: dict: Environmental configuration settings. @@ -128,8 +128,8 @@ def update_environmental_configuration(self, configuration, timeout=-1): Args: configuration (dict): Environmental configuration. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Environmental configuration settings. @@ -140,9 +140,9 @@ def update_environmental_configuration(self, configuration, timeout=-1): @ensure_resource_client def get_ilo_sso_url(self, ip=None): """ - Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is - unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials. - This is not supported on G7/iLO3 or earlier servers. + Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If + the server hardware is unsupported, the resulting URL will not use SSO and the iLO web + interface will prompt for credentials. This is not supported on G7/iLO3 or earlier servers. Args: ip: IP address or host name of the server's iLO management processor @@ -159,8 +159,9 @@ def get_ilo_sso_url(self, ip=None): def get_all_firmwares(self, filter='', start=0, count=-1, query='', sort=''): """ - Gets a list of firmware inventory across all servers. To filter the returned data, specify a filter - expression to select a particular server model, component name, and/or component firmware version. + Gets a list of firmware inventory across all servers. To filter the returned data, specify + a filter expression to select a particular server model, component name, and/or component + firmware version. Note: This method is available for API version 300 or later. @@ -177,8 +178,8 @@ def get_all_firmwares(self, filter='', start=0, count=-1, query='', sort=''): A general filter/query string to narrow the list of items returned. The default is no filter; all resources are returned. query: - A general query string to narrow the list of resources returned. The default is no query; all resources - are returned. + A general query string to narrow the list of resources returned. The default is + no query; all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. @@ -206,9 +207,11 @@ def get_firmware(self): @ensure_resource_client def get_java_remote_console_url(self, ip=None): """ - Generates a Single Sign-On (SSO) session for the iLO Java Applet console and returns the URL to launch it. - If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the iLO Java Applet - will prompt for credentials. This is not supported on G7/iLO3 or earlier servers. + Generates a Single Sign-On (SSO) session for the iLO Java Applet console and returns the + URL to launch it. + If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO + and the iLO Java Applet will prompt for credentials. This is not supported on G7/iLO3 or + earlier servers. Args: ip: IP address or host name of the server's iLO management processor @@ -226,13 +229,13 @@ def get_java_remote_console_url(self, ip=None): @ensure_resource_client def update_mp_firware_version(self, timeout=-1): """ - Updates the iLO firmware on a physical server to a minimum ILO firmware version required by OneView to - manage the server. + Updates the iLO firmware on a physical server to a minimum ILO firmware version required + by OneView to manage the server. Args: timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Resource """ @@ -246,8 +249,8 @@ def update_power_state(self, configuration, timeout=-1): Args: configuration (dict): Power state configuration. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Resource @@ -262,8 +265,8 @@ def refresh_state(self, configuration, timeout=-1): Args: configuration: Refresh state configuration. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: Resource @@ -274,10 +277,11 @@ def refresh_state(self, configuration, timeout=-1): @ensure_resource_client def get_remote_console_url(self, ip=None, consoleType=None): """ - Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application (IRC) and returns the - URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the - IRC application will prompt for credentials. Use of this URL requires a previous installation of the iLO IRC and - is supported only on Windows clients. + Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application + (IRC) and returns the URL to launch it. If the server hardware is unmanaged or unsupported, + the resulting URL will not use SSO and the IRC application will prompt for credentials. + Use of this URL requires a previous installation of the iLO IRC and is supported only on + Windows clients. Args: ip: IP address or host name of the server's iLO management processor @@ -299,8 +303,8 @@ def get_remote_console_url(self, ip=None, consoleType=None): @ensure_resource_client def get_physical_server_hardware(self): """ - Information describing an 'SDX' partition including a list of physical server blades represented by a server - hardware. Used with SDX enclosures only. + Information describing an 'SDX' partition including a list of physical server blades + represented by a server hardware. Used with SDX enclosures only. Returns: Resource @@ -311,8 +315,8 @@ def get_physical_server_hardware(self): @ensure_resource_client def get_local_storage(self, ip=None): """ - Gets the updated version 2 local storage resource for the server, including storage controllers, - drives, and volumes. + Gets the updated version 2 local storage resource for the server, including storage + controllers, drives, and volumes. Args: ip: IP address or host name of the server's iLO management processor diff --git a/hpeOneView/resources/servers/server_hardware_types.py b/hpeOneView/resources/servers/server_hardware_types.py index b05bde772..c0c0ce132 100644 --- a/hpeOneView/resources/servers/server_hardware_types.py +++ b/hpeOneView/resources/servers/server_hardware_types.py @@ -19,18 +19,17 @@ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource, ensure_resource_client from future import standard_library standard_library.install_aliases() -from hpeOneView.resources.resource import Resource, ensure_resource_client - - class ServerHardwareTypes(Resource): """ - The server hardware types resource is a representation/abstraction of a physical server managed by the appliance. + The server hardware types resource is a representation/abstraction of a physical server + managed by the appliance. It defines capabilities and settings that can be used in a server profile. """ @@ -46,8 +45,8 @@ def update(self, data, timeout=-1, force=False): Args: data (dict): Object to update. timeout: - Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. force: Flag to force the operation. Returns: dict: Updated server hardware type. diff --git a/hpeOneView/resources/servers/server_profile_templates.py b/hpeOneView/resources/servers/server_profile_templates.py index 0eec0f39d..dc5ccddd3 100644 --- a/hpeOneView/resources/servers/server_profile_templates.py +++ b/hpeOneView/resources/servers/server_profile_templates.py @@ -15,33 +15,35 @@ # limitations under the License. ### +from copy import deepcopy from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import +from hpeOneView.resources.resource import Resource, ResourcePatchMixin, ensure_resource_client + from future import standard_library standard_library.install_aliases() -from copy import deepcopy - -from hpeOneView.resources.resource import Resource, ResourcePatchMixin, ensure_resource_client class ServerProfileTemplate(Resource, ResourcePatchMixin): """ - The server profile template resource provides methods to create, retrieve, modify, and delete server - profile templates. + The server profile template resource provides methods to create, retrieve, modify, and delete + server profile templates. A server profile template serves as a structural reference when creating a server profile. - All of the configuration constructs of a server profile are present in the server profile template. - The server profile template serves as the initial and ongoing reference for the structure of a server profile. - The server profile template defines the centralized source for the configuration of firmware, connections, - local storage, SAN storage, boot, BIOS, profile affinity and hide unused flexNICs. + All of the configuration constructs of a server profile are present in the server profile + template. The server profile template serves as the initial and ongoing reference for the + structure of a server profile. The server profile template defines the centralized source for + the configuration of firmware, connections, local storage, SAN storage, boot, BIOS, profile + affinity and hide unused flexNICs. - After being created from a server profile template, the server profile continues to maintain an association to its - server profile template. Any drift in configuration consistency between the server profile template and server - profile(s) is monitored and made visible on both the server profile template and the associated server profile(s). + After being created from a server profile template, the server profile continues to maintain + an association to its server profile template. Any drift in configuration consistency between + the server profile template and server profile(s) is monitored and made visible on both the + server profile template and the associated server profile(s). """ @@ -66,30 +68,34 @@ def __init__(self, connection, data=None): def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''): """ - Gets a list of server profile templates based on optional sorting and filtering and is constrained by start and - count parameters. + Gets a list of server profile templates based on optional sorting and filtering and is + constrained by start and count parameters. Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. - count: The number of resources to return. Providing a -1 for the count parameter will restrict - the result set size to 64 server profile templates. The maximum number of profile templates - is restricted to 256, that is, if user requests more than 256, this will be internally limited to 256. - The actual number of items in the response might differ from the - requested count if the sum of start and count exceeds the total number of items, or if returning the - requested number of items would take too long. - filter (list or str): A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. Filters are supported for the name, description, affinity, macType, wwnType, - serialNumberType, status, serverHardwareTypeUri, enclosureGroupUri, and firmware.firmwareBaselineUri attributes. + count: The number of resources to return. Providing a -1 for the count parameter will + restrict the result set size to 64 server profile templates. The maximum number of + profile templates is restricted to 256, that is, if user requests more than 256, + this will be internally limited to 256. The actual number of items in the response + might differ from the requested count if the sum of start and count exceeds the + total number of items, or if returning the requested number of items would take too + long. + filter (list or str): A general filter/query string to narrow the list of items returned + The default is no filter; all resources are returned. Filters are supported for the name + description, affinity, macType, wwnType, serialNumberType, status, serverHardwareTypeUri + enclosureGroupUri, and firmware.firmwareBaselineUri attributes. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. - scope_uris: An expression to restrict the resources returned according to the scopes to which they are assigned. + scope_uris: An expression to restrict the resources returned according to the scopes to + which they are assigned. Returns: list: A list of server profile templates. """ - return self._helper.get_all(start=start, count=count, filter=filter, sort=sort, scope_uris=scope_uris) + return self._helper.get_all(start=start, count=count, filter=filter, sort=sort, scope_uris=\ + scope_uris) def create(self, data=None, uri=None, timeout=-1, force=True): """Makes a POST request to create a resource when a request body is required. @@ -97,8 +103,8 @@ def create(self, data=None, uri=None, timeout=-1, force=True): Args: data: Additional fields can be passed to create the resource. uri: Resouce uri - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. force: Flag to force the operation Returns: Created resource. @@ -122,8 +128,8 @@ def update(self, data=None, timeout=-1, force=True): Args: data: Data to update the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. force: Force the update operation. Returns: @@ -141,10 +147,11 @@ def update(self, data=None, timeout=-1, force=True): @ensure_resource_client def get_new_profile(self): """ - A profile object will be returned with the configuration based on this template. Specify the profile name and - server hardware to assign. If template has any fiber channel connection (which is specified as bootable) but no - boot target was defined, that connection will be instantiated as a non-bootable connection. So modify that - connection to change it to bootable and to specify the boot target. + A profile object will be returned with the configuration based on this template. Specify + the profile name and server hardware to assign. If template has any fiber channel connection + (which is specified as bootable) but no boot target was defined, that connection will be + instantiated as a non-bootable connection. So modify that connection to change it to + bootable and to specify the boot target. Returns: dict: The server profile resource. @@ -153,14 +160,15 @@ def get_new_profile(self): return self._helper.do_get(uri) @ensure_resource_client - def get_transformation(self, server_hardware_type_uri, enclosure_group_uri): + def get_transformation(self): """ - Transforms an existing profile template by supplying a new server hardware type and enclosure group or both. - A profile template will be returned with a new configuration based on the capabilities of the supplied - server hardware type and/or enclosure group. All configured connections will have their port assignments - set to 'Auto.' - The new profile template can subsequently be used in the update method, but is not guaranteed to pass - validation. Any incompatibilities will be flagged when the transformed server profile template is submitted. + Transforms an existing profile template by supplying a new server hardware type and + enclosure group or both. A profile template will be returned with a new configuration + based on the capabilities of the supplied server hardware type and/or enclosure group. + All configured connections will have their port assignments + set to 'Auto.' The new profile template can subsequently be used in the update method, + but is not guaranteed to pass validation. Any incompatibilities will be flagged when the + transformed server profile template is submitted. Note: This method is available for API version 300 or later. @@ -178,27 +186,31 @@ def get_transformation(self, server_hardware_type_uri, enclosure_group_uri): def get_available_networks(self, **kwargs): """ - Retrieves the list of Ethernet networks, Fibre Channel networks and network sets that are available - to a server profile template along with their respective ports. The scopeUris, serverHardwareTypeUri and - enclosureGroupUri parameters should be specified to get the available networks for a new server profile template. - The serverHardwareTypeUri, enclosureGroupUri, and profileTemplateUri should be specified to get available + Retrieves the list of Ethernet networks, Fibre Channel networks and network sets that are + available to a server profile template along with their respective ports. The scopeUris, + serverHardwareTypeUri and enclosureGroupUri parameters should be specified to get the + available networks for a new server profile template. The serverHardwareTypeUri, + enclosureGroupUri, and profileTemplateUri should be specified to get available networks for an existing server profile template. The scopeUris parameter is ignored when the profileTemplateUri is specified. Args: - enclosureGroupUri: The URI of the enclosure group is required when the serverHardwareTypeUri - specifies a blade server. - profileTemplateUri: If the URI of the server profile template is provided the list of available - networks will include only networks that share a scope with the server profile template. + enclosureGroupUri: The URI of the enclosure group is required when the + serverHardwareTypeUri specifies a blade server. + profileTemplateUri: If the URI of the server profile template is provided + the list of available networks will include only networks that share a scope with + the server profile template. scopeUris: An expression to restrict the resources returned according to the scopes to which they are assigned. serverHardwareTypeUri: If the server hardware type specifies a rack server, the list of - available network includes all networks that are applicable for the specified server hardware type. - If the server hardware type specifies a blade server, the enclosureGroupUri parameter must be - specified, and the list of available networks includes all networks that are applicable for the - specified server hardware type and all empty bays within the enclosure group that can support - the specified server hardware type. - view: The FunctionType (Ethernet or FibreChannel) to filter the list of networks returned. + available network includes all networks that are applicable for the specified server + hardware type. + If the server hardware type specifies a blade server, enclosureGroupUri parameter + must be specified, and the list of available networks includes all networks that are + applicable for the specified server hardware type and all empty bays within the + enclosure group that can support the specified server hardware type. + view: The FunctionType (Ethernet or FibreChannel) to filter the list of networks + returned. Returns: dict: Dictionary with available networks details. diff --git a/hpeOneView/resources/servers/server_profiles.py b/hpeOneView/resources/servers/server_profiles.py index 0ba6eab40..ed1114abb 100644 --- a/hpeOneView/resources/servers/server_profiles.py +++ b/hpeOneView/resources/servers/server_profiles.py @@ -15,19 +15,20 @@ # limitations under the License. ### +from copy import deepcopy + from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals +from hpeOneView.resources.resource import (Resource, ResourcePatchMixin, + ResourceSchemaMixin, ensure_resource_client) + from future import standard_library standard_library.install_aliases() -from copy import deepcopy - -from hpeOneView.resources.resource import (Resource, ResourcePatchMixin, - ResourceSchemaMixin, ensure_resource_client) class ServerProfiles(ResourcePatchMixin, ResourceSchemaMixin, Resource): @@ -57,8 +58,8 @@ def create(self, data=None, timeout=-1, force=''): Args: data: Additional fields can be passed to create the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. force: Flag to force the operation Returns: Created resource. @@ -82,8 +83,8 @@ def update(self, data=None, timeout=-1, force=''): Args: data: Data to update the resource. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. force: Force the update operation. Returns: @@ -106,8 +107,8 @@ def update(self, data=None, timeout=-1, force=''): def delete_all(self, filter, timeout=-1, force=False): """ Deletes all Server Profile objects from the appliance that match the provided filter. - Filters are supported only for the following profile attributes: name, description, serialnumber, uuid, - mactype, wwntype, serialnumbertype, status, and state. + Filters are supported only for the following profile attributes: name, description, + serialnumber, uuid, mactype, wwntype, serialnumbertype, status, and state. Examples: @@ -117,15 +118,15 @@ def delete_all(self, filter, timeout=-1, force=False): >>> server_profile_client.delete_all(filter="name matches'%25Database%25'") # Remove all profiles that have the word "Database" in its name - The filter function here operates similarly to the function defined for GET Server Profiles. It allows - for both actual and partial matches of data in the profile. Any requests that use a wildcard match - must include a %25 as illustrated in the previous example. This is how you encode that character for - transmission to the appliance. + The filter function here operates similarly to the function defined for GET Server Profiles. + It allows for both actual and partial matches of data in the profile. Any requests that use + a wildcard match must include a %25 as illustrated in the previous example. This is how you + encode that character for transmission to the appliance. Args: filter (dict): Object to delete. - timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation - in OneView; it just stops waiting for its completion. + timeout: Timeout in seconds. Wait for task completion by default. The timeout does not + abort the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates whether the server profile was successfully deleted. @@ -146,7 +147,8 @@ def get_compliance_preview(self): def get_profile_ports(self, **kwargs): """ - Retrieves the port model associated with a server or server hardware type and enclosure group. + Retrieves the port model associated with a server or server hardware type and enclosure + group. Args: enclosureGroupUri (str): @@ -177,12 +179,13 @@ def get_messages(self): def get_transformation(self, **kwargs): """ - Transforms an existing profile by supplying a new server hardware type or enclosure group or both. - A profile will be returned with a new configuration based on the capabilities of the supplied server hardware - type or enclosure group or both. The port assignment for all deployed connections will be set to Auto. - Re-selection of the server hardware may also be required. The new profile can subsequently be used for updating - the server profile, but passing validation is not guaranteed. Any incompatibilities will be flagged when the - transformed server profile is submitted. + Transforms an existing profile by supplying a new server hardware type or enclosure + group or both. A profile will be returned with a new configuration based on the + capabilities of the supplied server hardware type or enclosure group or both. The port + assignment for all deployed connections will be set to Auto. Re-selection of the server + hardware may also be required. The new profile can subsequently be used for updating + the server profile, but passing validation is not guaranteed. Any incompatibilities + will be flagged when the transformed server profile is submitted. Args: enclosureGroupUri (str): @@ -202,25 +205,27 @@ def get_transformation(self, **kwargs): def get_available_networks(self, **kwargs): """ - Retrieves the list of Ethernet networks, Fiber Channel networks, and network sets that are available to a - server profile, along with their respective ports. + Retrieves the list of Ethernet networks, Fiber Channel networks, and network sets that + are available to a server profile, along with their respective ports. Args: enclosureGroupUri (str): The URI of the enclosure group associated with the resource. - functionType (str): The FunctionType (Ethernet or FibreChannel) to filter the list of networks returned. - serverHardwareTypeUri (str): The URI of the server hardware type associated with the resource. + functionType (str): The FunctionType (Ethernet or FibreChannel) to filter the list + of networks returned. + serverHardwareTypeUri (str): The URI of the server hardware type associated with the + resource. serverHardwareUri (str): The URI of the server hardware associated with the resource. - view (str): Returns a specific subset of the attributes of the resource or collection, by - specifying the name of a predefined view. The default view is expand (show all attributes - of the resource and all elements of collections of resources). + view (str): Returns a specific subset of the attributes of the resource or collection, + by specifying the name of a predefined view. The default view is expand (show all + attributes of the resource and all elements of collections of resources). Values: Ethernet Specifies that the connection is to an Ethernet network or a network set. FibreChannel Specifies that the connection is to a Fibre Channel network. - profileUri (str): If the URI of the server profile is provided the list of available networks will - include only networks that share a scope with the server profile. + profileUri (str): If the URI of the server profile is provided the list of available + networks will include only networks that share a scope with the server profile. scopeUris (str): An expression to restrict the resources returned according to the scopes to which they are assigned @@ -236,7 +241,8 @@ def get_available_servers(self, **kwargs): Args: enclosureGroupUri (str): The URI of the enclosure group associated with the resource. - serverHardwareTypeUri (str): The URI of the server hardware type associated with the resource. + serverHardwareTypeUri (str): The URI of the server hardware type associated with the + resource. profileUri (str): The URI of the server profile resource. scopeUris (str): An expression to restrict the resources returned according to the scopes to which they are assigned. @@ -250,8 +256,8 @@ def get_available_servers(self, **kwargs): def get_available_storage_system(self, **kwargs): """ - Retrieves a specific storage system and its associated volumes available to the server profile based - on the given server hardware type and enclosure group. + Retrieves a specific storage system and its associated volumes available to the server + profile based on the given server hardware type and enclosure group. Args: enclosureGroupUri (str): @@ -269,23 +275,23 @@ def get_available_storage_system(self, **kwargs): def get_available_storage_systems(self, start=0, count=-1, filter='', sort='', **kwargs): """ - Retrieves the list of the storage systems and their associated volumes available to the server profile - based on the given server hardware type and enclosure group. + Retrieves the list of the storage systems and their associated volumes available to + the server profile based on the given server hardware type and enclosure group. Args: count: - The number of resources to return. A count of -1 requests all items. The actual number of items in - the response may differ from the requested count if the sum of start and count exceed the total - number of items. + The number of resources to return. A count of -1 requests all items. The actual + number of items in the response may differ from the requested count if the sum of + start and count exceed the total number of items. start: - The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the - first available item. + The first item to return, using 0-based indexing. If not specified, the default is 0 + - start with the first available item. filter (list or str): - A general filter/query string to narrow the list of items returned. The default is no filter; all - resources are returned. + A general filter/query string to narrow the list of items returned. The default is + no filter; all resources are returned. sort: - The sort order of the returned data set. By default, the sort order is based on create time, with the - oldest entry first. + The sort order of the returned data set. By default, the sort order is based on + create time, with the oldest entry first. enclosureGroupUri (str): The URI of the enclosure group associated with the resource. serverHardwareTypeUri (str): @@ -299,12 +305,13 @@ def get_available_storage_systems(self, start=0, count=-1, filter='', sort='', * def get_available_targets(self, **kwargs): """ - Retrieves a list of the target servers and empty device bays that are available for assignment to the server - profile. + Retrieves a list of the target servers and empty device bays that are available for + assignment to the server profile. Args: enclosureGroupUri (str): The URI of the enclosure group associated with the resource. - serverHardwareTypeUri (str): The URI of the server hardware type associated with the resource. + serverHardwareTypeUri (str): The URI of the server hardware type associated with the + resource. profileUri (str): The URI of the server profile associated with the resource. scopeUris (str): An expression to restrict the resources returned according to the scopes to which they are assigned. diff --git a/hpeOneView/resources/task_monitor.py b/hpeOneView/resources/task_monitor.py index becc7902e..4f01fe38e 100644 --- a/hpeOneView/resources/task_monitor.py +++ b/hpeOneView/resources/task_monitor.py @@ -15,6 +15,11 @@ # limitations under the License. ### +import logging +import time + +from errno import ECONNABORTED, ETIMEDOUT, ENOEXEC, EINVAL, ENETUNREACH, ECONNRESET,\ + ENETDOWN, ECONNREFUSED from __future__ import absolute_import from __future__ import division from __future__ import print_function @@ -24,12 +29,8 @@ standard_library.install_aliases() - -import logging -import time - -from errno import ECONNABORTED, ETIMEDOUT, ENOEXEC, EINVAL, ENETUNREACH, ECONNRESET, ENETDOWN, ECONNREFUSED -from hpeOneView.exceptions import HPEOneViewInvalidResource, HPEOneViewTimeout, HPEOneViewTaskError, HPEOneViewUnknownType +from hpeOneView.exceptions import HPEOneViewInvalidResource, HPEOneViewTimeout, \ + HPEOneViewTaskError, HPEOneViewUnknownType TASK_PENDING_STATES = ['New', 'Starting', 'Pending', 'Running', 'Suspended', 'Stopping'] TASK_ERROR_STATES = ['Error', 'Warning', 'Terminated', 'Killed'] @@ -76,7 +77,8 @@ def wait_for_task(self, task, timeout=-1): task = self.get(task) - logger.debug("Waiting for task. Percentage complete: " + str(task.get('computedPercentComplete'))) + logger.debug("Waiting for task. Percentage complete: " + \ + str(task.get('computedPercentComplete'))) logger.debug("Waiting for task. Task state: " + str(task.get('taskState'))) task_response = self.__get_task_response(task) @@ -114,11 +116,13 @@ def __wait_task_completion(self, task, timeout): # the value increases to avoid flooding server with requests i = i + 1 if i < 10 else 10 - logger.debug("Waiting for task. Percentage complete: " + str(task.get('computedPercentComplete'))) + logger.debug("Waiting for task. Percentage complete: " + \ + str(task.get('computedPercentComplete'))) logger.debug("Waiting for task. Task state: " + str(task.get('taskState'))) time.sleep(i) - if (timeout != UNLIMITED_TIMEOUT) and (start_time + timeout < self.get_current_seconds()): + if (timeout != UNLIMITED_TIMEOUT) and (start_time + timeout < \ + self.get_current_seconds()): raise HPEOneViewTimeout(MSG_TIMEOUT % str(timeout)) def __get_task_response(self, task): @@ -185,7 +189,8 @@ def is_task_running(self, task, connection_failure_control=None): return True except Exception as error: - logger.error('; '.join(str(e) for e in error.args) + ' when waiting for the task: ' + str(task)) + logger.error('; '.join(str(e) for e in error.args) + ' when waiting for the task: '\ + + str(task)) if not connection_failure_control: raise error