Beispiel #1
0
    def testNoStartEndTimeAndAdditionalReservation(self):

        schedule    = nsa.Schedule(None, None)
        criteria    = nsa.Criteria(0, schedule, nsa.Point2PointService(self.source_stp, self.dest_stp, 200, cnt.BIDIRECTIONAL, False, None) )

        self.header.newCorrelationId()
        acid = yield self.provider.reserve(self.header, None, None, None, criteria)
        header, cid, gid, desc, sc = yield self.requester.reserve_defer
        self.failUnlessEqual(cid, acid)

        yield self.provider.reserveCommit(self.header, acid)
        cid = yield self.requester.reserve_commit_defer

        # second reservation
        self.header.newCorrelationId()
        self.requester.reserve_defer = defer.Deferred()
        self.requester.reserve_commit_defer = defer.Deferred()

        schedule    = nsa.Schedule(None, None)
        criteria    = nsa.Criteria(0, schedule, nsa.Point2PointService(self.source_stp, self.dest_stp, 200, cnt.BIDIRECTIONAL, False, None) )

        acid2 = yield self.provider.reserve(header, None, None, None, criteria)
        _ = yield self.requester.reserve_defer

        yield self.provider.reserveCommit(self.header, acid2)
        cid = yield self.requester.reserve_commit_defer
Beispiel #2
0
    def testProvisionReleaseNoStartEndTime(self):

        schedule    = nsa.Schedule(None, None)
        criteria    = nsa.Criteria(0, schedule, nsa.Point2PointService(self.source_stp, self.dest_stp, 200, 'Bidirectional', False, None) )

        self.header.newCorrelationId()
        acid = yield self.provider.reserve(self.header, None, None, None, criteria)
        yield self.requester.reserve_defer

        yield self.provider.reserveCommit(self.header, acid)
        yield self.requester.reserve_commit_defer

        yield self.provider.provision(self.header, acid)
        yield self.requester.provision_defer

        self.clock.advance(3)

        header, cid, nid, timestamp, dps = yield self.requester.data_plane_change_defer
        active, version, consistent = dps
        self.failUnlessEquals(active, True)

        self.requester.data_plane_change_defer = defer.Deferred()

        yield self.provider.release(self.header, acid)
        yield self.requester.release_defer

        header, cid, nid, timestamp, dps = yield self.requester.data_plane_change_defer
        active, version, consistent = dps
        self.failUnlessEquals(active, False)

        yield self.provider.terminate(self.header, cid)
        yield self.requester.terminate_defer
Beispiel #3
0
    def testReserveTimeout(self):

        # these need to be constructed such that there is only one label option
        source_stp  = nsa.STP(self.network, self.source_port, nsa.Label(cnt.ETHERNET_VLAN, '1782') )
        dest_stp    = nsa.STP(self.network, self.dest_port,   nsa.Label(cnt.ETHERNET_VLAN, '1782') )
        criteria    = nsa.Criteria(0, self.schedule, nsa.Point2PointService(source_stp, dest_stp, self.bandwidth, cnt.BIDIRECTIONAL, False, None) )

        self.header.newCorrelationId()
        acid = yield self.provider.reserve(self.header, None, None, None, criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer

        self.clock.advance(self.backend.TPC_TIMEOUT + 1)

        header, cid, notification_id, timestamp, timeout_value, org_cid, org_nsa = yield self.requester.reserve_timeout_defer

        self.failUnlessEquals(cid, acid)

        self.requester.reserve_defer = defer.Deferred()

        # new criteria
        start_time  = datetime.datetime.utcnow() + datetime.timedelta(seconds=2)
        end_time    = datetime.datetime.utcnow() + datetime.timedelta(seconds=6)
        schedule    = nsa.Schedule(start_time, end_time)
        criteria    = nsa.Criteria(0, schedule, nsa.Point2PointService(source_stp, dest_stp, self.bandwidth, cnt.BIDIRECTIONAL, False, None) )

        # try to reserve the same resources
        acid2 = yield self.provider.reserve(self.header, None, None, None, criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer
Beispiel #4
0
    def setUp(self):

        self.clock = task.Clock()

        self.requester = common.DUDRequester()

        nrm_ports = nrm.parsePortSpec(StringIO.StringIO(topology.ARUBA_TOPOLOGY))

        self.backend = dud.DUDNSIBackend(self.network, nrm_ports, self.requester, {})

        self.provider = self.backend
        self.provider.scheduler.clock = self.clock
        self.provider.startService()

        db.setupDatabase()

        # request stuff
        self.start_time  = datetime.datetime.utcnow() + datetime.timedelta(seconds=2)
        self.end_time    = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)

        self.schedule = nsa.Schedule(self.start_time, self.end_time)
        self.sd = nsa.Point2PointService(self.source_stp, self.dest_stp, self.bandwidth, cnt.BIDIRECTIONAL, False ,None)
        self.criteria = nsa.Criteria(0, self.schedule, self.sd)

        return self.backend.restore_defer
Beispiel #5
0
    def setUp(self):

        db.setupDatabase()

        self.requester = common.DUDRequester()

        self.clock = task.Clock()

        nrm_map = StringIO.StringIO(topology.ARUBA_TOPOLOGY)
        nrm_ports, nml_network, link_vector = setup.setupTopology(nrm_map, self.network, 'aruba.net')

        self.backend = dud.DUDNSIBackend(self.network, nrm_ports, self.requester, {})
        self.backend.scheduler.clock = self.clock

        pl = plugin.BasePlugin()
        pl.init( { config.NETWORK_NAME: self.network }, None )

        pr = provreg.ProviderRegistry( { self.provider_agent.urn() : self.backend }, {} )
        self.provider = aggregator.Aggregator(self.network, self.provider_agent, nml_network, link_vector, self.requester, pr, [], pl)

        # set parent for backend, we need to create the aggregator before this can be done
        self.backend.parent_requester = self.provider
        self.backend.startService()

        # request stuff
        self.start_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=2)
        self.end_time   = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)

        self.schedule = nsa.Schedule(self.start_time, self.end_time)
        self.sd       = nsa.Point2PointService(self.source_stp, self.dest_stp, self.bandwidth, cnt.BIDIRECTIONAL, False, None)
        self.criteria = nsa.Criteria(0, self.schedule, self.sd)
