Пример #1
0
 def delete_network_precommit(self, mech_context):
     """Delete Network from the plugin specific database table."""
     LOG.debug("delete_network_precommit: called")
     network = mech_context.current
     network_id = network['id']
     context = mech_context._plugin_context
     if fortinet_db.query_record(context, ext_db.ExternalNetwork,
                                 network_id=network_id):
         # return when the network is external network
         # TODO(samsu): may check external network
         # before delete namespace
         return
     tenant_id = network['tenant_id']
     namespace = fortinet_db.query_record(context,
                                 fortinet_db.Fortinet_ML2_Namespace,
                                 tenant_id=tenant_id)
     if not namespace:
         return
     # TODO(samsu): type driver support vlan only,
     # need to check later
     vlanid = network['provider:segmentation_id']
     inf_name = const.PREFIX['inf'] + str(vlanid)
     try:
         utils.delete_vlanintf(self, context, name=inf_name,
                  vdom=namespace.vdom)
     except Exception as e:
         resources.Exinfo(e)
         raise ml2_exc.MechanismDriverError(
             method=sys._getframe().f_code.co_name)
Пример #2
0
def delete_reservedip(obj, context, **kwargs):
    cls = fortinet_db.Fortinet_ML2_ReservedIP
    reserved_ip = fortinet_db.query_record(context, cls, **kwargs)

    if reserved_ip:
        db_reservedips = fortinet_db.query_records(
            context, cls, subnet_id=reserved_ip.subnet_id)
        db_reservedips.remove(reserved_ip)
        reserved_addresses = []
        for rsrvdip in db_reservedips:
            reserved_addresses.append({
                'id': rsrvdip.edit_id,
                'ip': rsrvdip.ip,
                'mac': rsrvdip.mac
            })
        db_subnet = fortinet_db.query_record(context,
                                             fortinet_db.Fortinet_ML2_Subnet,
                                             subnet_id=reserved_ip.subnet_id)
        if db_subnet:
            op(obj,
               context,
               resources.DhcpServerRsvAddr.set,
               id=db_subnet.edit_id,
               vdom=reserved_ip.vdom,
               reserved_address=jsonutils.dumps(reserved_addresses))
        fortinet_db.delete_record(context, cls, **kwargs)
Пример #3
0
def network_migration(context, mech_driver):
    """
    # networks, ml2_network_segments
    network =  {
        #'status': 'ACTIVE',
        #'subnets': [],
        'name': u'test-net',
        #'provider: physical_network': u'physnet1',
        #'admin_state_up': True,
        'tenant_id': u'11513667f4ee4a14acb0985659459988',
        'provider: network_type': u'vlan',
        'router:external': False,
        #'shared': False,
        'id': 'ff0a1d64-ce30-4ed0-ba37-597eaf8976f0',
        #'provider: segmentation_id': 1200L
    }
    # ml2_network_segments
    segments = [{
        'segmentation_id': 1200L,
        'physical_network': u'physnet1',
        'id': u'e7dfa4fb-038a-4aad-b6fa-73afba788888',
        'network_type': u'vlan'
    }]
    """
    net = {
        'name': '',
        'tenant_id': '',
        'provider: network_type': '',
        'router:external': False,
        'id': '',
    }

    segment = {
        'segmentation_id': 0,
        'physical_network': '',
        'id': '',
        'network_type': ''
    }
    records = fortinet_db.query_records(context, models_v2.Network)
    with Progress(len(records), 'network_migration') as p:
        for record in records:
            reset(net)
            reset(segment)
            db_seg = fortinet_db.query_record(context,
                                              ml2_db.NetworkSegment,
                                              network_id=record.id)
            cls2dict(record, net)
            db_extnet = fortinet_db.query_record(context,
                                                 ExternalNetwork,
                                                 network_id=record.id)
            if db_extnet:
                net['router:external'] = True

            cls2dict(db_seg, segment)
            net['provider: network_type'] = db_seg.network_type
            mech_context = Fake_mech_context(_plugin_context=context,
                                             current=net,
                                             network_segments=[segment])
            mech_driver.create_network_postcommit(mech_context)
            p.update()
Пример #4
0
    def _disassociate_floatingip(self, context, id):
        l3db_fip = self._get_floatingip(context, id)
        db_namespace = fortinet_db.query_record(context,
                                    fortinet_db.Fortinet_ML2_Namespace,
                                    tenant_id=l3db_fip.tenant_id)
        db_fip = fortinet_db.query_record(context,
                            fortinet_db.Fortinet_FloatingIP_Allocation,
                            floating_ip_address=l3db_fip.floating_ip_address,
                            allocated=True)
        int_intf, ext_intf = utils.get_vlink_intf(self, context,
                                               vdom=db_namespace.vdom)
        db_ip = fortinet_db.query_record(context, models_v2.IPAllocation,
                                         port_id=l3db_fip.fixed_port_id)
        vlan_inf = utils.get_intf(context, db_ip.network_id)
        mappedip = utils.get_ipaddr(db_fip.ip_subnet, 0)
        utils.delete_fwpolicy(self, context,
                              vdom=db_namespace.vdom,
                              srcintf=vlan_inf,
                              srcaddr=l3db_fip.fixed_ip_address,
                              dstintf=int_intf,
                              poolname=mappedip)

        utils.delete_fwaddress(self, context,
                               name=l3db_fip.fixed_ip_address,
                               vdom=db_namespace.vdom)

        utils.delete_fwpolicy(self, context,
                              vdom=db_namespace.vdom,
                              dstaddr=db_fip.floating_ip_address)

        utils.delete_vip(self, context,
                         vdom=db_namespace.vdom,
                         name=db_fip.floating_ip_address)
Пример #5
0
 def delete_network_precommit(self, mech_context):
     """Delete Network from the plugin specific database table."""
     LOG.debug("delete_network_precommit: called")
     network = mech_context.current
     network_id = network['id']
     context = mech_context._plugin_context
     if fortinet_db.query_record(context, ext_db.ExternalNetwork,
                                 network_id=network_id):
         # return when the network is external network
         # TODO(samsu): may check external network
         # before delete namespace
         return
     tenant_id = network['tenant_id']
     namespace = fortinet_db.query_record(context,
                                 fortinet_db.Fortinet_ML2_Namespace,
                                 tenant_id=tenant_id)
     if not namespace:
         return
     # TODO(samsu): type driver support vlan only,
     # need to check later
     vlanid = network['provider:segmentation_id']
     inf_name = const.PREFIX['inf'] + str(vlanid)
     try:
         utils.delete_vlanintf(self, context, name=inf_name,
                  vdom=namespace.vdom)
     except Exception as e:
         resources.Exinfo(e)
         raise ml2_exc.MechanismDriverError(
             method=sys._getframe().f_code.co_name)
Пример #6
0
def set_ext_gw(obj, context, port):
    """
    :param context:
    :param port: example format
     port = {
        'status': 'DOWN',
        'binding:host_id': '',
        'allowed_address_pairs': [],
        'device_owner': 'network:router_gateway',
        'binding:profile': {},
        'fixed_ips': [{
            'subnet_id': u'09855a84-edfd-474d-b641-38a2bc63466a',
            'ip_address': u'10.160.37.111'
        }],
        'id': '6e68efc0-c0ca-40a2-a502-c2bf19304317',
        'security_groups': [],
        'device_id': u'8312d7a2-cae5-4e87-9c04-782c4a34bb8c',
        'name': '',
        'admin_state_up': True,
        'network_id': u'95eb736c-dd3b-4bf5-940a-8fa8e707a376',
        'tenant_id': '',
        'binding:vif_details': {},
        'binding:vnic_type': 'normal',
        'binding:vif_type': 'unbound',
        'mac_address': 'fa:16:3e:95:02:ab'
    }
    :return:
    """
    router_db = fortinet_db.query_record(context, l3_db.Router,
                                         id=port['device_id'])
    tenant_id = router_db.get('tenant_id', None)
    if not tenant_id:
        raise ValueError

    namespace = add_vdom(obj, context, tenant_id=tenant_id)
    ## Uncomment the line
    add_vlink(obj, context, namespace.vdom)
    vlink_db = fortinet_db.query_record(context,
                                fortinet_db.Fortinet_Vlink_Vlan_Allocation,
                                vdom=namespace.vdom)

    ip_address = port['fixed_ips'][0]['ip_address']

    add_fwippool(obj, context, vdom=const.EXT_VDOM,
                 name=ip_address, startip=ip_address)

    add_fwpolicy(obj, context,
                 vdom=const.EXT_VDOM,
                 srcintf=vlink_db.inf_name_ext_vdom,
                 dstintf=obj.fortigate.cfg['ext_interface'],
                 poolname=ip_address)
    subnet_db = fortinet_db.query_record(context, models_v2.Subnet,
                                id=port['fixed_ips'][0]['subnet_id'])
    if subnet_db:
        netmask = netaddr.IPNetwork(subnet_db.cidr).netmask
        add_interface_ip(obj, context,
                         name=obj.fortigate.cfg['ext_interface'],
                         vdom=const.EXT_VDOM,
                         ip="%s %s" % (ip_address, netmask))
