def _netic_remove_path(self, request, arg):
     path = str(arg["{path_ID}"])
     res = self.bodrt.netic_remove_path(path)
     if res == 0:
         # self.discoveryws.remove_existing_path(str(arg['{path_ID}']))
         neticResponse(request, NTC_OK, responseCode=204)
     else:
         errorCode = {"errorCode": NTC_VP_ERR_PATH_NOT_FOUND}
         webservice.badRequest(request, errcode2str[NTC_VP_ERR_PATH_NOT_FOUND], errorCode)
         return NOT_DONE_YET
     return
def ws_deny_group(request, args):
    """ WS interface to permit(). """
    content = webservice.json_parse_message_body(request)
    if content == None:
        print "error in getting state"
        return  webservice.badRequest(request, "missing eaddr")

    for eaddr in content:
        if not is_valid_eth(eaddr):
            return   webservice.badRequest(request, "malformed eaddr " + eaddr)

    for eaddr in content:
        deny(eaddr)
    return status()
def ws_whitelist_eth(request, args):
    """ Remove a mac address from filtering eap traffic. """
    eaddr = args.get('eaddr')
    if not eaddr: return webservice.badRequest(request, "missing eaddr")
    eaddr = util.convert_to_eaddr(eaddr)
    data = Homework._dhcp.whitelist_mac_addr(eaddr)
    return json.dumps(Homework._dhcp.get_blacklist_mac_status())
def ws_deny(request, args):
    """ WS interface to deny(). """
                                   
    eaddr = args.get('eaddr')
    if not eaddr: return webservice.badRequest(request, "missing eaddr")
    ipaddr = args.get('ipaddr')

    return deny(eaddr, ipaddr)
def ws_dns_deny_group(request, args):
    """ WS interface to dns_deny_group(). """
    
    print request
    print args

    content = webservice.json_parse_message_body(request)
    if content == None:
        print "error in getting state"
        return  webservice.badRequest(request, "missing eaddr")

    for permititem in content:
        if not is_valid_eth(permititem['eaddr']):
            return   webservice.badRequest(request, "malformed eaddr " + eaddr)

    for permititem in content:
        dns_deny(permititem['eaddr'], permititem['hostname'])
def ws_blacklist_eth(request, args):
    """ Aggressive mac address exclusion at the level of wpa connectivity. """
    eaddr = args.get('eaddr')
    if not eaddr: return webservice.badRequest(request, "missing eaddr")
    eaddr = util.convert_to_eaddr(eaddr)
    if eaddr in Homework.st['permitted']:
        del Homework.st['permitted'][eaddr]
        Homework._dhcp.revoke_mac_addr(eaddr)
    Homework._dhcp.blacklist_mac_addr(eaddr)
    return json.dumps(Homework._dhcp.get_blacklist_mac_status())
def ws_permit_group(request, args):
    """ WS interface to permit(). """
    content = webservice.json_parse_message_body(request)
    if content == None:
        print "error in getting state"
        return  webservice.badRequest(request, "missing eaddr")

    for eaddr in content:
        if not is_valid_eth(eaddr):
            return   webservice.badRequest(request, "malformed eaddr " + eaddr)

    for eaddr in content:
        permit(eaddr)
    return status()

#    eaddr = args.get('eaddr')
#    if not eaddr: return webservice.badRequest(request, "missing eaddr")

    return '{"status" : "success"}' #permit(eaddr)
def ws_dns_permit(request, args):
    """ WS interface to dns_permit(). """

    print request
    print args

    eaddr = args.get('eaddr')
    hostname = args.get('hostname')
    if not (eaddr and hostname): return webservice.badRequest(request, "missing eaddr")
      
    return dns_permit(eaddr, hostname)