Beispiel #6
0
    def reserveConfirmed(self, soap_data, request_info):

        header, reservation = helper.parseRequest(soap_data)

        criteria = reservation.criteria

        # Create DTOs - this overlaps heavily with the parsing done in providerservice - unify sometime

        start_time = xmlhelper.parseXMLTimestamp(criteria.schedule.startTime) if criteria.schedule.startTime is not None else None
        end_time   = xmlhelper.parseXMLTimestamp(criteria.schedule.endTime)   if criteria.schedule.endTime   is not None else None
        schedule   = nsa.Schedule(start_time, end_time)

        # check for service type sometime
        p2ps = criteria.serviceDefinition
        if type(p2ps) is not p2pservices.P2PServiceBaseType:
            raise ValueError('Only P2P service supported.')

        # (ERO missing)
        src_stp = helper.createSTP(p2ps.sourceSTP)
        dst_stp = helper.createSTP(p2ps.destSTP)

        if p2ps.ero:
            print('ERO parsing in reserveConfirmed not implemented yet, full path will not be available')

        sd = nsa.Point2PointService(src_stp, dst_stp, p2ps.capacity, p2ps.directionality, p2ps.symmetricPath, None)
        crt = nsa.Criteria(criteria.version, schedule, sd)

        self.requester.reserveConfirmed(header, reservation.connectionId,  reservation.globalReservationId, reservation.description, crt)

        return helper.createGenericRequesterAcknowledgement(header)
Beispiel #7
0
def buildSchedule(schedule):

    start_time = parseXMLTimestamp(
        schedule.startTime) if schedule.startTime is not None else None
    end_time = parseXMLTimestamp(
        schedule.endTime) if schedule.endTime is not None else None
    return nsa.Schedule(start_time, end_time)
Beispiel #8
0
    def testQueryRecursiveNoStartTime(self):
        # only available on aggregator and remote, we just do remote for now

        start_time = None
        criteria   = nsa.Criteria(0, nsa.Schedule(start_time, self.end_time), self.sd)

        self.header.newCorrelationId()
        acid = yield self.provider.reserve(self.header, None, 'gid-123', 'desc2', criteria)
        yield self.requester.reserve_defer

        yield self.provider.reserveCommit(self.header, acid)
        yield self.requester.reserve_commit_defer

        self.header.newCorrelationId()
        yield self.provider.queryRecursive(self.header, connection_ids = [ acid ] )
        header, reservations = yield self.requester.query_recursive_defer

        self.failUnlessEquals(len(reservations), 1)
        ci = reservations[0]

        self.failUnlessEquals(ci.connection_id, acid)
        self.failUnlessEquals(ci.global_reservation_id, 'gid-123')
        self.failUnlessEquals(ci.description, 'desc2')

        self.failUnlessEquals(ci.requester_nsa, self.requester_agent.urn())
        self.failUnlessEquals(len(ci.criterias), 1)
        crit = ci.criterias[0]

        src_stp = crit.service_def.source_stp
        dst_stp = crit.service_def.dest_stp

        self.failUnlessEquals(src_stp.network, self.network)
        self.failUnlessEquals(src_stp.port,    self.source_port)
        self.failUnlessEquals(src_stp.label.type_, cnt.ETHERNET_VLAN)
        self.failUnlessIn(src_stp.label.labelValue(), ('1781', '1782') )

        self.failUnlessEquals(dst_stp.network, self.network)
        self.failUnlessEquals(dst_stp.port,    self.dest_port)
        self.failUnlessEquals(dst_stp.label.type_, cnt.ETHERNET_VLAN)
        self.failUnlessIn(dst_stp.label.labelValue(), ('1782', '1783') )

        self.failUnlessEqual(crit.service_def.capacity, self.bandwidth)
        self.failUnlessEqual(crit.revision,   0)

        from opennsa import state
        rsm, psm, lsm, dps = ci.states
        self.failUnlessEquals(rsm, state.RESERVE_START)
        self.failUnlessEquals(psm, state.RELEASED)
        self.failUnlessEquals(lsm, state.CREATED)
        self.failUnlessEquals(dps[:2], (False, 0) )  # we cannot really expect a consistent result for consistent here

        self.failUnlessEqual(len(crit.children), 1)
        child = crit.children[0]

        rsm, psm, lsm, dps = ci.states # overwrite
        self.failUnlessEquals(rsm, state.RESERVE_START)
        self.failUnlessEquals(psm, state.RELEASED)
        self.failUnlessEquals(lsm, state.CREATED)
        self.failUnlessEquals(dps[:2], (False, 0) )  # we cannot really expect a consistent result for consistent here