Пример #7
0
def delete_vlink(obj, context, tenant_id):
    if fortinet_db.query_count(context, l3_db.Router,
                               tenant_id=tenant_id) or \
        fortinet_db.query_count(context, l3_db.FloatingIP,
                                tenant_id=tenant_id):
        db_routers = fortinet_db.query_records(context,
                                               l3_db.Router,
                                               tenant_id=tenant_id)
        db_fips = fortinet_db.query_records(context,
                                            l3_db.FloatingIP,
                                            tenant_id=tenant_id)
        LOG.debug(
            "Keeping vlink, because existing data "
            "db_routers: %(routers)s, db_fips: %(fips)s", {
                'routers': db_routers,
                'fips': db_fips
            })
        return False
    vdom = fortinet_db.query_record(context,
                                    fortinet_db.Fortinet_ML2_Namespace,
                                    tenant_id=tenant_id).vdom

    vlink_vlan = fortinet_db.query_record(
        context,
        fortinet_db.Fortinet_Vlink_Vlan_Allocation,
        vdom=vdom,
        allocated=True)
    if not vlink_vlan:
        return False
    vlink_ip = fortinet_db.query_record(
        context,
        fortinet_db.Fortinet_Vlink_IP_Allocation,
        vdom=vdom,
        vlink_id=vlink_vlan.id,
        allocated=True)
    if not vlink_ip:
        return False
    """
    delete_fwpolicy(obj, context,
                    vdom=const.EXT_VDOM,
                    srcintf=vlink_vlan.inf_name_ext_vdom,
                    dstintf=obj._fortigate['ext_interface'],
                    nat='enable')"""
    gateway_ip = get_ipaddr(netaddr.IPNetwork(vlink_ip.vlink_ip_subnet), 1)
    delete_routerstatic(obj,
                        context,
                        vdom=vdom,
                        dst=const.EXT_DEF_DST,
                        device=vlink_vlan.inf_name_int_vdom,
                        gateway=gateway_ip)
    delete_vlink_intf(obj, context, vlink_vlan)
    fortinet_db.delete_record(context,
                              fortinet_db.Fortinet_Vlink_IP_Allocation,
                              vdom=vdom,
                              vlink_id=vlink_vlan.id)
    fortinet_db.delete_record(context,
                              fortinet_db.Fortinet_Vlink_Vlan_Allocation,
                              id=vlink_vlan.id)
    return True
Пример #8
0
    def create_port_precommit(self, mech_context):
        """Create logical port on the fortigate (db update)."""
        LOG.debug("create_port_precommit: called")
        port = mech_context.current
        LOG.debug("create_port_precommit mech_context = %s", mech_context)
        context = mech_context._plugin_context
        namespace = fortinet_db.query_record(
            context,
            fortinet_db.Fortinet_ML2_Namespace,
            tenant_id=port['tenant_id'])
        port_id = port['id']
        subnet_id = port['fixed_ips'][0]['subnet_id']
        ip_address = port['fixed_ips'][0]['ip_address']
        mac = port['mac_address']
        db_subnetv2 = fortinet_db.query_record(context,
                                               models_v2.Subnet,
                                               id=subnet_id)
        if port['device_owner'] in ['network:router_gateway']:
            if fortinet_db.query_record(context,
                                        ext_db.ExternalNetwork,
                                        network_id=port['network_id']):
                utils.set_ext_gw(self, context, port)
        elif port['device_owner'] in ['compute:nova', 'compute:None', '']:
            # add dhcp related functions
            # '': create port before associate the port with a vm
            utils.add_reservedip(self,
                                 context,
                                 port_id=port_id,
                                 subnet_id=subnet_id,
                                 mac=mac,
                                 ip=ip_address,
                                 vdom=namespace.vdom)

        elif port['device_owner'] in ['network:router_interface']:
            if db_subnetv2.cidr:
                cidr = netaddr.IPNetwork(db_subnetv2.cidr)
                subnet = ' '.join([str(cidr.network), str(cidr.netmask)])
                utils.add_fwaddress(self,
                                    context,
                                    vdom=namespace.vdom,
                                    name=str(cidr.network),
                                    subnet=subnet)
                addrgrp_name = const.PREFIX['addrgrp'] + namespace.vdom
                utils.add_addrgrp(self,
                                  context,
                                  name=addrgrp_name,
                                  vdom=namespace.vdom,
                                  members=[str(cidr.network)])

                utils.add_fwpolicy(self,
                                   context,
                                   vdom=namespace.vdom,
                                   srcintf='any',
                                   srcaddr=addrgrp_name,
                                   dstintf='any',
                                   dstaddr=addrgrp_name,
                                   nat='disable')
        return
Пример #9
0
def network_migration(context, mech_driver):
    """
    # networks, ml2_network_segments
    network =  {
        #'status': 'ACTIVE',
        #'subnets': [],
        'name': u'test-net',
        #'provider: physical_network': u'physnet1',
        #'admin_state_up': True,
        'tenant_id': u'11513667f4ee4a14acb0985659459988',
        'provider: network_type': u'vlan',
        'router:external': False,
        #'shared': False,
        'id': 'ff0a1d64-ce30-4ed0-ba37-597eaf8976f0',
        #'provider: segmentation_id': 1200L
    }
    # ml2_network_segments
    segments = [{
        'segmentation_id': 1200L,
        'physical_network': u'physnet1',
        'id': u'e7dfa4fb-038a-4aad-b6fa-73afba788888',
        'network_type': u'vlan'
    }]
    """
    net = {
        'name': '',
        'tenant_id': '',
        'provider: network_type': '',
        'router:external': False,
        'id': '',
    }

    segment = {
        'segmentation_id': 0,
        'physical_network': '',
        'id': '',
        'network_type': ''
    }
    records = fortinet_db.query_records(context, models_v2.Network)
    with Progress(len(records), 'network_migration') as p:
        for record in records:
            reset(net)
            reset(segment)
            db_seg = fortinet_db.query_record(context, ml2_db.NetworkSegment,
                                              network_id=record.id)
            cls2dict(record, net)
            db_extnet = fortinet_db.query_record(context, ExternalNetwork,
                                                 network_id=record.id)
            if db_extnet:
                net['router:external'] = True

            cls2dict(db_seg, segment)
            net['provider: network_type'] = db_seg.network_type
            mech_context = Fake_mech_context(_plugin_context=context,
                                             current=net,
                                             network_segments=[segment])
            mech_driver.create_network_postcommit(mech_context)
            p.update()
Пример #10
0
    def create_port_precommit(self, mech_context):
        """Create logical port on the fortigate (db update)."""
        LOG.debug("create_port_precommit: called")
        port = mech_context.current
        LOG.debug("create_port_precommit mech_context = %s", mech_context)
        context = mech_context._plugin_context
        namespace = fortinet_db.query_record(context,
                            fortinet_db.Fortinet_ML2_Namespace,
                            tenant_id=port['tenant_id'])
        port_id = port['id']
        subnet_id = port['fixed_ips'][0]['subnet_id']
        ip_address = port['fixed_ips'][0]['ip_address']
        mac = port['mac_address']
        db_subnetv2 = fortinet_db.query_record(context, models_v2.Subnet,
                                             id=subnet_id)
        if port['device_owner'] in ['network:router_gateway']:
            if fortinet_db.query_record(context, ext_db.ExternalNetwork,
                                        network_id=port['network_id']):
                utils.set_ext_gw(self, context, port)
        elif port['device_owner'] in ['compute:nova', 'compute:None', '']:
            # add dhcp related functions
            # '': create port before associate the port with a vm
            utils.add_reservedip(self, context,
                                 port_id=port_id,
                                 subnet_id=subnet_id,
                                 mac=mac,
                                 ip=ip_address,
                                 vdom=namespace.vdom)

        elif port['device_owner'] in ['network:router_interface']:
            if db_subnetv2.cidr:
                cidr = netaddr.IPNetwork(db_subnetv2.cidr)
                subnet = ' '.join([str(cidr.network), str(cidr.netmask)])
                utils.add_fwaddress(self, context,
                                   vdom=namespace.vdom,
                                   name=str(cidr.network),
                                   subnet=subnet)
                addrgrp_name = const.PREFIX['addrgrp'] + namespace.vdom
                utils.add_addrgrp(self, context,
                                  name=addrgrp_name,
                                  vdom=namespace.vdom,
                                  members=[str(cidr.network)])

                utils.add_fwpolicy(self, context,
                                   vdom=namespace.vdom,
                                   srcintf='any',
                                   srcaddr=addrgrp_name,
                                   dstintf='any',
                                   dstaddr=addrgrp_name,
                                   nat='disable')
        return
