def consume_in_thread(self): """Runs the ZmqProxy service""" ipc_dir = CONF.rpc_zmq_ipc_dir consume_in = "tcp://%s:%s" % \ (CONF.rpc_zmq_bind_address, CONF.rpc_zmq_port) consumption_proxy = InternalContext(None) if not os.path.isdir(ipc_dir): try: utils.execute('mkdir', '-p', ipc_dir, run_as_root=True) utils.execute('chown', "%s:%s" % (os.getuid(), os.getgid()), ipc_dir, run_as_root=True) utils.execute('chmod', '750', ipc_dir, run_as_root=True) except utils.ProcessExecutionError: with excutils.save_and_reraise_exception(): LOG.error(_("Could not create IPC directory %s") % (ipc_dir, )) try: self.register(consumption_proxy, consume_in, zmq.PULL, out_bind=True) except zmq.ZMQError: with excutils.save_and_reraise_exception(): LOG.error(_("Could not create ZeroMQ receiver daemon. " "Socket may already be in use.")) super(ZmqProxy, self).consume_in_thread()
def lldp_update_systemname(self, systemname): try: self.manager.lldp_update_systemname(systemname) except exception.LLDPDriverError as e: LOG.exception(e) with excutils.save_and_reraise_exception(): LOG.error("LLDP update systemname failed")
def lldp_neighbours_clear(self): try: self.manager.lldp_neighbours_clear() except exception.LLDPDriverError as e: LOG.exception(e) with excutils.save_and_reraise_exception(): LOG.error("LLDP neighbours clear failed")
def lldp_has_neighbour(self, name): try: return self.manager.lldp_has_neighbour(name) except exception.LLDPDriverError as e: LOG.exception(e) with excutils.save_and_reraise_exception(): LOG.error("LLDP has neighbour failed")
def post(self, sdn_controller): """Perform semantic checks and create a new SDN Controller.""" try: # Ensure that SDN is enabled before proceeding if not utils.get_sdn_enabled(): raise wsme.exc.ClientSideError(exception.SDNNotEnabled.message) # Ensure that compulsory parameters are there # This is merely sanity since the args parse layer # will also ensure that they're provided ip_address = sdn_controller.ip_address port = sdn_controller.port transport = sdn_controller.transport if not (len(ip_address) and port and len(transport)): raise wsme.exc.ClientSideError( exception.SDNControllerRequiredParamsMissing.message) self._verify_sdn_controller_af(ip_address) new_controller = pecan.request.dbapi.sdn_controller_create( sdn_controller.as_dict()) except exception.SysinvException as e: LOG.exception(e) raise wsme.exc.ClientSideError(_("Invalid data")) try: pecan.request.rpcapi.update_sdn_controller_config( pecan.request.context) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) return sdn_controller.convert_with_links(new_controller)
def lldp_neighbours_list(self): try: neighbours = self.manager.lldp_neighbours_list() except exception.LLDPDriverError as e: LOG.exception(e) with excutils.save_and_reraise_exception(): LOG.error("LLDP neighbours list failed") return neighbours
def remove_path_on_error(path): """Protect code that wants to operate on PATH atomically. Any exception will cause PATH to be removed. :param path: File to work with """ try: yield except Exception: with excutils.save_and_reraise_exception(): delete_if_exists(path)
def _serialize(data): """ Serialization wrapper We prefer using JSON, but it cannot encode all types. Error if a developer passes us bad data. """ try: return jsonutils.dumps(data, ensure_ascii=True) except TypeError: with excutils.save_and_reraise_exception(): LOG.error(_("JSON serialization failed."))
def apply(self, body): """ Apply the service parameters.""" service = self._get_service(body) self._service_parameter_apply_semantic_check(service) try: pecan.request.rpcapi.update_service_config(pecan.request.context, service, do_apply=True) except rpc_common.RemoteError as e: raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e)
def post(self, uuid, body): """Assign label(s) to a host. """ if self._from_ihosts: raise exception.OperationNotPermitted LOG.info("patch_data: %s" % body) host = objects.host.get_by_uuid(pecan.request.context, uuid) _check_host_locked(host) try: pecan.request.rpcapi.update_kubernetes_label( pecan.request.context, host.uuid, body ) except rpc_common.RemoteError as e: raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) new_records = [] for key, value in body.items(): values = { 'host_id': host.id, 'label_key': key, 'label_value': value } try: new_label = pecan.request.dbapi.label_create(uuid, values) new_records.append(new_label) except exception.HostLabelAlreadyExists: pass try: vim_api.vim_host_update( None, uuid, host.hostname, constants.VIM_DEFAULT_TIMEOUT_IN_SECS) except Exception as e: LOG.warn(_("No response vim_api host:%s e=%s" % (host.hostname, e))) pass return LabelCollection.convert_with_links( new_records, limit=None, url=None, expand=False, sort_key='id', sort_dir='asc')
def post(self, itrapdest): """Create a new itrapdest. :param itrapdest: a itrapdest within the request body. """ try: new_itrapdest = pecan.request.dbapi.itrapdest_create( itrapdest.as_dict()) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) # update snmpd.conf pecan.request.rpcapi.update_snmp_config(pecan.request.context) return itrapdest.convert_with_links(new_itrapdest)
def __iter__(self): """Return a result until we get a 'None' response from consumer""" if self._done: raise StopIteration while True: try: next(self._iterator) except Exception: with excutils.save_and_reraise_exception(): self.done() if self._got_ending: self.done() raise StopIteration result = self._result if isinstance(result, Exception): self.done() raise result # pylint: disable=raising-bad-type yield result
def delete(self, uuid): """Delete a host label.""" if self._from_ihosts: raise exception.OperationNotPermitted lbl_obj = objects.label.get_by_uuid(pecan.request.context, uuid) host = objects.host.get_by_uuid(pecan.request.context, lbl_obj.host_id) label_dict = {lbl_obj.label_key: None} _check_host_locked(host) try: pecan.request.rpcapi.update_kubernetes_label( pecan.request.context, host.uuid, label_dict) except rpc_common.RemoteError as e: raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) try: pecan.request.dbapi.label_destroy(lbl_obj.uuid) except exception.HostLabelNotFound: msg = _("Delete host label failed: host %s label %s=%s" % (host.hostname, lbl_obj.label_key, lbl_obj.label_value)) raise wsme.exc.ClientSideError(msg) try: vim_api.vim_host_update( None, host.uuid, host.hostname, constants.VIM_DEFAULT_TIMEOUT_IN_SECS) except Exception as e: LOG.warn(_("No response vim_api host:%s e=%s" % (host.hostname, e))) pass
def deploy(address, port, iqn, lun, image_path, pxe_config_path, root_mb, swap_mb): """All-in-one function to deploy a node.""" dev = get_dev(address, port, iqn, lun) image_mb = get_image_mb(image_path) if image_mb > root_mb: root_mb = image_mb discovery(address, port) login_iscsi(address, port, iqn) try: root_uuid = work_on_disk(dev, root_mb, swap_mb, image_path) except exception.ProcessExecutionError as err: with excutils.save_and_reraise_exception(): # Log output if there was a error LOG.error("Cmd : %s" % err.cmd) LOG.error("StdOut : %s" % err.stdout) LOG.error("StdErr : %s" % err.stderr) finally: logout_iscsi(address, port, iqn) switch_pxe_config(pxe_config_path, root_uuid) # Ensure the node started netcat on the port after POST the request. time.sleep(3) notify(address, 10000)
def __iter__(self): """Return a result until we get a reply with an 'ending" flag""" if self._done: raise StopIteration while True: result = None try: data = self._dataqueue.get(timeout=self._timeout) result = self._process_data(data) except queue.Empty: self.done() raise rpc_common.Timeout() except Exception: with excutils.save_and_reraise_exception(): self.done() if self._got_ending: yield result self.done() raise StopIteration if isinstance(result, Exception): self.done() raise result # pylint: disable=raising-bad-type yield result
def work_on_disk(dev, root_mb, swap_mb, image_path): """Creates partitions and write an image to the root partition.""" root_part = "%s-part1" % dev swap_part = "%s-part2" % dev if not is_block_device(dev): LOG.warn(_("parent device '%s' not found") % dev) return make_partitions(dev, root_mb, swap_mb) if not is_block_device(root_part): LOG.warn(_("root device '%s' not found") % root_part) return if not is_block_device(swap_part): LOG.warn(_("swap device '%s' not found") % swap_part) return dd(image_path, root_part) mkswap(swap_part) try: root_uuid = block_uuid(root_part) except exception.ProcessExecutionError: with excutils.save_and_reraise_exception(): LOG.error("Failed to detect root device UUID.") return root_uuid
def post(self, body): """Create new Service Parameter.""" resource = body.get('resource') personality = body.get('personality') if personality is not None or resource is not None: return self.post_custom_resource(body, personality, resource) service = self._get_service(body) section = body.get('section') if not section: raise wsme.exc.ClientSideError(_("Unspecified section name.")) elif section not in service_parameter.SERVICE_PARAMETER_SCHEMA[ service]: msg = _("Invalid service section %s." % section) raise wsme.exc.ClientSideError(msg) new_records = [] parameters = body.get('parameters') if not parameters: raise wsme.exc.ClientSideError(_("Unspecified parameters.")) if service == constants.SERVICE_TYPE_CEPH: if not StorageBackendConfig.has_backend_configured( pecan.request.dbapi, constants.CINDER_BACKEND_CEPH): msg = _("Ceph backend is required.") raise wsme.exc.ClientSideError(msg) for name, value in parameters.items(): new_record = { 'service': service, 'section': section, 'name': name, 'value': value, } self._check_parameter_syntax(new_record) existing = False try: pecan.request.dbapi.service_parameter_get_one( service, section, name) existing = True except exception.NotFound: pass except exception.MultipleResults: # We'll check/handle this in the "finally" block existing = True finally: if existing: msg = _("Service parameter add failed: " "Parameter already exists: " "service=%s section=%s name=%s" % (service, section, name)) raise wsme.exc.ClientSideError(msg) new_records.append(new_record) svc_params = [] for n in new_records: try: new_parm = pecan.request.dbapi.service_parameter_create(n) except exception.NotFound: msg = _("Service parameter add failed: " "service %s section %s name %s value %s" % (service, section, n.name, n.value)) raise wsme.exc.ClientSideError(msg) svc_params.append(new_parm) try: pecan.request.rpcapi.update_service_config(pecan.request.context, service) except rpc_common.RemoteError as e: # rollback create service parameters for p in svc_params: try: pecan.request.dbapi.service_parameter_destroy_uuid(p.uuid) LOG.warn( _("Rollback service parameter create: " "destroy uuid {}".format(p.uuid))) except exception.SysinvException: pass raise wsme.exc.ClientSideError(str(e.value)) except Exception as e: with excutils.save_and_reraise_exception(): LOG.exception(e) return ServiceParameterCollection.convert_with_links(svc_params, limit=None, url=None, expand=False, sort_key='id', sort_dir='asc')