Java源码示例:org.onosproject.net.group.GroupService

示例1
/**
 * Returns a group with the given deviceId and appCookie.
 *
 * @param deviceId device identifier
 * @param appCookie group key
 * @return 200 OK with a group entry in the system
 * @onos.rsModel Group
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{deviceId}/{appCookie}")
public Response getGroupByDeviceIdAndAppCookie(@PathParam("deviceId") String deviceId,
                                               @PathParam("appCookie") String appCookie) {
    GroupService groupService = get(GroupService.class);
    final DeviceId deviceIdInstance = DeviceId.deviceId(deviceId);

    final GroupKey appCookieInstance = createKey(appCookie);

    Group group = nullIsNotFound(groupService.getGroup(deviceIdInstance, appCookieInstance),
            GROUP_NOT_FOUND);

    groupsNode.add(codec(Group.class).encode(group, this));
    return ok(root).build();
}
 
示例2
/**
 * Removes buckets from a group using the group service.
 *
 * @param deviceIdString device Id
 * @param appCookieString application cookie
 * @param bucketIds comma separated list of bucket Ids to remove
 */
private void removeGroupBuckets(String deviceIdString, String appCookieString, String bucketIds) {
    DeviceId deviceId = DeviceId.deviceId(deviceIdString);
    final GroupKey groupKey = createKey(appCookieString);
    GroupService groupService = get(GroupService.class);

    Group group = nullIsNotFound(groupService.getGroup(deviceId, groupKey), GROUP_NOT_FOUND);

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

    List<String> bucketsToRemove = ImmutableList.copyOf(bucketIds.split(","));

    bucketsToRemove.forEach(
            bucketIdToRemove -> {
                group.buckets().buckets().stream()
                        .filter(bucket -> Integer.toString(bucket.hashCode()).equals(bucketIdToRemove))
                        .forEach(groupBucketList::add);
            }
    );
    groupService.removeBucketsFromGroup(deviceId, groupKey,
                                        new GroupBuckets(groupBucketList), groupKey,
                                        group.appId());
}
 
示例3
/**
 * Returns the set of existing output ports in the group represented by
 * allActiveKeys.
 *
 * @param allActiveKeys list of group key chain
 * @param groupService the group service to get group information
 * @param deviceId the device id to get group
 * @return a set of output port from the list of group key chain
 */
public static Set<PortNumber> getExistingOutputPorts(List<Deque<GroupKey>> allActiveKeys,
                                                 GroupService groupService,
                                                 DeviceId deviceId) {
    Set<PortNumber> existingPorts = Sets.newHashSet();

    allActiveKeys.forEach(keyChain -> {
        GroupKey ifaceGroupKey = keyChain.peekLast();
        Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
        if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
            ifaceGroup.buckets().buckets().forEach(bucket -> {
                PortNumber portNumber = readOutPortFromTreatment(bucket.treatment());
                if (portNumber != null) {
                    existingPorts.add(portNumber);
                }
            });
        }
    });
    return existingPorts;
}
 
示例4
static Group retrieveTopLevelGroup(List<Deque<GroupKey>> allActiveKeys,
                                   DeviceId deviceId,
                                   GroupService groupService,
                                   int nextid) {
    GroupKey topLevelGroupKey;
    if (!allActiveKeys.isEmpty()) {
        topLevelGroupKey = allActiveKeys.get(0).peekFirst();
    } else {
        log.warn("Could not determine top level group while processing"
                         + "next:{} in dev:{}", nextid, deviceId);
        return null;
    }
    Group topGroup = groupService.getGroup(deviceId, topLevelGroupKey);
    if (topGroup == null) {
        log.warn("Could not find top level group while processing "
                         + "next:{} in dev:{}", nextid, deviceId);
    }
    return topGroup;
}
 
示例5
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;

    serviceDirectory = context.directory();
    coreService = serviceDirectory.get(CoreService.class);
    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    groupService = serviceDirectory.get(GroupService.class);
    flowObjectiveStore = context.store();
    deviceService = serviceDirectory.get(DeviceService.class);
    // Init the accumulator, if enabled
    if (isAccumulatorEnabled(this)) {
        accumulator = new ForwardingObjectiveAccumulator(context.accumulatorMaxObjectives(),
                context.accumulatorMaxBatchMillis(),
                context.accumulatorMaxIdleMillis());
    }

    initDriverId();
    initGroupHander(context);

    initializePipeline();
}
 
