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
 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
 def sync_conf_to_db(self, param):
     cls = getattr(fortinet_db, const.FORTINET_PARAMS[param]['cls'])
     conf_list = self.get_range(param)
     session = db_api.get_session()
     records = fortinet_db.query_records(session, cls)
     for record in records:
         kwargs = {}
         for key in const.FORTINET_PARAMS[param]['keys']:
             _element = const.FORTINET_PARAMS[param]['type'](record[key])
             if _element not in conf_list and not record.allocated:
                 kwargs.setdefault(key, record[key])
                 fortinet_db.delete_record(session, cls, **kwargs)
     try:
         for i in range(0, len(conf_list),
                        len(const.FORTINET_PARAMS[param]['keys'])):
             kwargs = {}
             for key in const.FORTINET_PARAMS[param]['keys']:
                 kwargs.setdefault(key, str(conf_list[i]))
                 i += 1
             cls.init_records(session, **kwargs)
     except IndexError:
         LOG.error(
             _LE("The number of the configure range is not even,"
                 "the last one of %(param)s can not be used"),
             {'param': param})
         raise IndexError
 def sync_conf_to_db(self, param):
     cls = getattr(fortinet_db, const.FORTINET_PARAMS[param]['cls'])
     conf_list = self.get_range(param)
     session = db_api.get_session()
     records = fortinet_db.query_records(session, cls)
     for record in records:
         kwargs = {}
         for key in const.FORTINET_PARAMS[param]['keys']:
             _element = const.FORTINET_PARAMS[param]['type'](record[key])
             if _element not in conf_list and not record.allocated:
                 kwargs.setdefault(key, record[key])
                 fortinet_db.delete_record(session, cls, **kwargs)
     try:
         for i in range(0, len(conf_list),
                        len(const.FORTINET_PARAMS[param]['keys'])):
             kwargs = {}
             for key in const.FORTINET_PARAMS[param]['keys']:
                 kwargs.setdefault(key, str(conf_list[i]))
                 i += 1
             cls.init_records(session, **kwargs)
     except IndexError:
         LOG.error(_LE("The number of the configure range is not even,"
                     "the last one of %(param)s can not be used"),
                   {'param': param})
         raise IndexError
Esempio n. 5
0
    def run(self):
        while True:
            try:
                if self._stopped:
                    # Gracefully terminate this thread if the _stopped
                    # attribute was set to true
                    LOG.info(_LI("Stopping TaskManager"))
                    break

                # get a task from queue, or timeout for periodic status check
                task = self._get_task()

                try:
                    #if constants.TaskStatus.ROLLBACK == task.status:
                    self._main_thread_exec_task = task
                    self._execute(task)
                finally:
                    self._main_thread_exec_task = None
                    if task.status in [
                            constants.TaskStatus.NONE,
                            constants.TaskStatus.ERROR,
                            constants.TaskStatus.COMPLETED
                    ]:
                        # The thread is killed during _execute(). To guarantee
                        # the task been aborted correctly, put it to the queue.
                        #self._enqueue(task)
                        self._dequeue(task)
                    else:
                        self._enqueue(task)
            except Exception:
                LOG.exception(
                    _LE("TaskManager terminating because "
                        "of an exception"))
                break
    def _check_clock_sync_on_agent_start(self, agent_state, agent_time):
        """Checks if the server and the agent times are in sync.

        Method checks if the agent time is in sync with the server time
        on start up. Ignores it, on subsequent re-connects.
        """
        if agent_state.get('start_flag'):
            time_server_now = timeutils.utcnow()
            diff = abs(timeutils.delta_seconds(time_server_now, agent_time))
            if True:
                LOG.debug("### _check_clock_sync_on_agent_start")
                return

            if diff > cfg.CONF.agent_down_time:
                agent_name = agent_state['agent_type']
                time_agent = timeutils.isotime(agent_time)
                host = agent_state['host']
                log_dict = {'host': host,
                            'agent_name': agent_name,
                            'agent_time': time_agent,
                            'threshold': cfg.CONF.agent_down_time,
                            'serv_time': timeutils.isotime(time_server_now),
                            'diff': diff}
                LOG.error(_LE("Message received from the host: %(host)s "
                              "during the registration of %(agent_name)s has "
                              "a timestamp: %(agent_time)s. This differs from "
                              "the current server timestamp: %(serv_time)s by "
                              "%(diff)s seconds, which is more than the "
                              "threshold agent down"
                              "time: %(threshold)s."), log_dict)
