def __init__(self, host, port, feature, timeout):
     self.host = host
     self.port = port
     self.feature = feature  # e.g., "bst"
     self._timeout = timeout
     self._swconfig = BroadViewBSTSwitches()
     self._auth = None
Esempio n. 2
0
    def test_CancelRequest(self):

        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = CancelRequest(host, port)
        x.setRequestId(2)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue(d["params"]["request-id"] == 2)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "cancel-request")
Esempio n. 3
0
    def test_ConfigureSystemFeature(self):

        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = ConfigureSystemFeature(host, port)
        x.setHeartbeatEnable(False)
        x.setMsgInterval(10)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue(d["params"]["msg-interval"] == 10)
        self.assertTrue(d["params"]["heartbeat-enable"] == 0)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "configure-system-feature")
Esempio n. 4
0
    def test_GetSFlowSamplingStatus(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetSFlowSamplingStatus(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "black-hole-detection")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "get-sflow-sampling-status")
        params = d["params"]
        self.assertTrue("port-list" in params)
        self.assertTrue(len(params["port-list"]) == 0)

        x.setPortList(["1", "11", "3", "4-10"])
        d = x.toDict()
        params = d["params"]

        self.assertTrue("1" in params["port-list"])
        self.assertTrue("11" in params["port-list"])
        self.assertTrue("3" in params["port-list"])
        self.assertTrue("4-10" in params["port-list"])
        self.assertTrue(len(params["port-list"]) == 4)