示例6
@Override
protected void doExecute() {
    DeviceService deviceService = get(DeviceService.class);
    GroupService groupService = get(GroupService.class);
    SortedMap<Device, List<Group>> sortedGroups =
            getSortedGroups(deviceService, groupService);

    if (referencedOnly && unreferencedOnly) {
        print("Options -r and -u cannot be used at the same time");
        return;
    }

    if (outputJson()) {
        print("%s", json(sortedGroups));
    } else {
        sortedGroups.forEach((device, groups) -> printGroups(device.id(), groups));
    }
}
 
示例7
private DefaultOFSwitch(DatapathId dpid, OFSwitchCapabilities capabilities,
                        NetworkId networkId, DeviceId deviceId,
                        ServiceDirectory serviceDirectory) {
    this.dpId = dpid;
    this.capabilities = capabilities;
    this.networkId = networkId;
    this.deviceId = deviceId;
    this.ofSwitchService = serviceDirectory.get(OFSwitchService.class);
    this.driverService = serviceDirectory.get(DriverService.class);
    this.virtualNetworkAdminService = serviceDirectory.get(VirtualNetworkAdminService.class);
    VirtualNetworkService virtualNetworkService = serviceDirectory.get(VirtualNetworkService.class);
    this.flowRuleService = virtualNetworkService.get(networkId, FlowRuleService.class);
    this.groupService = virtualNetworkService.get(networkId, GroupService.class);
    this.meterService = virtualNetworkService.get(networkId, MeterService.class);

    log = LoggerFactory.getLogger(OFAgent.TRACER_LOG_TENANT_ID_PREFIX + virtualNetworkService.getTenantId(networkId)
                                          + " " + getClass().getSimpleName() + " : " + dpid);
}
 
示例8
/**
 * Returns all groups of all devices.
 *
 * @return 200 OK with array of all the groups in the system
 * @onos.rsModel Groups
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getGroups() {
    GroupService groupService = get(GroupService.class);
    final Iterable<Device> devices = get(DeviceService.class).getDevices();
    devices.forEach(device -> {
        final Iterable<Group> groups = groupService.getGroups(device.id());
        if (groups != null) {
            groups.forEach(group -> groupsNode.add(codec(Group.class).encode(group, this)));
        }
    });

    return ok(root).build();
}
 
示例9
/**
 * Returns all groups associated with the given device.
 *
 * @param deviceId device identifier
 * @return 200 OK with array of all the groups in the system
 * @onos.rsModel Groups
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{deviceId}")
public Response getGroupsByDeviceId(@PathParam("deviceId") String deviceId) {
    GroupService groupService = get(GroupService.class);
    final Iterable<Group> groups = groupService.getGroups(DeviceId.deviceId(deviceId));

    groups.forEach(group -> groupsNode.add(codec(Group.class).encode(group, this)));

    return ok(root).build();
}
 
示例10
/**
 * 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);
    }
}
 
示例11
/**
 * Removes the specified group.
 *
 * @param deviceId  device identifier
 * @param appCookie application cookie to be used for lookup
 * @return 204 NO CONTENT
 */
@DELETE
@Path("{deviceId}/{appCookie}")
public Response deleteGroupByDeviceIdAndAppCookie(@PathParam("deviceId") String deviceId,
                                                  @PathParam("appCookie") String appCookie) {
    GroupService groupService = get(GroupService.class);
    DeviceId deviceIdInstance = DeviceId.deviceId(deviceId);

    final GroupKey appCookieInstance = createKey(appCookie);

    groupService.removeGroup(deviceIdInstance, appCookieInstance, null);
    return Response.noContent().build();
}
 
示例12
/**
 * Sets up the global values for all the tests.
 */
@Before
public void setUpTest() {
    // Mock device service
    expect(mockDeviceService.getDevice(deviceId1))
            .andReturn(device1);
    expect(mockDeviceService.getDevice(deviceId2))
            .andReturn(device2);
    expect(mockDeviceService.getDevices())
            .andReturn(ImmutableSet.of(device1, device2));

    // Mock Core Service
    expect(mockCoreService.getAppId(anyShort()))
            .andReturn(NetTestTools.APP_ID).anyTimes();
    expect(mockCoreService.registerApplication(GroupCodec.REST_APP_ID))
            .andReturn(APP_ID).anyTimes();
    replay(mockCoreService);

    // Register the services needed for the test
    final CodecManager codecService = new CodecManager();
    codecService.activate();
    ServiceDirectory testDirectory =
            new TestServiceDirectory()
                    .add(GroupService.class, mockGroupService)
                    .add(DeviceService.class, mockDeviceService)
                    .add(CodecService.class, codecService)
                    .add(CoreService.class, mockCoreService);

    setServiceDirectory(testDirectory);
}
 
