def get_content(self, name): base_path = self._get_config_set_drive_path() content_path = os.path.join(base_path, name) if not os.path.exists(content_path): raise base.NotExistingMetadataException() with open(content_path, 'rb') as f: return f.read()
def _get_data(self, path): norm_path = os.path.normpath(os.path.join(self._metadata_path, path)) try: with open(norm_path, 'rb') as stream: return stream.read() except IOError: raise base.NotExistingMetadataException()
def _get_data(self, name): # Return the requested field's value or raise an error if not found. if name not in self._dict_content: msg = "Metadata {} not found".format(name) LOG.debug(msg) raise base.NotExistingMetadataException(msg) return self._dict_content[name]
def _get_response(self, req): try: return request.urlopen(req) except error.HTTPError as ex: if ex.code == 404: raise base.NotExistingMetadataException() else: raise
def _get_data(self, path): """Used to read file from path string. NOTE: Not used for http data""" norm_path = os.path.normpath(os.path.join(self._metadata_path, path)) try: with open(norm_path, 'rb') as stream: return stream.read() except IOError: raise base.NotExistingMetadataException()
def test_get_network_details_v2_no_metadata(self, mock_log_exception, mock_get_network_data): mock_get_network_data.side_effect = ( base.NotExistingMetadataException('failed to get metadata')) network_details = self._service.get_network_details_v2() self.assertIsNone(network_details) self.assertTrue(mock_log_exception.called)
def _get_data(self, path): LOG.info('Init LocalFileService _get_data') # 读取文件数据 norm_path = os.path.normpath(os.path.join(self._metadata_path, path)) try: with open(norm_path, 'rb') as stream: return stream.read() except IOError: raise base.NotExistingMetadataException()
def _get_data(self, path): """Getting required metadata using CloudStack metadata API.""" metadata_uri = urllib.parse.urljoin(self._metadata_uri, path) try: content = self._http_request(metadata_uri) except urllib.error.HTTPError as exc: if exc.code == 404: raise base.NotExistingMetadataException() raise return content
def _get_data(self, path): # path.normpath规范化路径 norm_path = os.path.normpath(os.path.join(self._metadata_path, path)) try: # rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式 with open(norm_path, 'rb') as stream: # 读取整个文件 return stream.read() except IOError: raise base.NotExistingMetadataException()
def _get_data(self, name): # get the content if it's not already retrieved if not self._raw_content: if not self._context_path: msg = "No metadata file path found" LOG.debug(msg) raise base.NotExistingMetadataException(msg) with open(self._context_path, "r") as fin: self._raw_content = fin.read() # fill the dict with values vardict = OpenNebulaService._parse_shell_variables( self._raw_content) self._dict_content.update(vardict) # return the requested value if name not in self._dict_content: msg = "Metadata {} not found".format(name) LOG.debug(msg) raise base.NotExistingMetadataException(msg) return self._dict_content[name]
def _get_ovf_env_path(self): drive_path = self._get_config_drive_path() ovf_env_path = os.path.join(drive_path, CONF.ovf.config_file_name) if not os.path.exists(ovf_env_path): raise base.NotExistingMetadataException( "File %s does not exist in drive %s" % (CONF.ovf.config_file_name, drive_path)) return ovf_env_path
def _get_config_drive_path(self): if not self._config_drive_path: for drive_letter in self._osutils.get_logical_drives(): label = self._osutils.get_volume_label(drive_letter) if label and label.lower() == CONF.ovf.drive_label.lower(): self._config_drive_path = drive_letter if not self._config_drive_path: raise base.NotExistingMetadataException( "No drive with label %s could be found" % CONF.ovf.drive_label) return self._config_drive_path
def _parse_context(self): # Get the content if it's not already retrieved and parse it. if not self._raw_content: if not self._context_path: msg = "No metadata file path found" LOG.debug(msg) raise base.NotExistingMetadataException(msg) with open(self._context_path, "rb") as fin: self._raw_content = fin.read() # fill the dict with values vardict = OpenNebulaService._parse_shell_variables( self._raw_content) self._dict_content.update(vardict)
def test_test_api(self, mock_http_request): url = '127.0.0.1' mock_http_request.side_effect = [ '200 OK. Successfully!', # Request to Web Service urllib.error.HTTPError(url=url, code=404, hdrs={}, fp=None, msg='Testing 404 Not Found.'), urllib.error.HTTPError(url=url, code=427, hdrs={}, fp=None, msg='Testing 429 Too Many Requests.'), base.NotExistingMetadataException(), socket.error, ] self.assertTrue(self._service._test_api(url)) for _ in range(3): self.assertFalse(self._service._test_api(url))
def _get_cache_data(self, names, iid=None): # Solves caching issues when working with # multiple names (lists not hashable). # This happens because the caching function used # to store already computed results inside a dictionary # and the keys were strings (and must be anything that # is hashable under a dictionary, that's why the exception # is thrown). names = names[:] if iid is not None: for ind, value in enumerate(names): names[ind] = value.format(iid=iid) for name in names: try: return super(OpenNebulaService, self)._get_cache_data(name) except base.NotExistingMetadataException: pass msg = "None of {} metadata was found".format(", ".join(names)) LOG.debug(msg) raise base.NotExistingMetadataException(msg)
def load(self): super(BSIService, self).load() tries = 10 while tries > 0: try: f = open('C:/URL.tmp', 'r') break except FileNotFoundError: tries = tries - 1 LOG.debug('Could not find file, %i retries remaining', tries) time.sleep(5) if tries == 0: raise base.NotExistingMetadataException() self.URL = f.read() f.close() LOG.debug('%s', self.URL) raw_information = encoding.get_as_string(self._get_data(self.URL)) self.decoded_information = json.loads(raw_information) LOG.debug('%s', self.decoded_information) return True
class TestNoCloudConfigDriveService(unittest.TestCase): def setUp(self): self._win32com_mock = mock.MagicMock() self._ctypes_mock = mock.MagicMock() self._ctypes_util_mock = mock.MagicMock() self._win32com_client_mock = mock.MagicMock() self._pywintypes_mock = mock.MagicMock() self._module_patcher = mock.patch.dict( 'sys.modules', { 'win32com': self._win32com_mock, 'ctypes': self._ctypes_mock, 'ctypes.util': self._ctypes_util_mock, 'win32com.client': self._win32com_client_mock, 'pywintypes': self._pywintypes_mock }) self._module_patcher.start() self.addCleanup(self._module_patcher.stop) self.configdrive_module = importlib.import_module(MODULE_PATH) self._config_drive = ( self.configdrive_module.NoCloudConfigDriveService()) self.snatcher = testutils.LogSnatcher(MODULE_PATH) @mock.patch('os.path.normpath') @mock.patch('os.path.join') def test_get_data(self, mock_join, mock_normpath): fake_path = os.path.join('fake', 'path') with mock.patch('six.moves.builtins.open', mock.mock_open(read_data='fake data'), create=True): response = self._config_drive._get_data(fake_path) self.assertEqual('fake data', response) mock_join.assert_called_with(self._config_drive._metadata_path, fake_path) mock_normpath.assert_called_once_with(mock_join.return_value) @mock.patch('shutil.rmtree') def test_cleanup(self, mock_rmtree): fake_path = os.path.join('fake', 'path') self._config_drive._metadata_path = fake_path mock_mgr = mock.Mock() self._config_drive._mgr = mock_mgr mock_mgr.target_path = fake_path self._config_drive.cleanup() mock_rmtree.assert_called_once_with(fake_path, ignore_errors=True) self.assertEqual(None, self._config_drive._metadata_path) @mock.patch(MODULE_PATH + '.NoCloudConfigDriveService._get_meta_data') def test_get_public_keys(self, mock_get_metadata): fake_key = 'fake key' expected_result = [fake_key] mock_get_metadata.return_value = { 'public-keys': { '0': { 'openssh-key': fake_key } } } result = self._config_drive.get_public_keys() self.assertEqual(result, expected_result) @ddt.data(('', ('V2 network metadata is empty', None)), ('1', ('V2 network metadata is not a dictionary', None)), ('{}', ('V2 network metadata is empty', None)), ('{}}', ('V2 network metadata could not be deserialized', None)), ('{version: 2}', ("Network data version '2' is not supported", None)), (base.NotExistingMetadataException('exc'), ('V2 network metadata not found', True))) @ddt.unpack @mock.patch(MODULE_PATH + '.NoCloudConfigDriveService._get_cache_data') def test_network_details_v2_empty_result(self, input, expected_result, mock_get_cache_data): if expected_result[1]: mock_get_cache_data.side_effect = [input] else: mock_get_cache_data.return_value = input with self.snatcher: result = self._config_drive.get_network_details_v2() self.assertEqual(True, expected_result[0] in self.snatcher.output[0]) self.assertEqual(result, None) mock_get_cache_data.assert_called_with("network-config", decode=True)