Example #1
0
    def post_configure(self, address):
        """ The steps that must be done after a device is configured """
        route = CsRoute()
        if not self.get_type() in ["control"]:
            route.add_table(self.dev)

            CsRule(self.dev).addMark()

            interfaces = [CsInterface(address, self.config)]
            CsHelper.reconfigure_interfaces(self.cl, interfaces)
            self.set_mark()

            if 'gateway' in self.address:
                self.arpPing()

            CsRpsrfs(self.dev).enable()
            self.post_config_change("add")

        '''For isolated/redundant and dhcpsrvr routers, call this method after the post_config is complete '''
        if not self.config.is_vpc():
            self.setup_router_control()

        if self.config.is_vpc() or self.cl.is_redundant():
            # The code looks redundant here, but we actually have to cater for routers and
            # VPC routers in a different manner. Please do not remove this block otherwise
            # The VPC default route will be broken.
            if self.get_type() in ["public"] and address["device"] == CsHelper.PUBLIC_INTERFACES[self.cl.get_type()]:
                gateway = str(address["gateway"])
                route.add_defaultroute(gateway)
        else:
            # once we start processing public ip's we need to verify there
            # is a default route and add if needed
            if(self.cl.get_gateway()):
                route.add_defaultroute(self.cl.get_gateway())
Example #2
0
    def process(self):
        self.hosts = {}
        self.changed = []
        self.devinfo = CsHelper.get_device_info()
        self.preseed()
        self.cloud = CsFile(DHCP_HOSTS)
        self.conf = CsFile(CLOUD_CONF)

        self.cloud.repopulate()

        for item in self.dbag:
            if item == "id":
                continue
            self.add(self.dbag[item])
        self.write_hosts()
        
        if self.cloud.is_changed():
            self.delete_leases()

        self.configure_server()

        self.conf.commit()
        self.cloud.commit()

        # We restart DNSMASQ every time the configure.py is called in order to avoid lease problems.
        # But only do that on the master or else VMs will get leases from the backup resulting in
        # Cloud-init to get the passwd and other meta-data from the backup as well.
        if not self.cl.is_redundant() or self.cl.is_master():
            CsHelper.execute2("service dnsmasq restart")
Example #3
0
    def __update(self, vm_ip, password):
        token = ""
        try:
            tokenFile = open(self.TOKEN_FILE)
            token = tokenFile.read()
        except IOError:
            logging.debug("File %s does not exist" % self.TOKEN_FILE)

        logging.debug("Got VM '%s' and password '%s'" % (vm_ip, password))
        get_cidrs_cmd = "ip addr show | grep inet | grep -v secondary | awk '{print $2}'"
        cidrs = CsHelper.execute(get_cidrs_cmd)
        logging.debug("Found these CIDRs: %s" % cidrs)
        for cidr in cidrs:
            logging.debug("Processing CIDR '%s'" % cidr)
            if IPAddress(vm_ip) in IPNetwork(cidr):
                ip = cidr.split('/')[0]
                logging.debug("Cidr %s matches vm ip address %s so adding passwd to passwd server at %s" % (cidr, vm_ip, ip))
                proc = CsProcess(['/opt/cloud/bin/passwd_server_ip.py', ip])
                if proc.find():
                    update_command = 'curl --header "DomU_Request: save_password" "http://{SERVER_IP}:8080/" -F "ip={VM_IP}" -F "password={PASSWORD}" ' \
                                     '-F "token={TOKEN}" --interface 127.0.0.1 >/dev/null 2>/dev/null &'.format(SERVER_IP=ip, VM_IP=vm_ip, PASSWORD=password, TOKEN=token)
                    result = CsHelper.execute(update_command)
                    logging.debug("Update password server result ==> %s" % result)
                else:
                    logging.debug("Update password server skipped because we didn't find a passwd server process for %s (makes sense on backup routers)" % ip)