Esempio n. 5
0
    def test_GetPacketTraceFeature(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetPacketTraceFeature(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "get-packet-trace-feature")

        x.setASIC("2")
        d = x.toDict()

        self.assertEqual(d["asic-id"], "2")
Esempio n. 6
0
    def test_CancelPacketTraceECMPResolution(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = CancelPacketTraceECMPResolution(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "cancel-packet-trace-ecmp-resolution")

        x.setId(17)
        d = x.toDict()
        params = d["params"]

        self.assertTrue(params["id"] == 17)
Esempio n. 7
0
 def __init__(self, host, port, feature, timeout):
   self.host = host
   self.port = port
   self.feature = feature  # e.g., "bst"
   self._timeout = timeout
   self._swconfig = BroadViewBSTSwitches()
   self._auth = None
Esempio n. 8
0
    def test_ConfigureBSTFeature(self):

        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = ConfigureBSTFeature(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "bst")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "configure-bst-feature")

        params = d["params"]
        self.assertEqual(params["bst-enable"], False)
        self.assertEqual(params["send-async-reports"], False)
        self.assertEqual(params["collection-interval"], 60)
        self.assertEqual(params["stats-in-percentage"], False)
        self.assertEqual(params["stat-units-in-cells"], False)
        self.assertEqual(params["trigger-rate-limit"], 1)
        self.assertEqual(params["trigger-rate-limit-interval"], 1)
        self.assertEqual(params["send-snapshot-on-trigger"], True)
        self.assertEqual(params["async-full-reports"], False)

        x.setEnable(True)
        x.setSendAsyncReports(True)
        x.setCollectionInterval(120)
        x.setStatInPercentage(True)
        x.setStatUnitsInCells(True)
        x.setTriggerRateLimit(15)
        x.setTriggerRateLimitInterval(99)
        x.setSendSnapshotOnTrigger(False)
        x.setAsyncFullReports(True)
        d = x.toDict()

        params = d["params"]
        self.assertEqual(params["bst-enable"], True)
        self.assertEqual(params["send-async-reports"], True)
        self.assertEqual(params["collection-interval"], 120)
        self.assertEqual(params["stats-in-percentage"], True)
        self.assertEqual(params["stat-units-in-cells"], True)
        self.assertEqual(params["trigger-rate-limit"], 15)
        self.assertEqual(params["trigger-rate-limit-interval"], 99)
        self.assertEqual(params["send-snapshot-on-trigger"], False)
        self.assertEqual(params["async-full-reports"], True)
Esempio n. 9
0
    def test_ConfigurePacketTraceDropReason(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = ConfigurePacketTraceDropReason(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "configure-packet-trace-drop-reason")

        params = d["params"]
        self.assertEqual(len(params["reason"]), 0)
        self.assertEqual(len(params["port-list"]), 0)
        self.assertEqual(params["send-dropped-packet"], 0)
        self.assertEqual(params["trace-profile"], 0)
        self.assertEqual(params["packet-count"], 1)

        x.setReason(
            ["vlan-xlate-miss-drop", "bpdu-drop", "trill-slowpath-drop"])
        x.setPortList(["1", "5", "6", "10-15"])
        x.setSendDroppedPacket(True)
        x.setTraceProfile(True)
        x.setPacketCount(9)
        x.setPacketThreshold(5)
        d = x.toDict()
        params = d["params"]

        self.assertTrue(len(params["reason"]) == 3)
        self.assertTrue("vlan-xlate-miss-drop" in params["reason"])
        self.assertTrue("bpdu-drop" in params["reason"])
        self.assertTrue("trill-slowpath-drop" in params["reason"])

        self.assertTrue(len(params["port-list"]) == 4)
        self.assertTrue("1" in params["port-list"])
        self.assertEqual(params["send-dropped-packet"], 1)
        self.assertEqual(params["trace-profile"], 1)
        self.assertEqual(params["packet-count"], 9)
        self.assertEqual(params["packet-threshold"], 5)
Esempio n. 10
0
def getBSTSwitches():
    ret = []
    x = BroadViewBSTSwitches()
    for y in x:
        if not "ip" in y:
            LOG.warning(
                'getBSTSwitches: switch {} in /etc/broadviewswitches.conf has no ip'
                .format(y))
            continue
        if not "port" in y:
            LOG.warning(
                'getBSTSwitches: switch {} in /etc/broadviewswitches.conf has no port'
                .format(y))
            continue
        ret.append(y)
    return ret
Esempio n. 11
0
    def test_GetPacketTraceProfile(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetPacketTraceProfile(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "get-packet-trace-profile")
        params = d["params"]
        self.assertTrue("packet" in params)
        self.assertTrue(len(params["packet"]) == 0)
        self.assertTrue("port-list" in params)
        self.assertTrue(len(params["port-list"]) == 0)
        self.assertTrue("collection-interval" in params)
        self.assertTrue("drop-packet" in params)

        x.setPacket("100100330450001102003034040")
        x.setPortList(["1", "11", "3", "4-10"])
        x.setCollectionInterval(99)
        x.setDropPacket(False)
        d = x.toDict()
        params = d["params"]

        self.assertEqual(params["packet"], "100100330450001102003034040")
        self.assertEqual(params["collection-interval"], 99)
        self.assertEqual(params["drop-packet"], 0)

        self.assertTrue("1" in params["port-list"])
        self.assertTrue("11" in params["port-list"])
        self.assertTrue("3" in params["port-list"])
        self.assertTrue("4-10" in params["port-list"])
        self.assertTrue(len(params["port-list"]) == 4)
Esempio n. 12
0
    def test_GetPacketTraceDropCounterReport(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetPacketTraceDropCounterReport(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "get-packet-trace-drop-counter-report")
        params = d["params"]
        self.assertTrue("drop-reason" in params)
        self.assertTrue(len(params["drop-reason"]) == 0)
        self.assertTrue("port-list" in params)
        self.assertTrue(len(params["port-list"]) == 0)

        x.setPortList(["1", "11", "3", "4-10"])
        x.setDropReason(
            ["vlan-xlate-miss-drop", "bpdu-drop", "trill-slowpath-drop"])
        d = x.toDict()
        params = d["params"]

        self.assertTrue("1" in params["port-list"])
        self.assertTrue("11" in params["port-list"])
        self.assertTrue("3" in params["port-list"])
        self.assertTrue("4-10" in params["port-list"])
        self.assertTrue(len(params["port-list"]) == 4)

        self.assertTrue("vlan-xlate-miss-drop" in params["drop-reason"])
        self.assertTrue("bpdu-drop" in params["drop-reason"])
        self.assertTrue("trill-slowpath-drop" in params["drop-reason"])
        self.assertTrue(len(params["drop-reason"]) == 3)
Esempio n. 13
0
    def test_GetBlackHole(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetBlackHole(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "black-hole-detection")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "get-black-hole")
Esempio n. 14
0
    def test_CancelPacketTraceDropCounterReport(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = CancelPacketTraceDropCounterReport(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(
            d["method"] == "cancel-packet-trace-drop-counter-report")

        x.setDropReason(["l2-lookup-failure", "l3-failure", "vlan-mismatch"])
        x.setPortList(["1", "11", "3", "4-10"])
        d = x.toDict()
        params = d["params"]

        self.assertTrue("l2-lookup-failure" in params["drop-reason"])
        self.assertTrue("l3-failure" in params["drop-reason"])
        self.assertTrue("vlan-mismatch" in params["drop-reason"])
        self.assertTrue(len(params["drop-reason"]) == 3)

        self.assertTrue("1" in params["port-list"])
        self.assertTrue("11" in params["port-list"])
        self.assertTrue("3" in params["port-list"])
        self.assertTrue("4-10" in params["port-list"])
        self.assertTrue(len(params["port-list"]) == 4)
Esempio n. 15
0
    def test_GetPacketTraceSupportedDropReasons(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetPacketTraceSupportedDropReasons(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(
            d["method"] == "get-packet-trace-supported-drop-reasons")
Esempio n. 16
0
    def test_GetSwitchProperties(self):

        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = GetSwitchProperties(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "get-switch-properties")
Esempio n. 17
0
    def test_ConfigurePacketTraceFeature(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = ConfigurePacketTraceFeature(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "packettrace")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "configure-packet-trace-feature")

        params = d["params"]
        self.assertEqual(params["packet-trace-enable"], False)

        x.setEnable(True)
        d = x.toDict()

        params = d["params"]
        self.assertEqual(params["packet-trace-enable"], True)

        x.setEnable(False)
        d = x.toDict()

        params = d["params"]
        self.assertEqual(params["packet-trace-enable"], False)
Esempio n. 18
0
    def test_BlackHoleDetectionEnable(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = BlackHoleDetectionEnable(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "black-hole-detection")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)
        self.assertTrue(d["asic-id"] == "1")
        self.assertTrue(d["method"] == "black-hole-detection-enable")

        params = d["params"]
        self.assertEqual(params["enable"], False)

        x.setEnable(True)
        d = x.toDict()

        params = d["params"]
        self.assertEqual(params["enable"], True)

        x.setEnable(False)
        d = x.toDict()

        params = d["params"]
        self.assertEqual(params["enable"], False)
class AgentConnection():
    def __init__(self, host, port, feature, timeout):
        self.host = host
        self.port = port
        self.feature = feature  # e.g., "bst"
        self._timeout = timeout
        self._swconfig = BroadViewBSTSwitches()
        self._auth = None

    def close(self):
        if self._auth and self._auth.logout:
            self._auth.logout()
        self._auth = None

    def _is_ok(self, r):
        return r.status_code == 200

    def _raise_fail_if(self, url, r, timeout):
        if not self._is_ok(r):
            if timeout:
                j = {
                    "response_code": r.status_code,
                    "error_code": 0,
                    "msg": "Connection timeout"
                }
            else:
                try:
                    j = r.json()["status"]
                except:
                    try:
                        t = ElementTree.fromstring(r)
                        j = {
                            "response_code": r.status_code,
                            "error_code": 0,
                            "msg": "XML failure response from web server"
                        }

                    except:
                        j = {
                            "response_code": r.status_code,
                            "error_code": 0,
                            "msg": "Unparsable response from web server"
                        }

            raise RequestFailed(url, j["response_code"], j["error_code"],
                                j["msg"])

    def getAuth(self):
        return self._auth

    def getAuthConf(self):
        auth = {}
        auth["auth"] = None
        auth["username"] = None
        auth["password"] = None

        try:
            conf = self._swconfig.getByIP(self.host)
            if conf:
                if "username" in conf:
                    auth["username"] = conf["username"]
                if "password" in conf:
                    auth["password"] = conf["password"]
                if "auth" in conf:
                    auth["auth"] = conf["auth"]
        except:
            pass

        if auth["auth"] == None:
            auth["auth"] = os.getenv("BV_AUTH")
        if auth["username"] == None:
            auth["username"] = os.getenv("BV_USERNAME")
        if auth["password"] == None:
            auth["password"] = os.getenv("BV_PASSWORD", "")

        return auth

    def __makeRequest(self, request):

        headers = {"Content-Type": "application/json"}
        timeout = False

        isGet = False
        if request.getHttpMethod() == "GET":
            isGet = True

        auth = self.getAuth()

        payload = request.getjson().encode("utf-8")
        if self.feature:
            url = "http://%s:%d/broadview/%s/%s" % (
                self.host, self.port, self.feature, request.getMethod())
        else:
            url = "http://%s:%d/broadview/%s" % (self.host, self.port,
                                                 request.getMethod())
        if isGet:
            try:
                r = requests.get(url,
                                 timeout=self._timeout,
                                 data=payload,
                                 headers=headers,
                                 auth=auth)
            except requests.exceptions.Timeout:
                timeout = True
        else:
            try:
                r = requests.post(url,
                                  timeout=self._timeout,
                                  data=payload,
                                  headers=headers,
                                  auth=auth)
            except requests.exceptions.Timeout:
                timeout = True

        json_data = {}
        if timeout:
            r = RequestObj()
            r.status_code = 500

        if r.status_code == 200:
            try:
                # Data can come back with leading.trailing spaces, which trips
                # up requests' json parser. So get as test, string, and let
                # Python json do the parsing

                json_data = json.loads(r.text.strip())
            except:
                pass

        return (r, json_data)

    def makeRequest(self, request):
        r, json_data = self.__makeRequest(request)

        if r.status_code == 401:
            conf = self.getAuthConf()
            try:
                auth_method = r.headers["WWW-Authenticate"]
            except:
                # RFC 2616 requires a WWW-Authenticate header in 401 responses. If
                # we get here, it was missing. Check if there is configuration that
                # declares an auth method and use that.
                LOG.info("makeRequest: 401 but no WWW-Authenticate")
                auth_method = conf["auth"]
            if auth_method:
                auth_method = auth_method.lower()
                if auth_method == "basic":
                    self._auth = requests.HTTPBasicAuth(
                        conf["username"], conf["password"])
                elif auth_method == "digest":
                    self._auth = requests.HTTPDigestAuth(
                        conf["username"], conf["password"])
                elif auth_method == "sidauth":
                    self._auth = SIDAuth(self.host, self.port,
                                         conf["username"], conf["password"])
                else:
                    LOG.info("unknown auth {}".format(auth_method))
                    # return the 401 here
                    return (r.status_code, json_data)

                # try again

                r, json_data = self.__makeRequest(request)

        return (r.status_code, json_data)
Esempio n. 20
0
class AgentConnection():

  def __init__(self, host, port, feature, timeout):
    self.host = host
    self.port = port
    self.feature = feature  # e.g., "bst"
    self._timeout = timeout
    self._swconfig = BroadViewBSTSwitches()
    self._auth = None

  def close(self):
    if self._auth and self._auth.logout:
        self._auth.logout()
    self._auth = None

  def _is_ok(self, r):
    return r.status_code == 200

  def _raise_fail_if(self, url, r, timeout):
    if not self._is_ok(r):
      if timeout:
        j = {"response_code": r.status_code,
             "error_code": 0,
             "msg": "Connection timeout"}
      else:
        try:
          j = r.json()["status"]
        except:
          try:
            t = ElementTree.fromstring(r)
            j = {"response_code": r.status_code,
                 "error_code": 0,
                 "msg": "XML failure response from web server"}

          except:
            j = {"response_code": r.status_code,
                 "error_code": 0,
                 "msg": "Unparsable response from web server"}

      raise RequestFailed(url, j["response_code"], j["error_code"], j["msg"])

  def getAuth(self):
    return self._auth

  def getAuthConf(self):
    auth = {}
    auth["auth"] = None
    auth["username"] = None
    auth["password"] = None

    try:
        conf = self._swconfig.getByIP(self.host)
        if conf:
            if "username" in conf:
                auth["username"] = conf["username"]
            if "password" in conf:
                auth["password"] = conf["password"]
            if "auth" in conf:
                auth["auth"] = conf["auth"]
    except:
        pass

    if auth["auth"] == None:
        auth["auth"] = os.getenv("BV_AUTH")
    if auth["username"] == None:
        auth["username"] = os.getenv("BV_USERNAME")
    if auth["password"] == None:
        auth["password"] = os.getenv("BV_PASSWORD", "")

    return auth

  def __makeRequest(self, request):

    headers = {"Content-Type": "application/json"}
    timeout = False

    isGet = False
    if request.getHttpMethod() == "GET":
      isGet = True

    auth = self.getAuth()

    payload = request.getjson().encode("utf-8")
    if self.feature:
      url = "http://%s:%d/broadview/%s/%s" % (self.host, self.port, self.feature, request.getMethod())
    else:
      url = "http://%s:%d/broadview/%s" % (self.host, self.port, request.getMethod())
    if isGet:
      try:
        r = requests.get(url, timeout=self._timeout, data=payload, headers=headers, auth=auth)
      except requests.exceptions.Timeout:
        timeout = True
    else:
      try:
        r = requests.post(url, timeout=self._timeout, data=payload, headers=headers, auth=auth)
      except requests.exceptions.Timeout:
        timeout = True

    json_data = {}
    if timeout:
        r = RequestObj() 
        r.status_code = 500

    if r.status_code == 200:
        try:
            # Data can come back with leading.trailing spaces, which trips 
            # up requests' json parser. So get as test, string, and let
            # Python json do the parsing

            json_data = json.loads(r.text.strip())
        except:
            pass

    return (r, json_data)
       
  def makeRequest(self, request):
    r, json_data = self.__makeRequest(request)

    if r.status_code == 401:
        conf = self.getAuthConf()
        try:
            auth_method = r.headers["WWW-Authenticate"]
        except:
            # RFC 2616 requires a WWW-Authenticate header in 401 responses. If
            # we get here, it was missing. Check if there is configuration that
            # declares an auth method and use that.
            LOG.info("makeRequest: 401 but no WWW-Authenticate")
            auth_method = conf["auth"]
        if auth_method:
            auth_method = auth_method.lower()
            if auth_method == "basic":
                self._auth = requests.HTTPBasicAuth(conf["username"], conf["password"])
            elif auth_method == "digest":
                self._auth = requests.HTTPDigestAuth(conf["username"], conf["password"])
            elif auth_method == "sidauth":
                self._auth = SIDAuth(self.host, self.port, conf["username"], conf["password"])
            else:
                LOG.info("unknown auth {}".format(auth_method))
                # return the 401 here
                return (r.status_code, json_data)
        
            # try again

            r, json_data = self.__makeRequest(request)

    return (r.status_code, json_data)
Esempio n. 21
0
    def test_ConfigureBlackHole(self):
        sw = BroadViewBSTSwitches()
        if len(sw):
            for x in sw:
                host = x["ip"]
                port = x["port"]
                break
        else:
            host = "192.168.3.1"
            port = 8080

        x = ConfigureBlackHole(host, port)
        d = x.toDict()
        self.assertTrue("asic-id" in d)
        self.assertTrue("params" in d)
        self.assertTrue("method" in d)
        self.assertTrue(x.getFeature() == "black-hole-detection")
        self.assertTrue(x.getHttpMethod() == "POST")
        self.assertTrue(x.getHost() == host)
        self.assertTrue(x.getPort() == port)

        params = d["params"]
        samplingParams = params["sampling-params"]
        self.assertTrue(d["asic-id"] == "1")
        self.assertEqual(len(params["port-list"]), 0)
        self.assertEqual(params["sampling-method"], "agent")
        self.assertTrue(samplingParams["water-mark"] == 200)
        self.assertTrue(samplingParams["sample-periodicity"] == 15)
        self.assertTrue(samplingParams["sample-count"] == 10)

        x.setSamplingMethod("agent")
        x.setPortList(["1", "5", "6", "10-15"])
        x.setWaterMark(500)
        x.setSamplePeriodicity(25)
        x.setSampleCount(50)
        x.setVLANId(4000)
        x.setDestinationIP("10.0.0.4")
        x.setSourceUDPPort(1234)
        x.setDestinationUDPPort(5678)
        x.setMirrorPort(8)
        x.setSamplePoolSize(5)
        d = x.toDict()
        params = d["params"]
        samplingParams = params["sampling-params"]

        self.assertEqual(params["sampling-method"], "agent")
        self.assertTrue("port-list" in params)
        self.assertTrue("water-mark" in samplingParams)
        self.assertTrue("sample-periodicity" in samplingParams)
        self.assertTrue("sample-count" in samplingParams)
        self.assertTrue(not "vlan-id" in samplingParams)
        self.assertTrue(not "destination-ip" in samplingParams)
        self.assertTrue(not "source-udp-port" in samplingParams)
        self.assertTrue(not "destination-udp-port" in samplingParams)
        self.assertTrue(not "mirror-port" in samplingParams)
        self.assertTrue(not "sample-pool-size" in samplingParams)

        self.assertTrue(samplingParams["water-mark"] == 500)
        self.assertTrue(samplingParams["sample-periodicity"] == 25)
        self.assertTrue(samplingParams["sample-count"] == 50)
        self.assertTrue(len(params["port-list"]) == 4)
        self.assertTrue("1" in params["port-list"])
        self.assertTrue("5" in params["port-list"])
        self.assertTrue("6" in params["port-list"])
        self.assertTrue("10-15" in params["port-list"])

        x.setSamplingMethod("sflow")
        d = x.toDict()
        params = d["params"]
        samplingParams = params["sampling-params"]
        encapsulationParams = samplingParams["encapsulation-params"]

        self.assertEqual(params["sampling-method"], "sflow")
        self.assertTrue("port-list" in params)
        self.assertTrue(not "water-mark" in samplingParams)
        self.assertTrue(not "sample-periodicity" in samplingParams)
        self.assertTrue(not "sample-count" in samplingParams)
        self.assertTrue("vlan-id" in encapsulationParams)
        self.assertTrue("destination-ip" in encapsulationParams)
        self.assertTrue("source-udp-port" in encapsulationParams)
        self.assertTrue("destination-udp-port" in encapsulationParams)
        self.assertTrue("mirror-port" in samplingParams)
        self.assertTrue("sample-pool-size" in samplingParams)

        self.assertTrue(encapsulationParams["vlan-id"] == 4000)
        self.assertTrue(encapsulationParams["destination-ip"] == "10.0.0.4")
        self.assertTrue(encapsulationParams["source-udp-port"] == 1234)
        self.assertTrue(encapsulationParams["destination-udp-port"] == 5678)
        self.assertTrue(samplingParams["mirror-port"] == 8)
        self.assertTrue(samplingParams["sample-pool-size"] == 5)
        self.assertTrue(len(params["port-list"]) == 4)
        self.assertTrue("1" in params["port-list"])
        self.assertTrue("5" in params["port-list"])
        self.assertTrue("6" in params["port-list"])
        self.assertTrue("10-15" in params["port-list"])