Esempio n. 7
0
    def run(self):
        while True:
            try:
                if self._stopped:
                    # Gracefully terminate this thread if the _stopped
                    # attribute was set to true
                    LOG.info(_LI("Stopping TaskManager"))
                    break

                # get a task from queue, or timeout for periodic status check
                task = self._get_task()

                try:
                    #if constants.TaskStatus.ROLLBACK == task.status:
                    self._main_thread_exec_task = task
                    self._execute(task)
                finally:
                    self._main_thread_exec_task = None
                    if task.status in [constants.TaskStatus.NONE,
                                       constants.TaskStatus.ERROR,
                                       constants.TaskStatus.COMPLETED]:
                        # The thread is killed during _execute(). To guarantee
                        # the task been aborted correctly, put it to the queue.
                        #self._enqueue(task)
                        self._dequeue(task)
                    else:
                        self._enqueue(task)
            except Exception:
                LOG.exception(_LE("TaskManager terminating because "
                                "of an exception"))
                break
Esempio n. 8
0
    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if not message:
            try:
                message = self.msg_fmt % kwargs

            except Exception:
                exc_info = sys.exc_info()
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                LOG.exception(_LE('Exception in string format operation'))
                for name, value in six.iteritems(kwargs):
                    LOG.error("%s: %s" % (name, value))

                if CONF.fatal_exception_format_errors:
                    six.reraise(*exc_info)
                else:
                    # at least get the core message out if something happened
                    message = self.msg_fmt

        self.message = message
        super(FortinetException, self).__init__(message)
Esempio n. 9
0
 def _loopingcall_callback():
     self._monitor_busy = True
     try:
         self._check_pending_tasks()
     except Exception as e:
         resources.Exinfo(e)
         LOG.exception(_LE("Exception in _check_pending_tasks"))
     self._monitor_busy = False
Esempio n. 10
0
 def _loopingcall_callback():
     self._monitor_busy = True
     try:
         self._check_pending_tasks()
     except Exception as e:
         resources.Exinfo(e)
         LOG.exception(_LE("Exception in _check_pending_tasks"))
     self._monitor_busy = False
Esempio n. 11
0
 def __init__(self, exception):
     exc_type, exc_obj, exc_tb = sys.exc_info()
     fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
     LOG.error(_LE("An exception of type %(exception)s occured with "
                   "arguments %(args)s, line %(line)s, in %(file)s"),
               {'exception': type(exception).__name__,
                'args': exception.args,
                'line': exc_tb.tb_lineno,
                'file': fname})
Esempio n. 12
0
 def __init__(self, exception):
     exc_type, exc_obj, exc_tb = sys.exc_info()
     fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
     LOG.error(_LE("An exception of type %(exception)s occured with "
                   "arguments %(args)s, line %(line)s, in %(file)s"),
               {'exception': type(exception).__name__,
                'args': exception.args,
                'line': exc_tb.tb_lineno,
                'file': fname})
Esempio n. 13
0
    def launch(self, pause=False):
        """Starts a created guest.

        :param pause: Indicates whether to start and pause the guest
        """
        flags = pause and libvirt.VIR_DOMAIN_START_PAUSED or 0
        try:
            return self._domain.createWithFlags(flags)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE('Error launching a defined domain '
                              'with XML: %s') %
                          self._encoded_xml, errors='ignore')
Esempio n. 14
0
 def enable_hairpin(self):
     """Enables hairpin mode for this guest."""
     interfaces = self.get_interfaces()
     try:
         for interface in interfaces:
             utils.execute(
                 'tee',
                 '/sys/class/net/%s/brport/hairpin_mode' % interface,
                 process_input='1',
                 run_as_root=True,
                 check_exit_code=[0, 1])
     except Exception:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE('Error enabling hairpin mode with XML: %s') %
                       self._encoded_xml, errors='ignore')
