示例#1
0
    def processevent(self, event):
        """Process event

        @param event event to process
        @return True
        """
        if (isinstance(event, yapc.priv_callback)):
            lastr = self.lastresult
            r = self.get_stat()
            output.vdbg(r)

            if (lastr == None):
                self._server.post_event(yapc.priv_callback(self), self.interval)
                return True

            for k,v in r.items():
                for k2 in ["transmit", "receive"]:
                    try:
                        v[k2]["bps"] = (float(v[k2]["bytes"] - lastr[k][k2]["bytes"])*8.0/
                                        (v["timestamp"]-lastr[k]["timestamp"]))
                        v[k2]["pps"] = (float(v[k2]["packets"] - lastr[k][k2]["packets"])/
                                        (v["timestamp"]-lastr[k]["timestamp"]))
                    except KeyError:
                        output.warn("Interface "+str(k)+" is new or removed",
                                    self.__class__.__name__)

            self._server.post_event(yapc.priv_callback(self), self.interval)

        return True
示例#2
0
文件: nat.py 项目: yapkke/yapc
 def __route_check(self, o):
     """Check route
     
     @param o route check object (dictionary)
     """
     gw = self.get_if_route(mif=o["mif"])
     if gw == None:
         o["tried"] += 1
         if o["tried"] < MAX_RETRY:
             rc = yapc.priv_callback(self, o)
             self.server.post_event(rc, 1)
     else:
         no = self.switch.if_name2dpid_port_mac(o["if"])[1]
         mc.set(nat.get_gw_key(no), gw)
         output.info("Gateway of " + o["if"] + " is " + gw, self.__class__.__name__)
         # Check for route
         self.check_default_route()
         # Register ip range
         ipv4addr = self.ifmgr.ipv4_addr_n_mask(o["mif"])
         if ipv4addr == None:
             return
         ipr = (
             pu.ip_string2val(ipv4addr["addr"]),
             pu.ip_string2val(ipv4addr["netmask"]),
             pu.hex_str2array(self.ifmgr.ethernet_addr(o["mif"])),
         )
         mc.set(nat.get_ip_range_key(no), ipr)
         output.info(
             o["if"] + "(" + str(no) + ") has IP address %x and netmask %x" % (ipr[0], ipr[1]),
             self.__class__.__name__,
         )
         # Call for ARP
         rc = yapc.priv_callback(self, {"type": "arp", "tried": 0, "ip": gw, "if": o["mif"]})
         self.server.post_event(rc, 0)
示例#3
0
文件: nat.py 项目: yapkke/yapc
    def __init__(self, server, ofconn, coin=None, bwinterval=30):
        """Initialize

        @param server yapc core
        @param conn reference to connections
        @param sfr send flow removed or not
        @param coin reference to COIN
        @oaram bwinterval interval to query for bandwidth
        """
        core.component.__init__(self, ofconn, coin)

        self.server = server

        mc.get_client()
        server.register_event_handler(ofevents.pktin.name, self)

        ##Interval to maintain bandwidth
        self.bwinterval = bwinterval
        self.max_bw_port = None

        ##Reference to switch feature
        self.__sf = None

        if self.bwinterval != 0:
            self.server.post_event(yapc.priv_callback(self), 0)
        server.register_event_handler(coini.queryresponse.name, self)

        ##Reference to last interface chosen
        self.__last_intf_choosen = 0
        self.cookie = 0
示例#4
0
    def send(self, message, addr, action, timeout=3, retry=10, tried=0):
        """Send snmp.message

        @param message SNMP message to send
        @param addr (host, port) to send to
        @param timeout timeout in how many seconds
        @param retry number of times to retry (if None, try indefinitely)
        """
        pdu=None
        if (action == self.GET):
            pdu = message.pack_get_pdu()
        elif (action == self.SET):
            pdu = message.pack_set_pdu()
        elif (action == self.WALK):
            pdu = message.pack_walk_pdu()
            
        msg = message.pack_msg(pdu)
        reqId = message.get_req_id(pdu)
        output.vdbg("Transmitting SNMP message with id "+str(reqId)+\
                   " for the no. "+str(tried+1)+ " time",
                   self.__class__.__name__)
        self.client.send(msg, addr)
        self.messages[reqId] = {"timeout": timeout,
                                "retry": retry,
                                "tried": tried+1,
                                "request": message,
                                "addr": addr,
                                "action": action}
        self.server.post_event(yapc.priv_callback(self, reqId), timeout)
示例#5
0
    def processevent(self, event):
        """Process event

        @param event event to process
        @return True
        """
        if (isinstance(event, yapc.priv_callback)):
            output.vdbg(self.get_stat())
            self._server.post_event(yapc.priv_callback(self), self.interval)

        return True
