def connect(self): ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # ssl_context.verify_mode = ssl.CERT_NONE try: self.si = connect.SmartConnect(host=self._host, port=self._port, user=self._user, pwd=self._pwd, sslContext=ssl_context, **self._kwargs) except ssl.SSLError: try: self.si = connect.SmartConnectNoSSL(host=self._host, port=self._port, user=self._user, pwd=self._pwd, **self._kwargs) except Exception: LOG.Exception( _LE("Exception connect to the specified vcenter using " "specified username and password")) finally: if self.si is None: LOG.error( _LE("Could not connect to the specified vcenter using " "specified username and password"))
def wait(self, interval=5, exc=TimeoutHttpException(), max_time=300, func_exc_max_times=3): start_time = time.time() func_exc_times = 0 while True: try: if self.func(*self.args, **self.kwargs): db_api.db_session() return True except Exception as ex: LOG.exception(_LE('Hamal exception %(ex)s', {'ex': ex})) if func_exc_times >= func_exc_max_times: raise ex func_exc_times = func_exc_times + 1 if time.time() - start_time > max_time: db_api.dispose_engine() LOG.exception(_LE('Hamal exc exception %(exc)s', {'exc', exc})) raise exc time.sleep(5)
def _check_failed_status(self, status): if status.upper() in ('ERROR', ): LOG.error( _LE("%(type)s %(id)s is ERROR", { 'type': self.get_type, 'id': self.get_id })) raise Exception( _LE("%(type)s %(id)s is ERROR", { 'type': self.get_type, 'id': self.get_id }))
def __getattr__(self, name): try: return self.data[name] except KeyError: LOG.error(_LE("%(class_name)s object has no attribute %(name)s"), { 'class_name': self.__class__.__name__, 'name': name }) raise AttributeError( _LE("%(class_name)s object has no attribute %(name)s"), { 'class_name': self.__class__.__name__, 'name': name })
def verify_license_signature(self, license): license = eval(base64.b64decode(license)) signature = license.get('signature') message = license.get('message') if self._public_key is None: self.loading_public_key() try: if hasattr(self._public_key, 'verify'): self._public_key.verify( signature, message, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) # if the version of cryptography == 1.3.x # we should use verifier function to verify sign elif hasattr(self._public_key, 'verify'): verifier = self._public_key.verifier( signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) verifier.update(message) verifier.verify() return True except exceptions.InvalidSignature: LOG.exception(_LE("License signature invalid")) return False
def is_delete(): try: self.show() except HamalException as he: LOG.exception(_LE('Hamal Exception with the %(he)s'), {'he': he}) if he.code == 404: return True
def get_service_url(self, service_name): for service in self.service_catalog['access']['serviceCatalog']: if service_name == service['name']: return service['endpoints'][0]['publicURL'] LOG.exception( _LE("Hamal endpoint exception service name : %(service_name)s"), {"service_name": service_name}) raise HttpException(code=400, message="%s endpoint not found" % service_name)
def start_instance(self, instance_id): instance_url = self._instance_action_url.format( instance_id=instance_id) data = {"os-start": None} try: return post_request(instance_url, body=data, token=self.openstack_user_token, no_resp_content=True) except HamalException as he: LOG.exception( _LE("Start instance exception is : %(he)s", {"he": he})) if he.code != 409: raise he
def verify_token(token): """Verify token information :param token: context to token information """ try: payload = jwt.decode(token, CONF.token.secret, algorithms=['HS256']) payload['email'] = payload['username'] token = create_token(payload) return token except: LOG.exception(_LE('Verify token exception!')) return False
def shutdown(self, until_done=False): self.plugin.nova.stop_instance(self.id) if until_done: for i in range(3): try: wait = Wait(self.is_shutdown) wait.wait(interval=5, max_time=180) except TimeoutHttpException as timeoutHttpException: LOG.exception( _LE( 'Hamal time out http exception is %(timeoutHttpException)s', {'timeoutHttpException': timeoutHttpException})) self.plugin.nova.stop_instance(self.id) raise TimeoutHttpException()
def property_collector(self, container=None, object_type=None, property_spec=None): """Retrieve specified properties of specified objects :param container: A reference to an instance of a Folder, Datacenter, ResourcePool or HostSystem object. :type container: ManagedEntity Object :param object_type: An optional list of managed entity types. The server associates only objects of the specified types with the view. If you specify an empty list, the server uses all types. :type object_type: List :param property_spec: The property specifications need to be parsed. :type property_spec: dict :return: The ObjectContent data objects which retrieved from RetrievePropertiesEx. :useage with vSphere(host='localhost', user='******', pwd='') as vs: container = vs.si.content.rootFolder object_type = [vim.Datacenter] prop_spec = { "VirtualMachine": ["name"] } objects = vs.property_collector(container, object_type, prop_spec) """ # The type of object_type must be list if not isinstance(object_type, list): object_type = [object_type] objs = self.get_container_view(container=container, object_type=object_type) props = self._parse_propspec(property_spec) result = [] try: objects = self._do_property_collector(objs, props) except vmodl.query.InvalidProperty: LOG.error(_LE("Query invalid property")) raise for obj in objects: value = dict() for prop in obj.propSet: value[prop.name] = prop.val result.append(value) return result
def _server_list(self, req, body): vc = body.get('vc') user = body.get('user') pwd = body.get('pwd') uri = body.get('uri') servers = self._list_servers_on_exsi(vc, user, pwd, uri) if not isinstance(servers, list): return servers servers_list = [] for server in servers: try: server = self._server_detail(server)['server'] if not server.get('template', False): servers_list.append(server) except KeyError: LOG.error(_LE('Cannot get server detail')) return {"servers": servers_list}
def __init__(self, name, app, host=None, port=None, pool_size=None, protocol=eventlet.wsgi.HttpProtocol, backlog=128, use_ssl=False): """Initialize, but do not start, a WSGI server. :param name: Pretty name for logging. :param app: The WSGI application to serve. :param host: IP address to serve the application. :param port: Port number to server the application. :param pool_size: Maximum number of eventlets to spawn concurrently. :returns: None """ # Allow operators to customize http requests max header line size. eventlet.wsgi.MAX_HEADER_LINE = CONF.wsgi.max_header_line self.client_socket_timeout = CONF.wsgi.client_socket_timeout or None self.name = name self.app = app self._host = host or "0.0.0.0" self._port = port or 0 self._server = None self._socket = None self._protocol = protocol self.pool_size = pool_size or self.default_pool_size self._pool = eventlet.GreenPool(self.pool_size) self._logger = logging.getLogger("hamal.%s.wsgi.server" % self.name) self._use_ssl = use_ssl if backlog < 1: raise exception.InvalidInput( reason=_('The backlog must be more than 1')) bind_addr = (host, port) # TODO(dims): eventlet's green dns/socket module does not actually # support IPv6 in getaddrinfo(). We need to get around this in the # future or monitor upstream for a fix try: info = socket.getaddrinfo(bind_addr[0], bind_addr[1], socket.AF_UNSPEC, socket.SOCK_STREAM)[0] family = info[0] bind_addr = info[-1] except Exception: family = socket.AF_INET try: self._socket = eventlet.listen(bind_addr, family, backlog=backlog) except EnvironmentError: LOG.error(_LE("Could not bind to %(host)s:%(port)s"), { 'host': host, 'port': port }) raise (self._host, self._port) = self._socket.getsockname()[0:2] LOG.info(_LI("%(name)s listening on %(_host)s:%(_port)s"), { 'name': self.name, '_host': self._host, '_port': self._port })
def _list_servers_on_exsi(vc, user, pwd, uri): """ List servers and templates on specified ESXi :param vc: The IP address of vcenter :param user: The username of vcenter :param pwd: The password of vcenter :param uri: The uri of ESXi will be searched :returns: dict to list when return is dict, the return is fault message of connect to vcenter or search uri. when return is list. the return is list of servers and templates. """ # Ensure the uri does not start with '/' # and end with '/' if uri.startswith('/'): uri = uri.split('/', 1)[1] if uri.endswith('/'): uri = uri.split('/', 1)[0] uri = uri.split('/') with vSphere(host=vc, user=user, pwd=pwd) as vs: if vs.si is None: LOG.error(_LE("Could not connect to the specified vcenter " "using specified username and password.")) return { "msg": "Could not connect to the specified vcenter " "using specified username and password." } datacenters = vs.si.content.rootFolder.childEntity find_dc = False for dc in datacenters: if dc.name == uri[0]: find_dc = True break if not find_dc: LOG.error(_LE("Could not find specified datacenter %(datacenter_name)s.", {'datacenter_name': dc.name})) return {"msg": "Could not find specified datacenter %s." % dc.name} hosts = vs.get_container_view(dc, [vim.HostSystem]) find_host = False for host in hosts: if host.name == uri[-1]: find_host = True break if not find_host: LOG.error(_LE("Could not find specified esxi %(host_name)s.", {'host_name': host.name})) return {"msg": "Could not find specified esxi %s." % host.name} prop_spec = { "VirtualMachine": ["name", "guest.toolsStatus", "guest.toolsRunningStatus", "guest.guestFullName", "guest.hostName", "guest.ipAddress", "runtime.powerState", "config.template", "config.hardware.device", "config.hardware.numCPU", "config.hardware.memoryMB", "summary.storage.committed"] } servers = vs.property_collector(host, [vim.VirtualMachine], prop_spec) return servers