示例13
@Override
protected void populateTable(TableModel tm, ObjectNode payload) {
    String uri = string(payload, "devId");
    if (!Strings.isNullOrEmpty(uri)) {
        DeviceId deviceId = DeviceId.deviceId(uri);
        GroupService gs = get(GroupService.class);
        for (Group group : gs.getGroups(deviceId)) {
            populateRow(tm.addRow(), group);
        }
    }
}
 
示例14
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;

    serviceDirectory = context.directory();
    coreService = serviceDirectory.get(CoreService.class);
    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    groupService = serviceDirectory.get(GroupService.class);
    meterService = serviceDirectory.get(MeterService.class);
    deviceService = serviceDirectory.get(DeviceService.class);
    flowObjectiveStore = context.store();

    appId = coreService.registerApplication(APPLICATION_ID);

    device = deviceService.getDevice(deviceId);
    deviceHwVersion = device.hwVersion();

    //Initialization of model specific features
    log.debug("HP Driver - Initializing unsupported features for switch {}", deviceHwVersion);
    initUnSupportedFeatures();

    log.debug("HP Driver - Initializing features supported in hardware");
    initHardwareCriteria();
    initHardwareInstructions();

    log.debug("HP Driver - Initializing pipeline");
    installHPTableZero();
    installHPHardwareTable();
    installHPSoftwareTable();
}
 
示例15
/**
 * Returns a list of all indices in the allActiveKeys list (that represents
 * a group) if the list element (a bucket or group-chain) has treatments
 * that match the given outport and label.
 *
 * @param allActiveKeys the representation of the group
 * @param groupService groups service for querying group information
 * @param deviceId the device id for the device that contains the group
 * @param portToMatch the port to match in the group buckets
 * @param labelToMatch the MPLS label-id to match in the group buckets
 * @return a list of indexes in the allActiveKeys list where the list element
 *         has treatments that match the given portToMatch and labelToMatch.
 *         Could be empty if no list elements were found to match the given
 *         port and label.
 */
public static List<Integer> existingPortAndLabel(
                                           List<Deque<GroupKey>> allActiveKeys,
                                           GroupService groupService,
                                           DeviceId deviceId,
                                           PortNumber portToMatch,
                                           int labelToMatch) {
    List<Integer> indices = new ArrayList<>();
    int index = 0;
    for (Deque<GroupKey> keyChain : allActiveKeys) {
        GroupKey ifaceGroupKey = keyChain.peekLast();
        Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
        if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
            PortNumber portNumber = readOutPortFromTreatment(
               ifaceGroup.buckets().buckets().iterator().next().treatment());
            if (portNumber != null && portNumber.equals(portToMatch)) {
                // check for label in the 2nd group of this chain
                GroupKey secondKey = (GroupKey) keyChain.toArray()[1];
                Group secondGroup = groupService.getGroup(deviceId, secondKey);
                if (secondGroup != null &&
                        !secondGroup.buckets().buckets().isEmpty()) {
                    int label = readLabelFromTreatment(
                                    secondGroup.buckets().buckets()
                                    .iterator().next().treatment());
                    if (label == labelToMatch) {
                        indices.add(index);
                    }
                }
            }
        }
        index++;
    }

    return indices;
}
 
示例16
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    log.debug("Initiate OLT pipeline");
    this.serviceDirectory = context.directory();
    this.deviceId = deviceId;

    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    coreService = serviceDirectory.get(CoreService.class);
    groupService = serviceDirectory.get(GroupService.class);
    flowObjectiveStore = context.store();
    storageService = serviceDirectory.get(StorageService.class);

    appId = coreService.registerApplication(
            "org.onosproject.driver.OLTPipeline");


    pendingGroups = CacheBuilder.newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
                if (notification.getCause() == RemovalCause.EXPIRED) {
                    fail(notification.getValue(), ObjectiveError.GROUPINSTALLATIONFAILED);
                }
            }).build();

    groupService.addListener(new InnerGroupListener());

}
 