Пример #11
0
def delete_vlink(obj, context, tenant_id):
    if fortinet_db.query_count(context, l3_db.Router,
                               tenant_id=tenant_id) or \
        fortinet_db.query_count(context, l3_db.FloatingIP,
                                tenant_id=tenant_id):
        db_routers = fortinet_db.query_records(context, l3_db.Router,
                                               tenant_id=tenant_id)
        db_fips = fortinet_db.query_records(context, l3_db.FloatingIP,
                                            tenant_id=tenant_id)
        LOG.debug("Keeping vlink, because existing data "
                  "db_routers: %(routers)s, db_fips: %(fips)s",
                 {'routers': db_routers, 'fips': db_fips})
        return False
    vdom = fortinet_db.query_record(context,
                                    fortinet_db.Fortinet_ML2_Namespace,
                                   tenant_id=tenant_id).vdom

    vlink_vlan = fortinet_db.query_record(context,
                            fortinet_db.Fortinet_Vlink_Vlan_Allocation,
                            vdom=vdom,
                            allocated=True)
    if not vlink_vlan:
        return False
    vlink_ip = fortinet_db.query_record(context,
                              fortinet_db.Fortinet_Vlink_IP_Allocation,
                              vdom=vdom,
                              vlink_id=vlink_vlan.id,
                              allocated=True)
    if not vlink_ip:
        return False
    """
    delete_fwpolicy(obj, context,
                    vdom=const.EXT_VDOM,
                    srcintf=vlink_vlan.inf_name_ext_vdom,
                    dstintf=obj._fortigate['ext_interface'],
                    nat='enable')"""
    gateway_ip = get_ipaddr(netaddr.IPNetwork(vlink_ip.vlink_ip_subnet), 1)
    delete_routerstatic(obj, context,
                        vdom=vdom,
                        dst=const.EXT_DEF_DST,
                        device=vlink_vlan.inf_name_int_vdom,
                        gateway=gateway_ip)
    delete_vlink_intf(obj, context, vlink_vlan)
    fortinet_db.delete_record(context,
                        fortinet_db.Fortinet_Vlink_IP_Allocation,
                        vdom=vdom,
                        vlink_id=vlink_vlan.id)
    fortinet_db.delete_record(context,
                        fortinet_db.Fortinet_Vlink_Vlan_Allocation,
                        id=vlink_vlan.id)
    return True
Пример #12
0
    def delete_port_postcommit(self, mech_context):
        LOG.debug("delete_port_postcommit: called")
        port = mech_context.current
        context = mech_context._plugin_context
        try:
            port_id = port['id']
            subnet_id = port['fixed_ips'][0]['subnet_id']
            db_subnet = fortinet_db.query_record(
                context, fortinet_db.Fortinet_ML2_Subnet, subnet_id=subnet_id)
            db_subnetv2 = fortinet_db.query_record(context,
                                                   models_v2.Subnet,
                                                   id=subnet_id)
            if port['device_owner'] in ['network:router_gateway']:
                if fortinet_db.query_record(context,
                                            ext_db.ExternalNetwork,
                                            network_id=port['network_id']):
                    #delete ippool and its related firewall policy
                    utils.clr_ext_gw(self, context, port)

            elif port['device_owner'] in ['compute:nova', 'compute:None', '']:
                # delete dhcp related functions
                utils.delete_reservedip(self, context, port_id=port_id)

            elif port['device_owner'] in ['network:router_interface']:
                # add firewall address and address group
                name = const.PREFIX['addrgrp'] + db_subnet.vdom
                member = str(netaddr.IPNetwork(db_subnetv2.cidr).network)
                utils.delete_fwpolicy(self,
                                      context,
                                      vdom=db_subnet.vdom,
                                      srcintf='any',
                                      srcaddr=name,
                                      dstintf='any',
                                      dstaddr=name,
                                      nat='disable')
                utils.delete_addrgrp(self,
                                     context,
                                     name=name,
                                     vdom=db_subnet.vdom,
                                     members=member.split(' '))
                utils.delete_fwaddress(self,
                                       context,
                                       vdom=db_subnet.vdom,
                                       name=member)
        except Exception as e:
            resources.Exinfo(e)
            raise ml2_exc.MechanismDriverError(
                method=sys._getframe().f_code.co_name)
Пример #13
0
def delete_vdom(obj, context, **kwargs):
    cls = fortinet_db.Fortinet_ML2_Namespace
    namespace = fortinet_db.query_record(context, cls, **kwargs)
    if namespace:
        tenant_id = namespace.tenant_id
        if not fortinet_db.query_count(context, l3_db.Router,
                                       tenant_id=tenant_id) and \
            not fortinet_db.query_count(context, models_v2.Network,
                                       tenant_id=tenant_id) and \
            not fortinet_db.query_count(context, l3_db.FloatingIP,
                                        tenant_id=tenant_id):
            try:
                op(obj, context, resources.Vdom.get, name=namespace.vdom)
                op(obj, context, resources.Vdom.delete, name=namespace.vdom)
            except Exception as e:
                resources.Exinfo(e)
            fortinet_db.delete_record(context, cls, **kwargs)
        else:
            db_routers = fortinet_db.query_records(context,
                                                   l3_db.Router,
                                                   tenant_id=tenant_id)
            db_networks = fortinet_db.query_records(context,
                                                    models_v2.Network,
                                                    tenant_id=tenant_id)
            db_fips = fortinet_db.query_records(context,
                                                l3_db.FloatingIP,
                                                tenant_id=tenant_id)
            LOG.debug(
                "Keeping vdom, because existing db_routers: %(routers)s,"
                "db_networks: %(networks)s, db_fips: %(fips)s", {
                    'routers': db_routers,
                    'networks': db_networks,
                    'fips': db_fips
                })
    return namespace
Пример #14
0
def get_vlink_intf(obj, context, **kwargs):
    vlink_vlan = fortinet_db.query_record(context,
                        fortinet_db.Fortinet_Vlink_Vlan_Allocation,
                        **kwargs)
    if not vlink_vlan and kwargs.get('vdom', None):
        return add_vlink(obj, context, kwargs['vdom'])
    return (vlink_vlan.inf_name_int_vdom, vlink_vlan.inf_name_ext_vdom)
Пример #15
0
def delete_vdom(obj, context, **kwargs):
    cls = fortinet_db.Fortinet_ML2_Namespace
    namespace = fortinet_db.query_record(context, cls, **kwargs)
    if namespace:
        tenant_id = namespace.tenant_id
        if not fortinet_db.query_count(context, l3_db.Router,
                                       tenant_id=tenant_id) and \
            not fortinet_db.query_count(context, models_v2.Network,
                                       tenant_id=tenant_id) and \
            not fortinet_db.query_count(context, l3_db.FloatingIP,
                                        tenant_id=tenant_id):
            try:
                op(obj, context, resources.Vdom.get, name=namespace.vdom)
                op(obj, context, resources.Vdom.delete, name=namespace.vdom)
            except Exception as e:
                resources.Exinfo(e)
            fortinet_db.delete_record(context, cls, **kwargs)
        else:
            db_routers = fortinet_db.query_records(context, l3_db.Router,
                                                   tenant_id=tenant_id)
            db_networks = fortinet_db.query_records(context, models_v2.Network,
                                                    tenant_id=tenant_id)
            db_fips = fortinet_db.query_records(context, l3_db.FloatingIP,
                                                tenant_id=tenant_id)
            LOG.debug("Keeping vdom, because existing db_routers: %(routers)s,"
                      "db_networks: %(networks)s, db_fips: %(fips)s",
                      {'routers': db_routers, 'networks': db_networks,
                       'fips': db_fips})
    return namespace
Пример #16
0
def add_addrgrp(obj, context, **kwargs):
    """
    :param context:
    :param kwargs:
     {
        "name": "addrgrp_osvdm1",
        "vdom": "osvdm1",
        "members": ["192.168.33.0"]
     }
    :return:
    """
    cls = fortinet_db.Fortinet_Firewall_Address
    records = fortinet_db.query_records(context, cls, group=kwargs['name'])
    for name in kwargs['members']:
        record = fortinet_db.query_record(context, cls,
                                          name=name, vdom=kwargs['vdom'])
        if not record.group:
            cls.update_record(context, record, group=kwargs['name'])
            # TODO(samsu): need to add a rollback action to taskmanager
        else:
            LOG.debug("The member %(record)s already joined a group",
                      {"record": record})
    for record in records:
        kwargs['members'].append(record.name)
    try:
        op(obj, context, resources.FirewallAddrgrp.get,
           name=kwargs['name'], vdom=kwargs['vdom'])
        # TODO(samsu): need to add a rollback action to taskmanager
        op(obj, context, resources.FirewallAddrgrp.set, **kwargs)
    except exception.ResourceNotFound:
        op(obj, context, resources.FirewallAddrgrp.add, **kwargs)