Exemple #9
0
    def _create_flow_monitor(self, request, arg):
        a = {}
        content = request.content.read()

        errorCode = {}
        try:
            pathID = int(str(request.args['PathID'][0]),16)
            dpid = datapathid.from_host(int(request.args['dpid'][0]))
            
        except KeyError:
            errorCode['errorCode'] = NTC_ST_ERR_MISSING_M_FIELD
            webservice.badRequest(request,errcode2str[NTC_ST_ERR_MISSING_M_FIELD],errorCode)
            return NOT_DONE_YET
        except TypeError:
            errorCode['errorCode'] = NTC_ST_ERR_BAD_ARGUMENT
            webservice.badRequest(request,errcode2str[NTC_ST_ERR_BAD_ARGUMENT],errorCode)
            return NOT_DONE_YET
        
        try:
            duration = int(request.args['duration'][0])
            frequency = int(request.args['frequency'][0])
        except:
            duration = 100
            frequency = 1;
        
        monitorID,error = self.ll.create_new_flow_monitor(pathID,dpid,duration,frequency)
        
        if (error == 0):
            hexRes = "%x" %monitorID
            a['MonitorID'] = hexRes
            self.monitorIDs.append(monitorID)
            neticResponse(request,NTC_OK,a)
        if(error == 1):
            errorCode['errorCode'] = NTC_ST_ERR_PATH_NOT_FOUND
            webservice.badRequest(request,errcode2str[NTC_ST_ERR_PATH_NOT_FOUND],errorCode)
            return NOT_DONE_YET
        elif (error == 2):
            errorCode['errorCode'] = NTC_ST_ERR_DPID_NOT_FOUND
            webservice.badRequest(request,errcode2str[NTC_ST_ERR_DPID_NOT_FOUND],errorCode)
            return NOT_DONE_YET
    def _netic_create_path(self, request, arg):

        # content = json_parse_message_body(arg)

        content = request.content.read()

        errorCode = {}

        try:
            nw_src = str(request.args["nw_src"][0])
            nw_dst = str(request.args["nw_dst"][0])

            duration = int(request.args["duration"][0])
            bandwidth = int(request.args["bandwidth"][0])
            set_arp = int(request.args["set_arp"][0])
            bidirectional = int(request.args["bidirectional"][0])
        except:
            errorCode["errorCode"] = NTC_VP_ERR_MISSING_M_FIELD
            webservice.badRequest(request, errcode2str[NTC_VP_ERR_MISSING_M_FIELD], errorCode)
            return NOT_DONE_YET
        # bidirectional and set_arp has to be either 0 or 1:
        if ((set_arp != 0) and (set_arp != 1)) or ((bidirectional != 0) and (bidirectional != 1)):
            errorCode["errorCode"] = NTC_VP_ERR_MISSING_M_FIELD
            webservice.badRequest(request, errcode2str[NTC_VP_ERR_MISSING_M_FIELD], errorCode)
            return NOT_DONE_YET

        paramsMissing = 0
        try:
            dp_src = datapathid.from_host(int(request.args["dp_src"][0]))
            dp_dst = datapathid.from_host(int(request.args["dp_dst"][0]))
            first_port = int(request.args["first_port"][0])
            last_port = int(request.args["last_port"][0])
        except:
            dp_src = -1
            dp_dst = -1
            first_port = -1
            last_port = -1
            paramsMissing = 1

        info_src = self.discovery.find_host_by_ipstr(nw_src)
        info_dst = self.discovery.find_host_by_ipstr(nw_dst)

        if paramsMissing == 1:
            # Try to find in which port and switch the path will begin and
            # terminate
            if info_src == None or info_dst == None:
                errorCode["errorCode"] = NTC_VP_ERR_MISSING_LOC_INFO
                webservice.badRequest(request, errcode2str[NTC_VP_ERR_MISSING_LOC_INFO], errorCode)
                return NOT_DONE_YET
            else:
                dp_src = datapathid.from_host(info_src["dp"])
                first_port = info_src["port"]
                dp_dst = datapathid.from_host(info_dst["dp"])
                last_port = info_dst["port"]

        else:
            # the dp source and dest and also first and last ports
            # are those specified by the request, lets check them
            if not self.discoveryws.discovery.is_valid_dpid(
                dp_src.as_host()
            ) or not self.discoveryws.discovery.is_valid_dpid(dp_dst.as_host()):
                errorCode["errorCode"] = NTC_VP_ERR_UNKNOWN_SWITCH
                webservice.badRequest(request, errcode2str[NTC_VP_ERR_UNKNOWN_SWITCH], errorCode)
                return NOT_DONE_YET

            if not self.discoveryws.discovery.is_valid_port_in_dpid(
                dp_src.as_host(), first_port
            ) or not self.discoveryws.discovery.is_valid_port_in_dpid(dp_dst.as_host(), last_port):
                errorCode["errorCode"] = NTC_VP_ERR_UNKNOWN_PORT
                webservice.badRequest(request, errcode2str[NTC_VP_ERR_UNKNOWN_PORT], errorCode)
                return NOT_DONE_YET

        # At this point we have the mandatory params of the flow and
        # location of the source and destination point of the path

        paramsMissing = 0
        keyError = 0
        with_arp = False
        if set_arp == 1:
            with_arp = True
            try:
                dl_src = create_eaddr(str(request.args["dl_src"][0]))
                dl_dst = create_eaddr(str(request.args["dl_dst"][0]))
            except KeyError:
                dl_src = 0
                dl_dst = 0
                keyError = 1
                paramsMissing = 1
            except:
                print "other error"

            if (dl_src == None) | (dl_dst == None):
                paramsMissing = 1

            if paramsMissing == 1:
                if info_src != None:
                    dl_src = info_src["dl_addr"]
                if info_dst != None:
                    dl_dst = info_dst["dl_addr"]

            if (dl_src == None) | (dl_dst == None):
                if keyError == 1:
                    errorCode["errorCode"] = NTC_VP_ERR_MISSING_MAC_ADDRESS
                    webservice.badRequest(request, errcode2str[NTC_VP_ERR_MISSING_MAC_ADDRESS], errorCode)
                else:
                    errorCode["errorCode"] = NTC_VP_ERR_BAD_MAC_ADDRESS
                    webservice.badRequest(request, errcode2str[NTC_VP_ERR_MISSING_MAC_ADDRESS], errorCode)
                return NOT_DONE_YET

        # At this point even arp info is ready

        tp_src = 0
        tp_dst = 0
        ip_proto = 255
        granularity = True

        try:
            ip_proto = int(request.args["ip_proto"][0])
        except:
            granularity = False

        if granularity == True:
            try:
                tp_src = int(request.args["tp_src"][0])
            except:
                tp_src = 0
            try:
                tp_dst = int(request.args["tp_dst"][0])
            except:
                tp_dst = 0
        else:
            ip_proto = 255

        npi = Netic_path_info()
        npi.nw_src = nw_src
        npi.nw_dst = nw_dst
        npi.duration = duration
        npi.bandwidth = bandwidth
        if set_arp == True:
            npi.set_arp = True
        else:
            npi.set_arp = False

        if bidirectional == True:
            npi.bidirect = True
        else:
            npi.bidirect = False

        npi.dp_src = dp_src
        npi.dp_dst = dp_dst
        npi.first_port = first_port
        npi.last_port = last_port

        if set_arp == True:
            npi.dl_src = dl_src
            npi.dl_dst = dl_dst

        npi.ip_proto = ip_proto
        npi.tp_src = tp_src
        npi.tp_dst = tp_dst

        res, error = self.bodrt.netic_create_route(npi)

        if error == 0:
            a = {}
            a["directPath"] = res.directPath
            self.discoveryws.add_created_path(res.directPath)

            if res.reversPath >= 0:
                self.discoveryws.add_created_path(res.reversPath)
                a["reversPath"] = res.reversPath

            neticResponse(request, NTC_OK, a)
        else:
            neticResponse(request, NTC_VP_INFO_PATH_NOT_FOUND)
