org.onosproject.net.group.DefaultGroupDescription Java Examples

The following examples show how to use org.onosproject.net.group.DefaultGroupDescription. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Utils.java    From ngsdn-tutorial with Apache License 2.0 6 votes vote down vote up
public static GroupDescription buildSelectGroup(DeviceId deviceId,
                                                String tableId,
                                                String actionProfileId,
                                                int groupId,
                                                Collection<PiAction> actions,
                                                ApplicationId appId) {

    final GroupKey groupKey = new PiGroupKey(
            PiTableId.of(tableId), PiActionProfileId.of(actionProfileId), groupId);
    final List<GroupBucket> buckets = actions.stream()
            .map(action -> DefaultTrafficTreatment.builder()
                    .piTableAction(action).build())
            .map(DefaultGroupBucket::createSelectGroupBucket)
            .collect(Collectors.toList());
    return new DefaultGroupDescription(
            deviceId,
            GroupDescription.Type.SELECT,
            new GroupBuckets(buckets),
            groupKey,
            groupId,
            appId);
}
 
Example #2
Source File: ForwardingObjectiveTranslator.java    From onos with Apache License 2.0 6 votes vote down vote up
private DefaultGroupDescription createCloneGroup(
        ApplicationId appId,
        int cloneSessionId,
        PortNumber outPort) {
    final GroupKey groupKey = new DefaultGroupKey(
            FabricPipeliner.KRYO.serialize(cloneSessionId));

    final List<GroupBucket> bucketList = ImmutableList.of(
            createCloneGroupBucket(DefaultTrafficTreatment.builder()
                                           .setOutput(outPort)
                                           .build()));
    final DefaultGroupDescription cloneGroup = new DefaultGroupDescription(
            deviceId, GroupDescription.Type.CLONE,
            new GroupBuckets(bucketList),
            groupKey, cloneSessionId, appId);
    return cloneGroup;
}
 
Example #3
Source File: Ofdpa2GroupHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an Mpls group of type swap.
 *
 * @param nextGroupId the next group in the chain
 * @param subtype the mpls swap label group subtype
 * @param index the index of the group
 * @param mplsLabel the mpls label to swap
 * @param applicationId the application id
 * @return the group description
 */
protected GroupDescription createMplsSwap(int nextGroupId,
                                          OfdpaMplsGroupSubType subtype,
                                          int index,
                                          MplsLabel mplsLabel,
                                          ApplicationId applicationId) {
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    treatment.setMpls(mplsLabel);
    // We point the group to the next group.
    treatment.group(new GroupId(nextGroupId));
    GroupBucket groupBucket = DefaultGroupBucket
            .createIndirectGroupBucket(treatment.build());
    // Finally we build the group description.
    int groupId = makeMplsLabelGroupId(subtype, index);
    GroupKey groupKey = new DefaultGroupKey(
            Ofdpa2Pipeline.appKryo.serialize(index));
    return new DefaultGroupDescription(
            deviceId,
            INDIRECT,
            new GroupBuckets(Collections.singletonList(groupBucket)),
            groupKey,
            groupId,
            applicationId);
}
 
Example #4
Source File: PointToPointIntentCompiler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new failover group with the initial ports of the links
 * from the primary and backup path.
 *
 * @param links         links from the primary path
 * @param backupLinks   links from the backup path
 * @param intent        intent from which this call originates
 */
private void createFailoverTreatmentGroup(List<Link> links,
                                          List<Link> backupLinks,
                                          PointToPointIntent intent) {

    List<GroupBucket> buckets = new ArrayList<>();

    TrafficTreatment.Builder tBuilderIn = DefaultTrafficTreatment.builder();
    ConnectPoint src = links.get(0).src();
    tBuilderIn.setOutput(src.port());

    TrafficTreatment.Builder tBuilderIn2 = DefaultTrafficTreatment.builder();
    ConnectPoint src2 = backupLinks.get(0).src();
    tBuilderIn2.setOutput(src2.port());

    buckets.add(DefaultGroupBucket.createFailoverGroupBucket(tBuilderIn.build(), src.port(), null));
    buckets.add(DefaultGroupBucket.createFailoverGroupBucket(tBuilderIn2.build(), src2.port(), null));

    GroupBuckets groupBuckets = new GroupBuckets(buckets);

    GroupDescription groupDesc = new DefaultGroupDescription(src.deviceId(), Group.Type.FAILOVER,
                                     groupBuckets, makeGroupKey(intent.id()), null, intent.appId());
    log.trace("adding failover group {}", groupDesc);
    groupService.addGroup(groupDesc);
}
 
Example #5
Source File: OvsOfdpaPipeline.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a indirect group contains pop_vlan and punt actions.
 * <p>
 * Using group instead of immediate action to ensure that
 * the copy of packet on the data plane is not affected by the pop vlan action.
 */
private void initPopVlanPuntGroup() {
    GroupKey groupKey = popVlanPuntGroupKey();
    TrafficTreatment bucketTreatment = DefaultTrafficTreatment.builder()
            .popVlan().punt().build();
    GroupBucket bucket =
            DefaultGroupBucket.createIndirectGroupBucket(bucketTreatment);
    GroupDescription groupDesc =
            new DefaultGroupDescription(
                    deviceId,
                    GroupDescription.Type.INDIRECT,
                    new GroupBuckets(Collections.singletonList(bucket)),
                    groupKey,
                    POP_VLAN_PUNT_GROUP_ID,
                    driverId);
    groupService.addGroup(groupDesc);

    log.info("Initialized pop vlan punt group on {}", deviceId);
}
 