Пример #17
0
 def remove_router_interface(self, context, router_id, interface_info):
     """Deletes vlink, default router from Fortinet device."""
     LOG.debug("FortinetL3ServicePlugin.remove_router_interface called: "
               "router_id=%(router_id)s "
               "interface_info=%(interface_info)r",
               {'router_id': router_id, 'interface_info': interface_info})
     with context.session.begin(subtransactions=True):
         # TODO(jerryz): move this out of transaction.
         setattr(context, 'GUARD_TRANSACTION', False)
         info = (super(FortinetL3ServicePlugin, self).
                 remove_router_interface(context, router_id,
                                         interface_info))
         try:
             subnet = self._core_plugin._get_subnet(context,
                                                    info['subnet_id'])
             tenant_id = subnet['tenant_id']
             network_id = subnet['network_id']
             vlan_inf = utils.get_intf(context, network_id)
             db_namespace = fortinet_db.query_record(context,
                                     fortinet_db.Fortinet_ML2_Namespace,
                                     tenant_id=tenant_id)
             utils.delete_fwpolicy(self, context,
                                   vdom=db_namespace.vdom,
                                   srcintf=vlan_inf)
         except Exception:
             with excutils.save_and_reraise_exception():
                 LOG.error(_LE("Fail remove of interface from Fortigate "
                               "router interface. info=%(info)s, "
                               "router_id=%(router_id)s"),
                          {"info": info, "router_id": router_id})
     return info
Пример #18
0
def add_interface_ip(obj, context, **kwargs):
    """
    :param context:
    :param kwargs: example format as below
        {
            "ip": "10.160.37.20 255.255.255.0",
            "name": "port37",
            "vdom": "root"
        }
    :return:
    """
    inf_db = fortinet_db.query_record(context,
                            fortinet_db.Fortinet_Interface,
                            name=kwargs.get('name'))
    if const.EXT_DEF_DST in getattr(inf_db, 'ip'):
        inf_db.update_record(context, inf_db, **kwargs)
        op(obj, context, resources.VlanInterface.set, **kwargs)
    else:
        records = fortinet_db.query_records(context,
                                  fortinet_db.Fortinet_Interface_subip,
                                  name=kwargs.get('name'))
        org_subips = [getattr(record, 'ip') for record in records]

        if kwargs.get('ip') in org_subips:
            return
        add_record(obj, context,
                   fortinet_db.Fortinet_Interface_subip, **kwargs)
Пример #19
0
 def delete_network_precommit(self, mech_context):
     """Delete Network from the plugin specific database table."""
     LOG.debug("delete_network_precommit: called")
     context = mech_context._plugin_context
     network = mech_context.current
     if network["router:external"]:
         # return when the network is external network
         # TODO(samsu): may check external network
         # before delete namespace
         return
     tenant_id = network['tenant_id']
     namespace = fortinet_db.query_record(
         context, fortinet_db.Fortinet_ML2_Namespace, tenant_id=tenant_id)
     if not namespace:
         return
     records = fortinet_db.query_records(context,
                                         fortinet_db.Fortinet_Interface,
                                         network_id=network['id'])
     for record in records:
         try:
             utils.delete_vlanintf(self,
                                   context,
                                   name=record.name,
                                   vdom=namespace.vdom)
         except Exception as e:
             resources.Exinfo(e)
             raise ml2_exc.MechanismDriverError(
                 method=sys._getframe().f_code.co_name)
Пример #20
0
def add_interface_ip(obj, context, **kwargs):
    """
    :param context:
    :param kwargs: example format as below
        {
            "ip": "10.160.37.20 255.255.255.0",
            "name": "port37",
            "vdom": "root"
        }
    :return:
    """
    inf_db = fortinet_db.query_record(context,
                                      fortinet_db.Fortinet_Interface,
                                      name=kwargs.get('name'))
    if const.EXT_DEF_DST in getattr(inf_db, 'ip'):
        inf_db.update_record(context, inf_db, **kwargs)
        op(obj, context, resources.VlanInterface.set, **kwargs)
    else:
        records = fortinet_db.query_records(
            context,
            fortinet_db.Fortinet_Interface_subip,
            name=kwargs.get('name'))
        org_subips = [getattr(record, 'ip') for record in records]

        if kwargs.get('ip') in org_subips:
            return
        add_record(obj, context, fortinet_db.Fortinet_Interface_subip,
                   **kwargs)
Пример #21
0
 def delete_floatingip(self, context, id):
     LOG.debug("delete_floatingip called() id=%s", id)
     fip = fortinet_db.query_record(context, l3_db.FloatingIP, id=id)
     if fip and getattr(fip, 'fixed_port_id', None):
         self._disassociate_floatingip(context, id)
         super(FortinetL3ServicePlugin,
               self).disassociate_floatingips(context, fip['fixed_port_id'])
     self._release_floatingip(context, id)
Пример #22
0
 def delete_floatingip(self, context, id):
     LOG.debug("delete_floatingip called() id=%s", id)
     fip = fortinet_db.query_record(context, l3_db.FloatingIP, id=id)
     if fip and getattr(fip, 'fixed_port_id', None):
         self._disassociate_floatingip(context, id)
         super(FortinetL3ServicePlugin, self).disassociate_floatingips(
             context, fip['fixed_port_id'])
     self._release_floatingip(context, id)
Пример #23
0
    def add_router_interface(self, context, router_id, interface_info):
        """creates vlnk on the fortinet device."""
        LOG.debug("FortinetL3ServicePlugin.add_router_interface: "
                  "router_id=%(router_id)s "
                  "interface_info=%(interface_info)r",
                  {'router_id': router_id, 'interface_info': interface_info})
        with context.session.begin(subtransactions=True):
            info = super(FortinetL3ServicePlugin, self).add_router_interface(
                context, router_id, interface_info)
            port = db.get_port(context, info['port_id'])
            port['admin_state_up'] = True
            port['port'] = port
            LOG.debug("FortinetL3ServicePlugin: "
                      "context=%(context)s"
                      "port=%(port)s "
                      "info=%(info)r",
                      {'context': context, 'port': port, 'info': info})
            interface_info = info
            subnet = self._core_plugin._get_subnet(context,
                                                   interface_info['subnet_id'])
            network_id = subnet['network_id']
            tenant_id = port['tenant_id']
            port_filters = {'network_id': [network_id],
                            'device_owner': [DEVICE_OWNER_ROUTER_INTF]}
            port_count = self._core_plugin.get_ports_count(context,
                                                           port_filters)
            # port count is checked against 2 since the current port is already
            # added to db
            if port_count == 2:
                # This subnet is already part of some router
                LOG.error(_LE("FortinetL3ServicePlugin: adding redundant "
                              "router interface is not supported"))
                raise Exception(_("FortinetL3ServicePlugin:adding redundant "
                                  "router interface is not supported"))
            try:
                db_namespace = fortinet_db.query_record(context,
                                        fortinet_db.Fortinet_ML2_Namespace,
                                        tenant_id=tenant_id)
                vlan_inf = utils.get_intf(context, network_id)
                int_intf, ext_intf = utils.get_vlink_intf(self, context,
                                               vdom=db_namespace.vdom)
                utils.add_fwpolicy(self, context,
                                   vdom=db_namespace.vdom,
                                   srcintf=vlan_inf,
                                   dstintf=int_intf,
                                   nat='enable')

            except Exception as e:
                LOG.error(_LE("Failed to create Fortinet resources to add "
                            "router interface. info=%(info)s, "
                            "router_id=%(router_id)s"),
                          {"info": info, "router_id": router_id})
                utils._rollback_on_err(self, context, e)
                with excutils.save_and_reraise_exception():
                    self.remove_router_interface(context, router_id,
                                                 interface_info)
        utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
        return info
Пример #24
0
def set_by_keys(obj, context, cls, resource, *keys, **kwargs):
    params = _prepare_params(None, resource, *keys, **kwargs)
    record = fortinet_db.query_record(context, cls, **params)
    if record:
        record = cls.update_record(context, record, **kwargs)
        set_resource_with_keys(obj, context, record, resource, *keys, **kwargs)
    else:
        record = add_by_keys(obj, context, cls, resource, *keys, **kwargs)
    return record
Пример #25
0
def set_by_id(obj, context, cls, resource, **kwargs):
    params = _prepare_params(None, resource, 'vdom', 'id', **kwargs)
    record = fortinet_db.query_record(context, cls, **params)
    if record:
        cls.update_record(context, record, **kwargs)
        set_resource_with_id(obj, context, record, resource, **kwargs)
        return record
    else:
        return None
 def update_firewall_for_delete_router(self, context, router_id):
     LOG.debug("fwaas delete_router() called, router_id: %(rtid)s",
               {'rtid': router_id})
     cls = firewall_router_insertion_db.FirewallRouterAssociation
     db_fw_rt = fortinet_db.query_record(context, cls, router_id=router_id)
     if not db_fw_rt:
         return None
     firewall = {u'firewall': {'router_ids': []}}
     return self.update_firewall(context, db_fw_rt.fw_id, firewall)
 def update_firewall_for_delete_router(self, context, router_id):
     LOG.debug("fwaas delete_router() called, router_id: %(rtid)s",
               {'rtid': router_id})
     cls = firewall_router_insertion_db.FirewallRouterAssociation
     db_fw_rt = fortinet_db.query_record(context, cls, router_id=router_id)
     if not db_fw_rt:
         return None
     firewall = {u'firewall': {'router_ids': []}}
     return self.update_firewall(context, db_fw_rt.fw_id, firewall)