Example #4
0
    def set_fault(self):
        """ Set fault mode on this router """
        if not self.cl.is_redundant():
            logging.error("Set fault called on non-redundant router")
            return

        self.set_lock()
        logging.info("Router switched to fault mode")

        ips = [ip for ip in self.address.get_ips() if ip.is_public()]
        for ip in ips:
            CsHelper.execute("ifconfig %s down" % ip.get_device())

        cmd = "%s -C %s" % (self.CONNTRACKD_BIN, self.CONNTRACKD_CONF)
        CsHelper.execute("%s -s" % cmd)
        CsHelper.service("ipsec", "stop")
        CsHelper.service("xl2tpd", "stop")
        CsHelper.service("dnsmasq", "stop")

        ips = [ip for ip in self.address.get_ips() if ip.needs_vrrp()]
        for ip in ips:
            CsPasswdSvc(ip.get_gateway()).stop()

        self.cl.set_fault_state()
        self.cl.save()
        self.release_lock()
        logging.info("Router switched to fault mode")
Example #5
0
    def process(self):
        if "config" not in self.dbag.keys():
            return
        if 'configuration' not in self.dbag['config'][0].keys():
            return
        config = self.dbag['config'][0]['configuration']
        file1 = CsFile(HAPROXY_CONF_T)
        file2 = CsFile(HAPROXY_CONF_P)
        file1.empty()
        for x in config:
            [file1.append(w, -1) for w in x.split('\n')]
        if not file2.compare(file1):
            file1.commit()
            shutil.copy2(HAPROXY_CONF_T, HAPROXY_CONF_P)

            proc = CsProcess(['/var/run/haproxy.pid'])
            if not proc.find():
                logging.debug("CsLoadBalancer:: will restart HAproxy!")
                CsHelper.service("haproxy", "restart")
            else:
                logging.debug("CsLoadBalancer:: will reload HAproxy!")
                CsHelper.service("haproxy", "reload")

        add_rules = self.dbag['config'][0]['add_rules']
        remove_rules = self.dbag['config'][0]['remove_rules']
        self._configure_firewall(add_rules, remove_rules)
Example #6
0
 def preseed(self):
     self.add_host("127.0.0.1", "localhost %s" % CsHelper.get_hostname())
     self.add_host("::1", "localhost ip6-localhost ip6-loopback")
     self.add_host("ff02::1", "ip6-allnodes")
     self.add_host("ff02::2", "ip6-allrouters")
     if self.config.is_router():
         self.add_host(self.config.address().get_guest_ip(), "%s data-server" % CsHelper.get_hostname())
Example #7
0
 def get_unseen(self):
     del_list = [x for x in self.rules if x.unseen()]
     for r in del_list:
         cmd = "iptables -t %s %s" % (r.get_table(), r.to_str(True))
         CsHelper.execute(cmd)
         # print "Delete rule %s from table %s" % (r.to_str(True), r.get_table())
         logging.info("Delete rule %s from table %s", r.to_str(True), r.get_table())
Example #8
0
    def delete_leases(self):
        changed = []
        leases = []
        try:
            for line in open(LEASES):
                bits = line.strip().split(' ')
                to = {"device": bits[0],
                      "mac": bits[1],
                      "ip": bits[2],
                      "host": bits[3:],
                      "del": False
                      }
                changed.append(to)

                for v in changed:
                    if v['mac'] == to['mac'] or v['ip'] == to['ip'] or v['host'] == to['host']:
                        to['del'] = True
                leases.append(to)

            for o in leases:
                if o['del']:
                    cmd = "dhcp_release eth%s %s %s" % (o['device'], o['ip'], o['mac'])
                    logging.info(cmd)
                    CsHelper.execute(cmd)
        except IOError:
            return