示例17
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.serviceDirectory = context.directory();
    this.deviceId = deviceId;

    pendingGroups = CacheBuilder.newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
                if (notification.getCause() == RemovalCause.EXPIRED) {
                    fail(notification.getValue(), ObjectiveError.GROUPINSTALLATIONFAILED);
                }
            }).build();

    groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);

    coreService = serviceDirectory.get(CoreService.class);
    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    groupService = serviceDirectory.get(GroupService.class);
    flowObjectiveStore = context.store();

    groupService.addListener(new InnerGroupListener());

    appId = coreService.registerApplication(
            "org.onosproject.driver.CentecV350Pipeline");

    initializePipeline();
}
 
示例18
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.serviceDirectory = context.directory();
    this.deviceId = deviceId;

    pendingGroups = CacheBuilder
            .newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
                                 if (notification.getCause() == RemovalCause.EXPIRED) {
                                     fail(notification.getValue(),
                                          ObjectiveError.GROUPINSTALLATIONFAILED);
                                 }
                             }).build();

    coreService = serviceDirectory.get(CoreService.class);
    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    groupService = serviceDirectory.get(GroupService.class);
    flowObjectiveStore = context.store();

    groupService.addListener(new InnerGroupListener());

    appId = coreService
            .registerApplication("org.onosproject.driver.SpringOpenTTP");

    setTableMissEntries();
    log.info("Spring Open TTP driver initialized");
}
 
示例19
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    log.debug("Initiate OLT pipeline");
    this.serviceDirectory = context.directory();
    this.deviceId = deviceId;

    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    coreService = serviceDirectory.get(CoreService.class);
    groupService = serviceDirectory.get(GroupService.class);
    flowObjectiveStore = context.store();
    storageService = serviceDirectory.get(StorageService.class);

    appId = coreService.registerApplication(
            "org.onosproject.driver.OLTPipeline");


    pendingGroups = CacheBuilder.newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
                if (notification.getCause() == RemovalCause.EXPIRED) {
                    fail(notification.getValue(), ObjectiveError.GROUPINSTALLATIONFAILED);
                }
            }).build();

    groupService.addListener(new InnerGroupListener());

}
 
示例20
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;
    this.flowRuleService = context.directory().get(FlowRuleService.class);
    this.groupService = context.directory().get(GroupService.class);
    this.flowObjectiveStore = context.directory().get(FlowObjectiveStore.class);
    this.filteringTranslator = new FilteringObjectiveTranslator(deviceId, capabilities);
    this.forwardingTranslator = new ForwardingObjectiveTranslator(deviceId, capabilities);
    this.nextTranslator = new NextObjectiveTranslator(deviceId, capabilities);
}
 
示例21
/**
 * Returns the list of devices sorted using the device ID URIs.
 *
 * @param deviceService device service
 * @param groupService group service
 * @return sorted device list
 */
protected SortedMap<Device, List<Group>> getSortedGroups(DeviceService deviceService, GroupService groupService) {
    final GroupState groupsState = (this.state != null && !"any".equals(this.state)) ?
            GroupState.valueOf(this.state.toUpperCase()) :
            null;
    final Iterable<Device> devices = Optional.ofNullable(uri)
            .map(DeviceId::deviceId)
            .map(deviceService::getDevice)
            .map(dev -> (Iterable<Device>) Collections.singletonList(dev))
            .orElse(deviceService.getDevices());

    SortedMap<Device, List<Group>> sortedGroups = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
    for (Device d : devices) {
        Stream<Group> groupStream = Lists.newArrayList(groupService.getGroups(d.id())).stream();
        if (groupsState != null) {
            groupStream = groupStream.filter(g -> g.state().equals(groupsState));
        }
        if (referencedOnly) {
            groupStream = groupStream.filter(g -> g.referenceCount() != 0);
        }
        if (type != null && !"any".equals(type)) {
            groupStream = groupStream.filter(g ->
                    g.type().equals(GroupDescription.Type.valueOf(type.toUpperCase())));
        }
        if (unreferencedOnly) {
            groupStream = groupStream.filter(g -> g.referenceCount() == 0);
        }
        sortedGroups.put(d, groupStream.sorted(Comparators.GROUP_COMPARATOR).collect(Collectors.toList()));
    }
    return sortedGroups;
}
 