Exemple #11
0
    def handle_ws_request(self, request, data):
        if self.current_session != None:
            return webservice.conflictError(request, "Outstanding request pending. Try again later.")

        oscars_request = None

        try:
            json_content = webservice.json_parse_message_body(request)
            if json_content == None:
                raise ValueError('Invalid JSON request')

            oscars_request = OSCARSRequest(json_content)

            for path_element in oscars_request.path:
                dpid = None

                lg.debug("Trying to find switch in known_switches")
                for (curr_dpid, switch) in self.known_switches.items():
                    if switch["ip"] == path_element["switch"]:
                        dpid = switch["dpip"]
                        lg.debug("Found dpid for %s in existing switches" % (path_element["switch"]))
                        break

                if not dpid:
                    lg.debug("Trying to find switch in config")
                    try:
                        dpid = long(config.get(path_element["switch"], "datapath_id"), 0)
                    except Exception as e:
                        lg.error("Problem finding 'datapath_id' for '%s': %s" % (element["switch"], e.__str__()))
                        raise ValueError("Unknown switch '%s'" % element["switch"])

                curr_switch = None
                if dpid and self.known_switches.has_key(dpid):
                    curr_switch = self.known_switches[dpid]

                if not curr_switch:
                    error_msg = "Switch '%s' is not a known switch" % (path_element["switch"])
                    lg.error(error_msg)
                    raise ValueError(error_msg)

                lg.debug("Checking for commands")
                for key in "del-flows", "add-flows":
                    if key in path_element:
                        if len(path_element[key]) != 2:
                            raise ValueError("The flow needs to have two elements")
 
                        lg.debug("Trying %s" % key)
                        for i in range(0,1):
                            lg.debug("Parsing port")
                            port = int(path_element[key][i]["port"])
                            lg.debug("Checking ports_by_id")
                            if port in curr_switch["ports_by_id"]:
                                continue
                            lg.debug("Checking ports_by_name")
                            if str(port) in curr_switch["ports_by_name"]:
                                path_element[key][i]["port"] = curr_switch["ports_by_name"][str(port)]["port_no"]
                                continue
                            raise ValueError("Unknown port: %s in %s" % (path_element[key][i]["port"], hex(dpid)))
 
        except Exception as e:
            lg.error("Invalid request: %s" % e.__str__())
            return webservice.badRequest(request, e.__str__())

        self.current_session = OSCARSSession(request=oscars_request, raw_request=request)

        successful = True
        error_msg = ""
        try:
            if self.current_session.request.path:
                logger.debug("Request has a path")
                for path_element in self.current_session.request.path:
                    dpid = long(config.get(path_element["switch"], "datapath_id"), 0)

                    logger.debug("Configuring switch %s: %s" % (path_element["switch"], dpid))

                    for key in "del-flows", "add-flows":

                        logger.debug("Handling %s for switch %s/%s" % (key, path_element["switch"], dpid))
    
                        if key in path_element:
                            if key == "del-flows":
                                action = "delete"
                            else:
                                action = "add"
                    
                            logger.debug("Handling %s for switch %s" % (action, path_element["switch"]))
 
                            self.modify_flow(action, dpid, path_element[key][0], path_element[key][1]);
    
                            self.modify_flow(action, dpid, path_element[key][1], path_element[key][0]);
        except Exception as e:
            error_msg = "Problem handling request: %s" % e
            logger.error(error_msg)
            successful = False

        if successful:
            # wait 5 seconds and then check that the changes propagated
            self.post_callback(5, lambda: self.verify_changes(self.verify_changes_timeout_cb))
        else:
            self.undo_changes()

        return webservice.NOT_DONE_YET