Beispiel #9
0
    def setUp(self):
        from twisted.web import resource, server
        from twisted.application import internet
        from opennsa.protocols import nsi2
        from opennsa.protocols.shared import soapresource
        from opennsa.protocols.nsi2 import requesterservice, requesterclient

        db.setupDatabase()

        self.requester = common.DUDRequester()

        self.clock = task.Clock()

        nrm_map = StringIO.StringIO(topology.ARUBA_TOPOLOGY)
        nrm_ports, nml_network, link_vector = setup.setupTopology(nrm_map, self.network, 'aruba.net')

        self.backend = dud.DUDNSIBackend(self.network, nrm_ports, None, {}) # we set the parent later
        self.backend.scheduler.clock = self.clock

        pl = plugin.BasePlugin()
        pl.init( { config.NETWORK_NAME: self.network }, None )

        pr = provreg.ProviderRegistry( { self.provider_agent.urn() : self.backend }, {} )
        self.aggregator = aggregator.Aggregator(self.network, self.provider_agent, nml_network, link_vector, None, pr, [], pl) # we set the parent later

        self.backend.parent_requester = self.aggregator

        # provider protocol
        http_top_resource = resource.Resource()

        cs2_prov = nsi2.setupProvider(self.aggregator, http_top_resource)
        self.aggregator.parent_requester = cs2_prov

        provider_factory = server.Site(http_top_resource)
        self.provider_service = internet.TCPServer(self.PROVIDER_PORT, provider_factory)

        # requester protocol

        requester_top_resource = resource.Resource()
        soap_resource = soapresource.setupSOAPResource(requester_top_resource, 'RequesterService2')

        self.provider = requesterclient.RequesterClient(self.provider_agent.endpoint, self.requester_agent.endpoint)

        requester_service = requesterservice.RequesterService(soap_resource, self.requester) # this is the important part
        requester_factory = server.Site(requester_top_resource, logPath='/dev/null')

        # start engines!
        self.backend.startService()
        self.provider_service.startService()
        self.requester_iport = reactor.listenTCP(self.REQUESTER_PORT, requester_factory)

        # request stuff
        self.start_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=2)
        self.end_time   = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)

        self.schedule = nsa.Schedule(self.start_time, self.end_time)
        self.sd = nsa.Point2PointService(self.source_stp, self.dest_stp, self.bandwidth)
        self.criteria = nsa.Criteria(0, self.schedule, self.sd)