示例22
private void wipeOutGroups() {
    print("Wiping groups");
    GroupService groupService = get(GroupService.class);
    DeviceAdminService deviceAdminService = get(DeviceAdminService.class);
    for (Device device : deviceAdminService.getDevices()) {
        groupService.purgeGroupEntries(device.id());
    }
}
 
示例23
/**
 * Create a new vnet service instance.
 *
 * @param serviceKey service key
 * @return vnet service
 */
private VnetService create(ServiceKey serviceKey) {
    VirtualNetwork network = getVirtualNetwork(serviceKey.networkId());
    checkNotNull(network, NETWORK_NULL);

    VnetService service;
    if (serviceKey.serviceClass.equals(DeviceService.class)) {
        service = new VirtualNetworkDeviceManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(LinkService.class)) {
        service = new VirtualNetworkLinkManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(TopologyService.class)) {
        service = new VirtualNetworkTopologyManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(IntentService.class)) {
        service = new VirtualNetworkIntentManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(HostService.class)) {
        service = new VirtualNetworkHostManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(PathService.class)) {
        service = new VirtualNetworkPathManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(FlowRuleService.class)) {
        service = new VirtualNetworkFlowRuleManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(PacketService.class)) {
        service = new VirtualNetworkPacketManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(GroupService.class)) {
        service = new VirtualNetworkGroupManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(MeterService.class)) {
        service = new VirtualNetworkMeterManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(FlowObjectiveService.class)) {
        service = new VirtualNetworkFlowObjectiveManager(this, network.id());
    } else if (serviceKey.serviceClass.equals(MastershipService.class) ||
            serviceKey.serviceClass.equals(MastershipAdminService.class) ||
            serviceKey.serviceClass.equals(MastershipTermService.class)) {
        service = new VirtualNetworkMastershipManager(this, network.id());
    } else {
        return null;
    }
    networkServices.put(serviceKey, service);
    return service;
}
 
示例24
/**
 * Tests that the get() method returns saved service instances.
 */
@Test
public void testServiceGetReturnsSavedInstance() {
    manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
    VirtualNetwork virtualNetwork =
            manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));

    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), DeviceService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), LinkService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), TopologyService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), HostService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), PathService.class);

    // extra setup needed for FlowRuleService, PacketService, GroupService, and IntentService
    VirtualProviderManager virtualProviderManager = new VirtualProviderManager();
    virtualProviderManager.registerProvider(new DefaultVirtualFlowRuleProvider());
    virtualProviderManager.registerProvider(new DefaultVirtualPacketProvider());
    virtualProviderManager.registerProvider(new DefaultVirtualGroupProvider());
    testDirectory.add(CoreService.class, coreService)
            .add(VirtualProviderRegistryService.class, virtualProviderManager)
            .add(EventDeliveryService.class, new TestEventDispatcher())
            .add(ClusterService.class, new ClusterServiceAdapter())
            .add(VirtualNetworkFlowRuleStore.class, new SimpleVirtualFlowRuleStore())
            .add(VirtualNetworkPacketStore.class, new SimpleVirtualPacketStore())
            .add(VirtualNetworkGroupStore.class, new SimpleVirtualGroupStore())
            .add(VirtualNetworkIntentStore.class, new SimpleVirtualIntentStore())
            .add(VirtualNetworkFlowObjectiveStore.class, new SimpleVirtualFlowObjectiveStore());

    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), FlowRuleService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), FlowObjectiveService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), PacketService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), GroupService.class);
    validateServiceGetReturnsSavedInstance(virtualNetwork.id(), IntentService.class);
}
 
示例25
@Override
public void loadGroupNib() {
    GroupService groupService = get(GroupService.class);
    DeviceService deviceService = get(DeviceService.class);
    Set<Group> groups = new HashSet<>();

    Lists.newArrayList(deviceService.getDevices().iterator())
            .forEach(device -> groups.addAll(Lists.newArrayList(
                    groupService.getGroups(device.id()))));

    GroupNib groupNib = GroupNib.getInstance();
    groupNib.setGroups(groups);
}
 
示例26
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;
    this.flowRuleService = context.directory().get(FlowRuleService.class);
    this.groupService = context.directory().get(GroupService.class);
}
 