Example #9
0
 def set_backup(self):
     """ Set the current router to backup """
     if not self.cl.is_redundant():
         logging.error("Set backup called on non-redundant router")
         return
     """
     if not self.cl.is_master():
         logging.error("Set backup called on node that is already backup")
         return
     """
     self.set_lock()
     logging.debug("Setting router to backup")
     ads = [o for o in self.address.get_ips() if o.is_public()]
     dev = ''
     for o in ads:
         if dev == o.get_device():
             continue
         logging.info("Bringing public interface %s down" % o.get_device())
         cmd2 = "ip link set %s up" % o.get_device()
         CsHelper.execute(cmd2)
         dev = o.get_device()
     cmd = "%s -C %s" % (self.CONNTRACKD_BIN, self.CONNTRACKD_CONF)
     CsHelper.execute("%s -d" % cmd)
     CsHelper.service("ipsec", "stop")
     CsHelper.service("xl2tpd", "stop")
     ads = [o for o in self.address.get_ips() if o.needs_vrrp()]
     for o in ads:
         CsPasswdSvc(o.get_gateway()).stop()
     CsHelper.service("dnsmasq", "stop")
     # self._set_priority(self.CS_PRIO_DOWN)
     self.cl.set_master_state(False)
     self.cl.save()
     self.release_lock()
     logging.info("Router switched to backup mode")
Example #10
0
    def compare(self, list):
        """ Compare reality with what is needed """
        for c in self.chain.get("filter"):
            # Ensure all inbound/outbound chains have a default drop rule
            if c.startswith("ACL_INBOUND") or c.startswith("ACL_OUTBOUND"):
                list.append(["filter", "", "-A %s -j DROP" % c])
        # PASS 1:  Ensure all chains are present
        for fw in list:
            new_rule = CsNetfilter()
            new_rule.parse(fw[2])
            new_rule.set_table(fw[0])
            self.add_chain(new_rule)
        # PASS 2: Create rules
        for fw in list:
            new_rule = CsNetfilter()
            new_rule.parse(fw[2])
            new_rule.set_table(fw[0])
            if isinstance(fw[1], int):
                new_rule.set_count(fw[1])
            if self.has_rule(new_rule):
                logging.debug("rule %s exists in table %s", fw[2], new_rule.get_table())
            else:
                # print "Add rule %s in table %s" % ( fw[2], new_rule.get_table())
                logging.info("Add rule %s in table %s", fw[2], new_rule.get_table())
                # front means insert instead of append
                cpy = fw[2]
                if fw[1] == "front":
                    cpy = cpy.replace('-A', '-I')
                if isinstance(fw[1], int):
                    cpy = cpy.replace("-A %s" % new_rule.get_chain(), '-I %s %s' % (new_rule.get_chain(), fw[1]))

                CsHelper.execute("iptables -t %s %s" % (new_rule.get_table(), cpy))
        self.del_standard()
        self.get_unseen()
Example #11
0
 def check_is_up(self, device):
     """ Ensure device is up """
     cmd = "ip link show %s | grep 'state DOWN'" % device
     for i in CsHelper.execute(cmd):
         if " DOWN " in i:
             cmd2 = "ip link set %s up" % device
             CsHelper.execute(cmd2)
Example #12
0
    def process(self):
        self.hosts = {}
        self.changed = []
        self.devinfo = CsHelper.get_device_info()
        self.preseed()
        self.cloud = CsFile(DHCP_HOSTS)
        self.conf = CsFile(CLOUD_CONF)

        self.cloud.repopulate()

        for item in self.dbag:
            if item == "id":
                continue
            self.add(self.dbag[item])
        self.write_hosts()
        
        if self.cloud.is_changed():
            self.delete_leases()

        self.configure_server()

        self.conf.commit()
        self.cloud.commit()

        # We restart DNSMASQ every time the configure.py is called in order to avoid lease problems.
        if not self.cl.is_redundant() or self.cl.is_master():
            CsHelper.service("dnsmasq", "restart")
