Example #1
0
 def _execute(self, task):
     """Execute task."""
     msg = _("@@@ Start task %s") % str(task)
     LOG.debug(msg)
     try:
         task.wait()
     except Exception:
         msg = (_("Task %(task)s encountered exception"), {
             'task': str(task)
         })
         LOG.exception(msg)
         #status = constants.TaskStatus.ERROR
     LOG.debug("Task %(task)s return", {'task': str(task)})
Example #2
0
 def _add_interface_by_subnet(self, context, router, subnet_id, owner):
     LOG.debug(
         "_add_interface_by_subnet(): router=%(router)s, "
         "subnet_id=%(subnet_id)s, owner=%(owner)s", {
             'router': router,
             'subnet_id': subnet_id,
             'owner': owner
         })
     subnet = self._core_plugin._get_subnet(context, subnet_id)
     if not subnet['gateway_ip']:
         msg = _('Subnet for router interface must have a gateway IP')
         raise n_exc.BadRequest(resource='router', msg=msg)
     self._check_for_dup_router_subnets(context, router,
                                        subnet['network_id'], [subnet])
     fixed_ip = {
         'ip_address': subnet['gateway_ip'],
         'subnet_id': subnet['id']
     }
     # TODO(jerryz): move this out of transaction.
     setattr(context, 'GUARD_TRANSACTION', False)
     return (self._core_plugin.create_port(
         context, {
             'port': {
                 'tenant_id': subnet['tenant_id'],
                 'network_id': subnet['network_id'],
                 'fixed_ips': [fixed_ip],
                 'mac_address': utils.get_mac(self, context),
                 'admin_state_up': True,
                 'device_id': router.id,
                 'device_owner': owner,
                 'name': ''
             }
         }), [subnet], True)
Example #3
0
 def execute(self):
     if constants.TaskStatus.ROLLBACK != self.status:
         return
     while len(self._tasks):
         try:
             subtask = self._tasks.pop()
             subtask['func'](*subtask['params'])
         except Exception:
             msg = (_("Task %(task)s encountered exception in %(func)s "), {
                 'task': str(self),
                 'func': str(subtask['func'])
             })
             self.status = constants.TaskStatus.ERROR
             self._tasks = {}
             LOG.exception(msg)
     return self._update_status(constants.TaskStatus.COMPLETED)
Example #4
0
    def _result(self, task):
        """Notify task execution result."""
        try:
            return
        except Exception:
            msg = _("Task %(task)s encountered exception in %(cb)s") % {
                'task': str(task),
                'cb': str(task._result_callback)
            }
            LOG.exception(msg)

        LOG.debug("Task %(task)s return %(status)s", {
            'task': str(task),
            'status': task.status
        })

        task._finished()
Example #5
0
    def create_network_postcommit(self, mech_context):
        """Create Network as a portprofile on the fortigate."""
        LOG.debug("create_network_postcommit: called")
        network = mech_context.current
        if network["router:external"]:
            # TODO(samsu)
            return
        # use network_id to get the network attributes
        # ONLY depend on our db for getting back network attributes
        # this is so we can replay postcommit from db
        network_name = network['name']
        tenant_id = network['tenant_id']
        segment = mech_context.network_segments[0]
        LOG.debug("network is created in tenant %(tenant_id)s,"
                  "segment id is %(segment)s", {"tenant_id": tenant_id,
                                                "segment": segment['segmentation_id']})
        # currently supports only one segment per network
        if segment['network_type'] != 'vlan':
            raise Exception(_("Fortinet Mechanism: failed to create network,"
                              "only network type vlan is supported"))

        vlanid = segment['segmentation_id']
        context = mech_context._plugin_context
        try:
            namespace = utils.add_vdom(self, context, tenant_id=tenant_id)
            if not namespace:
                raise
            # TODO(samsu): type driver support vlan only,
            # need to check later
            inf_name = const.PREFIX['inf'] + str(vlanid)
            utils.add_vlanintf(self, context,
                               name=inf_name,
                               vdom=namespace.vdom,
                               vlanid=vlanid,
                               interface=self._fortigate['int_interface'],
                               alias=network_name)
        except Exception as e:
            utils._rollback_on_err(self, context, e)
            raise ml2_exc.MechanismDriverError(
                method=sys._getframe().f_code.co_name)
        utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
Example #6
0
 def create_router(self, context, router):
     LOG.debug("create_router: router=%s", router)
     # Limit one router per tenant
     if not router.get('router', None):
         return
     tenant_id = router['router']['tenant_id']
     if fortinet_db.query_count(context, l3_db.Router, tenant_id=tenant_id):
         raise Exception(
             _("FortinetL3ServicePlugin:create_router "
               "Only support one router per tenant"))
     with context.session.begin(subtransactions=True):
         try:
             namespace = utils.add_vdom(self, context, tenant_id=tenant_id)
             utils.add_vlink(self, context, 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 super(FortinetL3ServicePlugin, self).\
         create_router(context, router)
Example #7
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
Example #8
0
from oslo_config import cfg

from bell_fortinet._i18n import _

import configparser

ini_file_path = "/etc/neutron/plugins/ml2/ml2_conf.ini"
config = configparser.ConfigParser()
config.read(ini_file_path)

ml2_fortinet = config["ml2_fortinet"]

ML2_FORTINET = [
    cfg.StrOpt('address',
               default=ml2_fortinet["address"],
               help=_('The address of fortigates to connect to')),
    cfg.StrOpt('port',
               default=ml2_fortinet["port"],
               help=_('The FGT port to serve API requests')),
    cfg.StrOpt('protocol',
               default=ml2_fortinet["protocol"],
               help=_('The FGT uses which protocol: http or https')),
    cfg.StrOpt('username',
               default=ml2_fortinet["username"],
               help=_('The username used to login')),
    cfg.StrOpt('password',
               default=ml2_fortinet["password"],
               secret=True,
               help=_('The password used to login')),
    cfg.StrOpt('int_interface',
               default=ml2_fortinet["int_interface"],
Example #9
0
# Copyright (c) 2016 Fortinet Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from oslo_config import cfg

from bell_fortinet._i18n import _

FORTIGATE = [
    cfg.BoolOpt('enable_default_fwrule',
                default=False,
                help=_('If True, fwaas will add a deny all rule automatically,'
                       ' otherwise users need to add it manaully.'))
]


def register_opts():
    cfg.CONF.register_opts(FORTIGATE, "fortigate")
Example #10
0
class TaskStateSkipped(TaskException):
    message = _("State %(state)d skipped. Current state %(current)d")
Example #11
0
class InvalidState(TaskException):
    message = _("Invalid state %(state)d")