示例#1
0
文件: exception.py 项目: txdev/proton
    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 message:
            self.message = message

        try:
            self.message = self.message % kwargs
        except Exception as e:
            # 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 kwargs.iteritems():
                LOG.error(_LE("%(name)s: %(value)s") %
                          {'name': name, 'value': value})
            try:
                if CONF.fatal_exception_format_errors:
                    raise e
            except cfg.NoSuchOptError:
                # Note: work around for Bug: #1447873
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise e

        super(GluonException, self).__init__(self.message)
    def update_chain(self):
        ps = Popen(["iptables", "-L"], stdout=PIPE)
        output = ps.communicate()[0]

        # check if chain is present if not create new chain
        if "testchain" not in output:
            LOG.info(_LI("Creating new chain ..."))
            call(["iptables", "-F"])
            call(["iptables", "-N", "testchain"])
            call(
                ["iptables", "-t", "filter",
                 "-A", "FORWARD", "-j", "testchain"])
            call(["iptables", "-A", "FORWARD", "-j", "DROP"])

        # flush chain of existing rules
        call(["iptables", "-F", "testchain"])
        # return

        # Update chain with new rules
        LOG.info(_LI("Updating chain with new rules ..."))
        count = 0
        for rule in self.rules_json.get('rules'):
            LOG.info(_LI("adding rule %(count)d"), {'count': count})
            try:
                action_values = ["LOG", "ACCEPT"]
                action = rule['action'].upper()
                if action not in action_values:
                    sys.exit(
                        "Action %s is not valid action! Please enter "
                        "valid action (LOG or ACCEPT)" % (action))
                service = rule['service'].split('/')
            except KeyError as e:
                sys.exit('KeyError: Rule does not have key %s' % (e))

            if len(service) > 1:
                ps = Popen(["iptables", "-A", "testchain", "-p", service[
                           0], "--dport", service[1], "-j", action],
                           stdout=PIPE)
            else:
                ps = Popen(
                    ["iptables", "-A", "testchain", "-p", service[0],
                     "-j", action], stdout=PIPE)
            output = ps.communicate()[0]
            if output:
                LOG.error(_LE("Unable to add rule to chain due to: %(msg)s"),
                          {'msg': output})
            count = count + 1
        ps = Popen(["iptables", "-A", "testchain", "-m", "state", "--state",
                    "ESTABLISHED,RELATED", "-j", "ACCEPT"], stdout=PIPE)
        output = ps.communicate()[0]
        if output:
            LOG.error(_LE("Unable to add rule to chain due to: %(output)s"),
                      {'output': output})
    def update_chain(self):
        ps = Popen(["iptables", "-L"], stdout=PIPE)
        output = ps.communicate()[0]

        # check if chain is present if not create new chain
        if "testchain" not in output:
            LOG.info(_LI("Creating new chain ..."))
            call(["iptables", "-F"])
            call(["iptables", "-N", "testchain"])
            call(
                ["iptables", "-t", "filter",
                 "-A", "FORWARD", "-j", "testchain"])
            call(["iptables", "-A", "FORWARD", "-j", "DROP"])

        # flush chain of existing rules
        call(["iptables", "-F", "testchain"])
        # return

        # Update chain with new rules
        LOG.info(_LI("Updating chain with new rules ..."))
        count = 0
        for rule in self.rules_json.get('rules'):
            LOG.info(_LI("adding rule %(count)d") % {'count': count})
            try:
                action_values = ["LOG", "ACCEPT"]
                action = rule['action'].upper()
                if action not in action_values:
                    sys.exit(
                        "Action %s is not valid action! Please enter "
                        "valid action (LOG or ACCEPT)" % (action))
                service = rule['service'].split('/')
            except KeyError as e:
                sys.exit('KeyError: Rule does not have key %s' % (e))

            if len(service) > 1:
                ps = Popen(["iptables", "-A", "testchain", "-p", service[
                           0], "--dport", service[1], "-j", action],
                           stdout=PIPE)
            else:
                ps = Popen(
                    ["iptables", "-A", "testchain", "-p", service[0],
                     "-j", action], stdout=PIPE)
            output = ps.communicate()[0]
            if output:
                LOG.error(_LE("Unable to add rule to chain due to: %(output)s")
                          % {'output': output})
            count = count + 1
        ps = Popen(["iptables", "-A", "testchain", "-m", "state", "--state",
                    "ESTABLISHED,RELATED", "-j", "ACCEPT"], stdout=PIPE)
        output = ps.communicate()[0]
        if output:
            LOG.error(_LE("Unable to add rule to chain due to: %(output)s")
                      % {'output': output})
