def test_session_init(self, mock_logon): """Ensure proper parameter handling in the Session initializer.""" logfx = self.useFixture(fx.LoggingFx()) # No params - local, file-based, http. sess = adp.Session() self.assertTrue(sess.use_file_auth) self.assertIsNone(sess.password) self.assertTrue(sess.username.startswith('pypowervm_')) self.assertEqual(3, len(sess.username.split('_'))) self.assertEqual('localhost', sess.host) self.assertEqual('http', sess.protocol) self.assertEqual(12080, sess.port) self.assertEqual('http://localhost:12080', sess.dest) self.assertEqual(1200, sess.timeout) self.assertEqual('/etc/ssl/certs/', sess.certpath) self.assertEqual('.crt', sess.certext) # localhost + http is okay self.assertEqual(0, logfx.patchers['warn'].mock.call_count) # Ensure proper protocol, port, and certpath defaulting when remote sess = adp.Session(host='host', username='******', password='******') self.assertFalse(sess.use_file_auth) self.assertIsNotNone(sess.password) self.assertEqual('user', sess.username) self.assertEqual('host', sess.host) self.assertEqual('https', sess.protocol) self.assertEqual(12443, sess.port) self.assertEqual('https://host:12443', sess.dest) self.assertEqual(1200, sess.timeout) self.assertEqual('/etc/ssl/certs/', sess.certpath) self.assertEqual('.crt', sess.certext) # non-localhost + (implied) https is okay self.assertEqual(0, logfx.patchers['warn'].mock.call_count)
def init_host(self, host): """Initialize anything that is necessary for the driver to function. Includes catching up with currently running VMs on the given host. """ # Build the adapter. May need to attempt the connection multiple times # in case the PowerVM management API service is starting. # TODO(efried): Implement async compute service enable/disable like # I73a34eb6e0ca32d03e54d12a5e066b2ed4f19a61 self.adapter = pvm_apt.Adapter( pvm_apt.Session(conn_tries=60), helpers=[log_hlp.log_helper, vio_hlp.vios_busy_retry_helper]) # Make sure the Virtual I/O Server(s) are available. pvm_par.validate_vios_ready(self.adapter) self.host_wrapper = pvm_ms.System.get(self.adapter)[0] # Do a scrub of the I/O plane to make sure the system is in good shape LOG.info("Clearing stale I/O connections on driver init.") pvm_stor.ComprehensiveScrub(self.adapter).execute() # Initialize the disk adapter # TODO(efried): Other disk adapters (localdisk), by conf selection. self.disk_dvr = ssp.SSPDiskAdapter(self.adapter, self.host_wrapper.uuid) self.image_api = image.API() LOG.info("The PowerVM compute driver has been initialized.")
def test_session_ext_cfg(self, mock_load, mock_get_evts): """Test Session init with external config from env var.""" mock_get_evts.return_value = {'general': 'init'}, [], [] with mock.patch.dict(os.environ, {'PYPOWERVM_SESSION_CONFIG': 'path'}): sess = adp.Session() mock_load.assert_called_once_with('sesscfg', 'path') mock_load.return_value.session_config.assert_called_once_with(sess)
def test_Session(self, mock_sleep): """Ensure Session can be instantiated, and test logon retries.""" # Passing in 0.0.0.0 will raise a ConnectionError or SSLError, but only # if it gets past all the __init__ setup since _logon is the last # statement. self.assertRaises((pvmex.ConnectionError, pvmex.SSLError), adp.Session, '0.0.0.0', 'uid', 'pwd') mock_sleep.assert_not_called() # Now set up a retry self.assertRaises((pvmex.ConnectionError, pvmex.SSLError), adp.Session, '0.0.0.0', 'uid', 'pwd', conn_tries=5) # 5 tries = 4 sleeps mock_sleep.assert_has_calls([mock.call(2)] * 4) # Ensure 404 on the logon URI also retries mock_sleep.reset_mock() with mock.patch('requests.Session.request') as mock_rq: mock_rq.side_effect = [ mock.Mock(status_code=404), mock.Mock(status_code=204) ] adp.Session(conn_tries=5) # Only retried once, after the 404 mock_sleep.assert_called_once_with(2)
def setUp(self): super(TestAdapter, self).setUp() """Set up a mocked Session instance.""" # Init test data host = '0.0.0.0' user = '******' pwd = 'pwd' auditmemento = 'audit' # Create a Response object, that will serve as a mock return value my_response = self._mk_response(200, logon_text) # Mock out the method and class we are not currently testing with mock.patch('requests.Session') as mock_session: session = mock_session.return_value session.request.return_value = my_response # Create session for the test to use self.sess = adp.Session(host, user, pwd, auditmemento=auditmemento, certpath=None) # Mock out the logoff, which gets called when the session # goes out of scope during tearDown() self.sess._logoff = mock.Mock()
def init_host(self, host): """Initialize anything that is necessary for the driver to function. Includes catching up with currently running VMs on the given host. """ LOG.warning( 'The powervm virt driver is deprecated and may be removed in a ' 'future release. The driver is not tested by the OpenStack ' 'project nor does it have clear maintainers and thus its quality' 'can not be ensured. If you are using the driver in production ' 'please let us know the openstack-discuss mailing list or on IRC' ) # Build the adapter. May need to attempt the connection multiple times # in case the PowerVM management API service is starting. # TODO(efried): Implement async compute service enable/disable like # I73a34eb6e0ca32d03e54d12a5e066b2ed4f19a61 self.adapter = pvm_apt.Adapter( pvm_apt.Session(conn_tries=60), helpers=[log_hlp.log_helper, vio_hlp.vios_busy_retry_helper]) # Make sure the Virtual I/O Server(s) are available. pvm_par.validate_vios_ready(self.adapter) self.host_wrapper = pvm_ms.System.get(self.adapter)[0] # Do a scrub of the I/O plane to make sure the system is in good shape LOG.info("Clearing stale I/O connections on driver init.") pvm_stor.ComprehensiveScrub(self.adapter).execute() # Initialize the disk adapter self.disk_dvr = importutils.import_object_ns( DISK_ADPT_NS, DISK_ADPT_MAPPINGS[CONF.powervm.disk_driver.lower()], self.adapter, self.host_wrapper.uuid) self.image_api = glance.API() LOG.info("The PowerVM compute driver has been initialized.")
def test_session_clone(self, mock_logoff, mock_logon): sess = adp.Session() # Ensure the id that created the object is recorded. self.assertTrue(hasattr(sess, '_init_by')) # Create a shallow clone and ensure the _init_by does not match the id sess_clone = copy.copy(sess) self.assertTrue(hasattr(sess_clone, '_init_by')) self.assertNotEqual(sess._init_by, id(sess_clone)) # Now test what happens when the clone is garbage collected. self.assertFalse(mock_logoff.called) sess_clone = None gc.collect() # The clone was not logged off self.assertFalse(mock_logoff.called) if six.PY2: # Ensure deep copies raise an exception. self.assertRaises(TypeError, copy.deepcopy, sess) else: # Or if works, it is not logged off sess_deepclone = copy.deepcopy(sess) # Make pep8 happy, use the clone self.assertIsNotNone(sess_deepclone) sess_deepclone = None gc.collect() # The clone was not logged off self.assertFalse(mock_logoff.called) sess = None gc.collect() # The original session was logged off self.assertTrue(mock_logoff.called)
def init_host(self, host): """Initialize anything that is necessary for the driver to function. Includes catching up with currently running VMs on the given host. """ # Build the adapter. May need to attempt the connection multiple times # in case the PowerVM management API service is starting. # TODO(efried): Implement async compute service enable/disable like # I73a34eb6e0ca32d03e54d12a5e066b2ed4f19a61 self.adapter = pvm_apt.Adapter( pvm_apt.Session(conn_tries=60), helpers=[log_hlp.log_helper, vio_hlp.vios_busy_retry_helper]) # Make sure the Virtual I/O Server(s) are available. pvm_par.validate_vios_ready(self.adapter) self.host_wrapper = pvm_ms.System.get(self.adapter)[0] LOG.info("The PowerVM compute driver has been initialized.")
def __init__(self): super(PowerVMInspector, self).__init__() # Build the adapter to the PowerVM API. self.adpt = pvm_adpt.Adapter( pvm_adpt.Session(), helpers=[log_hlp.log_helper, vio_hlp.vios_busy_retry_helper]) # Get the host system UUID host_uuid = self._get_host_uuid(self.adpt) # Ensure that metrics gathering is running for the host. pvm_mon_util.ensure_ltm_monitors(self.adpt, host_uuid) # Get the VM Metric Utility self.vm_metrics = pvm_mon_util.LparMetricCache(self.adpt, host_uuid)
def __init__(self, conf): super(PowerVMInspector, self).__init__(conf) # Build the adapter. May need to attempt the connection multiple times # in case the REST server is starting. session = pvm_adpt.Session(conn_tries=300) self.adpt = pvm_adpt.Adapter( session, helpers=[log_hlp.log_helper, vio_hlp.vios_busy_retry_helper]) # Get the host system UUID host_uuid = self._get_host_uuid(self.adpt) # Ensure that metrics gathering is running for the host. pvm_mon_util.ensure_ltm_monitors(self.adpt, host_uuid) # Get the VM Metric Utility self.vm_metrics = pvm_mon_util.LparMetricCache(self.adpt, host_uuid)
def setup_adapter(self): """Configures the pypowervm adapter and utilities.""" self.adapter = pvm_adpt.Adapter( pvm_adpt.Session(), helpers=[log_hlp.log_helper, vio_hlp.vios_busy_retry_helper]) self.host_uuid = utils.get_host_uuid(self.adapter)
def test_logon(self, mock_session, mock_validate_cert): """Ensure a Session can be created and log on to PowerVM.""" # Init test data host = '0.0.0.0' user = '******' pwd = 'pwd' auditmemento = 'audit' # Create a Response object, that will serve as a mock return value my_response = req_mod.Response() my_response.status_code = 200 my_response.reason = 'OK' dict_headers = {'content-length': '576', 'x-powered-by': 'Servlet/3.0', 'set-cookie': 'JSESSIONID=0000a41BnJsGTNQvBGERA3wR1nj:' '759878cb-4f9a-4b05-a09a-3357abfea3b4; P' 'ath=/; Secure; HttpOnly, CCFWSESSION=E4' 'C0FFBE9130431DBF1864171ECC6A6E; Path=/;' ' Secure; HttpOnly', 'expires': 'Thu, 01 Dec 1994 16:00:00 GMT', 'x-transaction-id': 'XT10000073', 'cache-control': 'no-cache="set-cookie, set-cookie2"', 'date': 'Wed, 23 Jul 2014 21:51:10 GMT', 'content-type': 'application/vnd.ibm.powervm.web+xml; ' 'type=LogonResponse'} my_response.headers = req_struct.CaseInsensitiveDict(dict_headers) my_response._content = _logon_response_password # Mock out the method and class we are not currently testing session = mock_session.return_value session.request.return_value = my_response # Run the actual test result = adp.Session(host, user, pwd, auditmemento=auditmemento) # Verify the result self.assertTrue(result._logged_in) self.assertEqual('PUIoR6x0kP6fQqA7qZ8sLZQJ8MLx9JHfLCYzT4oGFSE2WaGIhaFX' 'IyQYvbqdKNS8QagjBpPi9NP7YR_h61SOJ3krS_RvKAp-oCf2p8x8' 'uvQrrDv-dUzc17IT5DkR7_jv2qc8iUD7DJ6Rw53a17rY0p63KqPg' '9oUGd6Bn3fNDLiEwaBR4WICftVxUFj-tfWMOyZZY2hWEtN2K8ScX' 'vyFMe-w3SleyRbGnlR34jb0A99s=', result._sessToken) self.assertEqual(1, mock_validate_cert.call_count) # No X-MC-Type header => 'HMC' is assumed. self.assertEqual('HMC', result.mc_type) # Now test file-based authentication and X-MC-Type my_response._content = _logon_response_file # Local/HMC is bad self.assertRaises(pvmex.Error, adp.Session) my_response.headers['X-MC-Type'] = 'PVM' result = adp.Session() # Verify the result. self.assertTrue(result._logged_in) # Token read from token_file, as indicated by logon_file.xml response. self.assertEqual('file-based-auth-token', result._sessToken) # validate_certificate should not have been called again self.assertEqual(1, mock_validate_cert.call_count) self.assertEqual('PVM', result.mc_type)
def test_session_init_remote_http(self, mock_logon): # Proper port defaulting and warning emitted when remote + http with self.assertLogs(adp.__name__, 'WARNING'): sess = adp.Session(host='host', protocol='http') self.assertEqual(12080, sess.port)
def test_traits_into_wrappers(self, mock_request): # Note traits param is None, which reflects the real value of # self.traits during _logon's request. httpresp = req_mod.Response() httpresp._content = _logon_response_text httpresp.status_code = 200 httpresp.headers = req_struct.CaseInsensitiveDict({ 'X-MC-Type': 'PVM', 'content-type': 'application/vnd.ibm.powervm.web+xml; type=LogonResponse' }) mock_request.return_value = httpresp sess = adp.Session() self.assertEqual('PVM', sess.mc_type) self.assertIsNotNone(sess.traits) self.assertTrue(sess.traits.local_api) self.assertFalse(sess.traits._is_hmc) adapter = adp.Adapter(sess) self.assertEqual(sess.traits, adapter.traits) # Response => Feed => Entrys => EntryWrappers => sub-ElementWrappers httpresp._content = _feed_file resp = adapter.read('NetworkBridge') self.assertEqual(sess.traits, resp.adapter.traits) nblist = net.NetBridge.wrap(resp) for nb in nblist: self.assertIsInstance(nb, net.NetBridge) self.assertEqual(sess.traits, nb.traits) seas = nblist[0].seas for sea in seas: self.assertIsInstance(sea, net.SEA) self.assertEqual(sess.traits, sea.traits) trunk = seas[0].primary_adpt self.assertIsInstance(trunk, net.TrunkAdapter) self.assertEqual(sess.traits, trunk.traits) # Response => Entry => EntryWrapper => sub-EntryWrappers # => sub-sub-ElementWrapper httpresp._content = _entry_file resp = adapter.read('VolumeGroup', root_id='abc123') self.assertEqual(sess.traits, resp.adapter.traits) vgent = stor.VG.wrap(resp) self.assertIsInstance(vgent, stor.VG) self.assertEqual(sess.traits, vgent.traits) pvs = vgent.phys_vols for pvent in pvs: self.assertIsInstance(pvent, stor.PV) self.assertEqual(sess.traits, pvent.traits) # Building raw wrappers from scratch class MyEntryWrapper(ewrap.EntryWrapper): schema_type = 'SomeObject' @classmethod def bld(cls, adpt): return super(MyEntryWrapper, cls)._bld(adpt) mew = MyEntryWrapper.bld(adapter) self.assertIsInstance(mew, MyEntryWrapper) self.assertEqual(sess.traits, mew.traits) class MyElementWrapper(ewrap.ElementWrapper): schema_type = 'SomeObject' @classmethod def bld(cls, adpt): return super(MyElementWrapper, cls)._bld(adpt) mew = MyElementWrapper.bld(adapter) self.assertIsInstance(mew, MyElementWrapper) self.assertEqual(sess.traits, mew.traits)
NODE_HOSTNAME = 'vios1.example.com' NODE_MTMS = '8247-22L*1234D0A' NODE_LPARID = 2 NODE_URI = ('https://9.1.2.3:12443/rest/api/uom/VirtualIOServer/' '58C9EB1D-7213-4956-A011-77D43CC4ACCC') REPOS_UDID = '01M0lCTTIxNDUxMjQ2MDA1MDc2ODAyODI4NjFEODgwMDAwMDAwMDAwMDAwMg==' REPOS_NAME = 'hdisk2' DATA1_UDID = '01M0lCTTIxNDUxMjQ2MDA1MDc2ODAyODI4NjFEODgwMDAwMDAwMDAwMDAwMw==' DATA1_NAME = 'hdisk3' DATA2_UDID = '01M0lCTTIxNDUxMjQ2MDA1MDc2ODAyODI4NjFEODgwMDAwMDAwMDAwMDAwNA==' DATA2_NAME = 'hdisk4' DATA3_UDID = '01M0lCTTIxNDUxMjQ2MDA1MDc2ODAyODI4NjFEODgwMDAwMDAwMDAwMDAwNQ==' DATA3_NAME = 'hdisk5' # <<<Replace the foregoing with real values<<< sess = adp.Session(HOST, USER, PASS, certpath=None) adap = adp.Adapter(sess) # Option 1: MTMS, LPAR_ID, Hostname node1 = clust.Node.bld(adap, hostname=NODE_HOSTNAME, mtms=NODE_MTMS, lpar_id=NODE_LPARID) # Option 2: URI node2 = clust.Node.bld(adap, vios_uri=NODE_URI) repos = stor.PV.bld(adap, udid=REPOS_UDID, name=REPOS_NAME) data_pvs = [ stor.PV.bld(adap, udid=udid, name=name)
def main(argv): new_response = pvmhttp.PVMResp() output_file = None file_to_refresh = None aindex = 0 while aindex < len(argv): if argv[aindex] == '-host': aindex += 1 new_response.host = argv[aindex] elif argv[aindex] == '-user': aindex += 1 new_response.user = argv[aindex] elif argv[aindex] == '-pw': aindex += 1 new_response.pw = argv[aindex] elif argv[aindex] == '-path': aindex += 1 new_response.path = argv[aindex] elif argv[aindex] == '-comment': aindex += 1 new_response.comment = argv[aindex] elif argv[aindex] == '-output': aindex += 1 output_file = argv[aindex] elif argv[aindex] == '-refresh': aindex += 1 file_to_refresh = argv[aindex] else: print("Unknown argument ", argv[aindex]) usage() aindex += 1 if file_to_refresh: rc = refresh_response(file_to_refresh) exit(rc) if (new_response.host is None or new_response.user is None or new_response.pw is None or new_response.path is None or output_file is None): usage() print("Connecting to ", new_response.host) conn = adp.Session(new_response.host, new_response.user, new_response.pw, certpath=None) oper = adp.Adapter(conn) print("Reading path: ", new_response.path) new_response.response = oper.read(new_response.path) print("Received ", new_response.response) orig_file_name = output_file dirname = os.path.dirname(output_file) if dirname is None or dirname == '': dirname = os.path.dirname(__file__) output_file = os.path.join(dirname, output_file) new_response.save(output_file) print("Response has been saved in ", output_file) print("Use the pvmhttp.load_pvm_resp('%s') method " "to load it in your testcase " % orig_file_name) print("You can have the %s file rebuilt by running: " "create_httpresp -refresh %s" % (orig_file_name, orig_file_name))