def _get_parent_port(self, neutron, pod): node_subnet_id = config.CONF.neutron_defaults.worker_nodes_subnet if not node_subnet_id: raise oslo_cfg.RequiredOptError('worker_nodes_subnet', 'neutron_defaults') try: # REVISIT(vikasc): Assumption is being made that hostIP is the IP # of trunk interface on the node(vm). node_fixed_ip = pod['status']['hostIP'] except KeyError: if pod['status']['conditions'][0]['type'] != "Initialized": LOG.debug("Pod condition type is not 'Initialized'") LOG.error(_LE("Failed to get parent vm port ip")) raise try: fixed_ips = [ 'subnet_id=%s' % str(node_subnet_id), 'ip_address=%s' % str(node_fixed_ip) ] ports = neutron.list_ports(fixed_ips=fixed_ips) except n_exc.NeutronClientException as ex: LOG.error(_LE("Parent vm port with fixed ips %s not found!"), fixed_ips) raise ex if ports['ports']: return ports['ports'][0] else: LOG.error( _LE("Neutron port for vm port with fixed ips %s" " not found!"), fixed_ips) raise k_exc.K8sNodeTrunkPortFailure
def _make_vif_network(neutron_port, subnets): """Gets a os-vif Network object for port. :param neutron_port: dict containing port information as returned by neutron client's 'show_port' :param subnets: subnet mapping as returned by PodSubnetsDriver.get_subnets :return: os-vif Network object """ try: network = next(net.obj_clone() for net in subnets.values() if net.id == neutron_port.get('network_id')) except StopIteration: raise k_exc.IntegrityError( _LE("Port %(port_id)s belongs to network %(network_id)s, " "but requested networks are: %(requested_networks)s") % { 'port_id': neutron_port.get('id'), 'network_id': neutron_port.get('network_id'), 'requested_networks': [net.id for net in subnets.values()] }) network.subnets = osv_subnet.SubnetList( objects=_make_vif_subnets(neutron_port, subnets)) return network
def osvif_to_neutron_fixed_ips(subnets): fixed_ips = [] for subnet_id, network in six.iteritems(subnets): ips = [] if len(network.subnets.objects) > 1: raise k_exc.IntegrityError( _LE("Network object for subnet %(subnet_id)s is invalid, " "must contain a single subnet, but %(num_subnets)s found") % { 'subnet_id': subnet_id, 'num_subnets': len(network.subnets.objects) }) for subnet in network.subnets.objects: if subnet.obj_attr_is_set('ips'): ips.extend([str(ip.address) for ip in subnet.ips.objects]) if ips: fixed_ips.extend([{ 'subnet_id': subnet_id, 'ip_address': ip } for ip in ips]) else: fixed_ips.append({'subnet_id': subnet_id}) return fixed_ips
def get_instance(cls): """Get an implementing driver instance.""" alias = cls.ALIAS try: manager = _DRIVER_MANAGERS[alias] except KeyError: name = config.CONF.kubernetes[alias + '_driver'] manager = stv_driver.DriverManager(namespace="%s.%s" % (_DRIVER_NAMESPACE_BASE, alias), name=name, invoke_on_load=True) _DRIVER_MANAGERS[alias] = manager driver = manager.driver if not isinstance(driver, cls): raise TypeError( _LE("Invalid %(alias)r driver type: %(driver)s, " "must be a subclass of %(type)s") % { 'alias': alias, 'driver': driver.__class__.__name__, 'type': cls }) return driver
def _make_vif_subnets(neutron_port, subnets): """Gets a list of os-vif Subnet objects for port. :param neutron_port: dict containing port information as returned by neutron client's 'show_port' :param subnets: subnet mapping as returned by PodSubnetsDriver.get_subnets :return: list of os-vif Subnet object """ vif_subnets = {} for neutron_fixed_ip in neutron_port.get('fixed_ips', []): subnet_id = neutron_fixed_ip['subnet_id'] ip_address = neutron_fixed_ip['ip_address'] if subnet_id not in subnets: continue try: subnet = vif_subnets[subnet_id] except KeyError: subnet = _make_vif_subnet(subnets, subnet_id) vif_subnets[subnet_id] = subnet subnet.ips.objects.append(osv_fixed_ip.FixedIP(address=ip_address)) if not vif_subnets: raise k_exc.IntegrityError( _LE("No valid subnets found for port %(port_id)s") % {'port_id': neutron_port.get('id')}) return list(vif_subnets.values())
def _add_subport(self, neutron, trunk_id, subport): """Adds subport port to Neutron trunk This method gets vlanid allocated from kuryr segmentation driver. In active/active HA type deployment, possibility of vlanid conflict is there. In such a case, vlanid will be requested again and subport addition is re-tried. This is tried DEFAULT_MAX_RETRY_COUNT times in case of vlanid conflict. """ # TODO(vikasc): Better approach for retrying in case of # vlan-id conflict. retry_count = 1 while True: try: vlan_id = self._get_vlan_id(trunk_id) except n_exc.NeutronClientException as ex: LOG.error( _LE("Getting VlanID for subport on " "trunk %s failed!!"), trunk_id) raise ex subport = [{ 'segmentation_id': vlan_id, 'port_id': subport, 'segmentation_type': 'vlan' }] try: neutron.trunk_add_subports(trunk_id, {'sub_ports': subport}) except n_exc.Conflict as ex: if retry_count < DEFAULT_MAX_RETRY_COUNT: LOG.error( _LE("vlanid already in use on trunk, " "%s. Retrying..."), trunk_id) retry_count += 1 sleep(DEFAULT_RETRY_INTERVAL) continue else: LOG.error( _LE("MAX retry count reached. Failed to add subport")) raise ex except n_exc.NeutronClientException as ex: LOG.error( _LE("Error happened during subport" "addition to trunk, %s"), trunk_id) raise ex return vlan_id
def _remove_subport(self, neutron, trunk_id, subport_id): subport_id = [{'port_id': subport_id}] try: neutron.trunk_remove_subports(trunk_id, {'sub_ports': subport_id}) except n_exc.NeutronClientException as ex: LOG.error( _LE("Error happened during subport removal from trunk," "%s"), trunk_id) raise ex
def _get_trunk_id(self, port): try: return port['trunk_details']['trunk_id'] except KeyError: LOG.error( _LE("Neutron port is missing trunk details. " "Please ensure that k8s node port is associated " "with a Neutron vlan trunk")) raise k_exc.K8sNodeTrunkPortFailure
def _get_endpoints_link(self, service): svc_link = service['metadata']['selfLink'] link_parts = svc_link.split('/') if link_parts[-2] != 'services': raise k_exc.IntegrityError( _LE("Unsupported service link: %(link)s") % {'link': svc_link}) link_parts[-2] = 'endpoints' return "/".join(link_parts)
def _ovs_vsctl(args, timeout=None): full_args = ['ovs-vsctl'] if timeout is not None: full_args += ['--timeout=%s' % timeout] full_args += args try: return processutils.execute(*full_args, run_as_root=True) except Exception as e: LOG.error(_LE("Unable to execute %(cmd)s. Exception: %(exception)s"), {'cmd': full_args, 'exception': e}) raise
def _get_network_id(self, subnets): ids = ovu.osvif_to_neutron_network_ids(subnets) if len(ids) != 1: raise k_exc.IntegrityError(_LE( "Subnet mapping %(subnets)s is not valid: %(num_networks)s " "unique networks found") % { 'subnets': subnets, 'num_networks': len(ids)}) return ids[0]
def make_json_error(ex): app.logger.error(_LE("Unexpected error happened: %s"), ex) traceback.print_exc(file=sys.stderr) response = flask.jsonify({"Err": str(ex)}) response.status_code = w_exceptions.InternalServerError.code if isinstance(ex, w_exceptions.HTTPException): response.status_code = ex.code elif isinstance(ex, n_exceptions.NeutronClientException): response.status_code = ex.status_code elif isinstance(ex, jsonschema.ValidationError): response.status_code = w_exceptions.BadRequest.code content_type = 'application/vnd.docker.plugins.v1+json; charset=utf-8' response.headers['Content-Type'] = content_type return response
def _get_subnet_id(self, service, project_id, ip): subnets_mapping = self._drv_subnets.get_subnets(service, project_id) subnet_ids = { subnet_id for subnet_id, network in six.iteritems(subnets_mapping) for subnet in network.subnets.objects if ip in subnet.cidr } if len(subnet_ids) != 1: raise k_exc.IntegrityError( _LE("Found %(num)s subnets for service %(link)s IP %(ip)s") % { 'link': service['metadata']['selfLink'], 'ip': ip, 'num': len(subnet_ids) }) return subnet_ids.pop()
def run(self, env, fin, fout): try: params = CNIParameters(env, jsonutils.load(fin)) if params.CNI_COMMAND == 'ADD': vif = self._plugin.add(params) self._write_vif(fout, vif) elif params.CNI_COMMAND == 'DEL': self._plugin.delete(params) elif params.CNI_COMMAND == 'VERSION': self._write_version(fout) else: raise k_exc.CNIError( _LE("unknown CNI_COMMAND: %s") % params.CNI_COMMAND) except Exception as ex: # LOG.exception self._write_exception(fout, str(ex)) return 1
def _make_vif_subnet(subnets, subnet_id): """Makes a copy of an os-vif Subnet from subnets mapping. :param subnets: subnet mapping as returned by PodSubnetsDriver.get_subnets :param subnet_id: ID of the subnet to extract from 'subnets' mapping :return: a copy of an os-vif Subnet object matching 'subnet_id' """ network = subnets[subnet_id] if len(network.subnets.objects) != 1: raise k_exc.IntegrityError( _LE("Network object for subnet %(subnet_id)s is invalid, " "must contain a single subnet, but %(num_subnets)s found") % { 'subnet_id': subnet_id, 'num_subnets': len(network.subnets.objects) }) subnet = network.subnets.objects[0].obj_clone() subnet.ips = osv_fixed_ip.FixedIPList(objects=[]) return subnet
def __init__(self, resource): super(ResourceNotReady, self).__init__(_LE("Resource not ready: %r") % resource)
def __call__(self, event): try: self._handler(event) except self._exceptions: LOG.exception(_LE("Failed to handle event %s"), event)