Java Code Examples for org.onosproject.core.CoreService#getAppId()

The following examples show how to use org.onosproject.core.CoreService#getAppId() . 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: FlowsListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Prints flows.
 *
 * @param d     the device
 * @param flows the set of flows for that device
 * @param coreService core system service
 */
protected void printFlows(Device d, List<FlowEntry> flows,
                          CoreService coreService) {
    List<FlowEntry> filteredFlows = filterFlows(flows);
    boolean empty = filteredFlows == null || filteredFlows.isEmpty();
    print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
    if (empty || countOnly) {
        return;
    }

    for (FlowEntry f : filteredFlows) {
        if (shortOutput) {
            print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
                    f.table(), f.priority(), f.selector().criteria(),
                    printTreatment(f.treatment()));
        } else {
            ApplicationId appId = coreService.getAppId(f.appId());
            print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
                    f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.table(),
                    appId != null ? appId.name() : "<none>",
                    f.selector().criteria(), f.treatment());
        }
    }
}
 
Example 2
Source File: SdnIpCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the encapsulation type for SDN-IP.
 *
 * @param encap the encapsulation type
 */
private void setEncap(String encap) {
    EncapsulationType encapType = EncapsulationType.enumFromString(encap);
    if (encapType.equals(EncapsulationType.NONE) &&
            !encapType.toString().equals(encap)) {
        print(ENCAP_NOT_FOUND, encap);
        return;
    }

    NetworkConfigService configService = get(NetworkConfigService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(SdnIp.SDN_IP_APP);

    SdnIpConfig config = configService.addConfig(appId, SdnIpConfig.class);

    config.setEncap(encapType);
    config.apply();

    //configService.applyConfig(appId, SdnIpConfig.class, config.node());
}
 
Example 3
Source File: FlowRuleCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectNode encode(FlowRule flowRule, CodecContext context) {
    checkNotNull(flowRule, "Flow rule cannot be null");

    CoreService service = context.getService(CoreService.class);
    ApplicationId appId = service.getAppId(flowRule.appId());
    String strAppId = (appId == null) ? "<none>" : appId.name();

    final ObjectNode result = context.mapper().createObjectNode()
            .put(ID, Long.toString(flowRule.id().value()))
            .put(APP_ID, strAppId)
            .put(PRIORITY, flowRule.priority())
            .put(TIMEOUT, flowRule.timeout())
            .put(IS_PERMANENT, flowRule.isPermanent())
            .put(DEVICE_ID, flowRule.deviceId().toString())
            .put(TABLE_ID, flowRule.tableId())
            .put(TABLE_NAME, flowRule.table().toString());

    if (flowRule.treatment() != null) {
        final JsonCodec<TrafficTreatment> treatmentCodec =
                context.codec(TrafficTreatment.class);
        result.set(TREATMENT, treatmentCodec.encode(flowRule.treatment(), context));
    }

    if (flowRule.selector() != null) {
        final JsonCodec<TrafficSelector> selectorCodec =
                context.codec(TrafficSelector.class);
        result.set(SELECTOR, selectorCodec.encode(flowRule.selector(), context));
    }

    return result;
}
 
Example 4
Source File: ApplicationsWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Gets applicationId entry by either id or name.
 *
 * @param id   id of application
 * @param name name of application
 * @return 200 OK; 404; 401
 * @onos.rsModel ApplicationId
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("ids/entry")
public Response getAppIdByName(@QueryParam("id") String id,
                               @QueryParam("name") String name) {
    CoreService service = get(CoreService.class);
    ApplicationId appId = null;
    if (id != null) {
        appId = service.getAppId(Short.valueOf(id));
    } else if (name != null) {
        appId = service.getAppId(name);
    }
    return response(appId);
}
 
Example 5
Source File: OpenstackConfigArpModeCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
private void purgeRules() {
    FlowRuleService flowRuleService = get(FlowRuleService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(Constants.OPENSTACK_NETWORKING_APP_ID);
    if (appId == null) {
        error("Failed to purge OpenStack networking flow rules.");
        return;
    }
    flowRuleService.removeFlowRulesById(appId);
}
 
Example 6
Source File: OpenstackConfigStatefulSnatCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
private void purgeRules() {
    FlowRuleService flowRuleService = get(FlowRuleService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(Constants.OPENSTACK_NETWORKING_APP_ID);
    if (appId == null) {
        error("Failed to purge OpenStack networking flow rules.");
        return;
    }
    flowRuleService.removeFlowRulesById(appId);
}
 
Example 7
Source File: AddSpeakerCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    NetworkConfigService configService = get(NetworkConfigService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(RoutingService.ROUTER_APP_ID);

    BgpConfig config = configService.addConfig(appId, BgpConfig.class);

    if (name != null) {
        BgpConfig.BgpSpeakerConfig speaker = config.getSpeakerWithName(name);
        if (speaker != null) {
            log.debug("Speaker already exists: {}", name);
            return;
        }
    }

    if (vlanId == null || vlanId.isEmpty()) {
        vlanIdObj = VlanId.NONE;
    } else {
        vlanIdObj = VlanId.vlanId(Short.valueOf(vlanId));
    }

    addSpeakerToConf(config);
    configService.applyConfig(appId, BgpConfig.class, config.node());

    print(SPEAKER_ADD_SUCCESS);
}
 
Example 8
Source File: RemoveSpeakerCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    NetworkConfigService configService = get(NetworkConfigService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(RoutingService.ROUTER_APP_ID);

    BgpConfig config = configService.getConfig(appId, BgpConfig.class);
    if (config == null || config.bgpSpeakers().isEmpty()) {
        print(NO_CONFIGURATION);
        return;
    }

    BgpConfig.BgpSpeakerConfig speaker = config.getSpeakerWithName(name);
    if (speaker == null) {
        print(SPEAKER_NOT_FOUND, name);
        return;
    } else {
        if (!speaker.peers().isEmpty()) {
            // Removal not allowed when peer connections exist.
            print(PEERS_EXIST, name);
            return;
        }
    }

    removeSpeakerFromConf(config);
    configService.applyConfig(appId, BgpConfig.class, config.node());

    print(SPEAKER_REMOVE_SUCCESS);
}
 
Example 9
Source File: BgpSpeakersListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    NetworkConfigService configService = get(NetworkConfigService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(RoutingService.ROUTER_APP_ID);

    BgpConfig config = configService.getConfig(appId, BgpConfig.class);
    if (config == null) {
        print("No speakers configured");
        return;
    }

    List<BgpConfig.BgpSpeakerConfig> bgpSpeakers =
            Lists.newArrayList(config.bgpSpeakers());

    Collections.sort(bgpSpeakers, SPEAKERS_COMPARATOR);

    if (config.bgpSpeakers().isEmpty()) {
        print("No speakers configured");
    } else {
        bgpSpeakers.forEach(
            s -> {
                if (s.name().isPresent()) {
                    print(NAME_FORMAT, s.name().get(), s.connectPoint().deviceId(),
                            s.connectPoint().port(), s.vlan(), s.peers());
                } else {
                    print(FORMAT, s.connectPoint().deviceId(),
                            s.connectPoint().port(), s.vlan(), s.peers());
                }
            });
    }
}
 
Example 10
Source File: RemovePeerCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    peerAddress = IpAddress.valueOf(ip);

    NetworkConfigService configService = get(NetworkConfigService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(RoutingService.ROUTER_APP_ID);

    BgpConfig config = configService.getConfig(appId, BgpConfig.class);
    if (config == null || config.bgpSpeakers().isEmpty()) {
        print(NO_CONFIGURATION);
        return;
    }

    peerAddress = IpAddress.valueOf(ip);

    BgpConfig.BgpSpeakerConfig speaker = config.getSpeakerFromPeer(peerAddress);
    if (speaker == null) {
        print(PEER_NOT_FOUND, ip);
        return;
    }

    removePeerFromSpeakerConf(speaker, config);
    configService.applyConfig(appId, BgpConfig.class, config.node());

    print(PEER_REMOVE_SUCCESS);
}
 
Example 11
Source File: AddPeerCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    peerAddress = IpAddress.valueOf(ip);

    NetworkConfigService configService = get(NetworkConfigService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(RoutingService.ROUTER_APP_ID);

    BgpConfig config = configService.getConfig(appId, BgpConfig.class);
    if (config == null || config.bgpSpeakers().isEmpty()) {
        print(NO_CONFIGURATION);
        return;
    }

    BgpConfig.BgpSpeakerConfig speaker = config.getSpeakerWithName(name);
    if (speaker == null) {
        print(SPEAKER_NOT_FOUND, name);
        return;
    } else {
        if (speaker.isConnectedToPeer(peerAddress)) {
            return; // Peering already exists.
        }
    }

    InterfaceService interfaceService = get(InterfaceService.class);
    if (interfaceService.getMatchingInterface(peerAddress) == null) {
        print(NO_INTERFACE, ip);
        return;
    }

    addPeerToSpeakerConf(config);
    configService.applyConfig(appId, BgpConfig.class, config.node());

    print(PEER_ADD_SUCCESS);
}
 
Example 12
Source File: ConnectivityIntentCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected ApplicationId appId() {
    ApplicationId appIdForIntent;
    if (appId == null) {
        appIdForIntent = super.appId();
    } else {
        CoreService service = get(CoreService.class);
        appIdForIntent = service.getAppId(appId);
    }
    return appIdForIntent;
}
 
Example 13
Source File: TelemetryVflowListCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute() {
    CoreService coreService = get(CoreService.class);
    FlowRuleService flowService = get(FlowRuleService.class);
    ApplicationId appId = coreService.getAppId(OPENSTACK_TELEMETRY_APP_ID);

    List<FlowEntry> flows =
            Lists.newArrayList(flowService.getFlowEntriesById(appId));

    print(FORMAT, "SrcIp", "SrcPort", "DstIp", "DstPort", "Protocol");

    for (FlowEntry entry : flows) {
        TrafficSelector selector = entry.selector();
        IpPrefix srcIp = ((IPCriterion) selector.getCriterion(IPV4_SRC)).ip();
        IpPrefix dstIp = ((IPCriterion) selector.getCriterion(IPV4_DST)).ip();

        TpPort srcPort = TpPort.tpPort(0);
        TpPort dstPort = TpPort.tpPort(0);
        String protocolStr = "ANY";

        Criterion ipProtocolCriterion = selector.getCriterion(IP_PROTO);

        if (ipProtocolCriterion != null) {
            short protocol = ((IPProtocolCriterion) selector.getCriterion(IP_PROTO)).protocol();

            if (protocol == PROTOCOL_TCP) {
                srcPort = ((TcpPortCriterion) selector.getCriterion(TCP_SRC)).tcpPort();
                dstPort = ((TcpPortCriterion) selector.getCriterion(TCP_DST)).tcpPort();
                protocolStr = TCP;
            }

            if (protocol == PROTOCOL_UDP) {
                srcPort = ((UdpPortCriterion) selector.getCriterion(UDP_SRC)).udpPort();
                dstPort = ((UdpPortCriterion) selector.getCriterion(UDP_SRC)).udpPort();
                protocolStr = UDP;
            }
        }

        print(FORMAT,
                srcIp.toString(),
                srcPort.toString(),
                dstIp.toString(),
                dstPort.toString(),
                protocolStr);
    }
}
 
Example 14
Source File: K8sPurgeRulesCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@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.");
    }
}
 
Example 15
Source File: OpenstackRemoveAclCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute() {

    OpenstackFlowRuleService flowRuleService = get(OpenstackFlowRuleService.class);
    CoreService coreService = get(CoreService.class);

    ApplicationId appId = coreService.getAppId(OPENSTACK_NETWORKING_APP_ID);

    InstancePortService instancePortService = get(InstancePortService.class);

    IpAddress srcIpAddress = null;

    IpAddress dstIpAddress = null;

    try {
        srcIpAddress = IpAddress.valueOf(srcIpStr);

        dstIpAddress = IpAddress.valueOf(dstIpStr);
    } catch (IllegalArgumentException e) {
        log.error("IllegalArgumentException occurred because of {}", e);
        return;
    }

    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
            .matchEthType(Ethernet.TYPE_IPV4)
            .matchIPSrc(srcIpAddress.toIpPrefix())
            .matchIPDst(dstIpAddress.toIpPrefix());

    TrafficTreatment treatment = DefaultTrafficTreatment.builder().
            drop().build();

    if (srcPort != 0 || dstPort != 0) {
        sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP);
        if (srcPort != 0) {
            sBuilder.matchTcpSrc(TpPort.tpPort(srcPort));
        }

        if (dstPort != 0) {
            sBuilder.matchTcpDst(TpPort.tpPort(dstPort));
        }
    }

    log.info("Deny the packet from srcIp: {}, dstPort: {} to dstIp: {}, dstPort: {}",
            srcIpAddress.toString(),
            srcPort,
            dstIpAddress.toString(),
            dstPort);

    Optional<InstancePort> instancePort = instancePortService.instancePorts().stream()
            .filter(port -> port.ipAddress().toString().equals(dstIpStr))
            .findAny();

    if (!instancePort.isPresent()) {
        log.info("Instance port that matches with the given dst ip address isn't present {}");
        return;
    }

    flowRuleService.setRule(
            appId,
            instancePort.get().deviceId(),
            sBuilder.build(),
            treatment,
            PRIORITY_FORCED_ACL_RULE,
            DHCP_TABLE,
            false);
}
 