示例#4
0
 def run(self):
     while 1:
         try:
             msg = self.input_q.get(True, 10.0)
             LOG.info(_LI("SyncThread: received message %s ") % msg)
             self.proc_sync_msg(msg)
         except Queue.Empty:
             LOG.debug("SyncThread: Queue timeout")
         except ValueError:
             LOG.error(_LE("Error processing sync message"))
             break
     LOG.error(_LE("SyncThread exiting"))
     SyncData.sync_thread_running = False
 def _add_routes(self, route_info):
     LOG.info(_LI("Configuring routes with configuration "
              "data : %(route_data)s ") %
              {'route_data': route_info['resource_data']})
     source_cidrs = route_info['resource_data']['source_cidrs']
     gateway_ip = route_info['resource_data']['gateway_ip']
     default_route_commands = []
     for cidr in source_cidrs:
         source_interface = self._get_if_name_by_cidr(cidr)
         try:
             interface_number_string = source_interface.split("eth", 1)[1]
         except IndexError:
             LOG.error(_LE("Retrieved wrong interface %(interface)s for "
                       "configuring routes") %
                       {'interface': source_interface})
         routing_table_number = 20 + int(interface_number_string)
         ip_rule_command = "ip rule add from %s table %s" % (
             cidr, routing_table_number)
         out1 = subprocess.Popen(ip_rule_command, shell=True,
                                 stdout=subprocess.PIPE).stdout.read()
         ip_rule_command = "ip rule add to %s table main" % (cidr)
         out2 = subprocess.Popen(ip_rule_command, shell=True,
                                 stdout=subprocess.PIPE).stdout.read()
         ip_route_command = "ip route add table %s default via %s" % (
                                 routing_table_number, gateway_ip)
         default_route_commands.append(ip_route_command)
         output = "%s\n%s" % (out1, out2)
         LOG.info(_LI("Static route configuration result: %(output)s") %
                  {'output': output})
     for command in default_route_commands:
         out = subprocess.Popen(command, shell=True,
                                stdout=subprocess.PIPE).stdout.read()
         LOG.info(_LI("Static route configuration result: %(output)s") %
                  {'output': out})
示例#6
0
 def proc_msg(self, msg):
     retVal = False
     if msg["operation"] == 'register':
         payload = {'id': msg["port_id"], 'owner': RegData.service_name}
         try:
             resp = post(self._make_url(self.base_url, 'ports'), json=payload)
             if resp.status_code == 201:
                 LOG.info(_LI("RegThread: port added gluon"))
                 retVal = True
             elif resp.status_code == 409:
                 LOG.info(_LI("RegThread: port already in gluon"))
                 retVal = True
             else:
                 LOG.info(_LI("RegThread: unexpected response code: %d" % resp.status_code))
         except:
             pass
     elif msg["operation"] == 'deregister':
         try:
             url = self._make_url(self.base_url, 'ports')
             url = self._make_url(url, msg["port_id"])
             resp = delete(url)
             if resp.status_code == 201 or resp.status_code == 200 or resp.status_code == 404:
                 LOG.info(_LI("RegThread: port removed from gluon"))
                 retVal = True
             else:
                 LOG.info(_LI("RegThread: unexpected response code: %d" % resp.status_code))
         except:
             pass
     else:
         LOG.error(_LE("Unknown reg message"))
         retVal = True
     return retVal
示例#7
0
 def run(self):
     while 1:
         try:
             msg = self.input_q.get(True, 3.0)
             LOG.info(_LI("RegThread: received message %s ") % msg)
             self.proc_reg_msg(msg)
         except Queue.Empty:
             LOG.debug("RegThread: Queue timeout")
             self.proc_timeout()
         except ValueError:
             LOG.error(_LE("Error processing reg message"))
             break
     LOG.info(_LI("RegThread exiting"))
     RegData.thread_running = False
示例#8
0
 def run(self):
     while 1:
         try:
             msg = self.input_q.get(True, 3.0)
             LOG.info(_LI("RegThread: received message %s ") % msg)
             self.proc_reg_msg(msg)
         except Queue.Empty:
             LOG.debug("RegThread: Queue timeout")
             self.proc_timeout()
         except ValueError:
             LOG.error(_LE("Error processing reg message"))
             break
     LOG.info(_LI("RegThread exiting"))
     RegData.thread_running = False