Example #13
0
    def set_backup(self):
        """ Set the current router to backup """
        if not self.cl.is_redundant():
            logging.error("Set backup called on non-redundant router")
            return

        self.set_lock()
        logging.debug("Setting router to backup")

        dev = ''
        ips = [ip for ip in self.address.get_ips() if ip.is_public()]
        for ip in ips:
            if dev == ip.get_device():
                continue
            logging.info("Bringing public interface %s down" % ip.get_device())
            cmd2 = "ip link set %s down" % ip.get_device()
            CsHelper.execute(cmd2)
            dev = ip.get_device()

        cmd = "%s -C %s" % (self.CONNTRACKD_BIN, self.CONNTRACKD_CONF)
        CsHelper.execute("%s -d" % cmd)
        CsHelper.service("ipsec", "stop")
        CsHelper.service("xl2tpd", "stop")

        ips = [ip for ip in self.address.get_ips() if ip.needs_vrrp()]
        for ip in ips:
            CsPasswdSvc(ip.get_gateway()).stop()
        CsHelper.service("dnsmasq", "stop")

        self.cl.set_master_state(False)
        self.cl.save()
        self.release_lock()
        logging.info("Router switched to backup mode")
Example #14
0
 def add_table(self, devicename):
     tablenumber = devicename[3:]
     tablename = self.get_tablename(devicename)
     str = "%s %s" % (tablenumber, tablename)
     filename = "/etc/iproute2/rt_tables"
     logging.info(
         "Adding route table: " + str + " to " + filename + " if not present ")
     CsHelper.addifmissing(filename, str)
Example #15
0
 def __update(self, route):
     if route['revoke']:
         command = "ip route del %s via %s" % (route['network'], route['gateway'])
         CsHelper.execute(command)
     else:
         command = "ip route show | grep %s | awk '{print $1, $3}'" % route['network']
         result = CsHelper.execute(command)
         if not result:
             route_command = "ip route add %s via %s" % (route['network'], route['gateway'])
             CsHelper.execute(route_command)
Example #16
0
 def add_table(self, devicename):
     tablenumber = 100 + int(devicename[3:])
     tablename = self.get_tablename(devicename)
     str = "%s %s" % (tablenumber, tablename)
     filename = "/etc/iproute2/rt_tables"
     logging.info("Adding route table: " + str + " to " + filename + " if not present ")
     if not CsHelper.definedinfile(filename, str):
         CsHelper.execute("sudo echo " + str + " >> /etc/iproute2/rt_tables")
     # remove "from all table tablename" if exists, else it will interfer with
     # routing of unintended traffic
     if self.findRule("from all lookup " + tablename):
         CsHelper.execute("sudo ip rule delete from all table " + tablename)
Example #17
0
    def configure(self, address):
        # When "add" is false, it means that the IP has to be removed.
        if address["add"]:
            try:
                logging.info("Configuring address %s on device %s", self.ip(), self.dev)
                cmd = "ip addr add dev %s %s brd +" % (self.dev, self.ip())
                CsHelper.execute(cmd)
            except Exception as e:
                logging.info("Exception occurred ==> %s" % e)

        else:
            self.delete(self.ip())
        self.post_configure(address)
Example #18
0
 def check_is_up(self):
     """ Ensure device is up """
     cmd = "ip link show %s | grep 'state DOWN'" % self.getDevice()
     for i in CsHelper.execute(cmd):
         if " DOWN " in i:
             cmd2 = "ip link set %s up" % self.getDevice()
             # If redundant do not bring up public interfaces
             # master.py and keepalived deal with tham
             if self.cl.is_redundant() and not self.is_public():
                 CsHelper.execute(cmd2)
             # if not redundant bring everything up
             if not self.cl.is_redundant():
                 CsHelper.execute(cmd2)
