def test_imc_context_manager_no_timeout(): try: import ConfigParser except: import configparser as ConfigParser from imcsdk.imchandle import ImcHandle from ..connection import info host = 'imc' config = ConfigParser.RawConfigParser() config.read(info.CONNECTION_CFG_FILEPATH) hostname = config.get(host, "hostname") username = config.get(host, "username") password = config.get(host, "password") handle = ImcHandle(hostname, username, password) with handle: server_dn = get_server_dn(handle) mo = handle.query_dn(server_dn, timeout=600) usr_lbl = "test-lbl2" mo.usr_lbl = usr_lbl handle.set_mo(mo, timeout=600) mo = handle.query_dn(server_dn) assert_equal(mo.usr_lbl, usr_lbl)
def test_vmedia_get_existing_status(login_mock, query_mock): # Patch ImcHandle.login to create a Faux ImcHandle w/o real CIMC # Patch ImcHandle.query_children to simulate CIMC interaction login_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: No pre-existing mappings query_mock.return_value = [] assert vmedia_get_existing_status(test_cimc) == [] # Assert query_children called with correct in_dn assert query_mock.mock_calls[0] == \ call(in_dn='sys/svc-ext/vmedia-svc') # Scenario: Three pre-existing mappings # mapping_status is not a read-write property, so mock it. vmedia1 = MagicMock() vmedia1.mapping_status = "In-Progress" vmedia2 = MagicMock() vmedia2.mapping_status = "OK" vmedia3 = MagicMock() vmedia3.mapping_status = "Error" query_mock.return_value = [vmedia1, vmedia2, vmedia3] assert vmedia_get_existing_status(test_cimc) == \ ["In-Progress", "OK", "Error"]
def test_valid_remove_vmedia_all(login_mock, query_mock, remove_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.query_children to simulate CIMC interaction w/o real CIMC # Patch ImcHandle.remove_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: server has no vmedia mounts query_mock.return_value = [] assert vmedia_mount_remove_all(test_cimc) is True assert remove_mock.mock_calls == [] # Scenario: Three pre-exising mounts, removed successfully vmedia1 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="One.iso") vmedia1.remote_share = "http://169.254.1.2/" vmedia1.remote_file = "One.iso" vmedia2 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="Two") vmedia2.remote_share = "http://169.254.1.2/" vmedia2.remote_file = "Two.iso" vmedia3 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="Three") vmedia3.remote_share = "http://169.254.1.2/" vmedia3.remote_file = "Three.iso" # query_mocked call first time in remove_existing_virtual_media # query_mock called a second time in get_existing_virtual_media_uri query_mock.side_effect = [[vmedia1, vmedia2, vmedia3], []] assert vmedia_mount_remove_all(test_cimc) is True assert remove_mock.mock_calls == [call(vmedia1), call(vmedia2), call(vmedia3)]
def test_valid_enable_ipmi(login_mock, query_dn_mock, set_mo_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True set_mo_mock.return_value = True ipmi_enabled_mock = MagicMock() ipmi_enabled_mock.admin_state = "enabled" test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) query_dn_mock.return_value = ipmi_enabled_mock # Scenario: Enable IPMI default values assert ipmi_enable(test_cimc) is ipmi_enabled_mock # Assert values of the object passed to add_mo() test_ipmi_mo = set_mo_mock.call_args[0][0] assert test_ipmi_mo.admin_state == "enabled" assert test_ipmi_mo.priv == CommIpmiLanConsts.PRIV_ADMIN assert test_ipmi_mo.key == '0'*40 # Scenario: Enable IPMI custom priv and key assert ipmi_enable(test_cimc, priv="user", key='1'*40) is ipmi_enabled_mock test_ipmi_mo = set_mo_mock.call_args[0][0] assert test_ipmi_mo.admin_state == "enabled" assert test_ipmi_mo.priv == "user" assert test_ipmi_mo.key == '1'*40
def login(self, username, password, server): # Test if the server reachable s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10) try: result = s.connect_ex((server, 443)) if result != 0: return None, "{0} on port 443 is not reachable".format(server) s.close() except socket.error as err: return None, "IMC Login Error: {0} {1}".format( server, err.strerror) handle = ImcHandle(server, username, password, auto_refresh=True, force=True) try: handle.login() except ImcException as err: print "Login Error: " + err.error_descr return None, err.error_descr except HTTPError as err: print "Connection Error: Bad IMCM? " + err.reason return None, err.reason except Exception as e: print "Issue logging in. Please check that all parameters are correct" print e return None, "Issue logging in. Please check that all parameters are correct." #TODO: get the right version of IMC firmware. Tested on 3.0(4a) #msg = self.ensure_version(handle) return handle, None
def test_valid_enable_ipmi(login_mock, query_dn_mock, set_mo_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True set_mo_mock.return_value = True ipmi_enabled_mock = MagicMock() ipmi_enabled_mock.admin_state = "enabled" test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) query_dn_mock.return_value = ipmi_enabled_mock # Scenario: Enable IPMI default values assert ipmi_enable(test_cimc) is ipmi_enabled_mock # Assert values of the object passed to add_mo() test_ipmi_mo = set_mo_mock.call_args[0][0] assert test_ipmi_mo.admin_state == "enabled" assert test_ipmi_mo.priv == CommIpmiLanConsts.PRIV_ADMIN assert test_ipmi_mo.key == '0' * 40 # Scenario: Enable IPMI custom priv and key assert ipmi_enable(test_cimc, priv="user", key='1' * 40) is ipmi_enabled_mock test_ipmi_mo = set_mo_mock.call_args[0][0] assert test_ipmi_mo.admin_state == "enabled" assert test_ipmi_mo.priv == "user" assert test_ipmi_mo.key == '1' * 40
def test_vmedia_get_existing_uri(login_mock, query_mock): # Patch ImcHandle.login to create a Faux ImcHandle w/o real CIMC # Patch ImcHandle.query_children to simulate CIMC interaction login_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: No pre-existing mappings query_mock.return_value = [] assert vmedia_get_existing_uri(test_cimc) == [] # Assert query_children called with correct in_dn assert query_mock.mock_calls[0] == \ call(in_dn='sys/svc-ext/vmedia-svc') # Scenario: Three pre-existing mappings vmedia1 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="One.iso") vmedia1.remote_share = "http://169.254.1.2/" vmedia1.remote_file = "One.iso" vmedia2 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="Two") vmedia2.remote_share = "http://169.254.1.2/" vmedia2.remote_file = "Two.iso" vmedia3 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="Three") vmedia3.remote_share = "http://169.254.1.2/" vmedia3.remote_file = "Three.iso" query_mock.return_value = [vmedia1, vmedia2, vmedia3] assert vmedia_get_existing_uri(test_cimc) == \ ["http://169.254.1.2/One.iso", "http://169.254.1.2/Two.iso", "http://169.254.1.2/Three.iso"]
def test_invalid_remove_vmedia_all(login_mock, query_mock, remove_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.query_children to simulate CIMC interaction w/o real CIMC # Patch ImcHandle.remove_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: Three pre-exising mounts, only two unsuccessfully vmedia1 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="One.iso") vmedia1.remote_share = "http://169.254.1.2/" vmedia1.remote_file = "One.iso" vmedia2 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="Two") vmedia2.remote_share = "http://169.254.1.2/" vmedia2.remote_file = "Two.iso" vmedia3 = CommVMediaMap(parent_mo_or_dn="sys/svc-ext/vmedia-svc", volume_name="Three") vmedia3.remote_share = "http://169.254.1.2/" vmedia3.remote_file = "Three.iso" query_mock.side_effect = [[vmedia1, vmedia2, vmedia3], [vmedia1]] assert_raises(ImcOperationError, vmedia_mount_remove_all, test_cimc)
def DoLogin(ip, user, pwd): log = logging.getLogger() log.info("Connecting to IMC Server <%s>....\n", ip) print "Connecting to IMC Server <%s>....\n" %(ip) handle = ImcHandle(ip,user,pwd) if handle.login(auto_refresh=True): log.info("Login successful: <%s>\n", handle._ImcSession__imc) print "Login successful: <%s>\n" %(handle._ImcSession__imc) handleList.append(handle) return handle
def handle(self): from imcsdk.imchandle import ImcHandle from urllib2 import URLError if self._handle is None: self._handle = ImcHandle(self.oob_ip, self.oob_username, self.oob_password) try: self._handle.login() except URLError as ex: raise RuntimeError('{}: {} {}'.format(self, ex, self.oob_ip)) return self._handle
def custom_setup(host="imc"): from imcsdk.imchandle import ImcHandle config = configparser.RawConfigParser() config.read(CONNECTION_CFG_FILEPATH) hostname = config.get(host, "hostname") username = config.get(host, "username") password = config.get(host, "password") handle = ImcHandle(hostname, username, password) handle.login(auto_refresh=True, force=True) return handle
def test_invalid_vmedia_mount_iso_uri(login_mock, add_mount_mock, exist_mock, state_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch vmedia_mount_add to simulate CIMC interaction w/o real CIMC # Patch vmedia_get_existing_uri to simulate existing ISOs # Patch vmedia_get_existing_status to simulate ISO status login_mock.return_value = True add_mount_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: Zero value passed in as check interval assert_raises(ValueError, vmedia_mount_iso_uri, test_cimc, 'http://1.1.1.1/test.iso', interval=0) # Scenario: Invalid protocol exist_mock.side_effect = [[], ["britt://1.1.1.1/test.iso"]] assert_raises(ValueError, vmedia_mount_iso_uri, test_cimc, 'britt://1.1.1.1/test.iso', interval=1) # Scenario: Mapping failed exist_mock.side_effect = [[], []] assert_raises(ImcOperationError, vmedia_mount_iso_uri, test_cimc, 'http://169.254.1.2/test.iso', interval=1) # Scenario: Timeout on state change exist_mock.side_effect = [[], ["http://169.254.1.2/test.iso"]] state_mock.side_effect = [['In Progress'], ['In Progress']] assert_raises(ImcOperationError, vmedia_mount_iso_uri, test_cimc, 'http://169.254.1.2/test.iso', interval=1, timeout=0) # State returns Error exist_mock.side_effect = [[], ["http://169.254.1.2/test.iso"]] state_mock.side_effect = [['In Progress'], ['ERROR: [404] File not found. ']] assert_raises(ImcOperationError, vmedia_mount_iso_uri, test_cimc, 'http://169.254.1.2/test.iso', interval=1)
def _login(ip, username, password, port=None, secure=None, proxy=None): from imcsdk.imchandle import ImcHandle results = {} try: server = ImcHandle(ip, username, password, port, secure, proxy) server.login() except Exception as e: results["msg"] = str(e) return server, results, True results["msg"] = "login succeded" results["changed"] = False return server, results, False
def test_invalid_enable_ipmi(login_mock, set_mo_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True set_mo_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: Invalid priv value assert_raises(ValueError, ipmi_enable, test_cimc, priv="Wrong") # Scenario: Invalid key assert_raises(ValueError, ipmi_enable, test_cimc, key='bacon')
def custom_setup(host="imc"): try: import ConfigParser except: import configparser as ConfigParser from imcsdk.imchandle import ImcHandle config = ConfigParser.RawConfigParser() config.read(CONNECTION_CFG_FILEPATH) hostname = config.get(host, "hostname") username = config.get(host, "username") password = config.get(host, "password") handle = ImcHandle(hostname, username, password) handle.login(auto_refresh=True, force=True) return handle
def test_valid_disable_ipmi(login_mock, query_dn_mock, set_mo_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True set_mo_mock.return_value = True ipmi_disabled_mock = MagicMock() ipmi_disabled_mock.admin_state = "disabled" test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) query_dn_mock.return_value = ipmi_disabled_mock # Scenario: Enable IPMI default values assert ipmi_disable(test_cimc) is ipmi_disabled_mock # Assert values of the object passed to add_mo() test_ipmi_mo = set_mo_mock.call_args[0][0] assert test_ipmi_mo.admin_state == "disabled"
def test_001_create_uri(): # Create an object of type LsServer with parent dn specified # check if the object has the right values populated temp_handle = ImcHandle("192.168.1.1", "admin", "password") assert_equal( temp_handle._ImcSession__create_uri( port=None, secure=None), 'https://192.168.1.1:443') assert_equal( temp_handle._ImcSession__create_uri( port=8080, secure=None), 'https://192.168.1.1:8080') assert_equal( temp_handle._ImcSession__create_uri( port=None, secure=True), 'https://192.168.1.1:443') assert_equal( temp_handle._ImcSession__create_uri( port=None, secure=False), 'http://192.168.1.1:80') assert_equal( temp_handle._ImcSession__create_uri( port=444, secure=False), 'http://192.168.1.1:444')
def custom_setup(): try: import ConfigParser except: import configparser as ConfigParser import os from imcsdk.imchandle import ImcHandle config = ConfigParser.RawConfigParser() config.read(os.path.join(os.path.dirname(__file__), '..', 'connection', 'connection.cfg')) hostname = config.get(host, "hostname") username = config.get(host, "username") password = config.get(host, "password") handle = ImcHandle(hostname, username, password, port=80) handle.login() return handle
def login(module): ansible = module.params server = ansible.get('server') if server: return server from imcsdk.imchandle import ImcHandle results = {} try: server = ImcHandle(ip=ansible["ip"], username=ansible["username"], password=ansible["password"], port=ansible["port"], secure=ansible["secure"], proxy=ansible["proxy"]) server.login() except Exception as e: results["msg"] = str(e) module.fail_json(**results) return server
def custom_setup(host="imc"): try: import ConfigParser except: import configparser as ConfigParser import os from imcsdk.imchandle import ImcHandle config = ConfigParser.RawConfigParser() config.read( os.path.join(os.path.dirname(__file__), '..', 'connection', 'connection.cfg')) hostname = config.get(host, "hostname") username = config.get(host, "username") password = config.get(host, "password") handle = ImcHandle(hostname, username, password) handle.login(auto_refresh=True, force=True) return handle
def test_invalid_power_up_server(login_mock, query_dn_mock, set_mo_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.query_dn to simulate CIMC interaction w/o real CIMC # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True set_mo_mock.return_value = True pwrd_off_mock = MagicMock() pwrd_off_mock.oper_power = "off" pwrd_on_mock = MagicMock() pwrd_on_mock.oper_power = "on" test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: Zero value passed in as check interval assert_raises(ValueError, server_power_up, test_cimc, 0, 0) # Scenario: server starts power off, and doesn't power on query_dn_mock.return_value = pwrd_off_mock assert_raises(ImcOperationError, server_power_up, test_cimc, 0, 1)
def test_valid_power_up_server(login_mock, query_dn_mock, set_mo_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch ImcHandle.query_dn to simulate CIMC interaction w/o real CIMC # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC login_mock.return_value = True set_mo_mock.return_value = True pwrd_off_mock = MagicMock() pwrd_off_mock.oper_power = "off" pwrd_on_mock = MagicMock() pwrd_on_mock.oper_power = "on" test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # Scenario: server starts powered on query_dn_mock.return_value = pwrd_on_mock assert server_power_up(test_cimc, 0, 1) is pwrd_on_mock # Scenario: server starts powered off, and powers on successfully query_dn_mock.side_effect = [pwrd_off_mock, pwrd_on_mock, pwrd_on_mock, pwrd_on_mock] assert server_power_up(test_cimc, 0, 1) is pwrd_on_mock
def reboot(cimc_ip, cimc_user, cimc_password): handle = ImcHandle(cimc_ip, cimc_user, cimc_password) handle.login(auto_refresh=False) mo = handle.config_resolve_dn("sys/rack-unit-1") mo.admin_power = ComputeRackUnit.ADMIN_POWER_BMC_RESET_IMMEDIATE try: handle.set_mo(mo) # handle.set_imc_managedobject( # mo, class_id="ComputeRackUnit", # params={ # ComputeRackUnit.ADMIN_POWER: # ComputeRackUnit.CONST_ADMIN_POWER_BMC_RESET_IMMEDIATE, # ComputeRackUnit.DN: "sys/rack-unit-1"}) except Exception as e: print(e)
def install(server, attrs): print("Logging in to %s" % server) print(attrs["user"], attrs["password"]) handle = ImcHandle(server, attrs["user"], attrs["password"], auto_refresh=True, force=True) try: handle.login() except ImcException as e: print("error logging in: %s" % e.error_descr, e.error_code) return except Exception as e: print "Error with server login. Could be your firmware is too old?" return print("successfully logged into %s" % server) mount_media(handle, attrs["hostname"]) set_boot(handle) handle.logout()
from imcsdk.imchandle import ImcHandle from imcsdk.imchandle import ImcHandle # Create a connection handle handle = ImcHandle("10.10.20.3", "admin", "ciscopsdt") # Login to the server handle.login()
import regex # filename = '/Users/your_user_name/Desktop/test.csv' filename = 'cimc.txt' file = open(filename, "r") o = file.read() ip1 = regex.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", o) hosts = ip1 for host in hosts: print("host: ", host) try: handle = ImcHandle(host, "admin", "ciscopsdt") handle.login() handle.set_dump_xml() print(handle.imc) # print("firmware: ", handle.query_dn("sys/rack-unit-1/mgmt/fw-system")) firmware_query = handle.query_dn("sys/rack-unit-1/mgmt/fw-system") name_query = handle.query_dn("sys/rack-unit-1") hostname_query = handle.query_dn("sys") # hostname_query = handle.query_classid(class_id="topSystem",need_response=True) #can get the same output through handle.imc() print(hostname_query)
def init_process(ucs_device, args, config_string): """ Performs initial processing of EasyUCS, depending on the arguments provided :param ucs_device: UCS device to be used for processing :param args: Command-line arguments provided (argparse format) :param config_string: The config content :return: True if successful, False otherwise """ bypass_version_checks = False if args.yes: bypass_version_checks = True ucs_device.set_task_progression(1) if args.scope == "config" and args.action == "push": # Adding configuration to the created UCS Device if config_string: if not ucs_device.config_manager.import_config( config=config_string): exit() config = ucs_device.config_manager.get_latest_config() # If we are doing a complete reset/setup cycle, we use the push_config method with the "reset" argument if args.setup and args.reset: if not args.yes: if not common.query_yes_no( "Are you sure you want to erase all configuration on " + ucs_device.name + "?"): # User declined configuration erase query # FIXME: handle proper disconnection if required exit() if ucs_device.__class__.__name__ == "UcsImc": ucs_device.config_manager.push_config( reset=True, imc_ip=args.setup[0], bypass_version_checks=bypass_version_checks) elif ucs_device.__class__.__name__ == "UcsSystem": ucs_device.config_manager.push_config( reset=True, fi_ip_list=args.setup, bypass_version_checks=bypass_version_checks) # If we are not doing a complete reset/setup cycle, we perform each action separately else: if args.reset: if not args.yes: if not common.query_yes_no( "Are you sure you want to erase all configuration on " + ucs_device.name + "?"): # User declined configuration erase query # FIXME: handle proper disconnection if required exit() # Executing reset action if not ucs_device.reset( bypass_version_checks=bypass_version_checks): ucs_device.logger( level="error", message="Error while performing UCS device reset") exit() if args.setup: ucs_device.logger(level="debug", message="Performing initial setup with IP " + str(args.setup[0])) if ucs_device.__class__.__name__ == "UcsImc": if not ucs_device.initial_setup( imc_ip=args.setup[0], config=config, bypass_version_checks=bypass_version_checks): ucs_device.logger( level="error", message= "Error while performing initial setup on UCS IMC") exit() # We now need to get the new IP address and admin password from the configuration imc_target_ip_address = "" if config.admin_networking[0].management_ipv4_address: imc_target_ip_address = config.admin_networking[ 0].management_ipv4_address else: ucs_device.logger( level="error", message= "Could not find Management IP address of UCS IMC in the config" ) exit() if not config.local_users: ucs_device.logger( level="error", message="Could not find local_users in the config") exit() # Going through all users to find admin target_admin_password = "" for user in config.local_users: if user.username: if user.username == "admin": if user.password: target_admin_password = user.password else: # Admin password is a mandatory input - Exiting ucs_device.logger( level="error", message= "Could not find password for user id admin in the config" ) exit() # We went through all users - Making sure we got the information we needed if not target_admin_password: ucs_device.logger( level="error", message="Could not find user id admin in the config" ) exit() # We need to refresh the UCS device handle so that it has the right attributes ucs_device.handle = ImcHandle( ip=imc_target_ip_address, username="******", password=target_admin_password) # Changing handle to the new one config.refresh_config_handle() ucs_device.logger( level="debug", message="Waiting for the IMC to come back with the IP " + imc_target_ip_address) if not ucs_device.wait_for_reboot_after_reset( timeout=60, imc_ip=imc_target_ip_address): exit() elif ucs_device.__class__.__name__ == "UcsSystem": if len(args.setup) == 2: ucs_device.sys_mode = "cluster" elif len(args.setup) == 1: ucs_device.sys_mode = "stand-alone" if not ucs_device.initial_setup(fi_ip_list=args.setup, config=config): ucs_device.logger( level="error", message= "Error while performing initial setup on UCS System" ) exit() # We now need to wait to be able to configure the device using the configuration if ucs_device.sys_mode == "cluster": ucs_device.logger( message= "Waiting up to 240 seconds for cluster election to complete" ) time.sleep(80) if config.system: if config.system[0].virtual_ip: ucs_device.target = config.system[0].virtual_ip elif config.system[0].virtual_ipv6: ucs_device.target = config.system[ 0].virtual_ipv6 if not ucs_device.target: ucs_device.logger( level="error", message= "Could not determine target IP of the device in the config" ) exit() elif ucs_device.sys_mode == "stand-alone": ucs_device.logger( message= "Waiting up to 180 seconds for initial configuration to complete" ) time.sleep(20) # TODO Handle Ipv6 if config.management_interfaces: for management_interface in config.management_interfaces: if management_interface.fabric.upper() == 'A': if management_interface.ip: ucs_device.target = management_interface.ip if not ucs_device.target: ucs_device.logger( level="error", message= "Could not determine target IP of the device in the config" ) exit() if not config.local_users: # Could not find local_users in config - Admin password is a mandatory parameter - Exiting ucs_device.logger( level="error", message="Could not find local_users in the config") exit() # Going through all users to find admin for user in config.local_users: if user.id: if user.id == "admin": ucs_device.username = "******" if user.password: ucs_device.password = user.password else: # Admin password is a mandatory input ucs_device.logger( level="error", message= "Could not find password for user id admin in the config" ) exit() # We need to refresh the UCS device handle so that it has the right attributes ucs_device.handle = UcsHandle(ip=ucs_device.target, username=ucs_device.username, password=ucs_device.password) # We also need to refresh the config handle config.refresh_config_handle() if not common.check_web_page( device=ucs_device, url="https://" + ucs_device.target, str_match="Cisco", timeout=160): ucs_device.logger( level="error", message="Impossible to reconnect to UCS system") exit() # Reconnecting and waiting for HA cluster to be ready (if in cluster mode) if not ucs_device.connect( bypass_version_checks=bypass_version_checks, retries=3): ucs_device.logger( level="error", message="Impossible to reconnect to UCS system") exit() # Bypass version checks for the rest of the procedure as potential warnings have already been made bypass_version_checks = True if ucs_device.sys_mode == "cluster": ucs_device.logger( message= "Waiting up to 300 seconds for UCS HA cluster to be ready..." ) if not ucs_device.wait_for_ha_cluster_ready( timeout=300): ucs_device.logger( level="error", message= "Timeout exceeded while waiting for UCS HA cluster to be in ready state" ) exit() elif ucs_device.sys_mode == "stand-alone": ucs_device.logger( message= "Waiting up to 300 seconds for UCS stand-alone FI to be ready..." ) if not ucs_device.wait_for_standalone_fi_ready( timeout=300): ucs_device.logger( level="error", message= "Timeout exceeded while waiting for UCS stand-alone FI to be ready" ) exit() if config_string: ucs_device.config_manager.push_config( bypass_version_checks=bypass_version_checks) elif args.scope == "config" and args.action == "fetch": # Fetching config from live UCS Device if not ucs_device.connect(bypass_version_checks=bypass_version_checks): ucs_device.logger(level="error", message="Impossible to connect to UCS device") exit() ucs_device.config_manager.fetch_config() ucs_device.set_task_progression(50) # Exporting config to specified output config file directory = os.path.dirname(args.output_config) filename = os.path.basename(args.output_config) ucs_device.config_manager.export_config(directory=directory, filename=filename) elif args.scope == "inventory" and args.action == "fetch": # Fetching inventory from live UCS Device if not ucs_device.connect(bypass_version_checks=bypass_version_checks): ucs_device.logger(level="error", message="Impossible to connect to UCS device") exit() ucs_device.inventory_manager.fetch_inventory() ucs_device.set_task_progression(50) # Exporting inventory to specified output config file directory = os.path.dirname(args.output_inventory) filename = os.path.basename(args.output_inventory) ucs_device.inventory_manager.export_inventory(directory=directory, filename=filename) elif args.scope == "schemas" and args.action == "create": # Fetching inventory from live UCS Device and create schemas of it if not ucs_device.connect(bypass_version_checks=bypass_version_checks): ucs_device.logger(level="error", message="Impossible to connect to UCS device") exit() ucs_device.inventory_manager.fetch_inventory() ucs_device.set_task_progression(50) ucs_device.inventory_manager.draw_inventory() ucs_device.set_task_progression(75) directory = args.output_directory ucs_device.inventory_manager.export_draw( directory=directory, export_clear_pictures=args.clear_pictures) elif args.scope == "report" and args.action == "generate": # Fetching inventory from live UCS Device, create schemas and generate report of it if not ucs_device.connect(bypass_version_checks=bypass_version_checks): ucs_device.logger(level="error", message="Impossible to connect to UCS device") exit() ucs_device.config_manager.fetch_config() ucs_device.set_task_progression(25) ucs_device.inventory_manager.fetch_inventory() ucs_device.set_task_progression(50) # Exporting report to specified output directory directory = args.output_directory # Exporting inventory & config to JSON files ucs_device.inventory_manager.export_inventory( directory=directory, filename="inventory_" + ucs_device.target + ".json") ucs_device.config_manager.export_config(directory=directory, filename="config_" + ucs_device.target + ".json") ucs_device.set_task_progression(60) ucs_device.inventory_manager.draw_inventory() ucs_device.set_task_progression(75) ucs_device.inventory_manager.export_draw(directory=directory, export_clear_pictures=True) ucs_device.set_task_progression(80) if ucs_device.device_type_short == "ucsm": ucs_device.config_manager.generate_config_plots() ucs_device.config_manager.export_config_plots(directory=directory) ucs_device.set_task_progression(90) ucs_device.generate_report(filename="report_" + ucs_device.target, directory=directory, page_layout=args.layout) ucs_device.set_task_progression(100) ucs_device.print_logger_summary()
def test_valid_vmedia_mount_iso_uri(login_mock, add_mount_mock, exist_mock, state_mock): # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC # Patch vmedia_mount_create to simulate CIMC interaction w/o real CIMC # Patch vmedia_get_existing_uri to simulate existing ISOs # Patch vmedia_get_existing_status to simulate ISO status login_mock.return_value = True add_mount_mock.return_value = True test_cimc = ImcHandle(ip='169.254.1.1', username='******', password='******') test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC) # http mapping succeeded exist_mock.return_value = ["http://169.254.1.2/test.iso"] state_mock.side_effect = [['In Progress'], ['OK']] assert vmedia_mount_iso_uri( test_cimc, 'http://169.254.1.2/test.iso', interval=1 ) is True # Assert values of the mount options assert add_mount_mock.call_args[1] == { 'volume_name': 'test.iso', 'map': 'www', 'mount_options': 'noauto', 'remote_share': "http://169.254.1.2/", 'remote_file': 'test.iso', 'username': '', 'password': '', 'server_id': 1 } # https mapping succeeded exist_mock.return_value = ["https://169.254.1.2/test.iso"] state_mock.side_effect = [['In Progress'], ['OK']] assert vmedia_mount_iso_uri( test_cimc, 'https://169.254.1.2/test.iso', interval=1 ) is True # Assert values of the mount options assert add_mount_mock.call_args[1] == { 'volume_name': 'test.iso', 'mount_options': 'noauto', 'map': 'www', 'remote_share': "https://169.254.1.2/", 'remote_file': 'test.iso', 'username': '', 'password': '', 'server_id': 1 } # CIFS mapping succeeded exist_mock.return_value = ["//169.254.1.2/test.iso"] state_mock.side_effect = [['In Progress'], ['OK']] assert vmedia_mount_iso_uri( test_cimc, '//169.254.1.2/test.iso', interval=1 ) is True # Assert values of the object passed to add_mo() assert add_mount_mock.call_args[1] == { 'volume_name': 'test.iso', 'mount_options': 'noauto', 'map': 'cifs', 'remote_share': "//169.254.1.2/", 'remote_file': 'test.iso', 'username': '', 'password': '', 'server_id': 1 } # NFS mapping succeeded exist_mock.return_value = ["169.254.1.2:/test.iso"] state_mock.side_effect = [['In Progress'], ['OK']] assert vmedia_mount_iso_uri( test_cimc, '169.254.1.2:/test.iso', interval=1 ) is True # Assert values of the object passed to add_mo() assert add_mount_mock.call_args[1] == { 'volume_name': 'test.iso', 'mount_options': 'noauto', 'map': 'nfs', 'remote_share': "169.254.1.2:/", 'remote_file': 'test.iso', 'username': '', 'password': '', 'server_id': 1 }
class CimcServer(LabServer): RAID_0, RAID_1, RAID_10 = '0', '1', '10' def __init__(self, pod, dic): super(CimcServer, self).__init__(pod=pod, dic=dic) self._handle = None self._dump_xml = False self._logout_on_each_command = False def logger(self, message): self.log('CIMC ' + message) @property def handle(self): from imcsdk.imchandle import ImcHandle from urllib2 import URLError if self._handle is None: self._handle = ImcHandle(self.oob_ip, self.oob_username, self.oob_password) try: self._handle.login() except URLError as ex: raise RuntimeError('{}: {} {}'.format(self, ex, self.oob_ip)) return self._handle def cimc_get_raid_battery_status(self): return self._handle.query_classid(class_id='storageRaidBattery') def _cimc_bios_lom(self, status): self.logger('{} all LOM'.format(status)) actual = self._handle.query_classid(class_id='BiosVfLOMPortOptionROM') if actual.Status != status: params = {'Dn': 'sys/rack-unit-1/bios/bios-settings/LOMPort-OptionROM', 'VpLOMPortsAllState': status, 'vpLOMPort0State': status, 'vpLOMPort1State': status} self._handle.set_mo('set_imc_managedobject', in_mo=None, class_id='BiosVfLOMPortOptionROM', params=params) self.cimc_power_cycle() def cimc_enable_loms_in_bios(self): self._cimc_bios_lom(status='Enable') def cimc_disable_loms_in_bios(self): self._cimc_bios_lom(status='Disable') def cimc_list_all_nics(self): self.log('{} getting CIMC NICs'.format(self.oob_ip)) r1 = self.handle.query_classid(class_id='networkAdapterEthIf') # physical Intel NICs (or others in PCI-E slots) r2 = self.handle.query_classid(class_id='adaptorExtEthIf') # physical Cisco VIC in MLOM return {x.dn: x.mac for x in r1 + r2} def cimc_list_all_nics_and_vnics(self): r1 = self.handle.query_classid(class_id='networkAdapterEthIf') # physical Intel NICs (or others in PCI-E slots) r2 = self.handle.query_classid(class_id='adaptorExtEthIf') # physical Cisco VIC in MLOM r3 = self.handle.query_classid(class_id='adaptorHostEthIf') # virtual Cisco vNIC in MLOM return {x.dn: x.mac for x in r1 + r2 + r3} def cimc_list_pci_nic(self): r = self.handle.query_classid('networkAdapterUnit') return [{'Dn': x.Dn, 'Model': x.Model} for x in r] def cimc_list_vnics(self): ans1 = self.handle.query_classid('adaptorHostEthIf') ans2 = self.handle.query_classid('adaptorEthGenProfile') vnics = {x.Name: {'mac': x.Mac, 'uplink': x.UplinkPort, 'pci-slot': x.UsnicCount, 'dn': x.Dn, 'mtu': x.Mtu, 'name': x.Name, 'pxe-boot': x.PxeBoot} for x in ans1} vlans_dict = {x.Dn.replace('/general', ''): {'vlan': x.Vlan, 'vlan_mode': x.VlanMode} for x in ans2} for vnic in vnics.values(): vlans = vlans_dict[vnic.get('dn')] vnic.update(vlans) return vnics def cimc_enable_sol(self): self.logger('enabling SOL') params = {'dn': 'sys/rack-unit-1/sol-if', 'adminState': 'enable', 'speed': '115200'} self.cimc_set_mo_by_class_id(class_id='solIf', params=params) def create_storage(self, raid=RAID_1, disks_needed=2, clean_vds=False): """ :param clean_vds: Clean all virtual drives before creating any :param raid: Please select from '0','1','10','5','6' :param disks_needed: Number of disks needed :return: """ if raid not in [self.RAID_0, self.RAID_1, self.RAID_10]: raise ValueError('RAID request is not correct. Use one of the {0}. Got: {1}'.format(','.join([self.RAID_0, self.RAID_1, self.RAID_10]), raid)) virtual_drives_list = self.handle.query_classid(class_id='storageVirtualDrive') if virtual_drives_list: if clean_vds: self.logger('Cleaning Virtual Drives to create new one.') for vd in virtual_drives_list: self.handle.remove_mo(vd) else: self.logger('Virtual Drive already exists.') return disks = self.handle.query_classid('storageLocalDisk') # get 2 or more disks to form RAID disks_by_size = {} map(lambda x: disks_by_size.setdefault(x.get_attr('CoercedSize'), []).append(x), disks) available_disks = filter(lambda x: len(disks_by_size[x]) > disks_needed, disks_by_size.keys()) if len(available_disks) == 0: raise Exception('Not enough disks to build RAID {0}. Minimum required are {1}.'.format(raid, disks_needed)) size = available_disks[0] drive_group = ','.join(map(lambda x: x.Id, disks_by_size[size])[:disks_needed]) params = {'raidLevel': raid, 'size': size, 'virtualDriveName': "RAID", 'dn': "sys/rack-unit-1/board/storage-SAS-SLOT-HBA/virtual-drive-create", 'driveGroup': '[{0}]'.format(drive_group), 'adminState': 'trigger', 'writePolicy': 'Write Through'} self.logger('Creating Virtual Drive RAID {0}. Using storage {0}'.format(raid, drive_group)) self.cimc_set_mo_by_class_id(class_id="storageVirtualDriveCreatorUsingUnusedPhysicalDrive", params=params) def cimc_delete_all_vnics(self): self.logger('deleting all vNICs') vnic_names = self.cimc_list_vnics().keys() for vnic_name in vnic_names: self.cimc_delete_vnic(vnic_name=vnic_name) def cimc_delete_vnic(self, vnic_name): dn = 'sys/rack-unit-1/adaptor-MLOM/host-eth-{}'.format(vnic_name) if 'eth0' in vnic_name or 'eth1' in vnic_name: # no way to delete eth0 or eth1, so reset them to default self.logger(message='Resetting vNIC ' + vnic_name) ethX = self.handle.query_dn(dn) ethX.mac = 'AUTO' ethX.mtu = 1500 ethX.pxe_boot = False ethX.uplink_port = vnic_name[-1] self.handle.set_mo(ethX) profile = self.handle.query_dn('sys/rack-unit-1/adaptor-{}/host-eth-{}/general'.format(pci_slot_id, name)) profile.vlan = None profile.order = 'ANY' self.handle.set_mo(profile) else: self.logger(message='Deleting vNIC ' + dn) vnic = self.handle.query_dn(dn=dn) self.handle.remove_mo(vnic) def cimc_set_ssh_timeout(self, timeout=3600): self.cmd('set_imc_managedobject', in_mo=None, class_id='commHttps', params={'Dn': 'sys/svc-ext/https-svc', 'sessionTimeout': str(timeout)}) def cimc_change_boot_order(self, pxe_order=1, hdd_order=2): self.logger('updating boot order: PXE as #{0}, HDD as #{1}'.format(pxe_order, hdd_order)) boot_configs = [{'params': {'Dn': 'sys/rack-unit-1/boot-policy/lan-read-only', 'Order': pxe_order, 'Access': 'read-only'}, 'class_id': 'LsbootLan'}, {'params': {'Dn': 'sys/rack-unit-1/boot-policy/storage-read-write', 'Order': hdd_order, 'Access': 'read-write'}, 'class_id': 'LsbootStorage'}] for boot_config in boot_configs: boot_device = self.cmd('get_imc_managedobject', in_mo=None, class_id=None, params={'Dn': boot_config['params']['Dn']}) if boot_device: self.cmd('set_imc_managedobject', in_mo=boot_device, class_id=None, params=boot_config['params']) else: self.cmd('add_imc_managedobject', in_mo=None, class_id=boot_config['class_id'], params=boot_config['params']) def cimc_create_vnic(self, pci_slot_id, uplink_port, order, name, mac, vlan, is_pxe_enabled): from imcsdk.mometa.adaptor.AdaptorHostEthIf import AdaptorHostEthIf self.logger(message='creating vNIC {} on PCI id {} uplink {} mac={} vlan={} pxe: {}'.format(name, pci_slot_id, uplink_port, mac, vlan, is_pxe_enabled)) if name in ['eth0', 'eth1']: # eth0 and eth1 are default, only possible to modify there parameters, no way to rename ot delete ethX = self.handle.query_dn('sys/rack-unit-1/adaptor-{}/host-eth-{}'.format(pci_slot_id, name)) ethX.mac = mac ethX.mtu = 1500 ethX.pxe_boot = is_pxe_enabled self.handle.set_mo(ethX) else: vnic = AdaptorHostEthIf(parent_mo_or_dn='sys/rack-unit-1/adaptor-' + pci_slot_id, name=name, mac=mac, mtu=1500, pxe_boot=is_pxe_enabled, uplink_port=uplink_port) self.handle.add_mo(vnic) profile = self.handle.query_dn('sys/rack-unit-1/adaptor-{}/host-eth-{}/general'.format(pci_slot_id, name)) profile.vlan = vlan profile.order = order self.handle.set_mo(profile) def cimc_get_power_status(self): return self.handle.query_classid('computeRackUnit')[0].get_attr('OperPower') def _cimc_power(self, requested_state): import time self.logger('power {0}'.format(requested_state)) rack = self.handle.query_dn('sys/rack-unit-1') rack.admin_power = requested_state self.handle.set_mo(rack) time.sleep(120) # wait for the server to come up def cimc_power_down(self): current_power_state = self.cimc_get_power_status() if current_power_state == 'on': self._cimc_power('down') else: self.log(' is already OFF') def cimc_power_up(self): current_power_state = self.cimc_get_power_status() if current_power_state == 'off': self._cimc_power('up') else: self.log(' is already ON') def cimc_reset(self): pass # from ImcSdk.ImcMos import ComputeRackUnit # mo = handle.config_resolve_dn("sys/rack-unit-1") # mo.admin_power = ComputeRackUnit.CONST_ADMIN_POWER_BMC_RESET_IMMEDIATE # set_imc_managedobject(mo, class_id="ComputeRackUnit", params={ComputeRackUnit.ADMIN_POWER: # ComputeRackUnit.CONST_ADMIN_POWER_BMC_RESET_IMMEDIATE, # ComputeRackUnit.DN: "sys/rack-unit-1"}) def cimc_power_cycle(self): current_power_state = self.cimc_get_power_status() self._cimc_power('up' if current_power_state == 'off' else 'cycle-immediate') def cimc_recreate_vnics(self): actual_vnics = self.cimc_list_all_nics_and_vnics() actual_loms = [x for x in self.cimc_list_pci_nic_ports() if 'L' in x['Dn']] for nic_order, nic in enumerate(self.lom_nics_dic.values()): # NIC order starts from 0 names = nic.get_names() macs = nic.get_macs() port_ids = nic.get_port_ids() for name, mac, port_id in zip(names, macs, port_ids): if port_id in ['LOM-1', 'LOM-2']: actual_mac = actual_loms[port_id]['mac'] if mac.upper() != actual_mac.upper(): raise ValueError('{}: "{}" actual mac is "{}" while requested "{}". Edit lab config!'.format(self.id, port_id, actual_mac, mac)) else: if 'eth' not in self.get_nics() and nic.is_ssh(): # if no NIC called eth and it's nic on ssh network, use default eth0, eth1 if name in actual_vnics: self.cimc_delete_vnic(vnic_name=name) name = 'eth' + name[-1] if name in actual_vnics: if mac == actual_vnics[name]['mac'] and str(nic.get_vlan_id()) == str(actual_vnics[name]['vlan']): # this nic is already in CIMC self.logger(message='vNIC {} is already configured'.format(name)) if name in actual_vnics: actual_vnics.pop(name) continue else: self.logger('deleting {} since mac or vlan is not correct: {}'.format(name, actual_vnics[name])) self.cimc_delete_vnic(vnic_name=name) pci_slot_id, uplink_port = port_id.split('/') self.cimc_create_vnic(pci_slot_id=pci_slot_id, uplink_port=uplink_port, order='ANY', name=name, mac=mac, vlan=nic.get_vlan_id(), is_pxe_enabled=nic.is_pxe()) if name in actual_vnics: actual_vnics.pop(name) for vnic_name in actual_vnics.keys(): # delete all actual which are not requested self.cimc_delete_vnic(vnic_name) def cimc_configure(self, is_debug=False): self._dump_xml = is_debug lab_type = self.pod.get_type() self.logger('configuring for {}'.format(lab_type)) self.cimc_set_hostname() self.cimc_power_up() if self.pod.get_type() == self.pod.MERCURY: self.cimc_disable_loms_in_bios() else: is_any_nic_on_lom = any(map(lambda x: x.is_on_lom(), self.get_nics().values())) if is_any_nic_on_lom: self.cimc_enable_loms_in_bios() self.cimc_recreate_vnics() self.cimc_change_boot_order(pxe_order=1, hdd_order=2) # if lab_type == self.lab().LAB_MERCURY: # self.create_storage('1', 2, True) def cimc_get_adaptors(self): r = self.handle.query_classid('AdaptorUnit') return r def cimc_set_mlom_adaptor(self, pci_slot, n_vnics): self.logger(message='allowing MLOM-{} to use up to {} vNICs'.format(pci_slot, n_vnics)) # self.cimc_set_mo_by_class_id(class_id='adaptorUnit', params={'dn': 'sys/rack-unit-1/adaptor-{0}'.format(pci_slot), 'description': str(self)}) self.cimc_set_mo_by_class_id(class_id='adaptorGenProfile', params={'dn': 'sys/rack-unit-1/adaptor-{0}/general'.format(pci_slot), 'fipMode': 'enabled', 'vntagMode': 'enabled', 'numOfVMFexIfs': n_vnics}) def cimc_get_mgmt_nic(self): return self.handle.query_classid('mgmtIf')[0] def cimc_set_hostname(self): current = self.cimc_get_mgmt_nic() new_cimc_hostname = '{}-ru{}-{}'.format(self.pod, self.hardware, self.id) if new_cimc_hostname != current.hostname: self.logger(message='setting hostname to {}'.format(new_cimc_hostname)) current.hostname = new_cimc_hostname self.handle.set_mo(current) else: self.logger(message='hostname is already {}'.format(new_cimc_hostname)) @staticmethod def cimc_deduce_wiring_by_lldp(pod): import yaml from lab.wire import Wire cimc_info_file_path = pod.get_artifact_file_path('cimc-{}.yaml'.format(pod)) try: with open(cimc_info_file_path) as f: cimc_info_dic = yaml.load(f.read()) except IOError: cimc_info_dic = {} for cimc in sorted(pod.cimc_servers_dic.values()): cimc_info_dic[cimc.oob_ip] = cimc.cimc_list_all_nics() # returns dic of {port_id: mac} with open(cimc_info_file_path, mode='w') as f: yaml.dump(cimc_info_dic, f) wires_cfg = [] for node in sorted(pod.cimc_servers_dic.values()): for port1, mac in cimc_info_dic[node.oob_ip].items(): neis = [x.find_neighbour_with_mac(mac=mac, cimc_port_id=port1) for x in pod.switches] neis = filter(lambda n: n is not None, neis) if neis: assert len(neis) == 1, 'More then 1 switch is found connected to {} {}'.format(node, port1) nei = neis[0] wires_cfg.append({'node1': node.id, 'port1': port1, 'mac': mac, 'node2': nei.n9.id, 'port2': nei.port.port_id, 'pc-id': nei.port.pc_id}) else: wires_cfg.append({'node1': node.id, 'port1': port1, 'mac': mac, 'node2': None, 'port2': None, 'pc-id': None}) pod.wires.extend(Wire.add_wires(pod=pod, wires_cfg=wires_cfg))
def main(): args = get_args() params = get_device_parameters(args) valid_addresses = get_valid_addresses(args.ucs_host, params['alternate_addresses']) login_success = False errors = [] # Try all valid addresses until one succeeds or they all fail. for host_addr in valid_addresses: if params['server_type'] == 'ucsm': handle = UcsHandle(host_addr, params['username'], params['password']) try: if not handle.login(): errors.append("Failed to connect to {} as user {}!".format( args.ucs_host, params['username'])) continue else: login_success = True except Exception as e: errors.append(str(e)) continue if args.severity is not None: # Build a filter string that we will pass into an API call (UCSM only) filter_str = '(severity, "{}", type="eq")'.format( args.severity) else: filter_str = None # Output the list of faults, if any, with the given severity level fault_list = handle.query_classid('faultInst', filter_str=filter_str) for fault in fault_list: print('{}: [{}] {}: {}'.format(fault.created, fault.severity, fault.cause, fault.descr)) handle.logout() break elif params['server_type'] == 'imc': handle = ImcHandle(host_addr, params['username'], params['password']) try: if not handle.login(timeout=10): errors.append("Failed to connect to {} as user {}!".format( args.ucs_host, params['username'])) continue else: login_success = True except IndexError: errors.append( 'An exception was thrown trying to connect to {}. ' 'It may be running an old/unsupported firmware version.' ''.format(args.ucs_host)) continue except Exception as e: errors.append(str(e)) continue # Output the list of faults, if any, with the given severity level fault_list = handle.query_classid('faultInst') for fault in fault_list: if args.severity is None or args.severity == fault.severity: print('{}: [{}] {}: {}'.format(fault.created, fault.severity, fault.cause, fault.descr)) handle.logout() break else: print("Unrecognized server type '{}'. " "It should be 'ucsm' or 'imc'.".format( params['server_type'])) exit(1) if not login_success: print('Failed all connection attempts:\n{}'.format('\n'.join(errors)))
from imcsdk.imchandle import ImcHandle # Create a connection handle handle = ImcHandle("192.168.1.23", "admin", "password") # Create a connection handle handle.login() # Query for the NTP Server imc_ntp_server_mo = handle.query_dn("sys/svc-ext/ntp-svc") print "NTP config inicial: " print imc_ntp_server_mo # Set NTP Server parameters imc_ntp_server_mo.ntp_enable = "yes" imc_ntp_server_mo.ntp_server1 = "5.5.5.5" # Commit the changes to the IMC handle.set_mo(imc_ntp_server_mo) print "NTP config applied" # Verify changes applied imc_ntp_server_mo = handle.query_dn("sys/svc-ext/ntp-svc") print "NTP new config: " print imc_ntp_server_mo # Logout from the server handle.logout()
def test_001_create_handle(): handle = ImcHandle("192.168.1.1", "admin", "my_extra_secure_password") assert_equal(handle.username, "admin") assert_equal(handle.ip, "192.168.1.1")
ro_json = ro.json() print " Storage 0 Name: %s" % ro_json['Name'] num_good_disks = 0 for device in ro_json['Devices']: if device['Status']['State'] == 'Enabled' and device['Status'][ 'Health'] == 'OK': print " Disk %s is Enabled and OK" % device['Name'] num_good_disks += 1 print " Number of Enabled, OK disks: %d" % num_good_disks pause = raw_input('') # IMC XML API operations # ---------------------- # setup RAID as specified in settings file handle = ImcHandle(settings_file['ip'], settings_file['user'], settings_file['pw'], secure=is_secure) handle.login() from imcsdk.mometa.storage.StorageVirtualDriveCreatorUsingUnusedPhysicalDrive import StorageVirtualDriveCreatorUsingUnusedPhysicalDrive for raid_params in settings_file['raid_config']: print "Create virtual drive %s with RAID level %s" % ( raid_params['drive_name'], raid_params['raid_level']) mo = StorageVirtualDriveCreatorUsingUnusedPhysicalDrive( parent_mo_or_dn=raid_params['dn'], virtual_drive_name=raid_params['drive_name'], raid_level=raid_params['raid_level'], size=raid_params['size'], drive_group=raid_params['drive_group'], write_policy="Write Through",
from imcsdk.imchandle import ImcHandle import argparse parser = argparse.ArgumentParser() parser.add_argument("-i", "--ip", help="IP Address") parser.add_argument("-u", "--username", help="Username") parser.add_argument("-p", "--password", help="Password") args = parser.parse_args() handle = ImcHandle(ip=args.ip, username=args.username, password=args.password) handle.login() rack = handle.query_dn('sys/rack-unit-1') print "Hostname:", rack.name, "Model:", rack.model, "Serial Number:", rack.serial storage_controllers = handle.query_classid("storageVirtualDrive") for storage_controller in storage_controllers: print "VD Name:", storage_controller.virtual_drive_name, "VD Status:", storage_controller.vd_status, "Raid Level:", storage_controller.raid_level, "Health:", storage_controller.health bbus = handle.query_classid("storageRaidBattery") for bbu in bbus: print "BBU Status:", bbu.battery_status, "BBU Health:", bbu.health, "BBU Learn Cycle:", bbu.learn_cycle_status, "Next Learn cycle:", bbu.next_learn_cycle local_disks = handle.query_classid("StorageLocalDisk") for local_disk in local_disks: print "Disk ID:", local_disk.id, "Disk Serial Number:", local_disk.drive_serial_number, "Disk State:", local_disk.drive_state, "Disk Health:", local_disk.health, "Predicitive failure count:", local_disk.predictive_failure_count handle.logout()