示例#9
0
 def proc_sync_msg(self, msg):
     try:
         obj_key = "_".join(msg["key"].split())  # Get rid of spaces
         etcd_key = "{0:s}/{1:s}/{2:s}/{3:s}".format(SyncData.service, SyncData.source, msg["table"], obj_key)
         if msg["operation"] == "update":
             table_class = getDBGen().get_table_class(msg["table"])
             data = self.db_instance.get_by_primary_key(table_class, msg["key"])
             values = data.as_dict()
             d = {}
             for key in values.iterkeys():
                 d[key] = str(values[key])
             json_str = json.dumps(d)
             self.etcd_client.write(etcd_key, json_str)
         elif msg["operation"] == "delete":
             self.etcd_client.delete(etcd_key)
         else:
             LOG.error(_LE("Unkown operation in msg %s") % (msg["operation"]))
     except etcd.EtcdKeyNotFound:
         LOG.warn(_LW("Unknown key %s") % obj_key)
     except Exception as e:
         print(e.__doc__)
         print(e.message)
         LOG.error(_LE("Error writing to etcd %s, %s") % (e.__doc__, e.message))
         raise ValueError
示例#10
0
 def _add_routes(self, route_info):
     LOG.info(
         _LI("Configuring routes with configuration "
             "data : %(route_data)s ") %
         {'route_data': route_info['resource_data']})
     source_cidrs = route_info['resource_data']['source_cidrs']
     gateway_ip = route_info['resource_data']['gateway_ip']
     default_route_commands = []
     for cidr in source_cidrs:
         source_interface = self._get_if_name_by_cidr(cidr)
         try:
             interface_number_string = source_interface.split("eth", 1)[1]
         except IndexError:
             LOG.error(
                 _LE("Retrieved wrong interface %(interface)s for "
                     "configuring routes") %
                 {'interface': source_interface})
         routing_table_number = 20 + int(interface_number_string)
         ip_rule_command = "ip rule add from %s table %s" % (
             cidr, routing_table_number)
         out1 = subprocess.Popen(ip_rule_command,
                                 shell=True,
                                 stdout=subprocess.PIPE).stdout.read()
         ip_rule_command = "ip rule add to %s table main" % (cidr)
         out2 = subprocess.Popen(ip_rule_command,
                                 shell=True,
                                 stdout=subprocess.PIPE).stdout.read()
         ip_route_command = "ip route add table %s default via %s" % (
             routing_table_number, gateway_ip)
         default_route_commands.append(ip_route_command)
         output = "%s\n%s" % (out1, out2)
         LOG.info(
             _LI("Static route configuration result: %(output)s") %
             {'output': output})
     for command in default_route_commands:
         out = subprocess.Popen(command, shell=True,
                                stdout=subprocess.PIPE).stdout.read()
         LOG.info(
             _LI("Static route configuration result: %(output)s") %
             {'output': out})
示例#11
0
 def proc_msg(self, msg):
     retVal = False
     if msg["operation"] == 'register':
         payload = {'id': msg["port_id"], 'owner': RegData.service_name}
         try:
             resp = post(self._make_url(self.base_url, 'ports'),
                         json=payload)
             if resp.status_code == 201:
                 LOG.info(_LI("RegThread: port added gluon"))
                 retVal = True
             elif resp.status_code == 409:
                 LOG.info(_LI("RegThread: port already in gluon"))
                 retVal = True
             else:
                 LOG.info(
                     _LI("RegThread: unexpected response code: %d" %
                         resp.status_code))
         except:
             pass
     elif msg["operation"] == 'deregister':
         try:
             url = self._make_url(self.base_url, 'ports')
             url = self._make_url(url, msg["port_id"])
             resp = delete(url)
             if resp.status_code == 201 or resp.status_code == 200 or resp.status_code == 404:
                 LOG.info(_LI("RegThread: port removed from gluon"))
                 retVal = True
             else:
                 LOG.info(
                     _LI("RegThread: unexpected response code: %d" %
                         resp.status_code))
         except:
             pass
     else:
         LOG.error(_LE("Unknown reg message"))
         retVal = True
     return retVal