Example #6
Source File: P4RuntimeActionGroupProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void performGroupOperation(DeviceId deviceId,
                                  GroupOperations groupOps) {
    if (!setupBehaviour("performGroupOperation()")) {
        return;
    }

    groupOps.operations().forEach(op -> {
        // ONOS-7785 We need the group app cookie (which includes
        // the action profile ID) but this is not part of the
        // GroupDescription.
        Group groupOnStore = groupStore.getGroup(deviceId, op.groupId());
        if (groupOnStore == null) {
            log.warn("Unable to find group {} in store, aborting {} operation [{}]",
                     op.groupId(), op.opType(), op);
            return;
        }
        GroupDescription groupDesc = new DefaultGroupDescription(
                deviceId, groupOnStore.type(), groupOnStore.buckets(), groupOnStore.appCookie(),
                groupOnStore.id().id(), groupOnStore.appId());
        DefaultGroup groupToApply = new DefaultGroup(op.groupId(), groupDesc);
        processPdGroup(groupToApply, op.opType());
    });
}
 
Example #7
Source File: Utils.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
public static GroupDescription buildSelectGroup(DeviceId deviceId,
                                                String tableId,
                                                String actionProfileId,
                                                int groupId,
                                                Collection<PiAction> actions,
                                                ApplicationId appId) {

    final GroupKey groupKey = new PiGroupKey(
            PiTableId.of(tableId), PiActionProfileId.of(actionProfileId), groupId);
    final List<GroupBucket> buckets = actions.stream()
            .map(action -> DefaultTrafficTreatment.builder()
                    .piTableAction(action).build())
            .map(DefaultGroupBucket::createSelectGroupBucket)
            .collect(Collectors.toList());
    return new DefaultGroupDescription(
            deviceId,
            GroupDescription.Type.SELECT,
            new GroupBuckets(buckets),
            groupKey,
            groupId,
            appId);
}
 
Example #8
Source File: Utils.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
public static GroupDescription buildSelectGroup(DeviceId deviceId,
                                                String tableId,
                                                String actionProfileId,
                                                int groupId,
                                                Collection<PiAction> actions,
                                                ApplicationId appId) {

    final GroupKey groupKey = new PiGroupKey(
            PiTableId.of(tableId), PiActionProfileId.of(actionProfileId), groupId);
    final List<GroupBucket> buckets = actions.stream()
            .map(action -> DefaultTrafficTreatment.builder()
                    .piTableAction(action).build())
            .map(DefaultGroupBucket::createSelectGroupBucket)
            .collect(Collectors.toList());
    return new DefaultGroupDescription(
            deviceId,
            GroupDescription.Type.SELECT,
            new GroupBuckets(buckets),
            groupKey,
            groupId,
            appId);
}
 
Example #9
Source File: SimpleGroupStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void deviceInitialAuditCompleted(DeviceId deviceId,
                                        boolean completed) {
    synchronized (deviceAuditStatus) {
        if (completed) {
            log.debug("deviceInitialAuditCompleted: AUDIT "
                    + "completed for device {}", deviceId);
            deviceAuditStatus.put(deviceId, true);
            // Execute all pending group requests
            ConcurrentMap<GroupKey, StoredGroupEntry> pendingGroupRequests =
                    getPendingGroupKeyTable(deviceId);
            for (Group group:pendingGroupRequests.values()) {
                GroupDescription tmp = new DefaultGroupDescription(
                                                                   group.deviceId(),
                                                                   group.type(),
                                                                   group.buckets(),
                                                                   group.appCookie(),
                                                                   group.givenGroupId(),
                                                                   group.appId());
                storeGroupDescriptionInternal(tmp);
            }
            getPendingGroupKeyTable(deviceId).clear();
        } else {
           if (deviceAuditStatus.getOrDefault(deviceId, false)) {
                log.debug("deviceInitialAuditCompleted: Clearing AUDIT "
                        + "status for device {}", deviceId);
                deviceAuditStatus.put(deviceId, false);
            }
        }
    }
}
 
Example #10
Source File: DistributedGroupStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void deviceInitialAuditCompleted(DeviceId deviceId,
                                        boolean completed) {
    synchronized (deviceAuditStatus) {
        if (completed) {
            log.debug("AUDIT completed for device {}",
                      deviceId);
            deviceAuditStatus.put(deviceId, true);
            // Execute all pending group requests
            List<StoredGroupEntry> pendingGroupRequests =
                    getPendingGroupKeyTable().values()
                            .stream()
                            .filter(g -> g.deviceId().equals(deviceId))
                            .collect(Collectors.toList());
            log.debug("processing pending group add requests for device {} and number of pending requests {}",
                      deviceId,
                      pendingGroupRequests.size());
            for (Group group : pendingGroupRequests) {
                GroupDescription tmp = new DefaultGroupDescription(
                        group.deviceId(),
                        group.type(),
                        group.buckets(),
                        group.appCookie(),
                        group.givenGroupId(),
                        group.appId());
                storeGroupDescriptionInternal(tmp);
                getPendingGroupKeyTable().
                        remove(new GroupStoreKeyMapKey(deviceId, group.appCookie()));
            }
        } else {
            Boolean audited = deviceAuditStatus.get(deviceId);
            if (audited != null && audited) {
                log.debug("Clearing AUDIT status for device {}", deviceId);
                deviceAuditStatus.put(deviceId, false);
            }
        }
    }
}
 