Beispiel #10
0
    def testSlowActivate(self):
        # key here is that end time is passed when activation is done

        start_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=2)
        end_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=4)
        schedule = nsa.Schedule(start_time, end_time)

        source_stp = nsa.STP(self.network, self.source_port,
                             nsa.Label(cnt.ETHERNET_VLAN, '1780'))
        dest_stp = nsa.STP(self.network, self.dest_port,
                           nsa.Label(cnt.ETHERNET_VLAN, '1780'))
        criteria = nsa.Criteria(
            0, schedule,
            nsa.Point2PointService(source_stp, dest_stp, 200,
                                   cnt.BIDIRECTIONAL, False, None))

        def setupLink(connection_id, src, dst, bandwidth):
            d = defer.Deferred()
            reactor.callLater(2, d.callback, None)
            return d

        # make activation fail via monkey patching
        self.backend.connection_manager.setupLink = setupLink

        self.header.newCorrelationId()
        acid = yield self.provider.reserve(self.header, None, None, None,
                                           criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer

        self.failUnlessEqual(cid, acid)

        yield self.provider.reserveCommit(self.header, cid)
        yield self.requester.reserve_commit_defer

        yield self.provider.provision(self.header, cid)
        yield self.requester.provision_defer

        self.clock.advance(3)

        header, cid, nid, timestamp, dps = yield self.requester.data_plane_change_defer
        active, version, consistent = dps

        self.failUnlessEqual(cid, acid)
        self.failUnlessEqual(active, True)
        self.failUnlessEqual(consistent, True)

        self.requester.data_plane_change_defer = defer.Deferred()

        self.clock.advance(2)
        header, cid, nid, timestamp, dps = yield self.requester.data_plane_change_defer
        active, version, consistent = dps

        self.failUnlessEqual(cid, acid)
        self.failUnlessEqual(active, False)

        yield self.provider.terminate(self.header, cid)
        yield self.requester.terminate_defer
Beispiel #11
0
    def testNoStartTime(self):

        start_time = None
        criteria = nsa.Criteria(0, nsa.Schedule(start_time, self.end_time),
                                self.sd)

        self.header.newCorrelationId()
        cid = yield self.provider.reserve(self.header, None, None, None,
                                          criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer
Beispiel #12
0
    def testStartTimeInPast(self):

        start_time = datetime.datetime.utcnow() - datetime.timedelta(seconds=60)
        criteria   = nsa.Criteria(0, nsa.Schedule(start_time, self.end_time), self.sd)

        self.header.newCorrelationId()
        try:
            yield self.provider.reserve(self.header, None, None, None, criteria)
            self.fail('Should have raised PayloadError') # Error type is somewhat debatable, but this what we use
        except error.PayloadError:
            pass # expected
Beispiel #13
0
    def setUp(self):

        tcf = os.path.expanduser('~/.opennsa-test.json')
        tc = json.load(open(tcf))
        database.setupDatabase(tc['database'], tc['database-user'],
                               tc['database-password'])

        self.requester = common.DUDRequester()

        self.clock = task.Clock()

        nrm_ports = nrm.parsePortSpec(
            StringIO.StringIO(topology.ARUBA_TOPOLOGY))
        network_topology = nml.createNMLNetwork(nrm_ports, self.network,
                                                self.network)

        self.backend = dud.DUDNSIBackend(self.network, nrm_ports,
                                         self.requester, {})
        self.backend.scheduler.clock = self.clock

        route_vectors = gns.RouteVectors([cnt.URN_OGF_PREFIX + self.network])
        route_vectors.updateVector(self.provider_agent.identity, 0,
                                   [self.network], {})

        pl = plugin.BasePlugin()
        pl.init({config.NETWORK_NAME: self.network}, None)

        pr = provreg.ProviderRegistry(
            {self.provider_agent.urn(): self.backend}, {})
        self.provider = aggregator.Aggregator(self.network,
                                              self.provider_agent,
                                              network_topology, route_vectors,
                                              self.requester, pr, [], pl)

        # set parent for backend, we need to create the aggregator before this can be done
        self.backend.parent_requester = self.provider
        self.backend.startService()

        # request stuff
        self.start_time = datetime.datetime.utcnow() + datetime.timedelta(
            seconds=2)
        self.end_time = datetime.datetime.utcnow() + datetime.timedelta(
            seconds=10)

        self.schedule = nsa.Schedule(self.start_time, self.end_time)
        self.sd = nsa.Point2PointService(self.source_stp, self.dest_stp,
                                         self.bandwidth, cnt.BIDIRECTIONAL,
                                         False, None)
        self.criteria = nsa.Criteria(0, self.schedule, self.sd)
Beispiel #14
0
def reserveonly(client, nsi_header, src, dst, start_time, end_time, capacity, ero, connection_id, global_id):

    schedule = nsa.Schedule(start_time, end_time)
    service_def = _createP2PS(src, dst, capacity, ero)
    crt = nsa.Criteria(0, schedule, service_def)

    try:
        nsi_header.connection_trace = [ nsi_header.requester_nsa + ':' + '1' ]
        connection_id, _,_,criteria  = yield client.reserve(nsi_header, connection_id, global_id, 'Test Connection', crt)
        nsi_header.connection_trace = None
        sd = criteria.service_def
        log.msg("Connection created and held. Id %s at %s" % (connection_id, nsi_header.provider_nsa))
        log.msg("Source - Destination: %s - %s" % (sd.source_stp, sd.dest_stp))

    except error.NSIError as e:
        _logError(e)
Beispiel #15
0
    def _query(self,
               header,
               connection_ids,
               global_reservation_ids,
               request_info=None):
        # generic query mechanism for summary and recursive

        # TODO: Match stps/ports that can be used with credentials and return connections using these STPs
        if connection_ids:
            conns = yield GenericBackendConnections.find(where=[
                'source_network = ? AND dest_network = ? AND requester_nsa = ? AND connection_id IN ?',
                self.network, self.network, header.requester_nsa,
                tuple(connection_ids)
            ])
        elif global_reservation_ids:
            conns = yield GenericBackendConnections.find(where=[
                'source_network = ? AND dest_network = ? AND requester_nsa = ? AND global_reservation_ids IN ?',
                self.network, self.network, header.requester_nsa,
                tuple(global_reservation_ids)
            ])
        else:
            raise error.MissingParameterError(
                'Must specify connectionId or globalReservationId')

        reservations = []
        for c in conns:
            source_stp = nsa.STP(c.source_network, c.source_port,
                                 c.source_label)
            dest_stp = nsa.STP(c.dest_network, c.dest_port, c.dest_label)
            schedule = nsa.Schedule(c.start_time, c.end_time)
            sd = nsa.Point2PointService(source_stp, dest_stp, c.bandwidth,
                                        cnt.BIDIRECTIONAL, False, None)
            criteria = nsa.QueryCriteria(c.revision, schedule, sd)
            data_plane_status = (c.data_plane_active, c.revision, True)
            states = (c.reservation_state, c.provision_state,
                      c.lifecycle_state, data_plane_status)
            notification_id = self.getNotificationId()
            result_id = notification_id  # whatever
            provider_nsa = cnt.URN_OGF_PREFIX + self.network.replace(
                'topology', 'nsa')  # hack on
            reservations.append(
                nsa.ConnectionInfo(c.connection_id, c.global_reservation_id,
                                   c.description, cnt.EVTS_AGOLE, [criteria],
                                   provider_nsa, c.requester_nsa, states,
                                   notification_id, result_id))

        defer.returnValue(reservations)
Beispiel #16
0
    def _doReserve(self, conn, correlation_id):

        # we have already checked resource availability, so can progress directly through checking
        state.reserveMultiSwitch(conn, state.RESERVE_CHECKING,
                                 state.RESERVE_HELD)
        yield conn.save()
        self.logStateUpdate(conn, 'RESERVE CHECKING/HELD')

        # schedule 2PC timeout
        if self.scheduler.hasScheduledCall(conn.connection_id):
            # this means that the build scheduler made a call while we yielded
            self.scheduler.cancelCall(conn.connection_id)

        now = datetime.datetime.utcnow()
        timeout_time = min(now + datetime.timedelta(seconds=self.TPC_TIMEOUT),
                           conn.end_time)

        self.scheduler.scheduleCall(conn.connection_id, timeout_time,
                                    self._doReserveTimeout, conn)
        td = timeout_time - datetime.datetime.utcnow()
        log.msg(
            'Connection %s: reserve abort scheduled for %s UTC (%i seconds)' %
            (conn.connection_id, timeout_time.replace(microsecond=0),
             td.total_seconds()),
            system=self.log_system)

        schedule = nsa.Schedule(conn.start_time, conn.end_time)
        sc_source_stp = nsa.STP(conn.source_network, conn.source_port,
                                conn.source_label)
        sc_dest_stp = nsa.STP(conn.dest_network, conn.dest_port,
                              conn.dest_label)
        sd = nsa.Point2PointService(
            sc_source_stp, sc_dest_stp, conn.bandwidth, cnt.BIDIRECTIONAL,
            False, None)  # we fake some things due to db limitations
        crit = nsa.Criteria(conn.revision, schedule, sd)

        header = nsa.NSIHeader(
            conn.requester_nsa,
            conn.requester_nsa,
            correlation_id=correlation_id
        )  # The NSA is both requester and provider in the backend, but this might be problematic without aggregator
        yield self.parent_requester.reserveConfirmed(
            header, conn.connection_id, conn.global_reservation_id,
            conn.description, crit)
Beispiel #17
0
    def testNoStartOrEndTime(self):

        criteria   = nsa.Criteria(0, nsa.Schedule(None, None), self.sd)

        self.header.newCorrelationId()
        cid = yield self.provider.reserve(self.header, None, None, None, criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer

        yield self.provider.reserveCommit(self.header, cid)
        yield self.requester.reserve_commit_defer

        yield self.provider.provision(self.header, cid)
        yield self.requester.provision_defer

        self.clock.advance(3)

        header, cid, nid, timestamp, dps = yield self.requester.data_plane_change_defer
        active, version, consistent = dps
        self.failUnlessEquals(active, True)
Beispiel #18
0
    def testNoEndtimeAbort(self):

        # these need to be constructed such that there is only one label option
        source_stp  = nsa.STP(self.network, self.source_port, nsa.Label(cnt.ETHERNET_VLAN, '1782') )
        dest_stp    = nsa.STP(self.network, self.dest_port,   nsa.Label(cnt.ETHERNET_VLAN, '1782') )
        end_time    = None
        criteria    = nsa.Criteria(0, nsa.Schedule(self.start_time, end_time), nsa.Point2PointService(source_stp, dest_stp, 200, cnt.BIDIRECTIONAL, False, None) )

        self.header.newCorrelationId()
        acid = yield self.provider.reserve(self.header, None, None, None, criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer

        yield self.provider.reserveAbort(self.header, acid)
        header, cid = yield self.requester.reserve_abort_defer

        self.requester.reserve_defer = defer.Deferred()

        # try to reserve the same resources
        acid2 = yield self.provider.reserve(self.header, None, None, None, criteria)
        header, cid, gid, desc, sp = yield self.requester.reserve_defer
Beispiel #19
0
def reserveprovision(client, nsi_header, src, dst, start_time, end_time,
                     capacity, connection_id, global_id, notification_wait):

    schedule = nsa.Schedule(start_time, end_time)
    service_def = _createP2PS(src, dst, capacity)
    crt = nsa.Criteria(0, schedule, service_def)

    try:
        nsi_header.connection_trace = [nsi_header.requester_nsa + ':' + '1']
        connection_id, _, _, criteria = yield client.reserve(
            nsi_header, connection_id, global_id, 'Test Connection', crt)
        nsi_header.connection_trace = []
        sd = criteria.service_def
        log.msg("Connection created and held. Id %s at %s" %
                (connection_id, nsi_header.provider_nsa))
        log.msg("Source - Destination: %s - %s" % (sd.source_stp, sd.dest_stp))

        nsi_header.newCorrelationId()
        yield client.reserveCommit(nsi_header, connection_id)
        log.msg("Connection committed at %s" % nsi_header.provider_nsa)

        # query
        nsi_header.newCorrelationId()
        qr = yield client.querySummary(nsi_header,
                                       connection_ids=[connection_id])
        print "Query result:", qr

        # provision
        nsi_header.newCorrelationId()
        yield client.provision(nsi_header, connection_id)
        log.msg('Connection %s provisioned' % connection_id)

        while notification_wait:
            event = yield client.notifications.get()
            exit = _handleEvent(event)
            if exit:
                break

    except error.NSIError, e:
        _logError(e)
Beispiel #20
0
def rprt(client, nsi_header, src, dst, start_time, end_time, capacity,
         connection_id, global_id):
    # reserve, provision, release,  terminate
    schedule = nsa.Schedule(start_time, end_time)
    service_def = _createP2PS(src, dst, capacity)
    crt = nsa.Criteria(0, schedule, service_def)

    try:
        nsi_header.connection_trace = [nsi_header.requester_nsa + ':' + '1']
        connection_id, _, _, criteria = yield client.reserve(
            nsi_header, connection_id, global_id, 'Test Connection', crt)
        nsi_header.connection_trace = []
        sd = criteria.service_def
        log.msg("Connection created and held. Id %s at %s" %
                (connection_id, nsi_header.provider_nsa))
        log.msg("Source - Destination: %s - %s" % (sd.source_stp, sd.dest_stp))

        # commit
        nsi_header.newCorrelationId()
        yield client.reserveCommit(nsi_header, connection_id)
        log.msg("Connection committed at %s" % nsi_header.provider_nsa)

        # provision
        nsi_header.newCorrelationId()
        yield client.provision(nsi_header, connection_id)
        log.msg('Connection %s provisioned' % connection_id)

        # release
        nsi_header.newCorrelationId()
        yield client.release(nsi_header, connection_id)
        log.msg('Connection %s released' % connection_id)

        # terminate
        nsi_header.newCorrelationId()
        yield client.terminate(nsi_header, connection_id)
        log.msg('Connection %s terminated' % connection_id)

    except error.NSIError, e:
        _logError(e)
Beispiel #21
0
    def setUp(self):
        from twisted.web import resource, server
        from twisted.application import internet
        from opennsa.protocols import nsi2
        from opennsa.protocols.shared import resource as soapresource
        from opennsa.protocols.nsi2 import requesterservice, requesterclient

        tcf = os.path.expanduser('~/.opennsa-test.json')
        tc = json.load(open(tcf))
        database.setupDatabase(tc['database'], tc['database-user'],
                               tc['database-password'])

        self.requester = common.DUDRequester()

        self.clock = task.Clock()

        nrm_ports = nrm.parsePortSpec(
            StringIO.StringIO(topology.ARUBA_TOPOLOGY))
        network_topology = nml.createNMLNetwork(nrm_ports, self.network,
                                                self.network)

        self.backend = dud.DUDNSIBackend(self.network, nrm_ports, None,
                                         {})  # we set the parent later
        self.backend.scheduler.clock = self.clock

        route_vectors = gns.RouteVectors([cnt.URN_OGF_PREFIX + self.network])
        route_vectors.updateVector(self.provider_agent.identity, 0,
                                   [self.network], {})

        pl = plugin.BasePlugin()
        pl.init({config.NETWORK_NAME: self.network}, None)

        pr = provreg.ProviderRegistry(
            {self.provider_agent.urn(): self.backend}, {})
        self.aggregator = aggregator.Aggregator(self.network,
                                                self.provider_agent,
                                                network_topology,
                                                route_vectors, None, pr, [],
                                                pl)  # we set the parent later

        self.backend.parent_requester = self.aggregator

        # provider protocol
        http_top_resource = resource.Resource()

        cs2_prov = nsi2.setupProvider(self.aggregator, http_top_resource)
        self.aggregator.parent_requester = cs2_prov

        provider_factory = server.Site(http_top_resource)
        self.provider_service = internet.TCPServer(self.PROVIDER_PORT,
                                                   provider_factory)

        # requester protocol

        requester_top_resource = resource.Resource()
        soap_resource = soapresource.setupSOAPResource(requester_top_resource,
                                                       'RequesterService2')

        self.provider = requesterclient.RequesterClient(
            self.provider_agent.endpoint, self.requester_agent.endpoint)

        requester_service = requesterservice.RequesterService(
            soap_resource, self.requester)  # this is the important part
        requester_factory = server.Site(requester_top_resource,
                                        logPath='/dev/null')

        # start engines!
        self.backend.startService()
        self.provider_service.startService()
        self.requester_iport = reactor.listenTCP(self.REQUESTER_PORT,
                                                 requester_factory)

        # request stuff
        self.start_time = datetime.datetime.utcnow() + datetime.timedelta(
            seconds=2)
        self.end_time = datetime.datetime.utcnow() + datetime.timedelta(
            seconds=10)

        self.schedule = nsa.Schedule(self.start_time, self.end_time)
        self.sd = nsa.Point2PointService(self.source_stp, self.dest_stp,
                                         self.bandwidth)
        self.criteria = nsa.Criteria(0, self.schedule, self.sd)
Beispiel #22
0
    def reserve(self, soap_data):

        t_start = time.time()

        header, reservation = helper.parseRequest(soap_data)

        # do some checking here

        #        print header.protocolVersion
        #        print header.correlationId
        #        print header.requesterNSA
        #        print header.providerNSA
        #        print header.replyTo

        criteria = reservation.criteria

        #version      = criteria.version # not used at the moment
        service_type = criteria.serviceType  # right now we just ignore this, either we know the service type or not
        p2ps = criteria.serviceDefinition

        #        if len(service_defs) == 0:
        #            err = failure.Failure ( error.PayloadError('No service definition element in message') )
        #            return self._createSOAPFault(err, header.provider_nsa, service_type=service_type)

        #        if len(service_defs) != 1:
        #            err = failure.Failure ( error.PayloadError('Only one service definition allowed') )
        #            return self._createSOAPFault(err, header.provider_nsa, service_type=service_type)

        if type(p2ps) is not p2pservices.P2PServiceBaseType:
            err = failure.Failure(
                error.PayloadError(
                    'Only supports Point2PointService service for now.'))
            return self._createSOAPFault(err,
                                         header.provider_nsa,
                                         service_type=service_type)

        if p2ps.directionality in (None, ''):
            err = failure.Failure(
                error.MissingParameterError(
                    'Directionality parameter not defined'))
            return self._createSOAPFault(err, header.provider_nsa)

        # create DTOs (EROs not supported yet)

        start_time = xmlhelper.parseXMLTimestamp(
            criteria.schedule.startTime
        ) if criteria.schedule.startTime is not None else None
        end_time = xmlhelper.parseXMLTimestamp(criteria.schedule.endTime)
        schedule = nsa.Schedule(start_time, end_time)

        src_stp = helper.createSTP(p2ps.sourceSTP)
        dst_stp = helper.createSTP(p2ps.destSTP)

        if p2ps.ero:
            err = failure.Failure(
                error.PayloadError('ERO not supported, go away.'))
            return self._createSOAPFault(err, header.provider_nsa)

#        if p2ps.parameter:
#            p = p2ps.parameter[0]
#            err = failure.Failure ( error.UnsupportedParameter('Unsupported parameter: %s/%s' % (p.type_, p.value) ) )
#            return self._createSOAPFault(err, header.provider_nsa)
        params = [(p.type_, p.value)
                  for p in p2ps.parameter] if p2ps.parameter else None
        symmetric = p2ps.symmetricPath or False  # the p2p service specifies default behaviour as false, but doesn't specify default
        sd = nsa.Point2PointService(src_stp, dst_stp, p2ps.capacity,
                                    p2ps.directionality, symmetric, None,
                                    params)

        crt = nsa.Criteria(criteria.version, schedule, sd)

        t_delta = time.time() - t_start
        log.msg('Profile: Reserve request parse time: %s' % round(t_delta, 3),
                profile=True,
                system=LOG_SYSTEM)

        d = self.provider.reserve(header, reservation.connectionId,
                                  reservation.globalReservationId,
                                  reservation.description, crt)

        def createReserveAcknowledgement(connection_id):
            # no reply to / security attrs / trace
            soap_header_element = helper.createProviderHeader(
                header.requester_nsa, header.provider_nsa, None,
                header.correlation_id)

            reserve_response = nsiconnection.ReserveResponseType(connection_id)
            reserve_response_element = reserve_response.xml(
                nsiconnection.reserveResponse)

            payload = minisoap.createSoapPayload(reserve_response_element,
                                                 soap_header_element)
            return payload

        d.addCallbacks(createReserveAcknowledgement,
                       self._createSOAPFault,
                       errbackArgs=(header.provider_nsa, ))
        return d
Beispiel #23
0
    def render_POST(self, request):

        allowed, msg, request_info = requestauthz.checkAuthz(
            request, self.allowed_hosts)
        if not allowed:
            payload = msg + RN
            return _requestResponse(request, 401, payload)  # Not Authorized

        payload = request.content.read()

        if len(payload) == 0:
            log.msg('No data received in request', system=LOG_SYSTEM)
            payload = 'No data received in request' + RN
            return _requestResponse(request, 400, payload)  # Bad Request

        if len(payload) > 32 * 1024:
            log.msg('Rejecting request, payload too large. Length %i' %
                    len(payload),
                    system=LOG_SYSTEM)
            payload = 'Requests too large' + RN
            return _requestResponse(request, 413, payload)  # Payload Too Large

        try:
            data = json.loads(payload)
        except ValueError:
            log.msg('Invalid JSON data received, returning 400',
                    system=LOG_SYSTEM)
            payload = 'Invalid JSON data' + RN
            return _requestResponse(request, 400, payload)  # Bad Request

        def createResponse(connection_id):

            payload = 'Connection created' + RN
            header = {'location': self.base_path + '/' + connection_id}
            _finishRequest(request, 201, payload, header)  # Created
            return connection_id

        # extract stuffs
        try:
            source = data['source']
            if not source.startswith(cnt.URN_OGF_PREFIX):
                source = cnt.URN_OGF_PREFIX + source

            destination = data['destination']
            if not destination.startswith(cnt.URN_OGF_PREFIX):
                destination = cnt.URN_OGF_PREFIX + destination

            source_stp = helper.createSTP(str(source))
            destination_stp = helper.createSTP(str(destination))

            start_time = xmlhelper.parseXMLTimestamp(
                data[START_TIME]) if START_TIME in data else None
            end_time = xmlhelper.parseXMLTimestamp(
                data[END_TIME]) if END_TIME in data else None
            capacity = data[
                'capacity'] if 'capacity' in data else 0  # Maybe None should just be best effort

            # auto commit (default true) and auto provision (defult false)
            auto_commit = False if 'auto_commit' in data and not data[
                'auto_commit'] else True
            auto_provision = True if 'auto_provision' in data and data[
                'auto_provision'] else False

            if auto_provision and not auto_commit:
                msg = 'Cannot have auto-provision without auto-commit'
                log.msg('Rejecting request: ' + msg, system=LOG_SYSTEM)
                return _requestResponse(request, 400, msg + RN)  # Bad Request

            # fillers, we don't really do this in this api
            symmetric = False
            ero = None
            params = None
            version = 0

            service_def = nsa.Point2PointService(source_stp, destination_stp,
                                                 capacity, cnt.BIDIRECTIONAL,
                                                 symmetric, ero, params)
            schedule = nsa.Schedule(start_time, end_time)
            criteria = nsa.Criteria(version, schedule, service_def)

            header = nsa.NSIHeader(
                'rest-dud-requester',
                'rest-dud-provider')  # completely bogus header

            d = self.provider.reserve(
                header, None, None, None, criteria, request_info
            )  # nones are connection_id, global resv id, description
            d.addCallbacks(createResponse,
                           _createErrorResponse,
                           errbackArgs=(request, ))

            if auto_commit:

                @defer.inlineCallbacks
                def connectionCreated(conn_id):
                    if conn_id is None:
                        # error creating connection
                        # not exactly optimal code flow here, but chainining the callback correctly for this is tricky
                        return

                    conn = yield self.provider.getConnection(conn_id)

                    def stateUpdate():
                        log.msg(
                            'stateUpdate reservation_state: %s, provision_state: %s'
                            % (str(conn.reservation_state),
                               str(conn.provision_state)),
                            debug=True,
                            system=LOG_SYSTEM)
                        if conn.reservation_state == state.RESERVE_HELD:
                            self.provider.reserveCommit(
                                header, conn_id, request_info)
                        if conn.reservation_state == state.RESERVE_START and conn.provision_state == state.RELEASED and auto_provision:
                            self.provider.provision(header, conn_id,
                                                    request_info)
                        if conn.provision_state == state.PROVISIONED:
                            state.desubscribe(conn_id, stateUpdate)

                    state.subscribe(conn_id, stateUpdate)

                d.addCallback(connectionCreated)

            return server.NOT_DONE_YET

        except Exception as e:
            #log.err(e, system=LOG_SYSTEM)
            log.msg('Error creating connection: %s' % str(e),
                    system=LOG_SYSTEM)

            error_code = _errorCode(e)
            return _requestResponse(request, error_code, str(e))