Пример #1
0
    def __init__(self, host, port):
        self.FILENAME_MY_CONFIG = 'Coordinator_cfg.py'

        CommonHandler.__init__(self, host, port)
        self.dispatch_handlers.update({
            'RackAlgorithmResourceInformationReq':
            self.RackAlgorithmResourceInformation,
            'ClusterDatabaseSubsystemCreateVMres':
            self.ClusterDatabaseSubsystemCreateVM,
            'NodeDatabaseSubsystemAddPortReq':
            self.NodeDatabaseSubsystemAddPort,
        })
        self.startup_functions.extend((
            #self.databaseSubsystem,
            self.CreateVmByCheckingDatabase,
            self.CheckPortmappingRequest,
            self.sayHello,  # hello function
        ))
        # database imformation, use config to replace this part
        # TODO replace all db connection with self.db
        try:
            self.db = mdb.connect(self.config['host'], self.config['db_user'],
                                  self.config['db_password'],
                                  self.config['db_name'])
        except:
            logger.error('connect to db failed')
            self.db = None
        self.host = self.config['host']
        self.db_account = self.config['db_account']
        self.db_password = self.config['db_password']
        self.db_name = self.config['db_name']

        self.cmd_iptables = self.config['cmd_iptables']
Пример #2
0
    def __init__(self, host, port):
        self.FILENAME_MY_CONFIG = 'Coordinator_cfg.py'

        CommonHandler.__init__(self, host, port)
        self.dispatch_handlers.update({
            'RackAlgorithmResourceInformationReq': self.RackAlgorithmResourceInformation,
            'ClusterDatabaseSubsystemCreateVMres': self.ClusterDatabaseSubsystemCreateVM,
            'NodeDatabaseSubsystemAddPortReq': self.NodeDatabaseSubsystemAddPort,
        })
        self.startup_functions.extend((
            #self.databaseSubsystem,      
            self.CreateVmByCheckingDatabase,
            self.CheckPortmappingRequest,
            self.sayHello,          # hello function
        ))
        # database imformation, use config to replace this part
        # TODO replace all db connection with self.db
        try:
            self.db = mdb.connect(self.config['host'], self.config['db_user'], self.config['db_password'], self.config['db_name'])
        except:
            logger.error('connect to db failed')
            self.db = None
        self.host = self.config['host']
        self.db_account = self.config['db_account']
        self.db_password = self.config['db_password']
        self.db_name = self.config['db_name']

        self.cmd_iptables = self.config['cmd_iptables']
Пример #3
0
    def run(self):
        logger.info('network layer listener begin to work...')
        while True:
            ospf_pkg = self.network_layer.recv_ospf()
            ordinary_pkg = self.network_layer.recv()
            if ospf_pkg is None and ordinary_pkg is None:
                time.sleep(0.01)
                continue
            if ospf_pkg:
                src_ip = ospf_pkg.dest_ip
                dest_ip = ospf_pkg.src_ip
                netmask = ospf_pkg.net_mask
                if ospf_pkg.protocol != 119:
                    logger.error(
                        'error! get ospf pkg, protocol is %d instead of 119',
                        ospf_pkg.protocol)
                ospf_msg = utilities.objDecode(ospf_pkg.data)
                logger.info("get ospf msg\n%s", ospf_msg)

                if ospf_msg['code'] == 0:
                    if not is_controller:
                        logger.warn(
                            "IM NOT CONTROLLER. get request msg. ignore.")
                        continue
                    src_index = ospf_msg['src_index']
                    init_global_route_table(GLOBAL_ROUTE_INFORMATIOIN_FILE,
                                            src_index)
                    sp = calculate_shortest_path(src_index)
                    response_msg = {
                        "code": 1,
                        "msg": "here's your route table",
                        "route_table": sp
                    }
                    response_msg_bytes = utilities.objEncode(response_msg)
                    pkg = route.IP_Package(src_ip, dest_ip, dest_ip, netmask,
                                           response_msg_bytes)
                    pkg.protocol = 119
                    errno = route.link_layer.send(pkg.to_bytes())
                    if errno < 0:
                        logger.warning(
                            'fail to send to link layer. errno is %d\n', errno)
                elif ospf_msg['code'] == 1:
                    logger.info('get route table response msg\n%s', ospf_msg)
                    route_table = ospf_msg['route_table']
                    for dest_net, netmask, dest_ip in route_table:
                        route.my_route_table.update_item(
                            dest_net, netmask, dest_ip)

            if ordinary_pkg:
                #TODO: refine here
                logger.info("get odinary msg\n%s", ordinary_pkg)