Example #11
Source File: DefaultOFSwitch.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processGroupMod(OFGroupMod groupMod) {
    log.debug("processing GROUP_MOD {} message", groupMod.getCommand());

    ApplicationId appId = ofSwitchService.appId();
    GroupKey appCookie = new DefaultGroupKey(networkId.toString().getBytes());
    switch (groupMod.getCommand()) {
        case ADD:
            // TODO return OFGroupModFailedCode.GROUP_EXISTS if group already exists
            int groupId = groupMod.getGroup().getGroupNumber();
            OFGroupAdd groupAdd = (OFGroupAdd) groupMod;
            GroupBuckets groupAddBuckets = new OFAgentVirtualGroupBucketEntryBuilder(
                    Dpid.dpid(Dpid.uri(dpid().getLong())),
                    groupAdd.getBuckets(), groupAdd.getGroupType(), driverService)
                    .build();
            GroupDescription groupDescription = new DefaultGroupDescription(
                    deviceId, getGroupType(groupAdd.getGroupType()), groupAddBuckets,
                    appCookie, groupId, appId);
            groupService.addGroup(groupDescription);
            break;
        case MODIFY:
            // TODO return OFGroupModFailedCode.INVALID_GROUP if group does not exist
            OFGroupModify groupModify = (OFGroupModify) groupMod;
            GroupBuckets groupModifyBuckets = new OFAgentVirtualGroupBucketEntryBuilder(
                    Dpid.dpid(Dpid.uri(dpid().getLong())),
                    groupModify.getBuckets(), groupModify.getGroupType(), driverService)
                    .build();
            groupService.setBucketsForGroup(deviceId, appCookie, groupModifyBuckets,
                                            appCookie, appId);
            break;
        case DELETE:
            groupService.removeGroup(deviceId, appCookie, appId);
            break;
        default:
            // INSERT_BUCKET, REMOVE_BUCKET are effective OF 1.5.  OFAgent supports 1.3.
            log.warn("Unsupported GROUP_MOD {} message received for switch {}",
                     groupMod.getCommand(), this);
    }
}
 
Example #12
Source File: SelectGroupHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates select type group description according to given deviceId.
 *
 * @param srcDeviceId target device id for group description
 * @param nodeList gateway node list for bucket action
 * @return created select type group description
 */
public GroupId createGatewayGroup(DeviceId srcDeviceId, List<GatewayNode> nodeList) {
    List<GroupBucket> bucketList = generateBucketsForSelectGroup(srcDeviceId, nodeList);
    GroupId groupId = getGroupId(srcDeviceId);
    GroupDescription groupDescription = new DefaultGroupDescription(
            srcDeviceId,
            GroupDescription.Type.SELECT,
            new GroupBuckets(bucketList),
            getGroupKey(srcDeviceId),
            groupId.id(),
            appId);

    groupService.addGroup(groupDescription);
    return groupId;
}
 
Example #13
Source File: Utils.java    From ngsdn-tutorial with Apache License 2.0 5 votes vote down vote up
private static GroupDescription buildReplicationGroup(
        ApplicationId appId,
        DeviceId deviceId,
        int groupId,
        Collection<PortNumber> ports,
        boolean isClone) {

    checkNotNull(deviceId);
    checkNotNull(appId);
    checkArgument(!ports.isEmpty());

    final GroupKey groupKey = new DefaultGroupKey(
            ByteBuffer.allocate(4).putInt(groupId).array());

    final List<GroupBucket> bucketList = ports.stream()
            .map(p -> DefaultTrafficTreatment.builder()
                    .setOutput(p).build())
            .map(t -> isClone ? createCloneGroupBucket(t)
                    : createAllGroupBucket(t))
            .collect(Collectors.toList());

    return new DefaultGroupDescription(
            deviceId,
            isClone ? GroupDescription.Type.CLONE : GroupDescription.Type.ALL,
            new GroupBuckets(bucketList),
            groupKey, groupId, appId);
}
 
Example #14
Source File: SimpleVirtualGroupStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void deviceInitialAuditCompleted(NetworkId networkId, DeviceId deviceId,
                                        boolean completed) {
    deviceAuditStatus.computeIfAbsent(networkId, k -> new HashMap<>());

    HashMap<DeviceId, Boolean> deviceAuditStatusByNetwork =
            deviceAuditStatus.get(networkId);

    synchronized (deviceAuditStatusByNetwork) {
        if (completed) {
            log.debug("deviceInitialAuditCompleted: AUDIT "
                              + "completed for device {}", deviceId);
            deviceAuditStatusByNetwork.put(deviceId, true);
            // Execute all pending group requests
            ConcurrentMap<GroupKey, StoredGroupEntry> pendingGroupRequests =
                    getPendingGroupKeyTable(networkId, deviceId);
            for (Group group:pendingGroupRequests.values()) {
                GroupDescription tmp = new DefaultGroupDescription(
                        group.deviceId(),
                        group.type(),
                        group.buckets(),
                        group.appCookie(),
                        group.givenGroupId(),
                        group.appId());
                storeGroupDescriptionInternal(networkId, tmp);
            }
            getPendingGroupKeyTable(networkId, deviceId).clear();
        } else {
            if (deviceAuditStatusByNetwork.get(deviceId)) {
                log.debug("deviceInitialAuditCompleted: Clearing AUDIT "
                                  + "status for device {}", deviceId);
                deviceAuditStatusByNetwork.put(deviceId, false);
            }
        }
    }
}
 