Пример #28
0
def set_by_keys(obj, context, cls, resource, *keys, **kwargs):
    params = _prepare_params(None, resource, *keys, **kwargs)
    record = fortinet_db.query_record(context, cls, **params)
    if record:
        record = cls.update_record(context, record, **kwargs)
        set_resource_with_keys(obj, context, record, resource, *keys, **kwargs)
    else:
        record = add_by_keys(obj, context, cls, resource, *keys, **kwargs)
    return record
Пример #29
0
def set_by_id(obj, context, cls, resource, **kwargs):
    params = _prepare_params(None, resource, 'vdom', 'id', **kwargs)
    record = fortinet_db.query_record(context, cls, **params)
    if record:
        cls.update_record(context, record, **kwargs)
        set_resource_with_id(obj, context, record, resource, **kwargs)
        return record
    else:
        return None
Пример #30
0
 def disassociate_floatingips(self, context, port_id, do_notify=True):
     fip = fortinet_db.query_record(context, l3_db.FloatingIP,
                                    fixed_port_id=port_id)
     if fip and getattr(fip, 'id', None):
         self._disassociate_floatingip(context, fip.id)
     return super(FortinetL3ServicePlugin,
                  self).disassociate_floatingips(context,
                                                 port_id,
                                                 do_notify=do_notify)
Пример #31
0
    def delete_port_postcommit(self, mech_context):
        LOG.debug("delete_port_postcommit: called")
        port = mech_context.current
        context = mech_context._plugin_context
        try:
            port_id = port['id']
            subnet_id = port['fixed_ips'][0]['subnet_id']
            db_subnet = fortinet_db.query_record(context,
                                             fortinet_db.Fortinet_ML2_Subnet,
                                             subnet_id=subnet_id)
            db_subnetv2 = fortinet_db.query_record(context, models_v2.Subnet,
                                                   id=subnet_id)
            if port['device_owner'] in ['network:router_gateway']:
                if fortinet_db.query_record(context, ext_db.ExternalNetwork,
                                            network_id=port['network_id']):
                    #delete ippool and its related firewall policy
                    utils.clr_ext_gw(self, context, port)

            elif port['device_owner'] in ['compute:nova', 'compute:None', '']:
                # delete dhcp related functions
                utils.delete_reservedip(self, context, port_id=port_id)

            elif port['device_owner'] in ['network:router_interface']:
                # add firewall address and address group
                name = const.PREFIX['addrgrp'] + db_subnet.vdom
                member = str(netaddr.IPNetwork(db_subnetv2.cidr).network)
                utils.delete_fwpolicy(self, context,
                                      vdom=db_subnet.vdom,
                                      srcintf='any',
                                      srcaddr=name,
                                      dstintf='any',
                                      dstaddr=name,
                                      nat='disable')
                utils.delete_addrgrp(self, context,
                                     name=name,
                                     vdom=db_subnet.vdom,
                                     members=member.split(' '))
                utils.delete_fwaddress(self, context,
                                       vdom=db_subnet.vdom,
                                       name=member)
        except Exception as e:
            resources.Exinfo(e)
            raise ml2_exc.MechanismDriverError(
                method=sys._getframe().f_code.co_name)
Пример #32
0
 def disassociate_floatingips(self, context, port_id, do_notify=True):
     fip = fortinet_db.query_record(context,
                                    l3_db.FloatingIP,
                                    fixed_port_id=port_id)
     if fip and getattr(fip, 'id', None):
         self._disassociate_floatingip(context, fip.id)
     return super(FortinetL3ServicePlugin,
                  self).disassociate_floatingips(context,
                                                 port_id,
                                                 do_notify=do_notify)
 def _get_fip_before_id(self, context, fwr_id):
     fwp_assed = fortinet_db.Fortinet_FW_Rule_Association.query_one(
             context, type=constants.TYPE_EXT, fwr_id=fwr_id)
     if not fwp_assed:
         fwp_assed = fortinet_db.Fortinet_FW_Rule_Association.query_one(
             context, type=constants.TYPE_INT, fwr_id=fwr_id)
     fwp = fortinet_db.query_record(context,
                                    fortinet_db.Fortinet_Firewall_Policy,
                                    id=fwp_assed.fortinet_pid)
     return getattr(fwp, 'edit_id', None)
 def _get_fip_before_id(self, context, fwr_id):
     fwp_assed = fortinet_db.Fortinet_FW_Rule_Association.query_one(
             context, type=constants.TYPE_EXT, fwr_id=fwr_id)
     if not fwp_assed:
         fwp_assed = fortinet_db.Fortinet_FW_Rule_Association.query_one(
             context, type=constants.TYPE_INT, fwr_id=fwr_id)
     fwp = fortinet_db.query_record(context,
                                    fortinet_db.Fortinet_Firewall_Policy,
                                    id=fwp_assed.fortinet_pid)
     return getattr(fwp, 'edit_id', None)
Пример #35
0
    def _disassociate_floatingip(self, context, id):
        l3db_fip = self._get_floatingip(context, id)
        db_namespace = fortinet_db.query_record(
            context,
            fortinet_db.Fortinet_ML2_Namespace,
            tenant_id=l3db_fip.tenant_id)
        db_fip = fortinet_db.query_record(
            context,
            fortinet_db.Fortinet_FloatingIP_Allocation,
            floating_ip_address=l3db_fip.floating_ip_address,
            allocated=True)
        int_intf, ext_intf = utils.get_vlink_intf(self,
                                                  context,
                                                  vdom=db_namespace.vdom)
        db_ip = fortinet_db.query_record(context,
                                         models_v2.IPAllocation,
                                         port_id=l3db_fip.fixed_port_id)
        vlan_inf = utils.get_intf(context, db_ip.network_id)
        mappedip = utils.get_ipaddr(db_fip.ip_subnet, 0)
        utils.delete_fwpolicy(self,
                              context,
                              vdom=db_namespace.vdom,
                              srcintf=vlan_inf,
                              srcaddr=l3db_fip.fixed_ip_address,
                              dstintf=int_intf,
                              poolname=mappedip)

        utils.delete_fwaddress(self,
                               context,
                               name=l3db_fip.fixed_ip_address,
                               vdom=db_namespace.vdom)

        utils.delete_fwpolicy(self,
                              context,
                              vdom=db_namespace.vdom,
                              dstaddr=db_fip.floating_ip_address)

        utils.delete_vip(self,
                         context,
                         vdom=db_namespace.vdom,
                         name=db_fip.floating_ip_address)
Пример #36
0
 def add_router_interface(self, context, port):
     """creates vlnk on the fortinet device."""
     db_namespace = fortinet_db.query_record(context,
                                             fortinet_db.Fortinet_ML2_Namespace,
                                             tenant_id=port['tenant_id'])
     vlan_inf = utils.get_intf(context, port['network_id'])
     int_intf, ext_intf = utils.get_vlink_intf(self, context,
                                               vdom=db_namespace.vdom)
     utils.add_fwpolicy(self, context,
                        vdom=db_namespace.vdom,
                        srcintf=vlan_inf,
                        dstintf=int_intf,
                        nat='enable')
Пример #37
0
def delete_reservedip(obj, context, **kwargs):
    cls = fortinet_db.Fortinet_ML2_ReservedIP
    reserved_ip = fortinet_db.query_record(context, cls, **kwargs)

    if reserved_ip:
        db_reservedips = fortinet_db.query_records(context, cls,
                                        subnet_id=reserved_ip.subnet_id)
        db_reservedips.remove(reserved_ip)
        reserved_addresses = []
        for rsrvdip in db_reservedips:
            reserved_addresses.append({'id': rsrvdip.edit_id,
                                       'ip': rsrvdip.ip,
                                       'mac': rsrvdip.mac})
        db_subnet = fortinet_db.query_record(context,
                                             fortinet_db.Fortinet_ML2_Subnet,
                                             subnet_id=reserved_ip.subnet_id)
        if db_subnet:
            op(obj, context, resources.DhcpServerRsvAddr.set,
               id=db_subnet.edit_id,
               vdom=reserved_ip.vdom,
               reserved_address=jsonutils.dumps(reserved_addresses))
        fortinet_db.delete_record(context, cls, **kwargs)
Пример #38
0
def clr_ext_gw(obj, context, port):
    ip_address = port['fixed_ips'][0]['ip_address']
    subnetv2_db = fortinet_db.query_record(context, models_v2.Subnet,
                                    id=port['fixed_ips'][0]['subnet_id'])
    netmask = netaddr.IPNetwork(subnetv2_db.cidr).netmask
    ip = "%s %s" % (ip_address, netmask)
    delete_interface_ip(obj, context,
                        name=obj._fortigate['ext_interface'],
                        vdom=const.EXT_VDOM,
                        ip=ip)

    delete_fwpolicy(obj, context, vdom=const.EXT_VDOM, poolname=ip_address)
    delete_fwippool(obj, context, vdom=const.EXT_VDOM, name=ip_address)