示例#6
0
文件: nat.py 项目: yapkke/yapc
    def dhclient_mirror(self, intf):
        """Perform dhclient on mirror interface
       
        @param intf interface (primary)
        """
        mif = self.mirror[intf].client_intf
        self.ifmgr.invoke_dhcp(mif)
        rc = yapc.priv_callback(self, {"type": "route", "tried": 0, "if": intf, "mif": mif})
        self.server.post_event(rc, 0)

        return "executed"
示例#7
0
    def processevent(self, event):
        """Process event

        @param event event to process
        @return True
        """
        if (isinstance(event, yapc.priv_callback)):
            self.probe()
            self.server.post_event(yapc.priv_callback(self), self.interval) 

        return True
示例#8
0
 def receive(self, sock, recvthread):
     """Receive new connection
     """
     output.vvdbg("Receiving packet on raw socket "+str(sock),
                 self.__class__.__name__)        
     data = sock.recv(self.maxlen)
     if (self.handler == None):
         self.scheduler.post_event(message(sock, data))
     else:
         self.scheduler.post_event(yapc.priv_callback(self.handler,
                                                      message(sock, data)))
示例#9
0
文件: nat.py 项目: yapkke/yapc
 def __arp_check(self, o):
     """Check ARP
     
     @param o arp check object (dictionary)
     """
     mac = self.get_ip_mac(o["ip"], self.loif.client_intf)
     if mac == None:
         o["tried"] += 1
         if o["tried"] < MAX_RETRY:
             rc = yapc.priv_callback(self, o)
             self.server.post_event(rc, 1)
     else:
         mc.set(nat.get_gw_mac_key(o["ip"]), mac.mac)
         output.info("ARP of " + o["ip"] + " is " + str(mac.mac), self.__class__.__name__)
示例#10
0
文件: nat.py 项目: yapkke/yapc
    def processevent(self, event):
        """Event handler

        @param event event to handle
        @return false if processed else true
        """
        if isinstance(event, yapc.priv_callback):
            self.__sf = mc.get(nat.SW_FEATURE)
            if self.__sf != None:
                bwquery = ns.bandwidth_query(ns.bandwidth_query.MODE_TOTAL_MAX)
                for p in self.__sf.ports:
                    if mc.get(nat.get_ip_range_key(p.port_no)) != None:
                        # Port exist
                        bwquery.interfaces.append(p.name)
                if len(bwquery.interfaces) != 0:
                    self.server.post_event(bwquery)

            # Query for bandwidth of intervals
            if self.bwinterval != 0:
                self.server.post_event(yapc.priv_callback(self), self.bwinterval)

        elif isinstance(event, coini.queryresponse) and isinstance(event.query, ns.bandwidth_query):
            for p in self.__sf.ports:
                if event.response[0]["interface"] == p.name:
                    self.max_bw_port = p.port_no
                    output.vdbg(
                        "Port " + str(p.port_no) + "(" + str(p.name) + ") has most bandwidth", self.__class__.__name__
                    )

        elif (
            isinstance(event, ofevents.pktin)
            and
            # Handle packet in
            event.match.dl_type == dpkt.ethernet.ETH_TYPE_IP
        ):
            iport = mc.get(nat.SW_INNER_PORT)
            intfs = self.get_intf_n_range()
            lointf = mc.get(nat.SW_INNER_PORT_ADDR)
            if iport == None:
                output.err("No inner port recorded!  Are we connected?", self.__class__.__name__)
                return True

            if event.match.in_port == iport:
                return self._process_outbound(event, intfs, iport, lointf)
            else:
                return self._process_inbound(event, intfs, iport, lointf)

        return True
示例#11
0
    def processevent(self, event):
        """Handle event
        """
        if (isinstance(event, yapc.priv_callback)):
            #Timer up
            self.server.post_event(yapc.priv_callback(self, None),
                                   self.period)

            output.info("yapc sees "+str(self.count)+" OpenFlow messages in the last "+\
                        str(self.period)+" seconds",
                       self.__class__.__name__)
            self.count = 0
        elif (isinstance(event, ofcomm.message)):
            self.count += 1
            
        return True
示例#12
0
    def __init__(self, server, period=5):
        """Initialize

        @param server yapc core
        @param period period before each printout
        """
        ##Reference to scheduler for timed events
        self.server = server
        server.register_event_handler(ofcomm.message.name,
                                      self)
        ##Count for number of messages
        self.count = 0
        ##How often to count
        self.period = period
        self.server.post_event(yapc.priv_callback(self, None),
                               self.period)