Example #19
0
 def set_route(self, cmd, method="add"):
     """ Add a route if it is not already defined """
     found = False
     for i in CsHelper.execute("ip route show " + cmd):
         found = True
     if not found and method == "add":
         logging.info("Add " + cmd)
         cmd = "ip route add " + cmd
     elif found and method == "delete":
         logging.info("Delete " + cmd)
         cmd = "ip route delete " + cmd
     else:
         return
     CsHelper.execute(cmd)
Example #20
0
 def check_is_up(self):
     """ Ensure device is up """
     cmd = "ip link show %s | grep 'state DOWN'" % self.getDevice()
     for i in CsHelper.execute(cmd):
         if " DOWN " in i:
             cmd2 = "ip link set %s up" % self.getDevice()
             # If redundant only bring up public interfaces that are not eth1.
             # Reason: private gateways are public interfaces.
             # master.py and keepalived will deal with eth1 public interface.
             if self.cl.is_redundant() and (not self.is_public() or self.getDevice() not in PUBLIC_INTERFACE):
                 CsHelper.execute(cmd2)
             # if not redundant bring everything up
             if not self.cl.is_redundant():
                 CsHelper.execute(cmd2)
Example #21
0
 def process(self):
     if "config" not in self.dbag.keys():
         return
     if 'configuration' not in self.dbag['config'][0].keys():
         return
     config = self.dbag['config'][0]['configuration']
     file1 = CsFile(HAPROXY_CONF_T)
     file2 = CsFile(HAPROXY_CONF_P)
     file1.empty()
     for x in config:
         [file1.append(w, -1) for w in x.split('\n')]
     if not file2.compare(file1):
         file1.commit()
         shutil.copy2(HAPROXY_CONF_T, HAPROXY_CONF_P)
         CsHelper.service("haproxy", "restart")
Example #22
0
 def check_if_link_exists(self,dev):
     cmd="ip link show dev %s"%dev
     result = CsHelper.execute(cmd)
     if(len(result) != 0):
        return True
     else:
        return False
Example #23
0
 def check_if_link_up(self,dev):
     cmd="ip link show dev %s | tr '\n' ' ' | cut -d ' ' -f 9"%dev
     result = CsHelper.execute(cmd)
     if(result and result[0].lower() == "up"):
         return True
     else:
         return False
Example #24
0
 def list(self):
     self.iplist = {}
     cmd = ("ip addr show dev " + self.dev)
     for i in CsHelper.execute(cmd):
         vals = i.lstrip().split()
         if (vals[0] == 'inet'):
             self.iplist[vals[1]] = self.dev
Example #25
0
    def compare(self, list):
        """ Compare reality with what is needed """
        # PASS 1:  Ensure all chains are present
        for fw in list:
            new_rule = CsNetfilter()
            new_rule.parse(fw[2])
            new_rule.set_table(fw[0])
            self.add_chain(new_rule)

        ruleSet = set()
        # PASS 2: Create rules
        for fw in list:
            tupledFw = tuple(fw)
            if tupledFw in ruleSet :
                logging.debug("Already processed : %s", tupledFw)
                continue

            new_rule = CsNetfilter()
            new_rule.parse(fw[2])
            new_rule.set_table(fw[0])
            if isinstance(fw[1], int):
                new_rule.set_count(fw[1])

            rule_chain = new_rule.get_chain()

            logging.debug("Checking if the rule already exists: rule=%s table=%s chain=%s", new_rule.get_rule(), new_rule.get_table(), new_rule.get_chain())
            if self.has_rule(new_rule):
                logging.debug("Exists: rule=%s table=%s", fw[2], new_rule.get_table())
            else:
                # print "Add rule %s in table %s" % ( fw[2], new_rule.get_table())
                logging.info("Add: rule=%s table=%s", fw[2], new_rule.get_table())
                # front means insert instead of append
                cpy = fw[2]
                if fw[1] == "front":
                    cpy = cpy.replace('-A', '-I')
                if isinstance(fw[1], int):
                    # if the rule is for ACLs, we want to insert them in order, right before the DROP all
                    if rule_chain.startswith("ACL_INBOUND"):
                        rule_count = self.chain.get_count(rule_chain)
                        cpy = cpy.replace("-A %s" % new_rule.get_chain(), '-I %s %s' % (new_rule.get_chain(), rule_count))
                    else:
                        cpy = cpy.replace("-A %s" % new_rule.get_chain(), '-I %s %s' % (new_rule.get_chain(), fw[1]))
                CsHelper.execute("iptables -t %s %s" % (new_rule.get_table(), cpy))
                ruleSet.add(tupledFw)
                self.chain.add_rule(rule_chain)
        self.del_standard()
        self.get_unseen()
