Java源码示例:org.onosproject.net.intent.Intent
示例1
/**
* Registers an intent compiler of the specified intent if an intent compiler
* for the intent is not registered. This method traverses the class hierarchy of
* the intent. Once an intent compiler for a parent type is found, this method
* registers the found intent compiler.
*
* @param intent intent
*/
private void registerSubclassCompilerIfNeeded(Intent intent) {
if (!compilers.containsKey(intent.getClass())) {
Class<?> cls = intent.getClass();
while (cls != Object.class) {
// As long as we're within the Intent class descendants
if (Intent.class.isAssignableFrom(cls)) {
VirtualIntentCompiler<?> compiler = compilers.get(cls);
if (compiler != null) {
compilers.put(intent.getClass(), compiler);
return;
}
}
cls = cls.getSuperclass();
}
}
}
示例2
@Test
public void testMatches() {
Intent intent = HostToHostIntent.builder()
.key(manager.generateKey(NETWORK, HOST_1, HOST_2))
.appId(manager.appId)
.one(HOST_1)
.two(HOST_2)
.build();
assertTrue(manager.matches(NETWORK, Optional.of(HOST_1), intent));
assertTrue(manager.matches(NETWORK, Optional.of(HOST_2), intent));
assertTrue(manager.matches(NETWORK, Optional.empty(), intent));
assertFalse(manager.matches(NETWORK, Optional.of(HOST_3), intent));
assertFalse(manager.matches(NETWORK_2, Optional.of(HOST_1), intent));
assertFalse(manager.matches(NETWORK_2, Optional.of(HOST_3), intent));
}
示例3
/**
* Gets intent installables by application ID and key.
* @param appId application identifier
* @param key intent key
*
* @return 200 OK with array of the intent installables
* @onos.rsModel Intents
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("installables/{appId}/{key}")
public Response getIntentWithInstallable(@PathParam("appId") String appId,
@PathParam("key") String key) {
final IntentService intentService = get(IntentService.class);
final ApplicationId app = get(CoreService.class).getAppId(appId);
nullIsNotFound(app, APP_ID_NOT_FOUND);
Intent intent = intentService.getIntent(Key.of(key, app));
if (intent == null) {
long numericalKey = Long.decode(key);
intent = intentService.getIntent(Key.of(numericalKey, app));
}
nullIsNotFound(intent, INTENT_NOT_FOUND);
final Iterable<Intent> installables = intentService.getInstallableIntents(intent.key());
final ObjectNode root = encodeArray(Intent.class, "installables", installables);
return ok(root).build();
}
示例4
@Override
public boolean isRelevant(FlowRuleEvent event) {
/*
* Check if the rule event is relevant and it needs to be managed
* A Rule event is relevant if the flow rule it refers to is
* part of one of the monitored intents
*/
FlowRule rule = event.subject();
for (Map.Entry<ApplicationId, Map<Key, ConnectivityIntent>> entry : monitoredIntents.entrySet()) {
for (Key key : entry.getValue().keySet()) {
List<Intent> ints = intentService.getInstallableIntents(key);
for (Intent i : ints) {
if (i instanceof FlowRuleIntent
&& ((FlowRuleIntent) i).flowRules().contains(rule)) {
return true;
}
}
}
}
return false;
}
示例5
/**
* Tests the compilation behavior of the path intent compiler in case of
* VLAN {@link EncapsulationType} encapsulation constraint {@link EncapsulationConstraint}
* and single-hop-indirect-link scenario. Ingress VLAN. No egress VLAN.
*/
@Test
public void testVlanEncapCompileSingleHopIndirectIngressVlan() {
sut.activate();
List<Intent> compiled = sut.compile(singleHopIndirectIntentIngressVlan, Collections.emptyList());
assertThat(compiled, hasSize(1));
Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();
assertThat(rules, hasSize(1));
FlowRule rule = rules.stream()
.filter(x -> x.deviceId().equals(d2p2.deviceId()))
.findFirst()
.get();
verifyIdAndPriority(rule, d2p2.deviceId());
assertThat(rule.selector(), is(DefaultTrafficSelector.builder().matchInPort(d2p2.port())
.matchVlanId(ingressVlan).build()));
assertThat(rule.treatment(),
is(DefaultTrafficTreatment.builder().setOutput(d2p3.port()).build()));
sut.deactivate();
}
示例6
@Test
public void withdrawIntent() {
flowRuleService.setFuture(true);
listener.setLatch(1, Type.INSTALLED);
Intent intent = new MockIntent(MockIntent.nextId());
service.submit(intent);
listener.await(Type.INSTALLED);
assertEquals(1L, service.getIntentCount());
assertEquals(1L, flowRuleService.getFlowRuleCount());
listener.setLatch(1, Type.WITHDRAWN);
service.withdraw(intent);
listener.await(Type.WITHDRAWN);
assertEquals(0L, flowRuleService.getFlowRuleCount());
verifyState();
}
示例7
/**
* Installs test Intents.
*/
@Test
public void testInstallIntent() {
IntentData toInstall = new IntentData(createTestIntent(),
IntentState.INSTALLING,
new WallClockTimestamp());
List<Intent> intents = Lists.newArrayList();
IntStream.range(0, 10).forEach(val -> {
intents.add(new TestInstallableIntent(val));
});
toInstall = IntentData.compiled(toInstall, intents);
installCoordinator.installIntents(Optional.empty(), Optional.of(toInstall));
Intent toInstallIntent = toInstall.intent();
TestTools.assertAfter(INSTALL_DELAY, INSTALL_DURATION, () -> {
IntentData newData = intentStore.newData;
assertEquals(toInstallIntent, newData.intent());
assertEquals(IntentState.INSTALLED, newData.state());
assertEquals(intents, newData.installables());
});
}
示例8
/**
* Creates a link collection intent from the specified path and original
* point to point intent.
*
* @param links the links of the packets
* @param cost the cost associated to the links
* @param intent the point to point intent we are compiling
* @return the link collection intent
*/
private Intent createLinkCollectionIntent(Set<Link> links,
double cost,
PointToPointIntent intent) {
return LinkCollectionIntent.builder()
.key(intent.key())
.appId(intent.appId())
.selector(intent.selector())
.treatment(intent.treatment())
.links(ImmutableSet.copyOf(links))
.filteredIngressPoints(ImmutableSet.of(
intent.filteredIngressPoint()
))
.filteredEgressPoints(ImmutableSet.of(
intent.filteredEgressPoint()
))
.applyTreatmentOnEgress(true)
.constraints(intent.constraints())
.priority(intent.priority())
.cost(cost)
.resourceGroup(intent.resourceGroup())
.build();
}
示例9
/**
* Test if domain Intent installation operations failed.
*/
@Test
public void testInstallFailed() {
domainIntentService = new TestFailedDomainIntentService();
installer.domainIntentService = domainIntentService;
List<Intent> intentsToUninstall = Lists.newArrayList();
List<Intent> intentsToInstall = createDomainIntents();
IntentData toUninstall = null;
IntentData toInstall = new IntentData(createP2PIntent(),
IntentState.INSTALLING,
new WallClockTimestamp());
toInstall = IntentData.compiled(toInstall, intentsToInstall);
IntentOperationContext<DomainIntent> operationContext;
IntentInstallationContext context = new IntentInstallationContext(toUninstall, toInstall);
operationContext = new IntentOperationContext(intentsToUninstall, intentsToInstall, context);
installer.apply(operationContext);
assertEquals(intentInstallCoordinator.failedContext, operationContext);
}
示例10
public void verifyState() {
// verify that all intents are parked and the batch operation is unblocked
Set<IntentState> parked = Sets.newHashSet(INSTALLED, WITHDRAWN, FAILED, CORRUPT);
for (Intent i : service.getIntents()) {
IntentState state = service.getIntentState(i.key());
assertTrue("Intent " + i.id() + " is in invalid state " + state,
parked.contains(state));
}
//the batch has not yet been removed when we receive the last event
// FIXME: this doesn't guarantee to avoid the race
//FIXME
// for (int tries = 0; tries < 10; tries++) {
// if (manager.batchService.getPendingOperations().isEmpty()) {
// break;
// }
// delay(10);
// }
// assertTrue("There are still pending batch operations.",
// manager.batchService.getPendingOperations().isEmpty());
}
示例11
/**
* Registers an intent compiler of the specified intent if an intent compiler
* for the intent is not registered. This method traverses the class hierarchy of
* the intent. Once an intent compiler for a parent type is found, this method
* registers the found intent compiler.
*
* @param intent intent
*/
private void registerSubclassCompilerIfNeeded(Intent intent) {
if (!compilers.containsKey(intent.getClass())) {
Class<?> cls = intent.getClass();
while (cls != Object.class) {
// As long as we're within the Intent class descendants
if (Intent.class.isAssignableFrom(cls)) {
IntentCompiler<?> compiler = compilers.get(cls);
if (compiler != null) {
compilers.put(intent.getClass(), compiler);
return;
}
}
cls = cls.getSuperclass();
}
}
}
示例12
/**
* Checks if the number of intents submitted to the intent framework is equal
* to the number of intents expected and if all intents are equivalent.
*
* @param intents the list of intents expected
*/
private void checkIntents(List<Intent> intents) {
assertEquals("The number of intents submitted differs from the number" +
" of intents expected. ",
intents.size(), intentService.getIntentCount());
for (Intent intentOne : intents) {
boolean found = false;
for (Intent intentTwo : intentService.getIntents()) {
if (intentOne.key().equals(intentTwo.key())) {
found = true;
assertTrue(format("The intent submitted is different from" +
" the intent expected. %s %s",
intentOne, intentTwo),
IntentUtils.intentsAreEqual(intentOne, intentTwo));
break;
}
}
assertTrue("The intent submitted is not equal to any of the expected" +
" intents. ", found);
}
}
示例13
/**
* Tests if compiling an intent without partial failure constraints set and
* with a missing ingress connect point generates an exception and no other
* results.
*/
@Test
public void testPartialFailureConstraintFailure() {
Set<FilteredConnectPoint> ingress = ImmutableSet.of(
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)),
new FilteredConnectPoint(new ConnectPoint(DID_5, PORT_1)));
FilteredConnectPoint egress =
new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_2));
MultiPointToSinglePointIntent intent =
makeIntent(ingress, egress);
String[] hops = {S3};
MultiPointToSinglePointIntentCompiler compiler =
makeCompiler(null,
new IntentTestsMocks.FixedMP2MPMockPathService(hops),
null);
assertThat(compiler, is(notNullValue()));
intentException.expect(IntentException.class);
List<Intent> result = compiler.compile(intent, null);
assertThat(result, null);
}
示例14
/**
* Submits a new optical intent.
* Creates and submits optical intents from the JSON request.
*
* @param stream input JSON
* @return status of the request - CREATED if the JSON is correct,
* BAD_REQUEST if the JSON is invalid
* @onos.rsModel CreateIntent
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createIntent(InputStream stream) {
try {
IntentService service = get(IntentService.class);
ObjectNode root = readTreeFromStream(mapper(), stream);
Intent intent = decode(root);
service.submit(intent);
UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
.path("intents")
.path(intent.appId().name())
.path(Long.toString(intent.id().fingerprint()));
return Response
.created(locationBuilder.build())
.build();
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe);
}
}
示例15
/**
* Creates a path intent from the specified path and original
* connectivity intent.
*
* @param path path to create an intent for
* @param intent original intent
* @param type primary or backup
*/
private Intent createPathIntent(Path path,
PointToPointIntent intent,
PathIntent.ProtectionType type) {
return PathIntent.builder()
.appId(intent.appId())
.key(intent.key())
.selector(intent.selector())
.treatment(intent.treatment())
.path(path)
.constraints(intent.constraints())
.priority(intent.priority())
.setType(type)
.resourceGroup(intent.resourceGroup())
.build();
}
示例16
/**
* Tests the compilation behavior of the path intent compiler in case of
* VLAN {@link EncapsulationType} encapsulation constraint {@link EncapsulationConstraint}
* and single-hop-direct-link scenario. No ingress VLAN. No egress VLAN.
*/
@Test
public void testVlanEncapCompileSingleHopDirectNoVlan() {
sut.activate();
List<Intent> compiled = sut.compile(singleHopDirectIntentNoVlan, Collections.emptyList());
assertThat(compiled, hasSize(1));
Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();
assertThat(rules, hasSize(1));
FlowRule rule = rules.stream()
.filter(x -> x.deviceId().equals(d2p4.deviceId()))
.findFirst()
.get();
verifyIdAndPriority(rule, d2p4.deviceId());
assertThat(rule.selector(), is(DefaultTrafficSelector.builder().matchInPort(d2p4.port())
.build()));
assertThat(rule.treatment(),
is(DefaultTrafficTreatment.builder().setOutput(d2p5.port()).build()));
sut.deactivate();
}
示例17
/**
* Test that if a suggested path isn't available it applies another available path.
*/
@Test
public void testSuggestedPathNotAvailable() {
String[] suggestedPathHops = {S1, S3, S8};
String[] shortestPath = {S1, S2, S8};
List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links();
PointToPointIntent intent = makeIntentSuggestedPath(new ConnectPoint(DID_1, PORT_1),
new ConnectPoint(DID_8, PORT_2),
suggestedPath);
String[][] path = {shortestPath};
PointToPointIntentCompiler compiler = makeCompilerSuggestedPath(path);
List<Intent> result = compiler.compile(intent, null);
assertThat(result, is(Matchers.notNullValue()));
assertThat(result, hasSize(1));
Intent resultIntent = result.get(0);
assertThat(resultIntent instanceof LinkCollectionIntent, is(true));
if (resultIntent instanceof LinkCollectionIntent) {
LinkCollectionIntent resultLinkIntent = (LinkCollectionIntent) resultIntent;
FilteredConnectPoint ingressPoint = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
FilteredConnectPoint egressPoint = new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_2));
// 5 links for the hops, plus one default link on ingress and egress
assertThat(resultLinkIntent.links(), hasSize(shortestPath.length - 1));
assertThat(resultLinkIntent.links(), linksHasPath(S1, S2));
assertThat(resultLinkIntent.links(), linksHasPath(S2, S8));
assertThat(resultLinkIntent.filteredIngressPoints(), is(ImmutableSet.of(ingressPoint)));
assertThat(resultLinkIntent.filteredEgressPoints(), is(ImmutableSet.of(egressPoint)));
}
assertThat("key is inherited", resultIntent.key(), is(intent.key()));
}
示例18
@Before
public void setUp() {
manager = new NetworkManager();
manager.appId = new TestApplicationId("network-test");
Intent.bindIdGenerator(idGenerator);
}
示例19
@Override
public void withdraw(Intent intent) {
intents.forEach(intentData -> {
if (intentData.intent().key().equals(intent.key())) {
intentData.setState(IntentState.FAILED);
if (listener != null) {
IntentEvent event = IntentEvent.getEvent(IntentState.FAILED, intent).get();
listener.event(event);
}
}
});
}
示例20
@Override
public List<Intent> compile(MockIntent intent, List<Intent> installable) {
return IntStream.rangeClosed(1, 5)
.mapToObj(mock -> (new MockInstallableIntent()))
.collect(Collectors.toList());
}
示例21
@Override
public void submit(Intent intent) {
checkNotNull(intent, INTENT_NULL);
checkState(intent instanceof VirtualNetworkIntent, "Only VirtualNetworkIntent is supported.");
checkArgument(validateIntent((VirtualNetworkIntent) intent), "Invalid Intent");
IntentData data = IntentData.submit(intent);
intentStore.addPending(networkId, data);
}
示例22
/**
* Tests filtered ingress and egress.
*/
@Test
public void testFilteredConnectPointIntent() {
Set<FilteredConnectPoint> ingress = ImmutableSet.of(
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1),
DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("100")).build()),
new FilteredConnectPoint(new ConnectPoint(DID_2, PORT_1),
DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("200")).build())
);
FilteredConnectPoint egress = new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_2));
MultiPointToSinglePointIntent intent = makeIntent(ingress, egress, selector);
String[] hops = {S3};
MultiPointToSinglePointIntentCompiler compiler = makeCompiler(hops);
assertThat(compiler, is(notNullValue()));
List<Intent> result = compiler.compile(intent, null);
assertThat(result, is(notNullValue()));
assertThat(result, hasSize(1));
Intent resultIntent = result.get(0);
assertThat(resultIntent, instanceOf(LinkCollectionIntent.class));
if (resultIntent instanceof LinkCollectionIntent) {
LinkCollectionIntent linkIntent = (LinkCollectionIntent) resultIntent;
assertThat(linkIntent.links(), hasSize(3));
assertThat(linkIntent.links(), linksHasPath(S1, S3));
assertThat(linkIntent.links(), linksHasPath(S2, S3));
assertThat(linkIntent.links(), linksHasPath(S3, S4));
}
assertThat("key is inherited", resultIntent.key(), is(intent.key()));
}
示例23
/**
* Tests the compilation behavior of the path intent compiler in case of
* VLAN {@link EncapsulationType} encapsulation constraint {@link EncapsulationConstraint}
* and edge communication. Ingress VLAN. Egress VLAN.
*/
@Test
public void testVlanEncapCompileEdgeVlan() {
sut.activate();
List<Intent> compiled = sut.compile(edgeIntentVlan, Collections.emptyList());
assertThat(compiled, hasSize(1));
Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();
assertThat(rules, hasSize(1));
FlowRule rule = rules.stream()
.filter(x -> x.deviceId().equals(d1p2.deviceId()))
.findFirst()
.get();
verifyIdAndPriority(rule, d1p2.deviceId());
assertThat(rule.selector(), is(DefaultTrafficSelector.builder().matchInPort(d1p2.port())
.matchVlanId(ingressVlan).build()));
assertThat(rule.treatment(), is(DefaultTrafficTreatment.builder().setVlanId(egressVlan)
.setOutput(d1p3.port()).build()));
Set<L2ModificationInstruction.ModVlanIdInstruction> vlanMod = rule.treatment().allInstructions().stream()
.filter(treat -> treat instanceof L2ModificationInstruction.ModVlanIdInstruction)
.map(x -> (L2ModificationInstruction.ModVlanIdInstruction) x)
.collect(Collectors.toSet());
assertThat(rule.treatment().allInstructions().stream()
.filter(treat -> treat instanceof L2ModificationInstruction.ModVlanIdInstruction)
.collect(Collectors.toSet()), hasSize(1));
assertThat(vlanMod.iterator().next().vlanId(), is(egressVlan));
assertThat(rule.treatment().allInstructions().stream()
.filter(treat -> treat instanceof L2ModificationInstruction.ModVlanHeaderInstruction)
.collect(Collectors.toSet()), hasSize(0));
sut.deactivate();
}
示例24
/**
* Tests the compilation of an intent which designates two different ports
* on the same switch.
*/
@Test
public void testSameSwitchDifferentPortsIntentCompilation() {
FilteredConnectPoint src =
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
FilteredConnectPoint dst =
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_2));
PointToPointIntent intent = makeIntent(new ConnectPoint(DID_1, PORT_1),
new ConnectPoint(DID_1, PORT_2));
String[] hops = {S1};
PointToPointIntentCompiler compiler = makeCompiler(hops);
List<Intent> compiled = compiler.compile(intent, null);
assertThat("key is inherited",
compiled.stream().map(Intent::key).collect(Collectors.toList()),
everyItem(is(intent.key())));
assertThat(compiled, hasSize(1));
assertThat(compiled.get(0), is(instanceOf(LinkCollectionIntent.class)));
LinkCollectionIntent linkCollectionIntent = (LinkCollectionIntent) compiled.get(0);
Set<Link> links = linkCollectionIntent.links();
assertThat(links, hasSize(0));
assertThat(linkCollectionIntent.filteredIngressPoints(), is(ImmutableSet.of(src)));
assertThat(linkCollectionIntent.filteredEgressPoints(), is(ImmutableSet.of(dst)));
}
示例25
@Override
protected void populateTable(TableModel tm, ObjectNode payload) {
IntentService is = get(IntentService.class);
for (Intent intent : is.getIntents()) {
populateRow(tm.addRow(), intent, is);
}
}
示例26
private void populateRow(TableModel.Row row, Intent intent, IntentService is) {
row.cell(APP_ID, intent.appId())
.cell(KEY, intent.key())
.cell(TYPE, intent.getClass().getSimpleName())
.cell(PRIORITY, intent.priority())
.cell(STATE, is.getIntentState(intent.key()))
.cell(RESOURCES, intent)
.cell(DETAILS, intent);
}
示例27
private List<Intent> createZeroHopIntent(ConnectPoint ingressPoint,
ConnectPoint egressPoint,
PointToPointIntent intent) {
List<Link> links = asList(createEdgeLink(ingressPoint, true), createEdgeLink(egressPoint, false));
return asList(createPathIntent(new DefaultPath(PID, links, ScalarWeight.toWeight(DEFAULT_COST)),
intent, PathIntent.ProtectionType.PRIMARY));
}
示例28
private Intent findIntentByPayload(ObjectNode payload) {
Intent intent;
Key key;
int appId = Integer.parseInt(string(payload, APP_ID));
String appName = string(payload, APP_NAME);
ApplicationId applicId = new DefaultApplicationId(appId, appName);
String stringKey = string(payload, KEY);
try {
// FIXME: If apps use different string key, but they contains
// same numeric value (e.g. "020", "0x10", "16", "#10")
// and one intent using long key (e.g. 16L)
// this function might return wrong intent.
long longKey = Long.decode(stringKey);
key = Key.of(longKey, applicId);
intent = services.intent().getIntent(key);
if (intent == null) {
// Intent might using string key, not long key
key = Key.of(stringKey, applicId);
intent = services.intent().getIntent(key);
}
} catch (NumberFormatException ex) {
// string key
key = Key.of(stringKey, applicId);
intent = services.intent().getIntent(key);
}
log.debug("Attempting to select intent by key={}", key);
return intent;
}
示例29
@Override
public List<Intent> getInstallableIntents(NetworkId networkId, Key intentKey) {
IntentData data = getCurrentMap(networkId).get(intentKey);
if (data != null) {
return data.installables();
}
return null;
}
示例30
@Override
protected void doExecute() {
VirtualNetworkService service = get(VirtualNetworkService.class);
IntentService virtualNetworkIntentService = service.get(NetworkId.networkId(networkId), IntentService.class);
ConnectPoint ingress = ConnectPoint.deviceConnectPoint(ingressDeviceString);
ConnectPoint egress = ConnectPoint.deviceConnectPoint(egressDeviceString);
TrafficSelector selector = buildTrafficSelector();
TrafficTreatment treatment = buildTrafficTreatment();
List<Constraint> constraints = buildConstraints();
Intent intent = VirtualNetworkIntent.builder()
.networkId(NetworkId.networkId(networkId))
.appId(appId())
.key(key())
.selector(selector)
.treatment(treatment)
.ingressPoint(ingress)
.egressPoint(egress)
.constraints(constraints)
.priority(priority())
.build();
virtualNetworkIntentService.submit(intent);
print("Virtual intent submitted:\n%s", intent.toString());
}