Пример #39
0
def clr_ext_gw(obj, context, port):
    ip_address = port['fixed_ips'][0]['ip_address']
    subnetv2_db = fortinet_db.query_record(
        context, models_v2.Subnet, id=port['fixed_ips'][0]['subnet_id'])
    netmask = netaddr.IPNetwork(subnetv2_db.cidr).netmask
    ip = "%s %s" % (ip_address, netmask)
    delete_interface_ip(obj,
                        context,
                        name=obj._fortigate['ext_interface'],
                        vdom=const.EXT_VDOM,
                        ip=ip)

    delete_fwpolicy(obj, context, vdom=const.EXT_VDOM, poolname=ip_address)
    delete_fwippool(obj, context, vdom=const.EXT_VDOM, name=ip_address)
Пример #40
0
def check(obj, context, vdom, resource=resources.VlanInterface):
    vlink_vlan = fortinet_db.query_record(context,
                     fortinet_db.Fortinet_Vlink_Vlan_Allocation, vdom=vdom)
    if vlink_vlan:
        try:
            op(obj, context, resource.get,
               vdom=vdom, name=vlink_vlan.inf_name_int_vdom)
            op(obj, context, resource.get,
               vdom=const.EXT_VDOM, name=vlink_vlan.inf_name_ext_vdom)
        except exception.ResourceNotFound as e:
            import inspect
            caller = inspect.stack()[1][3]
            LOG.debug("## Check vlink interface failed on the %(func)s.",
                      {'func': caller})
            resources.Exinfo(e)
Пример #41
0
 def add_router_interface(self, context, port):
     """creates vlnk on the fortinet device."""
     db_namespace = fortinet_db.query_record(
         context,
         fortinet_db.Fortinet_ML2_Namespace,
         tenant_id=port['tenant_id'])
     vlan_inf = utils.get_intf(context, port['network_id'])
     int_intf, ext_intf = utils.get_vlink_intf(self,
                                               context,
                                               vdom=db_namespace.vdom)
     utils.add_fwpolicy(self,
                        context,
                        vdom=db_namespace.vdom,
                        srcintf=vlan_inf,
                        dstintf=int_intf,
                        nat='enable')
Пример #42
0
def delete_interface_ip(obj, context, **kwargs):
    """
    :param context:
    :param kwargs: example format as below
        {
            "ip": "10.160.37.20 255.255.255.0",
            "name": "port37",
            "vdom": "root"
        }
    :return:
    """
    records = fortinet_db.query_records(context,
                                        fortinet_db.Fortinet_Interface_subip,
                                        name=kwargs.get('name'))
    org_subips = [getattr(record, 'ip') for record in records]
    if kwargs.get('ip') in org_subips:
        org_subips.remove(kwargs["ip"])
        #op(obj, context, resources.VlanInterface.set,
        #   name=kwargs.get('name'),
        #   vdom=kwargs.get('vdom'),
        #   secondaryips=org_subips)
        fortinet_db.delete_record(context,
                                  fortinet_db.Fortinet_Interface_subip,
                                  **kwargs)
    else:
        inf_db = fortinet_db.query_record(context,
                                          fortinet_db.Fortinet_Interface,
                                          **kwargs)
        if not inf_db:
            return
        if org_subips:
            kwargs['ip'] = org_subips.pop()
            op(obj,
               context,
               resources.VlanInterface.set,
               name=kwargs.get('name'),
               vdom=kwargs.get('vdom'),
               secondaryips=org_subips)
            fortinet_db.delete_record(context,
                                      fortinet_db.Fortinet_Interface_subip,
                                      **kwargs)
        else:
            kwargs['ip'] = const.EXT_DEF_DST

        op(obj, context, resources.VlanInterface.set, **kwargs)
        inf_db.update_record(context, inf_db, ip=kwargs['ip'])
    def ftnt_sync_routers(self, context, **kwargs):
        """Sync routers according to filters to a specific agent.

        @param context: contain user information
        @param kwargs: host, router_ids
        @return: a list of routers
                 with their interfaces and floating_ips
        """
        # import ipdb;ipdb.set_trace()
        host = kwargs.get('host')
        routers = kwargs.get('routers') or {}
        fortigate = fortinet_db.query_record(
            context, fortinet_db.Fortinet_Fortigate, host=host)
        for router in routers:
            rinfo = self._get_router_info(context, fortigate.id, router)
            rinfo.setdefault('fortigate', fortigate.make_dict())
            router['fortigate'] = rinfo
        return routers
Пример #44
0
def delete_interface_ip(obj, context, **kwargs):
    """
    :param context:
    :param kwargs: example format as below
        {
            "ip": "10.160.37.20 255.255.255.0",
            "name": "port37",
            "vdom": "root"
        }
    :return:
    """
    records = fortinet_db.query_records(context,
                                        fortinet_db.Fortinet_Interface_subip,
                                        name=kwargs.get('name'))
    org_subips = [getattr(record, 'ip') for record in records]
    if kwargs.get('ip') in org_subips:
        org_subips.remove(kwargs["ip"])
        #op(obj, context, resources.VlanInterface.set,
        #   name=kwargs.get('name'),
        #   vdom=kwargs.get('vdom'),
        #   secondaryips=org_subips)
        fortinet_db.delete_record(context,
                                  fortinet_db.Fortinet_Interface_subip,
                                  **kwargs)
    else:
        inf_db = fortinet_db.query_record(context,
                                          fortinet_db.Fortinet_Interface,
                                          **kwargs)
        if not inf_db:
            return
        if org_subips:
            kwargs['ip'] = org_subips.pop()
            op(obj, context, resources.VlanInterface.set,
               name=kwargs.get('name'),
               vdom=kwargs.get('vdom'),
               secondaryips=org_subips)
            fortinet_db.delete_record(context,
                                  fortinet_db.Fortinet_Interface_subip,
                                  **kwargs)
        else:
            kwargs['ip'] = const.EXT_DEF_DST

        op(obj, context, resources.VlanInterface.set, **kwargs)
        inf_db.update_record(context, inf_db, ip=kwargs['ip'])
Пример #45
0
def subnet_migration(context, mech_driver):
    # table subnets
    subnet = {
        'allocation_pools': [{
            'start': '172.20.21.2',
            'end': '172.20.21.254'
        }],
        'cidr': '172.20.21.0/24',
        'id': 'ee1506dc-d1a9-45b3-840e-137bdaebce52',
        'enable_dhcp': True,
        'network_id': u'ad47f7b8-4bb7-4591-b8ed-f720237dd24f',
        'tenant_id': u'11513667f4ee4a14acb0985659456f24',
        'dns_nameservers': [],
        'gateway_ip': u'172.20.21.1',
        'shared': False
    }
    ipallocation_pool = {
        'start': '172.20.21.2',
        'end': '172.20.21.254'
    }
    records = fortinet_db.query_records(context, models_v2.Subnet)
    with Progress(len(records), 'subnet_migration') as p:
        for record in records:
            dns_nameservers = []
            reset(subnet)
            reset(ipallocation_pool)
            db_ipallocation = fortinet_db.query_record(context,
                                                       models_v2.IPAllocationPool,
                                                       subnet_id=record.id)
            cls2dict(db_ipallocation, ipallocation_pool,
                     first_ip='start', last_ip='end')
            db_dnssrvs = fortinet_db.query_records(context,
                                                   models_v2.DNSNameServer,
                                                   subnet_id=record.id)

            for dns in db_dnssrvs:
                dns_nameservers.append(dns.address)
            cls2dict(record, subnet)
            subnet['dns_nameservers'] = dns_nameservers
            subnet['allocation_pools'] = [ipallocation_pool]
            mech_context = Fake_mech_context(_plugin_context=context,
                                             current=subnet)
            mech_driver.create_subnet_postcommit(mech_context)
            p.update()
Пример #46
0
def add_reservedip(obj, context, **kwargs):
    cls = fortinet_db.Fortinet_ML2_ReservedIP
    add_record(obj, context, cls, **kwargs)
    db_reservedips = fortinet_db.query_records(context, cls,
                                        subnet_id=kwargs.get('subnet_id'))
    db_subnet = fortinet_db.query_record(context,
                                         fortinet_db.Fortinet_ML2_Subnet,
                                         subnet_id=kwargs.get('subnet_id'))
    if db_subnet:
        reserved_addresses = []
        for rsrvdip in db_reservedips:
            reserved_addresses.append({'id': rsrvdip.edit_id,
                                       'ip': rsrvdip.ip,
                                       'mac': rsrvdip.mac})

        op(obj, context, resources.DhcpServerRsvAddr.set,
           id=db_subnet.edit_id,
           vdom=kwargs.get('vdom'),
           reserved_address=jsonutils.dumps(reserved_addresses))