示例27
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;
    this.flowRuleService = context.directory().get(FlowRuleService.class);
    this.groupService = context.directory().get(GroupService.class);
}
 
示例28
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;
    this.flowRuleService = context.directory().get(FlowRuleService.class);
    this.groupService = context.directory().get(GroupService.class);
}
 
示例29
/**
 * Get indices to remove comparing next group with next objective.
 *
 * @param allActiveKeys the representation of the group
 * @param nextObjective the next objective to verify
 * @param groupService groups service for querying group information
 * @param deviceId the device id for the device that contains the group
 * @return a list of indexes in the allActiveKeys to remove.
 */
public static List<Integer> indicesToRemoveFromNextGroup(List<Deque<GroupKey>> allActiveKeys,
                                                   NextObjective nextObjective,
                                                   GroupService groupService,
                                                   DeviceId deviceId) {
    List<Integer> indicesToRemove = Lists.newArrayList();
    int index = 0;
    // Iterate over the chain in the next data
    for (Deque<GroupKey> keyChain : allActiveKeys) {
        // Valid chain should have at least two elements
        if (keyChain.size() >= 2) {
            // Get last group (l2if) and retrieve port number
            GroupKey ifaceGroupKey = keyChain.peekLast();
            Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
            if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
                PortNumber portNumber = readOutPortFromTreatment(
                        ifaceGroup.buckets().buckets().iterator().next().treatment());
                // If there is not a port number continue
                if (portNumber != null) {
                    // check for label in the 2nd group of this chain
                    GroupKey secondKey = (GroupKey) keyChain.toArray()[1];
                    Group secondGroup = groupService.getGroup(deviceId, secondKey);
                    // If there is not a second group or there are no buckets continue
                    if (secondGroup != null && !secondGroup.buckets().buckets().isEmpty()) {
                        // Get label or -1
                        int label = readLabelFromTreatment(
                                secondGroup.buckets().buckets()
                                        .iterator().next().treatment());
                        // Iterate over the next treatments looking for the port and the label
                        boolean matches = false;
                        for (TrafficTreatment t : nextObjective.next()) {
                            PortNumber tPort = readOutPortFromTreatment(t);
                            int tLabel = readLabelFromTreatment(t);
                            if (tPort != null && tPort.equals(portNumber) && tLabel == label) {
                                // We found it, exit
                                matches = true;
                                break;
                            }
                        }
                        // Not found, we have to remove it
                        if (!matches) {
                            indicesToRemove.add(index);
                        }
                    }
                }
            }
        }
        index++;
    }
    return indicesToRemove;
}
 
示例30
@Override
protected void doExecute() {
    FlowRuleService flowRuleService = get(FlowRuleService.class);
    GroupService groupService = get(GroupService.class);
    CoreService coreService = get(CoreService.class);
    K8sNodeService k8sNodeService = get(K8sNodeService.class);
    ApplicationId appId = coreService.getAppId(K8S_NETWORKING_APP_ID);

    if (appId == null) {
        error("Failed to purge kubernetes networking flow rules.");
        return;
    }

    flowRuleService.removeFlowRulesById(appId);
    print("Successfully purged flow rules installed by kubernetes networking app.");

    boolean result = true;
    long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;

    // we make sure all flow rules are removed from the store
    while (stream(flowRuleService.getFlowEntriesById(appId)
            .spliterator(), false).count() > 0) {

        long  waitMs = timeoutExpiredMs - System.currentTimeMillis();

        try {
            sleep(SLEEP_MS);
        } catch (InterruptedException e) {
            log.error("Exception caused during rule purging...");
        }

        if (stream(flowRuleService.getFlowEntriesById(appId)
                .spliterator(), false).count() == 0) {
            break;
        } else {
            flowRuleService.removeFlowRulesById(appId);
            print("Failed to purging flow rules, retrying rule purging...");
        }

        if (waitMs <= 0) {
            result = false;
            break;
        }
    }

    for (K8sNode node : k8sNodeService.completeNodes()) {
        for (Group group : groupService.getGroups(node.intgBridge(), appId)) {
            groupService.removeGroup(node.intgBridge(), group.appCookie(), appId);
        }
    }

    if (result) {
        print("Successfully purged flow rules!");
    } else {
        error("Failed to purge flow rules.");
    }
}