Example #15
Source File: OpenstackGroupRuleManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void setRule(ApplicationId appId, DeviceId deviceId, int groupId,
                    GroupDescription.Type type, List<GroupBucket> buckets,
                    boolean install) {
    if (install) {
        GroupDescription groupDesc = new DefaultGroupDescription(deviceId,
                type, new GroupBuckets(buckets), getGroupKey(groupId), groupId, appId);
        groupService.addGroup(groupDesc);
        log.info("Adding group rule {}", groupId);
    } else {
        groupService.removeGroup(deviceId, getGroupKey(groupId), appId);
        log.info("Removing group rule {}", groupId);
    }
}
 
Example #16
Source File: K8sGroupRuleManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void setRule(ApplicationId appId, DeviceId deviceId, int groupId,
                    Type type, List<GroupBucket> buckets, boolean install) {

    if (install) {
        GroupDescription groupDesc = new DefaultGroupDescription(deviceId,
                type, new GroupBuckets(buckets), getGroupKey(groupId), groupId, appId);
        groupService.addGroup(groupDesc);
    } else {
        groupService.removeGroup(deviceId, getGroupKey(groupId), appId);
    }
}
 
Example #17
Source File: NextObjectiveTranslator.java    From onos with Apache License 2.0 5 votes vote down vote up
private int selectGroup(NextObjective obj,
                        ObjectiveTranslation.Builder resultBuilder)
        throws FabricPipelinerException {

    final PiTableId hashedTableId = FabricConstants.FABRIC_INGRESS_NEXT_HASHED;
    final List<DefaultNextTreatment> defaultNextTreatments =
            defaultNextTreatments(obj.nextTreatments(), true);
    final List<TrafficTreatment> piTreatments = Lists.newArrayList();

    for (DefaultNextTreatment t : defaultNextTreatments) {
        // Map treatment to PI...
        piTreatments.add(mapTreatmentToPiIfNeeded(t.treatment(), hashedTableId));
        // ...and handle egress if necessary.
        handleEgress(obj, t.treatment(), resultBuilder, false);
    }

    final List<GroupBucket> bucketList = piTreatments.stream()
            .map(DefaultGroupBucket::createSelectGroupBucket)
            .collect(Collectors.toList());

    final int groupId = obj.id();
    final PiGroupKey groupKey = new PiGroupKey(
            hashedTableId,
            FabricConstants.FABRIC_INGRESS_NEXT_HASHED_SELECTOR,
            groupId);

    resultBuilder.addGroup(new DefaultGroupDescription(
            deviceId,
            GroupDescription.Type.SELECT,
            new GroupBuckets(bucketList),
            groupKey,
            groupId,
            obj.appId()));

    return groupId;
}
 
Example #18
Source File: DistributedGroupStoreTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests pushing group metrics.
 */
@Test
public void testPushGroupMetrics() {
    groupStore.deviceInitialAuditCompleted(deviceId1, true);
    groupStore.deviceInitialAuditCompleted(deviceId2, true);

    GroupDescription groupDescription3 = new DefaultGroupDescription(
            deviceId1,
            ALL,
            allGroupBuckets,
            new DefaultGroupKey("aaa".getBytes()),
            null,
            APP_ID);

    groupStore.storeGroupDescription(groupDescription1);
    groupStore.storeGroupDescription(groupDescription2);
    groupStore.storeGroupDescription(groupDescription3);
    Group group1 = groupStore.getGroup(deviceId1, groupId1);

    assertThat(group1, instanceOf(DefaultGroup.class));
    DefaultGroup defaultGroup1 = (DefaultGroup) group1;
    defaultGroup1.setPackets(55L);
    defaultGroup1.setBytes(66L);
    groupStore.pushGroupMetrics(deviceId1, ImmutableList.of(group1));

    // Make sure the group was updated.

    Group requeryGroup1 = groupStore.getGroup(deviceId1, groupId1);
    assertThat(requeryGroup1.packets(), is(55L));
    assertThat(requeryGroup1.bytes(), is(66L));

}
 
Example #19
Source File: AbstractCorsaPipeline.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void next(NextObjective nextObjective) {
    switch (nextObjective.type()) {
        case SIMPLE:
            Collection<TrafficTreatment> treatments = nextObjective.next();
            if (treatments.size() == 1) {
                TrafficTreatment treatment = treatments.iterator().next();
                CorsaTrafficTreatment corsaTreatment = processNextTreatment(treatment);
                final GroupKey key = new DefaultGroupKey(appKryo.serialize(nextObjective.id()));
                if (corsaTreatment.type() == CorsaTrafficTreatmentType.GROUP) {
                    GroupBucket bucket = DefaultGroupBucket.createIndirectGroupBucket(corsaTreatment.treatment());
                    GroupBuckets buckets = new GroupBuckets(Collections.singletonList(bucket));
                    // group id == null, let group service determine group id
                    GroupDescription groupDescription = new DefaultGroupDescription(deviceId,
                                                                                    GroupDescription.Type.INDIRECT,
                                                                                    buckets,
                                                                                    key,
                                                                                    null,
                                                                                    nextObjective.appId());
                    groupService.addGroup(groupDescription);
                    pendingGroups.put(key, nextObjective);
                } else if (corsaTreatment.type() == CorsaTrafficTreatmentType.ACTIONS) {
                    pendingNext.put(nextObjective.id(), nextObjective);
                    flowObjectiveStore.putNextGroup(nextObjective.id(), new CorsaGroup(key));
                    nextObjective.context().ifPresent(context -> context.onSuccess(nextObjective));
                }
            }
            break;
        case HASHED:
        case BROADCAST:
        case FAILOVER:
            fail(nextObjective, ObjectiveError.UNSUPPORTED);
            log.warn("Unsupported next objective type {}", nextObjective.type());
            break;
        default:
            fail(nextObjective, ObjectiveError.UNKNOWN);
            log.warn("Unknown next objective type {}", nextObjective.type());
    }

}
 