Esempio n. 15
0
 def format_cookie(cookie):
     if not cookie:
         return None
     try:
         fmt_headers = {}
         cookies = Cookie.SimpleCookie(cookie)
         for key, morsel in six.iteritems(cookies):
             if "ccsrftoken" in morsel.key:
                 morsel.coded_value = morsel.value
                 fmt_headers["X-CSRFTOKEN"] = morsel.value
                 break
         fmt_headers["Cookie"] = cookies.output(header="").lstrip()
         return fmt_headers
     except (Cookie.CookieError, KeyError):
         LOG.error(_LE("The cookie ccsrftoken cannot be formatted"))
         raise Cookie.CookieError
Esempio n. 16
0
    def create(cls, xml, host):
        """Create a new Guest

        :param xml: XML definition of the domain to create
        :param host: host.Host connection to define the guest on

        :returns guest.Guest: Guest ready to be launched
        """
        try:
            # TODO(sahid): Host.write_instance_config should return
            # an instance of Guest
            domain = host.write_instance_config(xml)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE('Error defining a domain with XML: %s') %
                          encodeutils.safe_decode(xml))
        return cls(domain)
 def update_firewall_rule(self, context, id, firewall_rule):
     LOG.debug("update_firewall_rule() id: %(id)s, "
               "firewall_rule: %(firewall_rule)s",
               {'id': id, 'firewall_rule': firewall_rule})
     try:
         fwr = self._update_firewall_rule_dict(context, id, firewall_rule)
         self._update_firewall_rule(context, id, fwr)
         self._ensure_update_firewall_rule(context, id)
         fwr = super(FortinetFirewallPlugin,
                     self).update_firewall_rule(context, id, firewall_rule)
         utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
         return fwr
     except Exception as e:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE("update_firewall_rule %(fwr)s failed"),
                       {'fwr': firewall_rule})
             utils._rollback_on_err(self, context, e)
 def update_firewall_rule(self, context, id, firewall_rule):
     LOG.debug("update_firewall_rule() id: %(id)s, "
               "firewall_rule: %(firewall_rule)s",
               {'id': id, 'firewall_rule': firewall_rule})
     try:
         fwr = self._update_firewall_rule_dict(context, id, firewall_rule)
         self._update_firewall_rule(context, id, fwr)
         self._ensure_update_firewall_rule(context, id)
         fwr = super(FortinetFirewallPlugin,
                     self).update_firewall_rule(context, id, firewall_rule)
         utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
         return fwr
     except Exception as e:
         with excutils.save_and_reraise_exception():
             LOG.error(_LE("update_firewall_rule %(fwr)s failed"),
                       {'fwr': firewall_rule})
             utils._rollback_on_err(self, context, e)
Esempio n. 19
0
 def _wait_for_login(self, conn, headers=None):
     '''Block until a login has occurred for the current API provider.'''
     data = self._get_provider_data(conn)
     if data is None:
         LOG.error(_LE("Login request for an invalid connection: '%s'"),
                   api_client.ctrl_conn_to_str(conn))
         return
     provider_sem = data[0]
     if provider_sem.acquire(blocking=False):
         try:
             cookie = self._login(conn, headers)
             self.set_auth_cookie(conn, cookie)
         finally:
             provider_sem.release()
     else:
         LOG.debug("Waiting for auth to complete")
         # Wait until we can acquire then release
         provider_sem.acquire(blocking=True)
         provider_sem.release()
Esempio n. 20
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)
Esempio n. 21
0
    def get_connection(self):
        """Returns a connection to the hypervisor

        This method should be used to create and return a well
        configured connection to the hypervisor.

        :returns: a libvirt.virConnect object
        """
        try:
            conn = self._get_connection()
        except libvirt.libvirtError as ex:
            LOG.exception(_LE("Connection to libvirt failed: %s"), ex)
            payload = dict(ip=CONF.my_ip,
                           method='_connect',
                           reason=ex)
            rpc.get_notifier('compute').error(nova_context.get_admin_context(),
                                              'compute.libvirt.error',
                                              payload)
            raise exceptions.HypervisorUnavailable(host=CONF.host)

        return conn
Esempio n. 22
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)
 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