Пример #47
0
def subnet_migration(context, mech_driver):
    # table subnets
    subnet = {
        'allocation_pools': [{
            'start': '172.20.21.2',
            'end': '172.20.21.254'
        }],
        'cidr': '172.20.21.0/24',
        'id': 'ee1506dc-d1a9-45b3-840e-137bdaebce52',
        'enable_dhcp': True,
        'network_id': u'ad47f7b8-4bb7-4591-b8ed-f720237dd24f',
        'tenant_id': u'11513667f4ee4a14acb0985659456f24',
        'dns_nameservers': [],
        'gateway_ip': u'172.20.21.1',
        'shared': False
    }
    ipallocation_pool = {'start': '172.20.21.2', 'end': '172.20.21.254'}
    records = fortinet_db.query_records(context, models_v2.Subnet)
    with Progress(len(records), 'subnet_migration') as p:
        for record in records:
            dns_nameservers = []
            reset(subnet)
            reset(ipallocation_pool)
            db_ipallocation = fortinet_db.query_record(
                context, models_v2.IPAllocationPool, subnet_id=record.id)
            cls2dict(db_ipallocation,
                     ipallocation_pool,
                     first_ip='start',
                     last_ip='end')
            db_dnssrvs = fortinet_db.query_records(context,
                                                   models_v2.DNSNameServer,
                                                   subnet_id=record.id)

            for dns in db_dnssrvs:
                dns_nameservers.append(dns.address)
            cls2dict(record, subnet)
            subnet['dns_nameservers'] = dns_nameservers
            subnet['allocation_pools'] = [ipallocation_pool]
            mech_context = Fake_mech_context(_plugin_context=context,
                                             current=subnet)
            mech_driver.create_subnet_postcommit(mech_context)
            p.update()
Пример #48
0
 def delete_router(self, context, id):
     LOG.debug("delete_router: router id=%s", id)
     try:
         if self.enable_fwaas:
             fw_plugin = directory.get_plugin(service_consts.FIREWALL)
             fw_plugin.update_firewall_for_delete_router(context, id)
         with context.session.begin(subtransactions=True):
             router = fortinet_db.query_record(context, l3_db.Router, id=id)
             # TODO(jerryz): move this out of transaction.
             setattr(context, 'GUARD_TRANSACTION', False)
             super(FortinetL3ServicePlugin, self).delete_router(context, id)
             if getattr(router, 'tenant_id', None):
                 utils.delete_vlink(self, context, router.tenant_id)
                 utils.delete_vdom(self, context,
                                   tenant_id=router.tenant_id)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE("Failed to delete_router routerid=%(id)s"),
                       {"id": id})
             resources.Exinfo(e)
Пример #49
0
 def delete_router(self, context, id):
     LOG.debug("delete_router: router id=%s", id)
     try:
         if self.enable_fwaas:
             fw_plugin = directory.get_plugin(service_consts.FIREWALL)
             fw_plugin.update_firewall_for_delete_router(context, id)
         with context.session.begin(subtransactions=True):
             router = fortinet_db.query_record(context, l3_db.Router, id=id)
             # TODO(jerryz): move this out of transaction.
             setattr(context, 'GUARD_TRANSACTION', False)
             super(FortinetL3ServicePlugin, self).delete_router(context, id)
             if getattr(router, 'tenant_id', None):
                 utils.delete_vlink(self, context, router.tenant_id)
                 utils.delete_vdom(self,
                                   context,
                                   tenant_id=router.tenant_id)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE("Failed to delete_router routerid=%(id)s"),
                       {"id": id})
             resources.Exinfo(e)
Пример #50
0
def check(obj, context, vdom, resource=resources.VlanInterface):
    vlink_vlan = fortinet_db.query_record(
        context, fortinet_db.Fortinet_Vlink_Vlan_Allocation, vdom=vdom)
    if vlink_vlan:
        try:
            op(obj,
               context,
               resource.get,
               vdom=vdom,
               name=vlink_vlan.inf_name_int_vdom)
            op(obj,
               context,
               resource.get,
               vdom=const.EXT_VDOM,
               name=vlink_vlan.inf_name_ext_vdom)
        except exception.ResourceNotFound as e:
            import inspect
            caller = inspect.stack()[1][3]
            LOG.debug("## Check vlink interface failed on the %(func)s.",
                      {'func': caller})
            resources.Exinfo(e)
 def _get_router_info(self, context, fortigate_id, router):
     # Limit one router per tenant
     if not router.get('id', None):
         return
     rinfo = {}
     tenant_id = router.get('tenant_id', None)
     if not tenant_id:
         router_db = fortinet_db.query_record(
             context, l3_db.Router, id=router['id'])
         tenant_id = getattr(router_db, tenant_id, None)
     try:
         namespace = utils.allocate_vdom(self, context, tenant_id=tenant_id)
         rinfo['vdom'] = namespace.make_dict() if namespace else {}
         rinfo['vlink'] = utils.allocate_vlink(self, context, fortigate_id,
                                               namespace.vdom)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE("Failed to create_router router=%(router)s"),
                       {"router ": router})
             utils.rollback_on_err(self, context, e)
     utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
     return rinfo
Пример #52
0
 def remove_router_interface(self, context, router_id, interface_info):
     """Deletes vlink, default router from Fortinet device."""
     LOG.debug(
         "FortinetL3ServicePlugin.remove_router_interface called: "
         "router_id=%(router_id)s "
         "interface_info=%(interface_info)r", {
             'router_id': router_id,
             'interface_info': interface_info
         })
     with context.session.begin(subtransactions=True):
         # TODO(jerryz): move this out of transaction.
         setattr(context, 'GUARD_TRANSACTION', False)
         info = (super(FortinetL3ServicePlugin,
                       self).remove_router_interface(
                           context, router_id, interface_info))
         try:
             subnet = self._core_plugin._get_subnet(context,
                                                    info['subnet_id'])
             tenant_id = subnet['tenant_id']
             network_id = subnet['network_id']
             vlan_inf = utils.get_intf(context, network_id)
             db_namespace = fortinet_db.query_record(
                 context,
                 fortinet_db.Fortinet_ML2_Namespace,
                 tenant_id=tenant_id)
             utils.delete_fwpolicy(self,
                                   context,
                                   vdom=db_namespace.vdom,
                                   srcintf=vlan_inf)
         except Exception:
             with excutils.save_and_reraise_exception():
                 LOG.error(
                     _LE("Fail remove of interface from Fortigate "
                         "router interface. info=%(info)s, "
                         "router_id=%(router_id)s"), {
                             "info": info,
                             "router_id": router_id
                         })
     return info
Пример #53
0
def add_reservedip(obj, context, **kwargs):
    cls = fortinet_db.Fortinet_ML2_ReservedIP
    add_record(obj, context, cls, **kwargs)
    db_reservedips = fortinet_db.query_records(
        context, cls, subnet_id=kwargs.get('subnet_id'))
    db_subnet = fortinet_db.query_record(context,
                                         fortinet_db.Fortinet_ML2_Subnet,
                                         subnet_id=kwargs.get('subnet_id'))
    if db_subnet:
        reserved_addresses = []
        for rsrvdip in db_reservedips:
            reserved_addresses.append({
                'id': rsrvdip.edit_id,
                'ip': rsrvdip.ip,
                'mac': rsrvdip.mac
            })

        op(obj,
           context,
           resources.DhcpServerRsvAddr.set,
           id=db_subnet.edit_id,
           vdom=kwargs.get('vdom'),
           reserved_address=jsonutils.dumps(reserved_addresses))
Пример #54
0
def add_addrgrp(obj, context, **kwargs):
    """
    :param context:
    :param kwargs:
     {
        "name": "addrgrp_osvdm1",
        "vdom": "osvdm1",
        "members": ["192.168.33.0"]
     }
    :return:
    """
    cls = fortinet_db.Fortinet_Firewall_Address
    records = fortinet_db.query_records(context, cls, group=kwargs['name'])
    for name in kwargs['members']:
        record = fortinet_db.query_record(context,
                                          cls,
                                          name=name,
                                          vdom=kwargs['vdom'])
        if not record.group:
            cls.update_record(context, record, group=kwargs['name'])
            # TODO(samsu): need to add a rollback action to taskmanager
        else:
            LOG.debug("The member %(record)s already joined a group",
                      {"record": record})
    for record in records:
        kwargs['members'].append(record.name)
    try:
        op(obj,
           context,
           resources.FirewallAddrgrp.get,
           name=kwargs['name'],
           vdom=kwargs['vdom'])
        # TODO(samsu): need to add a rollback action to taskmanager
        op(obj, context, resources.FirewallAddrgrp.set, **kwargs)
    except exception.ResourceNotFound:
        op(obj, context, resources.FirewallAddrgrp.add, **kwargs)
Пример #55
0
def delete_by_id(obj, context, cls, resource, **kwargs):
    record = fortinet_db.query_record(context, cls, **kwargs)
    delete_resource_with_id(obj, context, record, resource)
    return fortinet_db.delete_record(context, cls, **kwargs)