Example #20
Source File: Utils.java    From onos-p4-tutorial with Apache License 2.0 5 votes vote down vote up
private static GroupDescription buildReplicationGroup(
        ApplicationId appId,
        DeviceId deviceId,
        int groupId,
        Collection<PortNumber> ports,
        boolean isClone) {

    checkNotNull(deviceId);
    checkNotNull(appId);
    checkArgument(!ports.isEmpty());

    final GroupKey groupKey = new DefaultGroupKey(
            ByteBuffer.allocate(4).putInt(groupId).array());

    final List<GroupBucket> bucketList = ports.stream()
            .map(p -> DefaultTrafficTreatment.builder()
                    .setOutput(p).build())
            .map(t -> isClone ? createCloneGroupBucket(t)
                    : createAllGroupBucket(t))
            .collect(Collectors.toList());

    return new DefaultGroupDescription(
            deviceId,
            isClone ? GroupDescription.Type.CLONE : GroupDescription.Type.ALL,
            new GroupBuckets(bucketList),
            groupKey, groupId, appId);
}
 
Example #21
Source File: Utils.java    From onos-p4-tutorial with Apache License 2.0 5 votes vote down vote up
private static GroupDescription buildReplicationGroup(
        ApplicationId appId,
        DeviceId deviceId,
        int groupId,
        Collection<PortNumber> ports,
        boolean isClone) {

    checkNotNull(deviceId);
    checkNotNull(appId);
    checkArgument(!ports.isEmpty());

    final GroupKey groupKey = new DefaultGroupKey(
            ByteBuffer.allocate(4).putInt(groupId).array());

    final List<GroupBucket> bucketList = ports.stream()
            .map(p -> DefaultTrafficTreatment.builder()
                    .setOutput(p).build())
            .map(t -> isClone ? createCloneGroupBucket(t)
                    : createAllGroupBucket(t))
            .collect(Collectors.toList());

    return new DefaultGroupDescription(
            deviceId,
            isClone ? GroupDescription.Type.CLONE : GroupDescription.Type.ALL,
            new GroupBuckets(bucketList),
            groupKey, groupId, appId);
}
 
Example #22
Source File: GroupsWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Create new group rule. Creates and installs a new group rule for the
 * specified device.
 *
 * @param deviceId device identifier
 * @param stream   group rule JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel GroupsPost
 */