Example 16
Source File: OpenstackAddAclCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute() {

    OpenstackFlowRuleService flowRuleService = get(OpenstackFlowRuleService.class);
    CoreService coreService = get(CoreService.class);

    ApplicationId appId = coreService.getAppId(OPENSTACK_NETWORKING_APP_ID);

    InstancePortService instancePortService = get(InstancePortService.class);

    IpAddress srcIpAddress;

    IpAddress dstIpAddress;

    try {
        srcIpAddress = IpAddress.valueOf(srcIpStr);

        dstIpAddress = IpAddress.valueOf(dstIpStr);
    } catch (IllegalArgumentException e) {
        log.error("IllegalArgumentException occurred because of {}", e);
        return;
    }

    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
            .matchEthType(Ethernet.TYPE_IPV4)
            .matchIPSrc(srcIpAddress.toIpPrefix())
            .matchIPDst(dstIpAddress.toIpPrefix());

    TrafficTreatment treatment = DefaultTrafficTreatment.builder().
            drop().build();

    if (srcPort != 0 || dstPort != 0) {
        sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP);
        if (srcPort != 0) {
            sBuilder.matchTcpSrc(TpPort.tpPort(srcPort));
        }

        if (dstPort != 0) {
            sBuilder.matchTcpDst(TpPort.tpPort(dstPort));
        }
    }

    log.info("Deny the packet from srcIp: {}, dstPort: {} to dstIp: {}, dstPort: {}",
            srcIpAddress.toString(),
            srcPort,
            dstIpAddress.toString(),
            dstPort);

    Optional<InstancePort> instancePort = instancePortService.instancePorts().stream()
            .filter(port -> port.ipAddress().toString().equals(dstIpStr))
            .findAny();

    if (!instancePort.isPresent()) {
        log.info("Instance port that matches with the given dst ip address isn't present {}");
        return;
    }

    flowRuleService.setRule(
            appId,
            instancePort.get().deviceId(),
            sBuilder.build(),
            treatment,
            PRIORITY_FORCED_ACL_RULE,
            DHCP_TABLE,
            true);
}
 