示例#13
0
    def __init__(self, server, interval=5, procfile="/proc/net/dev"):
        """Initialize

        @param server yapc core
        @param interval interval to look
        @param procfile file to look into
        """
        ##Proc file
        self.procfile = procfile
        ##Interval
        self.interval = interval
        ##Reference to yapc core
        self._server = server
        ##Last result
        self.lastresult = None
    
        server.post_event(yapc.priv_callback(self), 0) 
示例#14
0
    def __init__(self, server, interval=0.2):
        """Initialize
        """

        ##Configure stdin
        self.fd = sys.stdin.fileno()
        
        self.oldterm = termios.tcgetattr(self.fd)
        newattr = termios.tcgetattr(self.fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(self.fd, termios.TCSANOW, newattr)
        
        self.oldflags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
        fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK)

        ##Register for events
        self.interval = interval
        self.server = server
        server.register_cleanup(self)
        server.post_event(yapc.priv_callback(self), 0) 
示例#15
0
    def __init__(self, server, ofconn,
                 sendinterval=10, linktimeout=30):
        """Initialize

        @param server yapc core
        """
        if (sendinterval > linktimeout):
            output.warn("Probe interval of "+str(sendinterval)+\
                        "is smaller than timeout of "+str(linktimeout),
                        self.__class__.__name__)
        ##Interval to send LLDP per switch/port
        self.interval = sendinterval
        self.__minterval = sendinterval
        ##Time to wait before timing out link
        self.link_maintain = link_maintain(server, linktimeout)
        ##Reference to core
        self.server = server
        ##Reference to OpenFlow connections
        self.conn = ofconn
        ##Current list of switch/port LLDP is sent
        self.__sw_port = []
        ##Packet out template
        self.__po = pyof.ofp_packet_out()
        oao = pyof.ofp_action_output()
        self.__po.in_port = pyof.OFPP_NONE
        self.__po.actions_len = oao.len
        self.__po.actions.append(oao)

        mc.get_client()

        server.register_event_handler(ofevents.pktin.name,
                                      self)
        server.register_event_handler(ofevents.port_status.name,
                                      self)
        server.register_event_handler(ofevents.features_reply.name,
                                      self)
        server.post_event(yapc.priv_callback(self, True),
                          self.interval)
示例#16
0
    def processevent(self, event):
        """Handle event
        """
        if isinstance(event, ofevents.pktin):
            #Check for LLDP and discover/maintain links
            if (event.dpkt.type == lldppkt.LLDP_ETH):
                lldp = lldppkt.LLDP(event.dpkt.data)
                src_dpid = int(lldp.value[1:], 16)
                src_port = int(lldp.data.value[1:])
                dst_dpid = self.conn.db[event.sock].dpid
                dst_port = event.pktin.in_port
                self.link_maintain.update(src_dpid, src_port,
                                          dst_dpid, dst_port)
                output.vdbg("%x:" % dst_dpid + str(dst_port)+\
                            " receive LLDP packet from %x" % src_dpid+\
                            ":"+str(src_port),
                            self.__class__.__name__)
                
                return False
        
        elif isinstance(event, ofevents.port_status):
            #New port, so let's try to find a new link fast
            self.send_lldp(self.conn.db[event.sock].dpid,
                           event.port.desc)

        elif isinstance(event, ofevents.features_reply):
            #New switch, so let's try to find new links fast
            for p in event.features.ports:
                self.send_lldp(event.features.datapath_id, p)

        elif isinstance(event, yapc.priv_callback):
            if (event.magic ==True):
                #Periodic enumeration of switch port to maintain
                dpidsl = mc.get(swstate.dp_features.DP_SOCK_LIST)
                if (dpidsl != None):
                    for key in dpidsl:
                        sw = mc.get(key)
                        for p in sw.ports:
                            if (p.port_no <= pyof.OFPP_MAX and
                                (sw.datapath_id, p) not in self.__sw_port):
                                self.__sw_port.append((sw.datapath_id, p))
                    if (len(self.__sw_port) != 0):
                        self.__minterval = float(self.interval)/len(self.__sw_port)
                        self.server.post_event(yapc.priv_callback(self, False),0)
                    output.vdbg("Gather "+str(len(self.__sw_port))+" to send LLDP to",
                               self.__class__.__name__)
                else:
                    output.dbg("No switch port to send LLDP to",
                               self.__class__.__name__)
                self.server.post_event(yapc.priv_callback(self, True),
                                  self.interval)
            else:
                #Sending of LLDP for maintenance
                if (len(self.__sw_port) > 0):
                    (sw,port) = self.__sw_port.pop()
                    self.send_lldp(sw, port)
                    self.server.post_event(yapc.priv_callback(self, False),
                                           self.__minterval)
                self.link_maintain.check_expire()
                
        return True