Example #26
0
    def process(self):
        route = CsRoute()
        found_defaultroute = False

        for dev in self.dbag:
            if dev == "id":
                continue
            ip = CsIP(dev, self.config)

            for address in self.dbag[dev]:
                # check if link is up
                if not self.check_if_link_up(dev):
                    cmd = "ip link set %s up" % dev
                    CsHelper.execute(cmd)

                gateway = str(address["gateway"])
                network = str(address["network"])

                ip.setAddress(address)

                if ip.configured():
                    logging.info("Address %s on device %s already configured", ip.ip(), dev)

                    ip.post_configure()

                else:
                    logging.info("Address %s on device %s not configured", ip.ip(), dev)
                    if CsDevice(dev, self.config).waitfordevice():
                        ip.configure()

                route.add_route(dev, network)

                # The code looks redundant here, but we actually have to cater for routers and
                # VPC routers in a different manner. Please do not remove this block otherwise
                # The VPC default route will be broken.
                if address["nw_type"] == "public" and not found_defaultroute:
                    if not route.defaultroute_exists():
                        if route.add_defaultroute(gateway):
                            found_defaultroute = True

        # once we start processing public ip's we need to verify there
        # is a default route and add if needed
        if not route.defaultroute_exists():
            cmdline = self.config.cmdline()
            if cmdline.get_gateway():
                route.add_defaultroute(cmdline.get_gateway())
Example #27
0
 def find_pid(self):
     self.pid = []
     for i in CsHelper.execute("ps aux"):
         items = len(self.search)
         proc = re.split("\s+", i)[items*-1:]
         matches = len([m for m in proc if m in self.search])
         if matches == items:
             self.pid.append(re.split("\s+", i)[1])
     return self.pid
Example #28
0
    def setup(self):
        CsHelper.copy_if_needed("/etc/apache2/vhostexample.conf",
                                "/etc/apache2/conf.d/vhost%s.conf" % self.dev)

        file = CsFile("/etc/apache2/conf.d/vhost%s.conf" % (self.dev))
        file.search("<VirtualHost.*:80>", "\t<VirtualHost %s:80>" % (self.ip))
        file.search("<VirtualHost.*:80>", "\t<VirtualHost %s:80>" % (self.ip))
        file.search("<VirtualHost.*:443>", "\t<VirtualHost %s:443>" % (self.ip))
        file.search("Listen .*:80", "Listen %s:80" % (self.ip))
        file.search("Listen .*:443", "Listen %s:443" % (self.ip))
        file.search("ServerName.*", "\tServerName vhost%s.cloudinternal.com" % (self.dev))
        file.commit()
        if file.is_changed():
            CsHelper.service("apache2", "restart")

        self.fw.append(["", "front",
                        "-A INPUT -i %s -d %s/32 -p tcp -m tcp -m state --state NEW --dport 80 -j ACCEPT" % (self.dev, self.ip)
                        ])