@POST
@Path("{deviceId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createGroup(@PathParam("deviceId") String deviceId,
                            InputStream stream) {
    GroupService groupService = get(GroupService.class);
    try {

        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode specifiedDeviceId = jsonTree.get("deviceId");

        if (specifiedDeviceId != null &&
                !specifiedDeviceId.asText().equals(deviceId)) {
            throw new IllegalArgumentException(DEVICE_INVALID);
        }
        jsonTree.put("deviceId", deviceId);
        Group group = codec(Group.class).decode(jsonTree, this);
        GroupDescription description = new DefaultGroupDescription(
                group.deviceId(), group.type(), group.buckets(),
                group.appCookie(), group.id().id(), group.appId());
        groupService.addGroup(description);
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("groups")
                .path(deviceId)
                .path(Long.toString(group.id().id()));
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example #23
Source File: Ofdpa3GroupHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to create a mpls tunnel label group.
 *
 * @param nextGroupId the next group in the chain
 * @param subtype the mpls tunnel label group subtype
 * @param index the index of the group
 * @param instructions the instructions to push
 * @param applicationId the application id
 * @return the group description
 */
private GroupDescription createMplsTunnelLabelGroup(int nextGroupId,
                                                    OfdpaMplsGroupSubType subtype,
                                                    int index,
                                                    List<Instruction> instructions,
                                                    ApplicationId applicationId) {
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    // We add all the instructions.
    instructions.forEach(treatment::add);
    // We point the group to the next group.
    treatment.group(new GroupId(nextGroupId));
    GroupBucket groupBucket = DefaultGroupBucket
            .createIndirectGroupBucket(treatment.build());
    // Finally we build the group description.
    int groupId = makeMplsLabelGroupId(subtype, index);
    GroupKey groupKey = new DefaultGroupKey(
            Ofdpa2Pipeline.appKryo.serialize(index)
    );
    return new DefaultGroupDescription(
            deviceId,
            INDIRECT,
            new GroupBuckets(Collections.singletonList(groupBucket)),
            groupKey,
            groupId,
            applicationId
    );
}
 
Example #24
Source File: Ofdpa3GroupHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to create a mpls l2 vpn group.
 *
 * @param nextGroupId the next group in the chain
 * @param index the index of the group
 * @param instructions the instructions to push
 * @param applicationId the application id
 * @return the group description
 */
private GroupDescription createMplsL2VpnGroup(int nextGroupId,
                                              int index,
                                              List<Instruction> instructions,
                                              ApplicationId applicationId) {
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    // We add the extensions and the instructions.
    treatment.extension(new Ofdpa3PushL2Header(), deviceId);
    treatment.pushVlan();
    instructions.forEach(treatment::add);
    treatment.extension(new Ofdpa3PushCw(), deviceId);
    // We point the group to the next group.
    treatment.group(new GroupId(nextGroupId));
    GroupBucket groupBucket = DefaultGroupBucket
            .createIndirectGroupBucket(treatment.build());
    // Finally we build the group description.
    int groupId = makeMplsLabelGroupId(OfdpaMplsGroupSubType.L2_VPN, index);
    GroupKey groupKey = new DefaultGroupKey(
            Ofdpa2Pipeline.appKryo.serialize(index)
    );
    return new DefaultGroupDescription(
            deviceId,
            INDIRECT,
            new GroupBuckets(Collections.singletonList(groupBucket)),
            groupKey,
            groupId,
            applicationId
    );
}
 
Example #25
Source File: Ofdpa2GroupHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void createL2MulticastGroup(NextObjective nextObj, VlanId vlanId,  List<GroupInfo> groupInfos) {
    // Realize & represent L2 multicast group in OFDPA driver layer
    // TODO : Need to identify significance of OfdpaNextGroup.
    Integer l2MulticastGroupId = L2_MULTICAST_TYPE | (vlanId.toShort() << 16);
    final GroupKey l2MulticastGroupKey = l2MulticastGroupKey(vlanId, deviceId);
    List<Deque<GroupKey>> l2MulticastAllGroup = Lists.newArrayList();
    groupInfos.forEach(groupInfo -> {
        Deque<GroupKey> groupKeyChain = new ArrayDeque<>();
        groupKeyChain.addFirst(groupInfo.innerMostGroupDesc().appCookie());
        groupKeyChain.addFirst(l2MulticastGroupKey);
        l2MulticastAllGroup.add(groupKeyChain);
    });
    OfdpaNextGroup ofdpaL2MulticastGroup = new OfdpaNextGroup(l2MulticastAllGroup, nextObj);
    updatePendingNextObjective(l2MulticastGroupKey, ofdpaL2MulticastGroup);
    // Group Chain Hierarchy creation using group service and thus in device level
    List<GroupBucket> l2McastBuckets = new ArrayList<>();
    groupInfos.forEach(groupInfo -> {
        // Points to L2 interface group directly.
        TrafficTreatment.Builder trafficTreatment = DefaultTrafficTreatment.builder();
        trafficTreatment.group(new GroupId(groupInfo.innerMostGroupDesc().givenGroupId()));
        GroupBucket bucket = DefaultGroupBucket.createAllGroupBucket(trafficTreatment.build());
        l2McastBuckets.add(bucket);
    });
    GroupDescription l2MulticastGroupDescription =
            new DefaultGroupDescription(
                    deviceId,
                    ALL,
                    new GroupBuckets(l2McastBuckets),
                    l2MulticastGroupKey,
                    l2MulticastGroupId,
                    nextObj.appId());
    GroupChainElem l2MulticastGce = new GroupChainElem(l2MulticastGroupDescription,
                                                       groupInfos.size(), false, deviceId);
    groupInfos.forEach(groupInfo -> {
        updatePendingGroups(groupInfo.innerMostGroupDesc().appCookie(), l2MulticastGce);
        groupService.addGroup(groupInfo.innerMostGroupDesc());
    });
}
 
Example #26
Source File: VtnManager.java    From onos with Apache License 2.0 4 votes vote down vote up
private void programGroupTable(DeviceId deviceId, ApplicationId appid,
                               PortNumber portNumber, Iterable<Device> devices, Objective.Operation type) {
    if (type.equals(Objective.Operation.REMOVE)) {
        return;
    }

    List<GroupBucket> buckets = Lists.newArrayList();
    Sets.newHashSet(devices)
    .stream()
    .filter(d -> d.type() == Device.Type.CONTROLLER)
    .filter(d -> !deviceId.equals(d.id()))
    .forEach(d -> {
                String ipAddress = d.annotations()
                         .value(CONTROLLER_IP_KEY);
                Ip4Address dst = Ip4Address.valueOf(ipAddress);
                Builder builder = DefaultTrafficTreatment.builder();

                DriverHandler handler = driverService.createHandler(deviceId);
                ExtensionTreatmentResolver resolver =  handler.behaviour(ExtensionTreatmentResolver.class);
                ExtensionTreatment treatment = resolver.getExtensionInstruction(NICIRA_SET_TUNNEL_DST.type());
                try {
                    treatment.setPropertyValue("tunnelDst", dst);
                } catch (Exception e) {
                   log.error("Failed to get extension instruction to set tunnel dst {}", deviceId);
                }

                builder.extension(treatment, deviceId);
                builder.setOutput(portNumber);
                GroupBucket bucket = DefaultGroupBucket
                        .createAllGroupBucket(builder.build());
                buckets.add(bucket);
             });
    final GroupKey key = new DefaultGroupKey(APP_ID.getBytes());
    GroupDescription groupDescription = new DefaultGroupDescription(deviceId,
                                                                    GroupDescription.Type.ALL,
                                                                    new GroupBuckets(buckets),
                                                                    key,
                                                                    L2ForwardServiceImpl.GROUP_ID,
                                                                    appid);
    groupService.addGroup(groupDescription);
}
 
Example #27
Source File: DistributedGroupStore.java    From onos with Apache License 2.0 4 votes vote down vote up
private void updateGroupDescriptionInternal(DeviceId deviceId,
                                            GroupKey oldAppCookie,
                                            UpdateType type,
                                            GroupBuckets newBuckets,
                                            GroupKey newAppCookie) {
    // Check if a group is existing with the provided key
    Group oldGroup = getGroup(deviceId, oldAppCookie);
    if (oldGroup == null) {
        log.warn("updateGroupDescriptionInternal: Group not found...strange. "
                         + "GroupKey:{} DeviceId:{}", oldAppCookie, deviceId);
        return;
    }

    List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup,
                                                           type,
                                                           newBuckets);
    if (newBucketList != null) {
        // Create a new group object from the old group
        GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
        GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie;
        GroupDescription updatedGroupDesc = new DefaultGroupDescription(
                oldGroup.deviceId(),
                oldGroup.type(),
                updatedBuckets,
                newCookie,
                oldGroup.givenGroupId(),
                oldGroup.appId());
        StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(),
                                                     updatedGroupDesc);
        log.debug("updateGroupDescriptionInternal: group entry {} in device {} moving from {} to PENDING_UPDATE",
                  oldGroup.id(),
                  oldGroup.deviceId(),
                  oldGroup.state());
        newGroup.setState(GroupState.PENDING_UPDATE);
        newGroup.setLife(oldGroup.life());
        newGroup.setPackets(oldGroup.packets());
        newGroup.setBytes(oldGroup.bytes());
        //Update the group entry in groupkey based map.
        //Update to groupid based map will happen in the
        //groupkey based map update listener
        log.debug("updateGroupDescriptionInternal with type {}: Group updated with buckets",
                  type);
        getGroupStoreKeyMap().
                put(new GroupStoreKeyMapKey(newGroup.deviceId(),
                                            newGroup.appCookie()), newGroup);
        notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup));
    } else {
        log.warn("updateGroupDescriptionInternal with type {}: No "
                         + "change in the buckets in update", type);
    }
}
 