Esempio n. 24
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
Esempio n. 25
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)
Esempio n. 26
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)
    def _apply_firewall(self, context, **fw_with_rules):
        tenant_id = fw_with_rules['tenant_id']
        default_fwr = self._make_default_firewall_rule_dict(tenant_id)
        try:
            if fw_with_rules.get('del-router-ids', None):
                for fwr in list(fw_with_rules.get('firewall_rule_list', None)):
                    self._delete_firewall_rule(context, tenant_id, **fwr)
                if default_fwr:
                    self._delete_firewall_rule(
                        context, tenant_id, **default_fwr)
                self.update_firewall_status(
                    context, fw_with_rules['id'], const.INACTIVE)

            if fw_with_rules.get('add-router-ids', None):
                vdom = getattr(
                    fortinet_db.Fortinet_ML2_Namespace.query_one(
                        context, tenant_id=tenant_id), 'vdom', None)
                if not vdom:
                    raise fw_ext.FirewallInternalDriverError(
                        driver='Fortinet_fwaas_plugin')
                if default_fwr:
                    self._add_firewall_rule(context, tenant_id, **default_fwr)
                for fwr in reversed(
                        list(fw_with_rules.get('firewall_rule_list', None))):
                    self._add_firewall_rule(context, tenant_id, **fwr)
                self.update_firewall_status(
                    context, fw_with_rules['id'], const.ACTIVE)
            else:
                self.update_firewall_status(
                    context, fw_with_rules['id'], const.INACTIVE)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("apply_firewall %(fws)s failed"),
                          {'fws': fw_with_rules})
                utils._rollback_on_err(self, context, e)
        utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
    def _apply_firewall(self, context, **fw_with_rules):
        tenant_id = fw_with_rules['tenant_id']
        default_fwr = self._make_default_firewall_rule_dict(tenant_id)
        try:
            if fw_with_rules.get('del-router-ids', None):
                for fwr in list(fw_with_rules.get('firewall_rule_list', None)):
                    self._delete_firewall_rule(context, tenant_id, **fwr)
                if default_fwr:
                    self._delete_firewall_rule(
                        context, tenant_id, **default_fwr)
                self.update_firewall_status(
                    context, fw_with_rules['id'], n_consts.INACTIVE)

            if fw_with_rules.get('add-router-ids', None):
                vdom = getattr(
                    fortinet_db.Fortinet_ML2_Namespace.query_one(
                        context, tenant_id=tenant_id), 'vdom', None)
                if not vdom:
                    raise fw_exc.FirewallInternalDriverError(
                        driver='Fortinet_fwaas_plugin')
                if default_fwr:
                    self._add_firewall_rule(context, tenant_id, **default_fwr)
                for fwr in reversed(
                        list(fw_with_rules.get('firewall_rule_list', None))):
                    self._add_firewall_rule(context, tenant_id, **fwr)
                self.update_firewall_status(
                    context, fw_with_rules['id'], n_consts.ACTIVE)
            else:
                self.update_firewall_status(
                    context, fw_with_rules['id'], n_consts.INACTIVE)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("apply_firewall %(fws)s failed"),
                          {'fws': fw_with_rules})
                utils._rollback_on_err(self, context, e)
        utils.update_status(self, context, t_consts.TaskStatus.COMPLETED)