Example #29
0
    def process(self):
        route = CsRoute()

        for dev in self.dbag:
            if dev == "id":
                continue
            ip = CsIP(dev, self.config)

            for address in self.dbag[dev]:
                if(address["nw_type"]!="public"):
                    continue

                #check if link is up
                if (not self.check_if_link_exists(dev)):
                    logging.info("link %s does not exist, so not processing"%dev)
                    continue
                if not self.check_if_link_up(dev):
                   cmd="ip link set %s up"%dev
                   CsHelper.execute(cmd)

                network = str(address["network"])

                ip.setAddress(address)

                if ip.configured():
                    logging.info(
                        "Address %s on device %s already configured", ip.ip(), dev)

                    ip.post_configure()

                else:
                    logging.info(
                        "Address %s on device %s not configured", ip.ip(), dev)
                    if CsDevice(dev, self.config).waitfordevice():
                        ip.configure()
                route.add_route(dev, network)

        # once we start processing public ip's we need to verify there
        # is a default route and add if needed
        if not route.defaultroute_exists():
            cmdline=self.config.get_cmdline_instance()
            if(cmdline.get_gateway()):
                route.add_defaultroute(cmdline.get_gateway())
Example #30
0
    def compare(self, list):
        """ Compare reality with what is needed """
        # PASS 1:  Ensure all chains are present
        for fw in list:
            new_rule = CsNetfilter()
            new_rule.parse(fw[2])
            new_rule.set_table(fw[0])
            self.add_chain(new_rule)

        ruleSet = set()
        # PASS 2: Create rules
        for fw in list:
            tupledFw = tuple(fw)
            if tupledFw in ruleSet :
                logging.debug("Already processed : %s", tupledFw)
                continue

            new_rule = CsNetfilter()
            new_rule.parse(fw[2])
            new_rule.set_table(fw[0])
            if isinstance(fw[1], int):
                new_rule.set_count(fw[1])

            rule_chain = new_rule.get_chain()

            logging.debug("Checking if the rule already exists: rule=%s table=%s chain=%s", new_rule.get_rule(), new_rule.get_table(), new_rule.get_chain())
            if self.has_rule(new_rule):
                logging.debug("Exists: rule=%s table=%s", fw[2], new_rule.get_table())
            else:
                # print "Add rule %s in table %s" % ( fw[2], new_rule.get_table())
                logging.info("Add: rule=%s table=%s", fw[2], new_rule.get_table())
                # front means insert instead of append
                cpy = fw[2]
                if fw[1] == "front":
                    cpy = cpy.replace('-A', '-I')
                if isinstance(fw[1], int):
                    # if the rule is for ACLs, we want to insert them in order, right before the DROP all
                    if rule_chain.startswith("ACL_INBOUND") or rule_chain.startswith("ACL_OUTBOUND"):
                        rule_count = self.chain.get_count(rule_chain)
                        cpy = cpy.replace("-A %s" % new_rule.get_chain(), '-I %s %s' % (new_rule.get_chain(), rule_count))
                    else:
                        cpy = cpy.replace("-A %s" % new_rule.get_chain(), '-I %s %s' % (new_rule.get_chain(), fw[1]))
                ret = CsHelper.execute2("iptables -t %s %s" % (new_rule.get_table(), cpy))
                #There are some issues in this framework causing failures  .. like adding a chain without checking it is present causing
                # the failures. Also some of the rule like removeFromLoadBalancerRule is deleting rule and deleteLoadBalancerRule
                #trying to delete which causes the failure.
                #For now raising the log.
                #TODO: Need to fix in the framework.
                if ret.returncode != 0 :
                    error = ret.communicate()[0]
                    logging.debug("iptables command got failed ... continuing")
                ruleSet.add(tupledFw)
                self.chain.add_rule(rule_chain)
        self.del_standard()
        self.get_unseen()
 def grep(self, str):
     for i in CsHelper.execute("ps aux"):
         if i.find(str) != -1:
             return re.split("\s+", i)[1]
     return -1
Example #32
0
 def configure_rp(self):
     """
     Configure Reverse Path Filtering
     """
     filename = "/proc/sys/net/ipv4/conf/%s/rp_filter" % self.dev
     CsHelper.updatefile(filename, "1\n", "w")