Пример #4
0
    def portmapping(self, vmname, vmip, vmport, hostport, action):
        if action == 'a':
            iptables_cmd = '%s %s PREROUTING -p tcp --dport %s -j DNAT --to %s:%s' \
                    %(self.cmd_iptables, '-A', hostport, vmip, vmport)
            logger.info(
                'Add port mapping for %s, from %s to %s on hostmachine' %
                (vmname, vmport, hostport))
            logger.debug(iptables_cmd)

        elif action == 'd':
            iptables_cmd = '%s %s PREROUTING -p tcp --dport %s -j DNAT --to %s:%s' \
                    %(self.cmd_iptables, '-D', hostport, vmip, vmport)
            logger.info(
                'Delete port mapping for %s, from %s to %s on hostmachine' %
                (vmname, vmport, hostport))
            logger.debug(iptables_cmd)
        else:
            logger.error('Error argument!')
            return 0

        (result, value) = pexpect.run(iptables_cmd, withexitstatus=1)

        if value != 0:
            logger.error(result)
            return 0

        return 1

        if connect:
            logger.info('Start.')
            logger.info('Database connected.')
            while 1:
                query_portreq = "SELECT * FROM %s WHERE state='adding' \
                        OR state='deleting 'ORDER BY hostport" % (porttb)
                db.query(query_portreq)
                req_res = db.store_result()
                fetched_req_data = req_res.fetch_row()
                while fetched_req_data:
                    state = fetched_req_data[0][idx_state]
                    vmname = fetched_req_data[0][idx_vmname]
                    vmport = fetched_req_data[0][idx_vmport]
                    oldhostport = fetched_req_data[0][idx_hostport]

                    if (state == 'adding'):
                        vmip = socket.gethostbyname(vmname)
                        newport = oldhostport
                        if (newport == '-1'):
                            newport = get_port()
                        if (newport != -1):
                            portmapping(vmname, vmip, vmport, newport, 'a')
                            query = "UPDATE %s SET state='using', \
                                hostport='%s', ip='%s' \
                                WHERE hostport=%s" % (porttb, newport, vmip,
                                                      oldhostport)
                            db.query(query)
                        else:
                            logger.error('No more port!')
                    elif (fetched_req_data[0][idx_state] == 'deleting'):
                        #delete port
                        vmip = fetched_req_data[0][idx_ip]
                        portmapping(vmname, vmip, vmport, oldhostport, 'd')
                        query = "DELETE FROM %s WHERE hostport=%s" % (
                            porttb, oldhostport)
                        db.query(query)
                    else:
                        logger.error("I don't know what's wrong!")

                fetched_req_data = req_res.fetch_row()
            time.sleep(sleep_time)
Пример #5
0
    def portmapping(self, vmname, vmip, vmport, hostport, action):
        if action == 'a':
            iptables_cmd = '%s %s PREROUTING -p tcp --dport %s -j DNAT --to %s:%s' \
                    %(self.cmd_iptables, '-A', hostport, vmip, vmport)
            logger.info('Add port mapping for %s, from %s to %s on hostmachine'%(vmname, vmport, hostport))
            logger.debug(iptables_cmd)

        elif action == 'd':
            iptables_cmd = '%s %s PREROUTING -p tcp --dport %s -j DNAT --to %s:%s' \
                    %(self.cmd_iptables, '-D', hostport, vmip, vmport)
            logger.info('Delete port mapping for %s, from %s to %s on hostmachine'%(vmname, vmport, hostport))
            logger.debug(iptables_cmd)
        else :
            logger.error('Error argument!')
            return 0

        (result, value) = pexpect.run(iptables_cmd, withexitstatus = 1)

        if value != 0 :
            logger.error(result)
            return 0

        return 1

        if connect:
            logger.info('Start.')
            logger.info('Database connected.')
            while 1:
                query_portreq = "SELECT * FROM %s WHERE state='adding' \
                        OR state='deleting 'ORDER BY hostport"%(porttb)
                db.query(query_portreq)
                req_res = db.store_result()
                fetched_req_data = req_res.fetch_row()
                while fetched_req_data:
                    state = fetched_req_data[0][idx_state]
                    vmname = fetched_req_data[0][idx_vmname]
                    vmport = fetched_req_data[0][idx_vmport]
                    oldhostport = fetched_req_data[0][idx_hostport]

                    if (state == 'adding') :
                        vmip = socket.gethostbyname(vmname)
                        newport = oldhostport
                        if (newport == '-1') :
                            newport = get_port()
                        if (newport != -1) :
                            portmapping(vmname, vmip, vmport, newport, 'a')
                            query = "UPDATE %s SET state='using', \
                                hostport='%s', ip='%s' \
                                WHERE hostport=%s"%(porttb, newport, vmip, oldhostport)
                            db.query(query)
                        else :
                            logger.error('No more port!')
                    elif (fetched_req_data[0][idx_state] == 'deleting') :
                        #delete port
                        vmip = fetched_req_data[0][idx_ip]
                        portmapping(vmname, vmip, vmport, oldhostport, 'd')
                        query = "DELETE FROM %s WHERE hostport=%s"%(porttb, oldhostport)
                        db.query(query)
                    else :
                        logger.error("I don't know what's wrong!")

                fetched_req_data = req_res.fetch_row()
            time.sleep(sleep_time)