Пример #56
0
def port_migration(context, mech_driver, l3_driver):
    """
    :param mech_driver:
    :param context:
    :return:
    # table ports
    port
    {
        'status': 'DOWN',
        'binding: host_id': '',
        'allowed_address_pairs': [],
        'device_owner': 'network: router_interface',
        'binding: profile': {

        },
        # table ipallocations
        'fixed_ips': [{
            'subnet_id': u'f645b09c-a34a-42fb-9c14-b999e43a54c7',
            'ip_address': u'172.20.21.1'
        }],
        'id': 'fb66def6-bd5e-44a0-a3f7-7c0e8e08d9ff',
        'security_groups': [],
        'device_id': u'e4020c65-7003-468b-a34d-31af297397a0',
        'name': '',
        'admin_state_up': True,
        'network_id': u'f8e34426-ccf7-429c-b726-3809d54cabdc',
        'tenant_id': u'11513667f4ee4a14acb0985659456f24',
        'binding: vif_details': {
        },
        'binding: vnic_type': 'normal',
        'binding: vif_type': 'unbound',
        'mac_address': u'00: 0c: 29: d9: 18: 3f'
    }
    """
    port = {
        'device_owner': 'network: router_interface',
        'fixed_ips': [{
            'subnet_id': u'f645b09c-a34a-42fb-9c14-b999e43a54c7',
            'ip_address': u'172.20.21.1'
        }],
        'id': 'fb66def6-bd5e-44a0-a3f7-7c0e8e08d9ff',
        'device_id': u'e4020c65-7003-468b-a34d-31af297397a0',
        'admin_state_up': True,
        'network_id': u'f8e34426-ccf7-429c-b726-3809d54cabdc',
        'tenant_id': u'11513667f4ee4a14acb0985659456f24',
        'mac_address': u'00: 0c: 29: d9: 18: 3f'
    }
    ipallocation = {
        'subnet_id': u'f645b09c-a34a-42fb-9c14-b999e43a54c7',
        'ip_address': u'172.20.21.1'
    }
    MAC = utils.get_mac(mech_driver, context)
    records = fortinet_db.query_records(context, models_v2.Port)
    with Progress(len(records), 'port_migration') as p:
        for record in records:
            reset(port)
            cls2dict(record, port)
            if port['fixed_ips']:
                fixed_ips = []
                for fixed_ip in port['fixed_ips']:
                    cls2dict(fixed_ip, ipallocation)
                    fixed_ips.append(ipallocation)
                port['fixed_ips'] = fixed_ips
            if port['device_owner'] in [ROUTER_INTF, ROUTER_GW] and \
                            MAC not in port['mac_address']:
                port['mac_address'] = MAC
                if not fortinet_db.query_count(context, models_v2.Port,
                                               mac_address=MAC,
                                               network_id=record.network_id):
                    fortinet_db.update_record(context, record,
                                              mac_address=MAC)
            mech_context = Fake_mech_context(_plugin_context=context,
                                             current=port)
            mech_driver.create_port_precommit(mech_context)
            mech_driver.create_port_postcommit(mech_context)
            db_routerport = fortinet_db.query_record(context,
                                                     l3_db.RouterPort,
                                                     port_id=record.id)
            if getattr(db_routerport, 'port_type', None) in [ROUTER_INTF]:
                l3_driver.add_router_interface(context, port)
            p.update()
Пример #57
0
def get_vlink_intf(obj, context, **kwargs):
    vlink_vlan = fortinet_db.query_record(
        context, fortinet_db.Fortinet_Vlink_Vlan_Allocation, **kwargs)
    if not vlink_vlan and kwargs.get('vdom', None):
        return add_vlink(obj, context, kwargs['vdom'])
    return (vlink_vlan.inf_name_int_vdom, vlink_vlan.inf_name_ext_vdom)
Пример #58
0
    def create_subnet_postcommit(self, mech_context, update=False):
        if not update:
            # log the context for debugging
            LOG.debug("create_subnetwork_postcommit: called, context %(ctx)s",
                      {'ctx': mech_context.current})
        gateway = mech_context.current['gateway_ip']
        network_id = mech_context.current['network_id']
        subnet_id = mech_context.current['id']
        tenant_id = mech_context.current['tenant_id']
        context = mech_context._plugin_context
        dns_nameservers = mech_context.current.setdefault(
            'dns_nameservers', [])
        if update:
            router_func = utils.set_routerstatic
            dhcp_func = utils.set_dhcpserver
        else:
            router_func = utils.add_routerstatic
            dhcp_func = utils.add_dhcpserver
        try:
            if fortinet_db.query_record(context,
                                        ext_db.ExternalNetwork,
                                        network_id=network_id):

                router_func(self,
                            context,
                            subnet_id=subnet_id,
                            vdom=const.EXT_VDOM,
                            dst=const.EXT_DEF_DST,
                            device=self._fortigate['ext_interface'],
                            gateway=gateway)
            else:
                namespace = fortinet_db.query_record(
                    context,
                    fortinet_db.Fortinet_ML2_Namespace,
                    tenant_id=tenant_id)
                interface = utils.get_intf(context,
                                           mech_context.current['network_id'])
                netmask = str(
                    netaddr.IPNetwork(mech_context.current['cidr']).netmask)
                start_ip = mech_context.current['allocation_pools'][0]['start']
                end_ip = mech_context.current['allocation_pools'][0]['end']
                dhcp_func(self,
                          context,
                          subnet_id=subnet_id,
                          vdom=namespace.vdom,
                          interface=interface,
                          dns_nameservers=dns_nameservers,
                          gateway=gateway,
                          netmask=netmask,
                          start_ip=start_ip,
                          end_ip=end_ip)

                # TODO(samsu): need to add rollback for the update and set
                cls = fortinet_db.Fortinet_Interface
                record = fortinet_db.query_record(context,
                                                  cls,
                                                  name=interface,
                                                  vdom=namespace.vdom)
                if gateway:
                    cls.update_record(context,
                                      record,
                                      ip="%s %s" % (gateway, netmask))
                    utils.op(self,
                             context,
                             resources.VlanInterface.set,
                             name=interface,
                             vdom=namespace.vdom,
                             ip="%s %s" % (gateway, netmask))
        except Exception as e:
            utils._rollback_on_err(self, context, e)
            raise ml2_exc.MechanismDriverError(
                method=sys._getframe().f_code.co_name)
        if not update:
            utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
Пример #59
0
 def _get_floatingip(self, context, id):
     return fortinet_db.query_record(context, l3_db.FloatingIP, id=id)
Пример #60
0
def port_migration(context, mech_driver, l3_driver):
    """
    :param mech_driver:
    :param context:
    :return:
    # table ports
    port
    {
        'status': 'DOWN',
        'binding: host_id': '',
        'allowed_address_pairs': [],
        'device_owner': 'network: router_interface',
        'binding: profile': {

        },
        # table ipallocations
        'fixed_ips': [{
            'subnet_id': u'f645b09c-a34a-42fb-9c14-b999e43a54c7',
            'ip_address': u'172.20.21.1'
        }],
        'id': 'fb66def6-bd5e-44a0-a3f7-7c0e8e08d9ff',
        'security_groups': [],
        'device_id': u'e4020c65-7003-468b-a34d-31af297397a0',
        'name': '',
        'admin_state_up': True,
        'network_id': u'f8e34426-ccf7-429c-b726-3809d54cabdc',
        'tenant_id': u'11513667f4ee4a14acb0985659456f24',
        'binding: vif_details': {
        },
        'binding: vnic_type': 'normal',
        'binding: vif_type': 'unbound',
        'mac_address': u'00: 0c: 29: d9: 18: 3f'
    }
    """
    port = {
        'device_owner':
        'network: router_interface',
        'fixed_ips': [{
            'subnet_id': u'f645b09c-a34a-42fb-9c14-b999e43a54c7',
            'ip_address': u'172.20.21.1'
        }],
        'id':
        'fb66def6-bd5e-44a0-a3f7-7c0e8e08d9ff',
        'device_id':
        u'e4020c65-7003-468b-a34d-31af297397a0',
        'admin_state_up':
        True,
        'network_id':
        u'f8e34426-ccf7-429c-b726-3809d54cabdc',
        'tenant_id':
        u'11513667f4ee4a14acb0985659456f24',
        'mac_address':
        u'00: 0c: 29: d9: 18: 3f'
    }
    ipallocation = {
        'subnet_id': u'f645b09c-a34a-42fb-9c14-b999e43a54c7',
        'ip_address': u'172.20.21.1'
    }
    MAC = utils.get_mac(mech_driver, context)
    records = fortinet_db.query_records(context, models_v2.Port)
    with Progress(len(records), 'port_migration') as p:
        for record in records:
            reset(port)
            cls2dict(record, port)
            if port['fixed_ips']:
                fixed_ips = []
                for fixed_ip in port['fixed_ips']:
                    cls2dict(fixed_ip, ipallocation)
                    fixed_ips.append(ipallocation)
                port['fixed_ips'] = fixed_ips
            if port['device_owner'] in [ROUTER_INTF, ROUTER_GW] and \
               MAC not in port['mac_address']:
                port['mac_address'] = MAC
                if not fortinet_db.query_count(context,
                                               models_v2.Port,
                                               mac_address=MAC,
                                               network_id=record.network_id):
                    fortinet_db.update_record(context, record, mac_address=MAC)
            mech_context = Fake_mech_context(_plugin_context=context,
                                             current=port)
            mech_driver.create_port_precommit(mech_context)
            mech_driver.create_port_postcommit(mech_context)
            db_routerport = fortinet_db.query_record(context,
                                                     l3_db.RouterPort,
                                                     port_id=record.id)
            if getattr(db_routerport, 'port_type', None) in [ROUTER_INTF]:
                l3_driver.add_router_interface(context, port)
            p.update()