Example #28
Source File: DistributedGroupStore.java    From onos with Apache License 2.0 4 votes vote down vote up
@Activate
public void activate(ComponentContext context) {
    cfgService.registerProperties(getClass());
    modified(context);
    KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
            .register(KryoNamespaces.API)
            .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
            .register(DefaultGroup.class,
                      DefaultGroupBucket.class,
                      DefaultGroupDescription.class,
                      DefaultGroupKey.class,
                      GroupDescription.Type.class,
                      Group.GroupState.class,
                      GroupBuckets.class,
                      GroupStoreMessage.class,
                      GroupStoreMessage.Type.class,
                      UpdateType.class,
                      GroupStoreMessageSubjects.class,
                      MultiValuedTimestamp.class,
                      GroupStoreKeyMapKey.class,
                      GroupStoreIdMapKey.class,
                      GroupStoreMapKey.class
            );

    clusterMsgSerializer = kryoBuilder.build("GroupStore");
    Serializer serializer = Serializer.using(clusterMsgSerializer);

    messageHandlingExecutor = Executors.
            newFixedThreadPool(MESSAGE_HANDLER_THREAD_POOL_SIZE,
                               groupedThreads("onos/store/group",
                                              "message-handlers",
                                              log));

    clusterCommunicator.addSubscriber(GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
                                      clusterMsgSerializer::deserialize,
                                      this::process,
                                      messageHandlingExecutor);

    log.debug("Creating Consistent map onos-group-store-keymap");

    groupStoreEntriesByKey = storageService.<GroupStoreKeyMapKey, StoredGroupEntry>consistentMapBuilder()
            .withName("onos-group-store-keymap")
            .withSerializer(serializer)
            .build();
    groupStoreEntriesByKey.addListener(mapListener);
    log.debug("Current size of groupstorekeymap:{}",
              groupStoreEntriesByKey.size());
    synchronizeGroupStoreEntries();

    log.debug("Creating GroupStoreId Map From GroupStoreKey Map");
    matchGroupEntries();
    executor = newSingleThreadScheduledExecutor(groupedThreads("onos/group", "store", log));
    statusChangeListener = status -> {
        if (status == Status.ACTIVE) {
            executor.execute(this::matchGroupEntries);
        }
    };
    groupStoreEntriesByKey.addStatusChangeListener(statusChangeListener);

    log.debug("Creating Consistent map pendinggroupkeymap");

    auditPendingReqQueue = storageService.<GroupStoreKeyMapKey, StoredGroupEntry>consistentMapBuilder()
            .withName("onos-pending-group-keymap")
            .withSerializer(serializer)
            .build();
    log.debug("Current size of pendinggroupkeymap:{}",
              auditPendingReqQueue.size());

    groupTopic = getOrCreateGroupTopic(serializer);
    groupTopic.subscribe(this::processGroupMessage);

    local = clusterService.getLocalNode().id();

    log.info("Started");
}
 
Example #29
Source File: SimpleGroupStore.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the existing group entry with the information
 * from group description.
 *
 * @param deviceId the device ID
 * @param oldAppCookie the current group key
 * @param type update type
 * @param newBuckets group buckets for updates
 * @param newAppCookie optional new group key
 */