Esempio n. 29
0
    def create_router(self, router):
        # Limit one router per tenant
        cfg = router.get('fortigate', None)
        if not cfg:
            return
        res = {}
        # may need to generate a uuid for task_id
        task_id = uuidutils.generate_uuid()
        try:
            if 'vdom' in cfg:
                #self.ns_name = cfg['vdom']['vdom']
                self.fgt.add_resource(task_id, resources.Vdom,
                                      name=cfg['vdom']['vdom'])

            for inf in router.get('_interfaces', []):
                subnet = inf['subnets'][0]
                cidr = netaddr.IPNetwork(subnet['cidr'])
                name = str(cidr.network)
                subnet = ' '.join([str(cidr.network), str(cidr.netmask)])
                self.fgt.add_resource(task_id, resources.FirewallAddress,
                                      vdom=self.vdom,
                                      name=name,
                                      subnet=subnet)
                self.fgt_fwaddresses.append(name)
            self.fgt_addr_grp = const.PREFIX['addrgrp'] + self.vdom
            self.fgt.add_resource(task_id, resources.FirewallAddrgrp,
                                  name=self.fgt_addr_grp,
                                  vdom=self.vdom,
                                  members=self.fgt_fwaddresses)
            print "### self.driver.get_fwpolicy(self.ns_name) =", self.driver.get_fwpolicy(self.ns_name)
            if not self.driver.get_fwpolicy(self.ns_name):
                fwpolicy = self.fgt.add_resource(task_id,
                                                 resources.FirewallPolicy,
                                                 vdom=self.vdom,
                                                 srcintf='any',
                                                 srcaddr=self.fgt_addr_grp,
                                                 dstintf='any',
                                                 dstaddr=self.fgt_addr_grp,
                                                 nat='disable')
                self.fgt_fw_policies.append(fwpolicy['results']['mkey'])
                self.driver.save_fwpolicy(self.ns_name,
                                          fwpolicy['results']['mkey'])
            '''
            if 'vlink' in cfg:
                vlinkinfo = cfg['vlink']
                if 'vdomlink' in vlinkinfo:
                    self.fgt.add_resource(task_id, resources.VdomLink,
                                          name=vlinkinfo['vdomlink']['name'])
                if 'vlaninterface' in vlinkinfo:
                    for inf in vlinkinfo['vlaninterface']:
                        self.fgt.set_resource(task_id, resources.VlanInterface,
                                              **inf)
                if 'routestatic' in vlinkinfo:
                    r = self.fgt.add_resource(task_id, resources.RouterStatic,
                                              **vlinkinfo['routestatic'])
                    if 'ADD' == r['http_method']:
                        res['routestatic'] = vlinkinfo['routestatic']
                        res['routestatic']['edit_id'] = r['results']['mkey']
            '''

        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Failed to create_router router=%(router)s"),
                          {"router": router})
                self.fgt.rollback(task_id)
        self.fgt.finish(task_id)
        return res
Esempio n. 30
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
Esempio n. 31
0
    def request(self, opt, content_type="application/json", **message):
        '''Issues request to controller.'''
        self.message = self._render(getattr(templates, opt), **message)
        method = self.message['method']
        url = self.message['path']
        body = self.message['body'] if 'body' in self.message else None
        g = eventlet_request.GenericRequestEventlet(
            self, method, url, body, content_type, auto_login=True,
            http_timeout=self._http_timeout,
            retries=self._retries, redirects=self._redirects)
        g.start()
        response = g.join()

        # response is a modified HTTPResponse object or None.
        # response.read() will not work on response as the underlying library
        # request_eventlet.ApiRequestEventlet has already called this
        # method in order to extract the body and headers for processing.
        # ApiRequestEventlet derived classes call .read() and
        # .getheaders() on the HTTPResponse objects and store the results in
        # the response object's .body and .headers data members for future
        # access.

        if response is None:
            # Timeout.
            LOG.error(_LE('Request timed out: %(method)s to %(url)s'),
                      {'method': method, 'url': url})
            raise exception.RequestTimeout()

        status = response.status
        if status == 401:
            raise exception.UnAuthorizedRequest()
        # Fail-fast: Check for exception conditions and raise the
        # appropriate exceptions for known error codes.
        if status in [404]:
            LOG.warning(_LW("Resource not found. Response status: %(status)s, "
                            "response body: %(response.body)s"),
                        {'status': status, 'response.body': response.body})
            exception.ERROR_MAPPINGS[status](response)
        elif status in exception.ERROR_MAPPINGS:
            LOG.error(_LE("Received error code: %s"), status)
            LOG.error(_LE("Server Error Message: %s"), response.body)
            exception.ERROR_MAPPINGS[status](response)

        # Continue processing for non-error condition.
        if status != 200 and status != 201 and status != 204:
            LOG.error(_LE("%(method)s to %(url)s, unexpected response code: "
                        "%(status)d (content = '%(body)s')"),
                      {'method': method, 'url': url,
                       'status': response.status, 'body': response.body})
            return None

        if url == jsonutils.loads(templates.LOGOUT)['path']:
            return response.body
        else:
            try:
                return jsonutils.loads(response.body)
            except UnicodeDecodeError:
                LOG.debug("The following strings cannot be decoded with "
                          "'utf-8, trying 'ISO-8859-1' instead. %(body)s",
                          {'body': response.body})
                return jsonutils.loads(response.body, encoding='ISO-8859-1')
            except Exception as e:
                LOG.error(_LE("Decode error, the response.body %(body)s"),
                          {'body': response.body})
                raise e