Example #33
0
 def arpPing(self):
     cmd = "arping -c 1 -I %s -A -U -s %s %s" % (
         self.dev, self.address['public_ip'], self.address['public_ip'])
     CsHelper.execute(cmd)
Example #34
0
 def findRule(self, rule):
     for i in CsHelper.execute("ip rule show"):
         if rule in i.strip():
             return True
     return False
Example #35
0
    def configure_server(self):
        # self.conf.addeq("dhcp-hostsfile=%s" % DHCP_HOSTS)
        idx = 0
        listen_address = ["127.0.0.1"]
        for i in self.devinfo:
            if not i['dnsmasq']:
                continue
            device = i['dev']
            ip = i['ip'].split('/')[0]
            gn = CsGuestNetwork(device, self.config)
            # Gateway
            gateway = ''
            if self.config.is_vpc():
                gateway = gn.get_gateway()
            else:
                gateway = i['gateway']
            sline = "dhcp-range=set:interface-%s-%s" % (device, idx)
            if self.cl.is_redundant():
                line = "dhcp-range=set:interface-%s-%s,%s,static" % (
                    device, idx, gateway)
            else:
                line = "dhcp-range=set:interface-%s-%s,%s,static" % (device,
                                                                     idx, ip)
            self.conf.search(sline, line)
            sline = "dhcp-option=tag:interface-%s-%s,15" % (device, idx)
            line = "dhcp-option=tag:interface-%s-%s,15,%s" % (device, idx,
                                                              gn.get_domain())
            self.conf.search(sline, line)
            # DNS search order
            if gn.get_dns() and device:
                sline = "dhcp-option=tag:interface-%s-%s,6" % (device, idx)
                dns_list = [x for x in gn.get_dns() if x]
                line = "dhcp-option=tag:interface-%s-%s,6,%s" % (
                    device, idx, ','.join(dns_list))
                self.conf.search(sline, line)
            if gateway != '0.0.0.0':
                sline = "dhcp-option=tag:interface-%s-%s,3," % (device, idx)
                line = "dhcp-option=tag:interface-%s-%s,3,%s" % (device, idx,
                                                                 gateway)
                self.conf.search(sline, line)
            # Netmask
            netmask = ''
            if self.config.is_vpc():
                netmask = gn.get_netmask()
            else:
                netmask = str(i['network'].netmask)
            sline = "dhcp-option=tag:interface-%s-%s,1," % (device, idx)
            line = "dhcp-option=tag:interface-%s-%s,1,%s" % (device, idx,
                                                             netmask)
            self.conf.search(sline, line)
            # Listen Address
            if self.cl.is_redundant():
                listen_address.append(gateway)
            else:
                listen_address.append(ip)
            # Add localized "data-server" records in /etc/hosts for VPC routers
            if self.config.is_vpc():
                self.add_host(gateway,
                              "%s data-server" % CsHelper.get_hostname())
            idx += 1

        # Listen Address
        sline = "listen-address="
        line = "listen-address=%s" % (','.join(listen_address))
        self.conf.search(sline, line)
Example #36
0
 def remove(self):
     file = "/etc/apache2/sites-enabled/vhost-%s.conf" % self.dev
     if os.path.isfile(file):
         os.remove(file)
         CsHelper.service("apache2", "restart")
Example #37
0
 def start(self):
     CsHelper.service("cloud-password-server@%s" % self.ip, "start")
 def kill(self, pid):
     if pid > 1:
         CsHelper.execute("kill -9 %s" % pid)
Example #39
0
 def flush_table(self, tablename):
     CsHelper.execute("ip route flush table %s" % (tablename))
     CsHelper.execute("ip route flush cache")
 def kill_all(self):
     pids = self.find_pid()
     for p in pids:
         CsHelper.execute("kill -9 %s" % p)