@Override
public void updateGroupDescription(DeviceId deviceId,
                            GroupKey oldAppCookie,
                            UpdateType type,
                            GroupBuckets newBuckets,
                            GroupKey newAppCookie) {
    // Check if a group is existing with the provided key
    Group oldGroup = getGroup(deviceId, oldAppCookie);
    if (oldGroup == null) {
        return;
    }

    List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup,
                                                           type,
                                                           newBuckets);
    if (newBucketList != null) {
        // Create a new group object from the old group
        GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
        GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie;
        GroupDescription updatedGroupDesc = new DefaultGroupDescription(
                                                    oldGroup.deviceId(),
                                                    oldGroup.type(),
                                                    updatedBuckets,
                                                    newCookie,
                                                    oldGroup.givenGroupId(),
                                                    oldGroup.appId());
        StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(),
                                                 updatedGroupDesc);
        newGroup.setState(GroupState.PENDING_UPDATE);
        newGroup.setLife(oldGroup.life());
        newGroup.setPackets(oldGroup.packets());
        newGroup.setBytes(oldGroup.bytes());
        // Remove the old entry from maps and add new entry using new key
        ConcurrentMap<GroupKey, StoredGroupEntry> keyTable =
                getGroupKeyTable(oldGroup.deviceId());
        ConcurrentMap<GroupId, StoredGroupEntry> idTable =
                getGroupIdTable(oldGroup.deviceId());
        keyTable.remove(oldGroup.appCookie());
        idTable.remove(oldGroup.id());
        keyTable.put(newGroup.appCookie(), newGroup);
        idTable.put(newGroup.id(), newGroup);
        notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup));
    }
}
 
Example #30
Source File: Ofdpa2GroupHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
private List<GroupInfo> prepareL2UnfilteredGroup(NextObjective nextObj) {
    ImmutableList.Builder<GroupInfo> groupInfoBuilder = ImmutableList.builder();
    // break up broadcast next objective to multiple groups
    Collection<TrafficTreatment> treatments = nextObj.nextTreatments().stream()
            .filter(nt -> nt.type() == NextTreatment.Type.TREATMENT)
            .map(nt -> ((DefaultNextTreatment) nt).treatment())
            .collect(Collectors.toSet());
    Collection<Integer> nextIds = nextObj.nextTreatments().stream()
            .filter(nt -> nt.type() == NextTreatment.Type.ID)
            .map(nt -> ((IdNextTreatment) nt).nextId())
            .collect(Collectors.toSet());

    // Each treatment is converted to an L2 unfiltered group
    treatments.forEach(treatment -> {
        TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
        // Extract port information
        PortNumber port = treatment.allInstructions().stream()
                .map(instr -> (Instructions.OutputInstruction) instr)
                .map(instr -> instr.port())
                .findFirst().orElse(null);
        if (port == null) {
            log.debug("Skip bucket without output instruction");
            return;
        }
        tBuilder.setOutput(port);
        if (requireAllowVlanTransition()) {
            tBuilder.extension(new OfdpaSetAllowVlanTranslation(Ofdpa3AllowVlanTranslationType.ALLOW), deviceId);
        }

        // Build L2UG
        int l2ugk = l2UnfilteredGroupKey(deviceId, port.toLong());
        final GroupKey l2UnfilterGroupKey = new DefaultGroupKey(appKryo.serialize(l2ugk));
        int l2UnfilteredGroupId = L2_UNFILTERED_TYPE | ((int) port.toLong() & FOUR_NIBBLE_MASK);
        GroupBucket l2UnfilteredGroupBucket = DefaultGroupBucket.createIndirectGroupBucket(tBuilder.build());
        GroupDescription l2UnfilteredGroupDesc = new DefaultGroupDescription(deviceId,
                GroupDescription.Type.INDIRECT,
                new GroupBuckets(Collections.singletonList(l2UnfilteredGroupBucket)),
                l2UnfilterGroupKey,
                l2UnfilteredGroupId,
                nextObj.appId());
        log.debug("Trying L2-Unfiltered: device:{} gid:{} gkey:{} nextid:{}",
                deviceId, Integer.toHexString(l2UnfilteredGroupId), l2UnfilterGroupKey, nextObj.id());
        groupInfoBuilder.add(new GroupInfo(l2UnfilteredGroupDesc, l2UnfilteredGroupDesc));
    });
    // Save the current count
    int counts = groupInfoBuilder.build().size();
    // Lookup each nextId in the store and obtain the group information
    nextIds.forEach(nextId -> {
        NextGroup nextGroup = flowObjectiveStore.getNextGroup(nextId);
        if (nextGroup != null) {
            List<Deque<GroupKey>> allActiveKeys = appKryo.deserialize(nextGroup.data());
            GroupKey topGroupKey = allActiveKeys.get(0).getFirst();
            GroupDescription groupDesc = groupService.getGroup(deviceId, topGroupKey);
            if (groupDesc != null) {
                log.debug("Trying L2-Hash device:{} gid:{}, gkey:{}, nextid:{}",
                          deviceId, Integer.toHexString(((Group) groupDesc).id().id()), topGroupKey, nextId);
                groupInfoBuilder.add(new GroupInfo(groupDesc, groupDesc));
            } else {
                log.error("Not found L2-Hash device:{}, gkey:{}, nextid:{}", deviceId, topGroupKey, nextId);
            }
        } else {
            log.error("Not found NextGroup device:{}, nextid:{}", deviceId, nextId);
        }
    });
    // Compare the size before and after to detect problems during the creation
    ImmutableList<GroupInfo> groupInfos = groupInfoBuilder.build();
    return (counts + nextIds.size()) == groupInfos.size() ? groupInfos : ImmutableList.of();
}