Example 17
Source File: OpenstackPurgeRulesCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute() {
    FlowRuleService flowRuleService = get(FlowRuleService.class);
    CoreService coreService = get(CoreService.class);
    ApplicationId appId = coreService.getAppId(Constants.OPENSTACK_NETWORKING_APP_ID);

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

    flowRuleService.removeFlowRulesById(appId);
    print("Successfully purged flow rules installed by OpenStack 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;
        }
    }

    if (result) {
        print("Successfully purged flow rules!");
    } else {
        error("Failed to purge flow rules.");
    }
}
 
Example 18
Source File: IntentRemoveCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the intents passed as argument, assuming these
 * belong to the application's ID provided (if any) and
 * contain a key string.
 *
 * If an application ID is provided, it will be used to further
 * filter the intents to be removed.
 *
 * @param intents list of intents to remove
 * @param applicationIdString application ID to filter intents
 * @param keyString string to filter intents
 * @param purgeAfterRemove states whether the intents should be also purged
 * @param sync states whether the cli should wait for the operation to finish
 *             before returning
 */
private void removeIntent(Iterable<Intent> intents,
                         String applicationIdString, String keyString,
                         boolean purgeAfterRemove, boolean sync) {
    IntentService intentService = get(IntentService.class);
    CoreService coreService = get(CoreService.class);
    this.applicationIdString = applicationIdString;
    this.keyString = keyString;
    this.purgeAfterRemove = purgeAfterRemove;
    this.sync = sync;
    if (purgeAfterRemove || sync) {
        print("Using \"sync\" to remove/purge intents - this may take a while...");
        print("Check \"summary\" to see remove/purge progress.");
    }

    ApplicationId appId = appId();
    if (!isNullOrEmpty(applicationIdString)) {
        appId = coreService.getAppId(applicationIdString);
        if (appId == null) {
            print("Cannot find application Id %s", applicationIdString);
            return;
        }
    }

    if (isNullOrEmpty(keyString)) {
        removeIntentsByAppId(intentService, intents, appId);

    } else {
        final Key key;
        if (keyString.startsWith("0x")) {
            // The intent uses a LongKey
            keyString = keyString.replaceFirst("0x", "");
            key = Key.of(new BigInteger(keyString, 16).longValue(), appId);
        } else {
            // The intent uses a StringKey
            key = Key.of(keyString, appId);
        }

        Intent intent = intentService.getIntent(key);
        if (intent != null) {
            removeIntent(intentService, intent);
        }
    }
}