Cherry pick gNMI and Stratum related changes to this branch
Cherry picked commits:
20211 Update gNMI version and build script
20247 [ONOS-7829] Implement AbstractGrpcClient and AbstractGrpcClientControl
20233 [ONOS-7141][ONOS-7142] Add GnmiClient and GnmiController
20234 Refactor OpenConfig gNMI device description descovery
20260 [ONOS-7831] Implement GnmiHandshaker
20270 Add Stratum driver
Change-Id: I81ad8bce45251af5909cfcac0edbcfd11c8ebf1d
diff --git a/protocols/gnmi/BUILD b/protocols/gnmi/BUILD
index 30599ae..0b6b6e6 100644
--- a/protocols/gnmi/BUILD
+++ b/protocols/gnmi/BUILD
@@ -1,12 +1,13 @@
BUNDLES = [
- "//protocols/gnmi/stub:gnmi_java_grpc",
- "//protocols/gnmi/stub:gnmi_java_proto",
+ "//protocols/gnmi/stub:onos-protocols-gnmi-stub",
+ "//protocols/gnmi/ctl:onos-protocols-gnmi-ctl",
+ "//protocols/gnmi/api:onos-protocols-gnmi-api",
]
onos_app(
app_name = "org.onosproject.protocols.gnmi",
category = "Protocol",
- description = "ONOS gNMI protocol subsystem",
+ description = "gNMI protocol subsystem",
included_bundles = BUNDLES,
required_apps = [
"org.onosproject.protocols.grpc",
diff --git a/protocols/gnmi/api/BUILD b/protocols/gnmi/api/BUILD
new file mode 100644
index 0000000..1cf1a3d
--- /dev/null
+++ b/protocols/gnmi/api/BUILD
@@ -0,0 +1,8 @@
+COMPILE_DEPS = CORE_DEPS + [
+ "//protocols/grpc/api:onos-protocols-grpc-api",
+ "//protocols/gnmi/stub:onos-protocols-gnmi-stub",
+]
+
+osgi_jar(
+ deps = COMPILE_DEPS,
+)
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiClient.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiClient.java
new file mode 100644
index 0000000..5beb238
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiClient.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.gnmi.api;
+
+import com.google.common.annotations.Beta;
+import gnmi.Gnmi.CapabilityResponse;
+import gnmi.Gnmi.GetRequest;
+import gnmi.Gnmi.GetResponse;
+import gnmi.Gnmi.SetRequest;
+import gnmi.Gnmi.SetResponse;
+import org.onosproject.grpc.api.GrpcClient;
+
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * Client to control a gNMI server.
+ */
+@Beta
+public interface GnmiClient extends GrpcClient {
+
+ /**
+ * Gets capability from a target.
+ *
+ * @return the capability response
+ */
+ CompletableFuture<CapabilityResponse> capability();
+
+ /**
+ * Retrieves a snapshot of data from the device.
+ *
+ * @param request the get request
+ * @return the snapshot of data from the device
+ */
+ CompletableFuture<GetResponse> get(GetRequest request);
+
+ /**
+ * Modifies the state of data on the device.
+ *
+ * @param request the set request
+ * @return the set result
+ */
+ CompletableFuture<SetResponse> set(SetRequest request);
+
+ /**
+ * Check weather the gNMI service is available or not by sending a
+ * dummy get request message.
+ *
+ * @return true if gNMI service available; false otherwise
+ */
+ CompletableFuture<Boolean> isServiceAvailable();
+
+ // TODO: Support gNMI subscription
+}
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiClientKey.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiClientKey.java
new file mode 100644
index 0000000..bc18b9a
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiClientKey.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.gnmi.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.grpc.api.GrpcClientKey;
+import org.onosproject.net.DeviceId;
+
+/**
+ * Key that uniquely identifies a gNMI client.
+ */
+@Beta
+public class GnmiClientKey extends GrpcClientKey {
+
+ private static final String GNMI = "gnmi";
+
+ /**
+ * Creates a new gNMI client key.
+ *
+ * @param deviceId ONOS device ID
+ * @param serverAddr gNMI server address
+ * @param serverPort gNMI server port
+ */
+ public GnmiClientKey(DeviceId deviceId, String serverAddr, int serverPort) {
+ super(GNMI, deviceId, serverAddr, serverPort);
+ }
+}
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiController.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiController.java
new file mode 100644
index 0000000..f4964ed
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiController.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.gnmi.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.grpc.api.GrpcClientController;
+
+/**
+ * Controller of gNMI devices.
+ */
+@Beta
+public interface GnmiController
+ extends GrpcClientController<GnmiClientKey, GnmiClient> {
+}
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEvent.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEvent.java
new file mode 100644
index 0000000..5129926
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEvent.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.gnmi.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.event.AbstractEvent;
+
+/**
+ * Representation of an event received from a gNMI device.
+ */
+@Beta
+public final class GnmiEvent extends AbstractEvent<GnmiEvent.Type, GnmiEventSubject> {
+
+ /**
+ * Type of gNMI event.
+ */
+ public enum Type {
+ /**
+ * Update.
+ */
+ UPDATE,
+
+ /**
+ * Sync response.
+ */
+ SYNC_RESPONSE
+ }
+
+ protected GnmiEvent(Type type, GnmiEventSubject subject) {
+ super(type, subject);
+ }
+}
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEventListener.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEventListener.java
new file mode 100644
index 0000000..0fe2fd3
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEventListener.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.gnmi.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.event.EventListener;
+
+/**
+ * A listener of events received from gNMI devices.
+ */
+@Beta
+public interface GnmiEventListener extends EventListener<GnmiEvent> {
+}
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEventSubject.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEventSubject.java
new file mode 100644
index 0000000..d1563ed
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/GnmiEventSubject.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.gnmi.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.net.DeviceId;
+
+/**
+ * Information about an event generated by a gNMI device .
+ */
+@Beta
+public interface GnmiEventSubject {
+
+ /**
+ * Returns the deviceId associated to this subject.
+ *
+ * @return the device ID
+ */
+ DeviceId deviceId();
+}
diff --git a/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/package-info.java b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/package-info.java
new file mode 100644
index 0000000..5f07b46
--- /dev/null
+++ b/protocols/gnmi/api/src/main/java/org/onosproject/gnmi/api/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * gNMI protocol API.
+ */
+package org.onosproject.gnmi.api;
\ No newline at end of file
diff --git a/protocols/gnmi/ctl/BUILD b/protocols/gnmi/ctl/BUILD
new file mode 100644
index 0000000..db4cd44
--- /dev/null
+++ b/protocols/gnmi/ctl/BUILD
@@ -0,0 +1,23 @@
+COMPILE_DEPS = CORE_DEPS + KRYO + [
+ "//protocols/gnmi/api:onos-protocols-gnmi-api",
+ "//protocols/gnmi/stub:onos-protocols-gnmi-stub",
+ "//protocols/grpc/api:onos-protocols-grpc-api",
+ "//protocols/grpc/ctl:onos-protocols-grpc-ctl",
+ "//protocols/grpc:grpc-core-repkg",
+ "@com_google_protobuf//:protobuf_java",
+ "@io_grpc_grpc_java//netty",
+ "@io_grpc_grpc_java//protobuf-lite",
+ "@io_grpc_grpc_java//stub",
+ "@com_google_api_grpc_proto_google_common_protos//jar",
+]
+
+TEST_DEPS = TEST + [
+ "@minimal_json//jar",
+ "@io_grpc_grpc_java//core:inprocess",
+ "@io_grpc_grpc_java//protobuf-lite",
+]
+
+osgi_jar_with_tests(
+ test_deps = TEST_DEPS,
+ deps = COMPILE_DEPS,
+)
diff --git a/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/GnmiClientImpl.java b/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/GnmiClientImpl.java
new file mode 100644
index 0000000..22b226b
--- /dev/null
+++ b/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/GnmiClientImpl.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package protocols.gnmi.ctl.java.org.onosproject.gnmi.ctl;
+
+import gnmi.Gnmi.CapabilityRequest;
+import gnmi.Gnmi.CapabilityResponse;
+import gnmi.Gnmi.GetRequest;
+import gnmi.Gnmi.GetResponse;
+import gnmi.Gnmi.Path;
+import gnmi.Gnmi.PathElem;
+import gnmi.Gnmi.SetRequest;
+import gnmi.Gnmi.SetResponse;
+import gnmi.gNMIGrpc;
+import io.grpc.ManagedChannel;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import org.onosproject.gnmi.api.GnmiClient;
+import org.onosproject.gnmi.api.GnmiClientKey;
+import org.onosproject.grpc.ctl.AbstractGrpcClient;
+import org.slf4j.Logger;
+
+import java.util.concurrent.CompletableFuture;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of gNMI client.
+ */
+public class GnmiClientImpl extends AbstractGrpcClient implements GnmiClient {
+ private static final PathElem DUMMY_PATH_ELEM = PathElem.newBuilder().setName("onos-gnmi-test").build();
+ private static final Path DUMMY_PATH = Path.newBuilder().addElem(DUMMY_PATH_ELEM).build();
+ private static final GetRequest DUMMY_REQUEST = GetRequest.newBuilder().addPath(DUMMY_PATH).build();
+ private final Logger log = getLogger(getClass());
+ private final gNMIGrpc.gNMIBlockingStub blockingStub;
+
+ GnmiClientImpl(GnmiClientKey clientKey, ManagedChannel managedChannel) {
+ super(clientKey);
+ this.blockingStub = gNMIGrpc.newBlockingStub(managedChannel);
+ }
+
+ @Override
+ public CompletableFuture<CapabilityResponse> capability() {
+ return supplyInContext(this::doCapability, "capability");
+ }
+
+ @Override
+ public CompletableFuture<GetResponse> get(GetRequest request) {
+ return supplyInContext(() -> doGet(request), "get");
+ }
+
+ @Override
+ public CompletableFuture<SetResponse> set(SetRequest request) {
+ return supplyInContext(() -> doSet(request), "set");
+ }
+
+ @Override
+ public CompletableFuture<Boolean> isServiceAvailable() {
+ return supplyInContext(this::doServiceAvailable, "isServiceAvailable");
+ }
+
+ private CapabilityResponse doCapability() {
+ CapabilityRequest request = CapabilityRequest.newBuilder().build();
+ try {
+ return blockingStub.capabilities(request);
+ } catch (StatusRuntimeException e) {
+ log.warn("Unable to get capability from {}: {}", deviceId, e.getMessage());
+ return null;
+ }
+ }
+
+ private GetResponse doGet(GetRequest request) {
+ try {
+ return blockingStub.get(request);
+ } catch (StatusRuntimeException e) {
+ log.warn("Unable to get data from {}: {}", deviceId, e.getMessage());
+ return null;
+ }
+ }
+
+ private SetResponse doSet(SetRequest request) {
+ try {
+ return blockingStub.set(request);
+ } catch (StatusRuntimeException e) {
+ log.warn("Unable to set data to {}: {}", deviceId, e.getMessage());
+ return null;
+ }
+ }
+
+ private boolean doServiceAvailable() {
+ try {
+ return blockingStub.get(DUMMY_REQUEST) != null;
+ } catch (StatusRuntimeException e) {
+ // This gRPC call should throw INVALID_ARGUMENT status exception
+ // since "/onos-gnmi-test" path does not exists in any config model
+ // For other status code such as UNIMPLEMENT, means the gNMI
+ // service is not available on the device.
+ return e.getStatus().getCode().equals(Status.Code.INVALID_ARGUMENT);
+ }
+ }
+}
diff --git a/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/GnmiControllerImpl.java b/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/GnmiControllerImpl.java
new file mode 100644
index 0000000..7ddc3f0
--- /dev/null
+++ b/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/GnmiControllerImpl.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package protocols.gnmi.ctl.java.org.onosproject.gnmi.ctl;
+
+import io.grpc.ManagedChannel;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Service;
+import org.onosproject.gnmi.api.GnmiEvent;
+import org.onosproject.gnmi.api.GnmiEventListener;
+import org.onosproject.grpc.ctl.AbstractGrpcClientController;
+import org.onosproject.gnmi.api.GnmiClient;
+import org.onosproject.gnmi.api.GnmiClientKey;
+import org.onosproject.gnmi.api.GnmiController;
+import org.slf4j.Logger;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of gNMI controller.
+ */
+@Component(immediate = true)
+@Service
+public class GnmiControllerImpl
+ extends AbstractGrpcClientController<GnmiClientKey, GnmiClient, GnmiEvent, GnmiEventListener>
+ implements GnmiController {
+ private final Logger log = getLogger(getClass());
+
+ @Activate
+ public void activate() {
+ super.activate();
+ log.info("Started");
+ }
+
+ @Deactivate
+ public void deactivate() {
+ super.deactivate();
+ log.info("Stopped");
+ }
+
+ @Override
+ protected GnmiClient createClientInstance(GnmiClientKey clientKey, ManagedChannel channel) {
+ return new GnmiClientImpl(clientKey, channel);
+ }
+}
diff --git a/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/package-info.java b/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/package-info.java
new file mode 100644
index 0000000..ae46aa4
--- /dev/null
+++ b/protocols/gnmi/ctl/src/main/java/org/onosproject/gnmi/ctl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Implementation classes of the gNMI protocol subsystem.
+ */
+package protocols.gnmi.ctl.java.org.onosproject.gnmi.ctl;
\ No newline at end of file
diff --git a/protocols/gnmi/stub/BUILD b/protocols/gnmi/stub/BUILD
index 3b1a2dc..cf79265 100644
--- a/protocols/gnmi/stub/BUILD
+++ b/protocols/gnmi/stub/BUILD
@@ -1,43 +1,14 @@
-load("//tools/build/bazel:osgi_java_library.bzl", "wrapped_osgi_jar")
-load("@io_grpc_grpc_java//:java_grpc_library.bzl", "java_grpc_library")
+load("//tools/build/bazel:osgi_java_library.bzl", "osgi_proto_jar")
-wrapped_osgi_jar(
- name = "gnmi_java_grpc",
- jar = ":gnmi_java_grpc_native",
- visibility = ["//visibility:public"],
+PROTOS = [
+ "@com_github_openconfig_gnmi//:gnmi_proto",
+ "@com_github_openconfig_gnmi//:gnmi_ext_proto",
+]
+
+osgi_proto_jar(
+ grpc_proto_lib = "@com_github_openconfig_gnmi//:gnmi_proto",
+ proto_libs = PROTOS,
deps = [
- "@io_grpc_grpc_java//core",
- "@io_grpc_grpc_java//protobuf",
- "@io_grpc_grpc_java//stub",
- ],
-)
-
-wrapped_osgi_jar(
- name = "gnmi_java_proto",
- jar = ":gnmi_java_proto_native",
- visibility = ["//visibility:public"],
- deps = [
- "@com_google_protobuf//:protobuf_java",
- ],
-)
-
-java_proto_library(
- name = "gnmi_java_proto_native",
- visibility = ["//visibility:public"],
- deps = [":gnmi_proto"],
-)
-
-java_grpc_library(
- name = "gnmi_java_grpc_native",
- srcs = [":gnmi_proto"],
- deps = [":gnmi_java_proto_native"],
-)
-
-proto_library(
- name = "gnmi_proto",
- srcs = ["src/main/proto/gnmi.proto"],
- deps = [
- "@com_google_protobuf//:any_proto",
- "@com_google_protobuf//:descriptor_proto",
+ "@com_google_api_grpc_proto_google_common_protos//jar",
],
)
diff --git a/protocols/gnmi/stub/src/main/proto/COMMIT_ID b/protocols/gnmi/stub/src/main/proto/COMMIT_ID
deleted file mode 100644
index acf773d..0000000
--- a/protocols/gnmi/stub/src/main/proto/COMMIT_ID
+++ /dev/null
@@ -1,2 +0,0 @@
-https://github.com/openconfig/gnmi/blob/master/proto/gnmi/gnmi.proto
-9c8d9e965b3e854107ea02c12ab11b70717456f2
diff --git a/protocols/gnmi/stub/src/main/proto/gnmi.proto b/protocols/gnmi/stub/src/main/proto/gnmi.proto
deleted file mode 100644
index 1f3bb7c..0000000
--- a/protocols/gnmi/stub/src/main/proto/gnmi.proto
+++ /dev/null
@@ -1,423 +0,0 @@
-//
-// Copyright 2016 Google Inc. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-syntax = "proto3";
-
-import "google/protobuf/any.proto";
-import "google/protobuf/descriptor.proto";
-
-// Package gNMI defines a service specification for the gRPC Network Management
-// Interface. This interface is defined to be a standard interface via which
-// a network management system ("client") can subscribe to state values,
-// retrieve snapshots of state information, and manipulate the state of a data
-// tree supported by a device ("target").
-//
-// This document references the gNMI Specification which can be found at
-// http://github.com/openconfig/reference/blob/master/rpc/gnmi
-package gnmi;
-
-// Define a protobuf FileOption that defines the gNMI service version.
-extend google.protobuf.FileOptions {
- // The gNMI service semantic version.
- string gnmi_service = 1001;
-}
-
-// gNMI_service is the current version of the gNMI service, returned through
-// the Capabilities RPC.
-option (gnmi_service) = "0.5.0";
-
-service gNMI {
- // Capabilities allows the client to retrieve the set of capabilities that
- // is supported by the target. This allows the target to validate the
- // service version that is implemented and retrieve the set of models that
- // the target supports. The models can then be specified in subsequent RPCs
- // to restrict the set of data that is utilized.
- // Reference: gNMI Specification Section 3.2
- rpc Capabilities(CapabilityRequest) returns (CapabilityResponse);
- // Retrieve a snapshot of data from the target. A Get RPC requests that the
- // target snapshots a subset of the data tree as specified by the paths
- // included in the message and serializes this to be returned to the
- // client using the specified encoding.
- // Reference: gNMI Specification Section 3.3
- rpc Get(GetRequest) returns (GetResponse);
- // Set allows the client to modify the state of data on the target. The
- // paths to modified along with the new values that the client wishes
- // to set the value to.
- // Reference: gNMI Specification Section 3.4
- rpc Set(SetRequest) returns (SetResponse);
- // Subscribe allows a client to request the target to send it values
- // of particular paths within the data tree. These values may be streamed
- // at a particular cadence (STREAM), sent one off on a long-lived channel
- // (POLL), or sent as a one-off retrieval (ONCE).
- // Reference: gNMI Specification Section 3.5
- rpc Subscribe(stream SubscribeRequest) returns (stream SubscribeResponse);
-}
-
-// Notification is a re-usable message that is used to encode data from the
-// target to the client. A Notification carries two types of changes to the data
-// tree:
-// - Deleted values (delete) - a set of paths that have been removed from the
-// data tree.
-// - Updated values (update) - a set of path-value pairs indicating the path
-// whose value has changed in the data tree.
-// Reference: gNMI Specification Section 2.1
-message Notification {
- int64 timestamp = 1; // Timestamp in nanoseconds since Epoch.
- Path prefix = 2; // Prefix used for paths in the message.
- // An alias for the path specified in the prefix field.
- // Reference: gNMI Specification Section 2.4.2
- string alias = 3;
- repeated Update update = 4; // Data elements that have changed values.
- repeated Path delete = 5; // Data elements that have been deleted.
-}
-
-// Update is a re-usable message that is used to store a particular Path,
-// Value pair.
-// Reference: gNMI Specification Section 2.1
-message Update {
- Path path = 1; // The path (key) for the update.
- Value value = 2 [deprecated=true]; // The value (value) for the update.
- TypedValue val = 3; // The explicitly typed update value.
- uint32 duplicates = 4; // Number of coalesced duplicates.
-}
-
-// TypedValue is used to encode a value being sent between the client and
-// target (originated by either entity).
-message TypedValue {
- // One of the fields within the val oneof is populated with the value
- // of the update. The type of the value being included in the Update
- // determines which field should be populated. In the case that the
- // encoding is a particular form of the base protobuf type, a specific
- // field is used to store the value (e.g., json_val).
- oneof value {
- string string_val = 1; // String value.
- int64 int_val = 2; // Integer value.
- uint64 uint_val = 3; // Unsigned integer value.
- bool bool_val = 4; // Bool value.
- bytes bytes_val = 5; // Arbitrary byte sequence value.
- float float_val = 6; // Floating point value.
- Decimal64 decimal_val = 7; // Decimal64 encoded value.
- ScalarArray leaflist_val = 8; // Mixed type scalar array value.
- google.protobuf.Any any_val = 9; // protobuf.Any encoded bytes.
- bytes json_val = 10; // JSON-encoded text.
- bytes json_ietf_val = 11; // JSON-encoded text per RFC7951.
- string ascii_val = 12; // Arbitrary ASCII text.
- }
-}
-
-// Path encodes a data tree path as a series of repeated strings, with
-// each element of the path representing a data tree node name and the
-// associated attributes.
-// Reference: gNMI Specification Section 2.2.2.
-message Path {
- // Elements of the path are no longer encoded as a string, but rather within
- // the elem field as a PathElem message.
- repeated string element = 1 [deprecated=true];
- string origin = 2; // Label to disambiguate path.
- repeated PathElem elem = 3; // Elements of the path.
- string target = 4; // The name of the target
- // (Sec. 2.2.2.1)
-}
-
-// PathElem encodes an element of a gNMI path, along ith any attributes (keys)
-// that may be associated with it.
-// Reference: gNMI Specification Section 2.2.2.
-message PathElem {
- string name = 1; // The name of the element in the path.
- map<string, string> key = 2; // Map of key (attribute) name to value.
-}
-
-// Value encodes a data tree node's value - along with the way in which
-// the value is encoded. This message is deprecated by gNMI 0.3.0.
-// Reference: gNMI Specification Section 2.2.3.
-message Value {
- option deprecated = true;
- bytes value = 1; // Value of the variable being transmitted.
- Encoding type = 2; // Encoding used for the value field.
-}
-
-// Encoding defines the value encoding formats that are supported by the gNMI
-// protocol. These encodings are used by both the client (when sending Set
-// messages to modify the state of the target) and the target when serializing
-// data to be returned to the client (in both Subscribe and Get RPCs).
-// Reference: gNMI Specification Section 2.3
-enum Encoding {
- JSON = 0; // JSON encoded text.
- BYTES = 1; // Arbitrarily encoded bytes.
- PROTO = 2; // Encoded according to out-of-band agreed Protobuf.
- ASCII = 3; // ASCII text of an out-of-band agreed format.
- JSON_IETF = 4; // JSON encoded text as per RFC7951.
-}
-
-// Error message previously utilised to return errors to the client. Deprecated
-// in favour of using the google.golang.org/genproto/googleapis/rpc/status
-// message in the RPC response.
-// Reference: gNMI Specification Section 2.5
-message Error {
- option deprecated = true;
- uint32 code = 1; // Canonical gRPC error code.
- string message = 2; // Human readable error.
- google.protobuf.Any data = 3; // Optional additional information.
-}
-
-// Decimal64 is used to encode a fixed precision decimal number. The value
-// is expressed as a set of digits with the precision specifying the
-// number of digits following the decimal point in the digit set.
-message Decimal64 {
- int64 digits = 1; // Set of digits.
- uint32 precision = 2; // Number of digits following the decimal point.
-}
-
-// ScalarArray is used to encode a mixed-type array of values.
-message ScalarArray {
- // The set of elements within the array. Each TypedValue message should
- // specify only elements that have a field identifier of 1-7 (i.e., the
- // values are scalar values).
- repeated TypedValue element = 1;
-}
-
-// SubscribeRequest is the message sent by the client to the target when
-// initiating a subscription to a set of paths within the data tree. The
-// request field must be populated and the initial message must specify a
-// SubscriptionList to initiate a subscription. The message is subsequently
-// used to define aliases or trigger polled data to be sent by the target.
-// Reference: gNMI Specification Section 3.5.1.1
-message SubscribeRequest {
- oneof request {
- SubscriptionList subscribe = 1; // Specify the paths within a subscription.
- Poll poll = 3; // Trigger a polled update.
- AliasList aliases = 4; // Aliases to be created.
- }
-}
-
-// Poll is sent within a SubscribeRequest to trigger the device to
-// send telemetry updates for the paths that are associated with the
-// subscription.
-// Reference: gNMI Specification Section Section 3.5.1.4
-message Poll {
-}
-
-// SubscribeResponse is the message used by the target within a Subscribe RPC.
-// The target includes a Notification message which is used to transmit values
-// of the path(s) that are associated with the subscription. The same message
-// is to indicate that the target has sent all data values once (is
-// synchronized).
-// Reference: gNMI Specification Section 3.5.1.4
-message SubscribeResponse {
- oneof response {
- Notification update = 1; // Changed or sampled value for a path.
- // Indicate target has sent all values associated with the subscription
- // at least once.
- bool sync_response = 3;
- // Deprecated in favour of google.golang.org/genproto/googleapis/rpc/status
- Error error = 4 [deprecated=true];
- }
-}
-
-// SubscriptionList is used within a Subscribe message to specify the list of
-// paths that the client wishes to subscribe to. The message consists of a
-// list of (possibly prefixed) paths, and options that relate to the
-// subscription.
-// Reference: gNMI Specification Section 3.5.1.2
-message SubscriptionList {
- Path prefix = 1; // Prefix used for paths.
- repeated Subscription subscription = 2; // Set of subscriptions to create.
- // Whether target defined aliases are allowed within the subscription.
- bool use_aliases = 3;
- QOSMarking qos = 4; // DSCP marking to be used.
- // Mode of the subscription.
- enum Mode {
- STREAM = 0; // Values streamed by the target (Sec. 3.5.1.5.2).
- ONCE = 1; // Values sent once-off by the target (Sec. 3.5.1.5.1).
- POLL = 2; // Values sent in response to a poll request (Sec. 3.5.1.5.3).
- }
- Mode mode = 5;
- // Whether elements of the schema that are marked as eligible for aggregation
- // should be aggregated or not.
- bool allow_aggregation = 6;
- // The set of schemas that define the elements of the data tree that should
- // be sent by the target.
- repeated ModelData use_models = 7;
- // The encoding that the target should use within the Notifications generated
- // corresponding to the SubscriptionList.
- Encoding encoding = 8;
- // An optional field to specify that only updates to current state should be
- // sent to a client. If set, the initial state is not sent to the client but
- // rather only the sync message followed by any subsequent updates to the
- // current state. For ONCE and POLL modes, this causes the server to send only
- // the sync message (Sec. 3.5.2.3).
- bool updates_only = 9;
-}
-
-// Subscription is a single request within a SubscriptionList. The path
-// specified is interpreted (along with the prefix) as the elements of the data
-// tree that the client is subscribing to. The mode determines how the target
-// should trigger updates to be sent.
-// Reference: gNMI Specification Section 3.5.1.3
-message Subscription {
- Path path = 1; // The data tree path.
- SubscriptionMode mode = 2; // Subscription mode to be used.
- uint64 sample_interval = 3; // ns between samples in SAMPLE mode.
- // Indicates whether values that not changed should be sent in a SAMPLE
- // subscription.
- bool suppress_redundant = 4;
- // Specifies the maximum allowable silent period in nanoseconds when
- // suppress_redundant is in use. The target should send a value at least once
- // in the period specified.
- uint64 heartbeat_interval = 5;
-}
-
-// SubscriptionMode is the mode of the subscription, specifying how the
-// target must return values in a subscription.
-// Reference: gNMI Specification Section 3.5.1.3
-enum SubscriptionMode {
- TARGET_DEFINED = 0; // The target selects the relevant mode for each element.
- ON_CHANGE = 1; // The target sends an update on element value change.
- SAMPLE = 2; // The target samples values according to the interval.
-}
-
-// QOSMarking specifies the DSCP value to be set on transmitted telemetry
-// updates from the target.
-// Reference: gNMI Specification Section 3.5.1.2
-message QOSMarking {
- uint32 marking = 1;
-}
-
-// Alias specifies a data tree path, and an associated string which defines an
-// alias which is to be used for this path in the context of the RPC. The alias
-// is specified as a string which is prefixed with "#" to disambiguate it from
-// data tree element paths.
-// Reference: gNMI Specification Section 2.4.2
-message Alias {
- Path path = 1; // The path to be aliased.
- string alias = 2; // The alias value, a string prefixed by "#".
-}
-
-// AliasList specifies a list of aliases. It is used in a SubscribeRequest for
-// a client to create a set of aliases that the target is to utilize.
-// Reference: gNMI Specification Section 3.5.1.6
-message AliasList {
- repeated Alias alias = 1; // The set of aliases to be created.
-}
-
-// SetRequest is sent from a client to the target to update values in the data
-// tree. Paths are either deleted by the client, or modified by means of being
-// updated, or replaced. Where a replace is used, unspecified values are
-// considered to be replaced, whereas when update is used the changes are
-// considered to be incremental. The set of changes that are specified within
-// a single SetRequest are considered to be a transaction.
-// Reference: gNMI Specification Section 3.4.1
-message SetRequest {
- Path prefix = 1; // Prefix used for paths in the message.
- repeated Path delete = 2; // Paths to be deleted from the data tree.
- repeated Update replace = 3; // Updates specifying elements to be replaced.
- repeated Update update = 4; // Updates specifying elements to updated.
-}
-
-// SetResponse is the response to a SetRequest, sent from the target to the
-// client. It reports the result of the modifications to the data tree that were
-// specified by the client. Errors for this RPC should be reported using the
-// https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto
-// message in the RPC return. The gnmi.Error message can be used to add additional
-// details where required.
-// Reference: gNMI Specification Section 3.4.2
-message SetResponse {
- Path prefix = 1; // Prefix used for paths.
- // A set of responses specifying the result of the operations specified in
- // the SetRequest.
- repeated UpdateResult response = 2;
- Error message = 3 [deprecated=true]; // The overall status of the transaction.
- int64 timestamp = 4; // Timestamp of transaction (ns since epoch).
-}
-
-// UpdateResult is used within the SetResponse message to communicate the
-// result of an operation specified within a SetRequest message.
-// Reference: gNMI Specification Section 3.4.2
-message UpdateResult {
- // The operation that was associated with the Path specified.
- enum Operation {
- INVALID = 0;
- DELETE = 1; // The result relates to a delete of Path.
- REPLACE = 2; // The result relates to a replace of Path.
- UPDATE = 3; // The result relates to an update of Path.
- }
- // Deprecated timestamp for the UpdateResult, this field has been
- // replaced by the timestamp within the SetResponse message, since
- // all mutations effected by a set should be applied as a single
- // transaction.
- int64 timestamp = 1 [deprecated=true];
- Path path = 2; // Path associated with the update.
- Error message = 3 [deprecated=true]; // Status of the update operation.
- Operation op = 4; // Update operation type.
-}
-
-// GetRequest is sent when a client initiates a Get RPC. It is used to specify
-// the set of data elements for which the target should return a snapshot of
-// data. The use_models field specifies the set of schema modules that are to
-// be used by the target - where use_models is not specified then the target
-// must use all schema models that it has.
-// Reference: gNMI Specification Section 3.3.1
-message GetRequest {
- Path prefix = 1; // Prefix used for paths.
- repeated Path path = 2; // Paths requested by the client.
- // Type of elements within the data tree.
- enum DataType {
- ALL = 0; // All data elements.
- CONFIG = 1; // Config (rw) only elements.
- STATE = 2; // State (ro) only elements.
- // Data elements marked in the schema as operational. This refers to data
- // elements whose value relates to the state of processes or interactions
- // running on the device.
- OPERATIONAL = 3;
- }
- DataType type = 3; // The type of data being requested.
- Encoding encoding = 5; // Encoding to be used.
- repeated ModelData use_models = 6; // The schema models to be used.
-}
-
-// GetResponse is used by the target to respond to a GetRequest from a client.
-// The set of Notifications corresponds to the data values that are requested
-// by the client in the GetRequest.
-// Reference: gNMI Specification Section 3.3.2
-message GetResponse {
- repeated Notification notification = 1; // Data values.
- Error error = 2 [deprecated=true]; // Errors that occurred in the Get.
-}
-
-// CapabilityRequest is sent by the client in the Capabilities RPC to request
-// that the target reports its capabilities.
-// Reference: gNMI Specification Section 3.2.1
-message CapabilityRequest {
-}
-
-// CapabilityResponse is used by the target to report its capabilities to the
-// client within the Capabilities RPC.
-// Reference: gNMI Specification Section 3.2.2
-message CapabilityResponse {
- repeated ModelData supported_models = 1; // Supported schema models.
- repeated Encoding supported_encodings = 2; // Supported encodings.
- string gNMI_version = 3; // Supported gNMI version.
-}
-
-// ModelData is used to describe a set of schema modules. It can be used in a
-// CapabilityResponse where a target reports the set of modules that it
-// supports, and within the SubscribeRequest and GetRequest messages to specify
-// the set of models from which data tree elements should be reported.
-// Reference: gNMI Specification Section 3.2.3
-message ModelData {
- string name = 1; // Name of the model.
- string organization = 2; // Organization publishing the model.
- string version = 3; // Semantic version of the model.
-}
diff --git a/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcController.java b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcChannelController.java
similarity index 98%
rename from protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcController.java
rename to protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcChannelController.java
index 33df22b..5b6771c 100644
--- a/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcController.java
+++ b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcChannelController.java
@@ -30,7 +30,7 @@
* Abstraction of a gRPC controller that stores and manages gRPC channels.
*/
@Beta
-public interface GrpcController {
+public interface GrpcChannelController {
int CONNECTION_TIMEOUT_SECONDS = 20;
diff --git a/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClient.java b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClient.java
new file mode 100644
index 0000000..d040a23
--- /dev/null
+++ b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClient.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.grpc.api;
+
+import com.google.common.annotations.Beta;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * Abstraction of a gRPC client.
+ *
+ */
+@Beta
+public interface GrpcClient {
+
+ /**
+ * Shutdowns the client by terminating any active RPC.
+ *
+ * @return a completable future to signal the completion of the shutdown
+ * procedure
+ */
+ CompletableFuture<Void> shutdown();
+}
diff --git a/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientController.java b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientController.java
new file mode 100644
index 0000000..3cdbcd1
--- /dev/null
+++ b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientController.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.grpc.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.net.DeviceId;
+
+/**
+ * Abstraction of a gRPC controller which controls specific gRPC client {@link
+ * C} with specific client key {@link K}.
+ *
+ * @param <K> the gRPC client key
+ * @param <C> the gRPC client type
+ */
+@Beta
+public interface GrpcClientController<K extends GrpcClientKey, C extends GrpcClient> {
+
+ /**
+ * Instantiates a new client to operate on a gRPC server identified by the
+ * given information. As a result of this method, a client can be later
+ * obtained by invoking {@link #getClient(DeviceId)}.
+ * <p>
+ * Only one client can exist for the same device ID. Calls to this method
+ * are idempotent fot the same client key, i.e. returns true if such client
+ * already exists but a new one is not created. If there exists a client
+ * with same device ID but different address and port, removes old one and
+ * recreate new one.
+ *
+ * @param clientKey the client key
+ * @return true if the client was created and the channel to the server is
+ * open; false otherwise
+ */
+ boolean createClient(K clientKey);
+
+ /**
+ * Retrieves the gRPC client to operate on the given device.
+ *
+ * @param deviceId the device identifier
+ * @return the gRPC client of the device if exists; null otherwise
+ */
+ C getClient(DeviceId deviceId);
+
+ /**
+ * Removes the gRPC client for the given device. If no client exists for the
+ * given device, the result is a no-op.
+ *
+ * @param deviceId the device identifier
+ */
+ void removeClient(DeviceId deviceId);
+
+ /**
+ * Check reachability of the gRPC server running on the given device.
+ * Reachability can be tested only if a client is previously created using
+ * {@link #createClient(GrpcClientKey)}. Note that this only checks the
+ * reachability instead of checking service availability, different
+ * service-specific gRPC clients might check service availability in a
+ * different way.
+ *
+ * @param deviceId the device identifier
+ * @return true if client was created and is able to contact the gNMI
+ * server; false otherwise
+ */
+ boolean isReachable(DeviceId deviceId);
+}
diff --git a/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientKey.java b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientKey.java
new file mode 100644
index 0000000..ad8a7da
--- /dev/null
+++ b/protocols/grpc/api/src/main/java/org/onosproject/grpc/api/GrpcClientKey.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.grpc.api;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Objects;
+import org.onosproject.net.DeviceId;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Key that uniquely identifies a gRPC client.
+ */
+@Beta
+public class GrpcClientKey {
+ private final String serviceName;
+ private final DeviceId deviceId;
+ private final String serverAddr;
+ private final int serverPort;
+
+ /**
+ * Creates a new client key.
+ *
+ * @param serviceName gRPC service name of the client
+ * @param deviceId ONOS device ID
+ * @param serverAddr gRPC server address
+ * @param serverPort gRPC server port
+ */
+ public GrpcClientKey(String serviceName, DeviceId deviceId, String serverAddr, int serverPort) {
+ checkNotNull(serviceName);
+ checkNotNull(deviceId);
+ checkNotNull(serverAddr);
+ checkArgument(!serviceName.isEmpty(),
+ "Service name can not be null");
+ checkArgument(!serverAddr.isEmpty(),
+ "Server address should not be empty");
+ checkArgument(serverPort > 0 && serverPort <= 65535, "Invalid server port");
+ this.serviceName = serviceName;
+ this.deviceId = deviceId;
+ this.serverAddr = serverAddr;
+ this.serverPort = serverPort;
+ }
+
+ /**
+ * Gets the gRPC service name of the client.
+ *
+ * @return the service name
+ */
+ public String serviceName() {
+ return serviceName;
+ }
+
+ /**
+ * Gets the device ID.
+ *
+ * @return the device ID
+ */
+ public DeviceId deviceId() {
+ return deviceId;
+ }
+
+ /**
+ * Gets the gRPC server address.
+ *
+ * @return the gRPC server address.
+ */
+ public String serverAddr() {
+ return serverAddr;
+ }
+
+ /**
+ * Gets the gRPC server port.
+ *
+ * @return the gRPC server port.
+ */
+ public int serverPort() {
+ return serverPort;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ GrpcClientKey that = (GrpcClientKey) o;
+ return serverPort == that.serverPort &&
+ Objects.equal(serviceName, that.serviceName) &&
+ Objects.equal(deviceId, that.deviceId) &&
+ Objects.equal(serverAddr, that.serverAddr);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(serviceName, deviceId, serverAddr, serverPort);
+ }
+
+ protected MoreObjects.ToStringHelper toStringHelper() {
+ return MoreObjects.toStringHelper(this)
+ .add("serviceName", serviceName)
+ .add("deviceId", deviceId)
+ .add("serverAddr", serverAddr)
+ .add("serverPort", serverPort);
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper().toString();
+ }
+}
\ No newline at end of file
diff --git a/protocols/grpc/ctl/BUILD b/protocols/grpc/ctl/BUILD
index 20c7ab8..ac0703d 100644
--- a/protocols/grpc/ctl/BUILD
+++ b/protocols/grpc/ctl/BUILD
@@ -2,6 +2,7 @@
"//protocols/grpc/api:onos-protocols-grpc-api",
"//protocols/grpc/proto:onos-protocols-grpc-proto",
"@io_grpc_grpc_java//core",
+ "@io_grpc_grpc_java//netty",
]
osgi_jar(
diff --git a/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/AbstractGrpcClient.java b/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/AbstractGrpcClient.java
new file mode 100644
index 0000000..05e2978
--- /dev/null
+++ b/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/AbstractGrpcClient.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.grpc.ctl;
+
+import io.grpc.Context;
+import io.grpc.StatusRuntimeException;
+import org.onlab.util.SharedExecutors;
+import org.onosproject.grpc.api.GrpcClient;
+import org.onosproject.grpc.api.GrpcClientKey;
+import org.onosproject.net.DeviceId;
+import org.slf4j.Logger;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Supplier;
+
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Abstract client for gRPC service.
+ *
+ */
+public abstract class AbstractGrpcClient implements GrpcClient {
+
+ // Timeout in seconds to obtain the request lock.
+ private static final int LOCK_TIMEOUT = 60;
+ private static final int DEFAULT_THREAD_POOL_SIZE = 10;
+
+ protected final Logger log = getLogger(getClass());
+
+ private final Lock requestLock = new ReentrantLock();
+ private final Context.CancellableContext cancellableContext =
+ Context.current().withCancellation();
+ private final Executor contextExecutor;
+
+ protected final ExecutorService executorService;
+ protected final DeviceId deviceId;
+
+ protected AbstractGrpcClient(GrpcClientKey clientKey) {
+ this.deviceId = clientKey.deviceId();
+ this.executorService = Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE, groupedThreads(
+ "onos-grpc-" + clientKey.serviceName() + "-client-" + deviceId.toString(), "%d"));
+ this.contextExecutor = this.cancellableContext.fixedContextExecutor(executorService);
+ }
+
+ @Override
+ public CompletableFuture<Void> shutdown() {
+ return supplyWithExecutor(this::doShutdown, "shutdown",
+ SharedExecutors.getPoolThreadExecutor());
+ }
+
+ protected Void doShutdown() {
+ log.debug("Shutting down client for {}...", deviceId);
+ cancellableContext.cancel(new InterruptedException(
+ "Requested client shutdown"));
+ this.executorService.shutdownNow();
+ try {
+ executorService.awaitTermination(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ log.warn("Executor service didn't shutdown in time.");
+ Thread.currentThread().interrupt();
+ }
+ return null;
+ }
+
+ /**
+ * Equivalent of supplyWithExecutor using the gRPC context executor of this
+ * client, such that if the context is cancelled (e.g. client shutdown) the
+ * RPC is automatically cancelled.
+ *
+ * @param <U> return type of supplier
+ * @param supplier the supplier to be executed
+ * @param opDescription the description of this supplier
+ * @return CompletableFuture includes the result of supplier
+ */
+ protected <U> CompletableFuture<U> supplyInContext(
+ Supplier<U> supplier, String opDescription) {
+ return supplyWithExecutor(supplier, opDescription, contextExecutor);
+ }
+
+ /**
+ * Submits a task for async execution via the given executor. All tasks
+ * submitted with this method will be executed sequentially.
+ *
+ * @param <U> return type of supplier
+ * @param supplier the supplier to be executed
+ * @param opDescription the description of this supplier
+ * @param executor the executor to execute this supplier
+ * @return CompletableFuture includes the result of supplier
+ */
+ private <U> CompletableFuture<U> supplyWithExecutor(
+ Supplier<U> supplier, String opDescription, Executor executor) {
+ return CompletableFuture.supplyAsync(() -> {
+ // TODO: explore a more relaxed locking strategy.
+ try {
+ if (!requestLock.tryLock(LOCK_TIMEOUT, TimeUnit.SECONDS)) {
+ log.error("LOCK TIMEOUT! This is likely a deadlock, "
+ + "please debug (executing {})",
+ opDescription);
+ throw new IllegalThreadStateException("Lock timeout");
+ }
+ } catch (InterruptedException e) {
+ log.warn("Thread interrupted while waiting for lock (executing {})",
+ opDescription);
+ throw new IllegalStateException(e);
+ }
+ try {
+ return supplier.get();
+ } catch (StatusRuntimeException ex) {
+ log.warn("Unable to execute {} on {}: {}",
+ opDescription, deviceId, ex.toString());
+ throw ex;
+ } catch (Throwable ex) {
+ log.error("Exception in client of {}, executing {}",
+ deviceId, opDescription, ex);
+ throw ex;
+ } finally {
+ requestLock.unlock();
+ }
+ }, executor);
+ }
+}
diff --git a/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/AbstractGrpcClientController.java b/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/AbstractGrpcClientController.java
new file mode 100644
index 0000000..f82d2f8
--- /dev/null
+++ b/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/AbstractGrpcClientController.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.grpc.ctl;
+
+import com.google.common.collect.Maps;
+import com.google.common.util.concurrent.Striped;
+import io.grpc.ManagedChannel;
+import io.grpc.ManagedChannelBuilder;
+import io.grpc.netty.NettyChannelBuilder;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.event.AbstractListenerManager;
+import org.onosproject.event.Event;
+import org.onosproject.event.EventListener;
+import org.onosproject.grpc.api.GrpcChannelController;
+import org.onosproject.grpc.api.GrpcChannelId;
+import org.onosproject.grpc.api.GrpcClient;
+import org.onosproject.grpc.api.GrpcClientController;
+import org.onosproject.grpc.api.GrpcClientKey;
+import org.onosproject.net.DeviceId;
+import org.slf4j.Logger;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Supplier;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Abstract class of a gRPC based client controller for specific gRPC client
+ * which provides basic gRPC client management and thread safe mechanism.
+ *
+ * @param <C> the gRPC client type
+ * @param <K> the key type of the gRPC client
+ * @param <E> the event type of the gRPC client
+ * @param <L> the event listener of event {@link E}
+ */
+@Component
+public abstract class AbstractGrpcClientController
+ <K extends GrpcClientKey, C extends GrpcClient, E extends Event, L extends EventListener<E>>
+ extends AbstractListenerManager<E, L>
+ implements GrpcClientController<K, C> {
+
+ /**
+ * The default max inbound message size (MB).
+ */
+ private static final int DEFAULT_MAX_INBOUND_MSG_SIZE = 256; // Megabytes.
+ private static final int MEGABYTES = 1024 * 1024;
+ private static final int DEFAULT_DEVICE_LOCK_SIZE = 30;
+
+ private final Logger log = getLogger(getClass());
+ private final Map<DeviceId, K> clientKeys = Maps.newHashMap();
+ private final Map<K, C> clients = Maps.newHashMap();
+ private final Map<DeviceId, GrpcChannelId> channelIds = Maps.newHashMap();
+ private final Striped<Lock> stripedLocks = Striped.lock(DEFAULT_DEVICE_LOCK_SIZE);
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ private GrpcChannelController grpcChannelController;
+
+ @Activate
+ public void activate() {
+ log.info("Started");
+ }
+
+ @Deactivate
+ public void deactivate() {
+ clientKeys.keySet().forEach(this::removeClient);
+ clientKeys.clear();
+ clients.clear();
+ channelIds.clear();
+ log.info("Stopped");
+ }
+
+ @Override
+ public boolean createClient(K clientKey) {
+ checkNotNull(clientKey);
+ return withDeviceLock(() -> doCreateClient(clientKey), clientKey.deviceId());
+ }
+
+ private boolean doCreateClient(K clientKey) {
+ DeviceId deviceId = clientKey.deviceId();
+ String serverAddr = clientKey.serverAddr();
+ int serverPort = clientKey.serverPort();
+
+ if (clientKeys.containsKey(deviceId)) {
+ final GrpcClientKey existingKey = clientKeys.get(deviceId);
+ if (clientKey.equals(existingKey)) {
+ log.debug("Not creating client for {} as it already exists (key={})...",
+ deviceId, clientKey);
+ return true;
+ } else {
+ log.info("Requested client for {} with new " +
+ "endpoint, removing old client (key={})...",
+ deviceId, clientKey);
+ doRemoveClient(deviceId);
+ }
+ }
+ log.info("Creating client for {} (server={}:{})...",
+ deviceId, serverAddr, serverPort);
+ GrpcChannelId channelId = GrpcChannelId.of(clientKey.deviceId(), clientKey.toString());
+ ManagedChannelBuilder channelBuilder = NettyChannelBuilder
+ .forAddress(serverAddr, serverPort)
+ .maxInboundMessageSize(DEFAULT_MAX_INBOUND_MSG_SIZE * MEGABYTES)
+ .usePlaintext();
+
+ ManagedChannel channel;
+ try {
+ channel = grpcChannelController.connectChannel(channelId, channelBuilder);
+ } catch (IOException e) {
+ log.warn("Unable to connect to gRPC server of {}: {}",
+ clientKey.deviceId(), e.getMessage());
+ return false;
+ }
+
+ C client = createClientInstance(clientKey, channel);
+ if (client == null) {
+ log.warn("Cannot create client for {} (key={})", deviceId, clientKey);
+ return false;
+ }
+ clientKeys.put(deviceId, clientKey);
+ clients.put(clientKey, client);
+ channelIds.put(deviceId, channelId);
+
+ return true;
+ }
+
+ protected abstract C createClientInstance(K clientKey, ManagedChannel channel);
+
+ @Override
+ public C getClient(DeviceId deviceId) {
+ checkNotNull(deviceId);
+ return withDeviceLock(() -> doGetClient(deviceId), deviceId);
+ }
+
+ private C doGetClient(DeviceId deviceId) {
+ if (!clientKeys.containsKey(deviceId)) {
+ return null;
+ }
+ return clients.get(clientKeys.get(deviceId));
+ }
+
+ @Override
+ public void removeClient(DeviceId deviceId) {
+ checkNotNull(deviceId);
+ withDeviceLock(() -> doRemoveClient(deviceId), deviceId);
+ }
+
+ private Void doRemoveClient(DeviceId deviceId) {
+ if (clientKeys.containsKey(deviceId)) {
+ final K clientKey = clientKeys.get(deviceId);
+ clients.get(clientKey).shutdown();
+ grpcChannelController.disconnectChannel(channelIds.get(deviceId));
+ clientKeys.remove(deviceId);
+ clients.remove(clientKey);
+ channelIds.remove(deviceId);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isReachable(DeviceId deviceId) {
+ checkNotNull(deviceId);
+ return withDeviceLock(() -> doIsReachable(deviceId), deviceId);
+ }
+
+ private boolean doIsReachable(DeviceId deviceId) {
+ // Default behaviour checks only the gRPC channel, should
+ // check according to different gRPC service
+ if (!clientKeys.containsKey(deviceId)) {
+ log.debug("No client for {}, can't check for reachability", deviceId);
+ return false;
+ }
+ return grpcChannelController.isChannelOpen(channelIds.get(deviceId));
+ }
+
+ private <U> U withDeviceLock(Supplier<U> task, DeviceId deviceId) {
+ final Lock lock = stripedLocks.get(deviceId);
+ lock.lock();
+ try {
+ return task.get();
+ } finally {
+ lock.unlock();
+ }
+ }
+}
diff --git a/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/GrpcControllerImpl.java b/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/GrpcChannelControllerImpl.java
similarity index 97%
rename from protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/GrpcControllerImpl.java
rename to protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/GrpcChannelControllerImpl.java
index fb87571..6bd6a82 100644
--- a/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/GrpcControllerImpl.java
+++ b/protocols/grpc/ctl/src/main/java/org/onosproject/grpc/ctl/GrpcChannelControllerImpl.java
@@ -41,8 +41,8 @@
import org.apache.felix.scr.annotations.Service;
import org.onlab.util.Tools;
import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.grpc.api.GrpcChannelController;
import org.onosproject.grpc.api.GrpcChannelId;
-import org.onosproject.grpc.api.GrpcController;
import org.onosproject.grpc.proto.dummy.Dummy;
import org.onosproject.grpc.proto.dummy.DummyServiceGrpc;
import org.onosproject.net.DeviceId;
@@ -64,12 +64,13 @@
import static com.google.common.base.Preconditions.checkNotNull;
/**
- * Default implementation of the GrpcController.
+ * Default implementation of the GrpcChannelController.
*/
@Component(immediate = true)
@Service
-public class GrpcControllerImpl implements GrpcController {
+public class GrpcChannelControllerImpl implements GrpcChannelController {
+ // FIXME: Should use message size to determine whether it needs to log the message or not.
private static final String SET_FORWARDING_PIPELINE_CONFIG_METHOD = "p4.P4Runtime/SetForwardingPipelineConfig";
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
diff --git a/protocols/p4runtime/api/BUCK b/protocols/p4runtime/api/BUCK
index fd05763..c775aea 100644
--- a/protocols/p4runtime/api/BUCK
+++ b/protocols/p4runtime/api/BUCK
@@ -3,6 +3,7 @@
COMPILE_DEPS = [
'//lib:CORE_DEPS',
'//incubator/grpc-dependencies:grpc-core-repkg-' + GRPC_VER,
+ '//protocols/grpc/api:onos-protocols-grpc-api',
]
TEST_DEPS = [
diff --git a/protocols/p4runtime/api/BUILD b/protocols/p4runtime/api/BUILD
index 531d734..2fb15ba 100644
--- a/protocols/p4runtime/api/BUILD
+++ b/protocols/p4runtime/api/BUILD
@@ -1,4 +1,5 @@
COMPILE_DEPS = CORE_DEPS + [
+ "//protocols/grpc/api:onos-protocols-grpc-api",
"@io_grpc_grpc_java//core",
]
diff --git a/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClient.java b/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClient.java
index f44c629..7a08668 100644
--- a/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClient.java
+++ b/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClient.java
@@ -17,6 +17,7 @@
package org.onosproject.p4runtime.api;
import com.google.common.annotations.Beta;
+import org.onosproject.grpc.api.GrpcClient;
import org.onosproject.net.pi.model.PiActionProfileId;
import org.onosproject.net.pi.model.PiCounterId;
import org.onosproject.net.pi.model.PiMeterId;
@@ -42,7 +43,7 @@
* Client to control a P4Runtime device.
*/
@Beta
-public interface P4RuntimeClient {
+public interface P4RuntimeClient extends GrpcClient {
/**
* Type of write operation.
@@ -70,15 +71,6 @@
boolean isStreamChannelOpen();
/**
- * Shutdowns the client by terminating any active RPC such as the Stream
- * one.
- *
- * @return a completable future to signal the completion of the shutdown
- * procedure
- */
- CompletableFuture<Void> shutdown();
-
- /**
* Sends a master arbitration update to the device with a new election ID
* that is guaranteed to be the highest value between all clients.
*
diff --git a/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClientKey.java b/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClientKey.java
new file mode 100644
index 0000000..70bf33c
--- /dev/null
+++ b/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeClientKey.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.p4runtime.api;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.grpc.api.GrpcClientKey;
+import org.onosproject.net.DeviceId;
+
+import java.util.Objects;
+
+/**
+ * Key that uniquely identifies a P4Runtime client.
+ */
+@Beta
+public final class P4RuntimeClientKey extends GrpcClientKey {
+ private static final String P4R_SERVICE_NAME = "p4runtime";
+ private final long p4DeviceId;
+
+ /**
+ * Creates a new client key.
+ *
+ * @param deviceId ONOS device ID
+ * @param serverAddr P4Runtime server address
+ * @param serverPort P4Runtime server port
+ * @param p4DeviceId P4Runtime server-internal device ID
+ */
+ public P4RuntimeClientKey(DeviceId deviceId, String serverAddr,
+ int serverPort, long p4DeviceId) {
+ super(P4R_SERVICE_NAME, deviceId, serverAddr, serverPort);
+ this.p4DeviceId = p4DeviceId;
+ }
+
+ /**
+ * Returns the P4Runtime server-internal device ID.
+ *
+ * @return P4Runtime server-internal device ID
+ */
+ public long p4DeviceId() {
+ return p4DeviceId;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ if (!super.equals(o)) {
+ return false;
+ }
+ P4RuntimeClientKey that = (P4RuntimeClientKey) o;
+ return p4DeviceId == that.p4DeviceId;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(super.hashCode(), p4DeviceId);
+ }
+
+ @Override
+ public String toString() {
+ return super.toStringHelper()
+ .add("p4DeviceId", p4DeviceId)
+ .toString();
+ }
+}
diff --git a/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeController.java b/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeController.java
index 159e313..0bc8ed6 100644
--- a/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeController.java
+++ b/protocols/p4runtime/api/src/main/java/org/onosproject/p4runtime/api/P4RuntimeController.java
@@ -18,6 +18,7 @@
import com.google.common.annotations.Beta;
import org.onosproject.event.ListenerService;
+import org.onosproject.grpc.api.GrpcClientController;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceAgentListener;
import org.onosproject.net.provider.ProviderId;
@@ -27,73 +28,8 @@
*/
@Beta
public interface P4RuntimeController
- extends ListenerService<P4RuntimeEvent, P4RuntimeEventListener> {
-
- /**
- * Instantiates a new client to operate on a P4Runtime device identified by
- * the given information. As a result of this method, a {@link
- * P4RuntimeClient} can be later obtained by invoking {@link
- * #getClient(DeviceId)}. Returns true if the client was created and the
- * channel to the device is open, false otherwise.
- * <p>
- * Only one client can exist for the same device ID. Calls to this method
- * are idempotent for the same [device ID, address, port, p4DeviceId]
- * triplet, i.e. returns true if such client already exists but a new one is
- * not created. Throws an {@link IllegalStateException} if a client for
- * device ID already exists but for different [address, port, p4DeviceId].
- *
- * @param deviceId device identifier
- * @param serverAddr address of the P4Runtime server
- * @param serverPort port of the P4Runtime server
- * @param p4DeviceId P4Runtime-specific device identifier
- * @return true if the client was created and the channel to the device is
- * open
- * @throws IllegalStateException if a client already exists for this device
- * ID but for different [address, port,
- * p4DeviceId] triplet.
- */
- boolean createClient(DeviceId deviceId, String serverAddr, int serverPort,
- long p4DeviceId);
-
- /**
- * Returns a client to operate on the given device, or null if a client for
- * such device does not exist in this controller.
- *
- * @param deviceId device identifier
- * @return client instance or null
- */
- P4RuntimeClient getClient(DeviceId deviceId);
-
- /**
- * Removes the client for the given device. If no client exists for the
- * given device identifier, the result is a no-op.
- *
- * @param deviceId device identifier
- */
- void removeClient(DeviceId deviceId);
-
- /**
- * Returns true if a client exists for the given device identifier, false
- * otherwise.
- *
- * @param deviceId device identifier
- * @return true if client exists, false otherwise.
- */
- boolean hasClient(DeviceId deviceId);
-
- /**
- * Returns true if the P4Runtime server running on the given device is
- * reachable, i.e. the channel is open and the server is able to respond to
- * RPCs, false otherwise. Reachability can be tested only if a client was
- * previously created using {@link #createClient(DeviceId, String, int,
- * long)}, otherwise this method returns false.
- *
- * @param deviceId device identifier.
- * @return true if a client was created and is able to contact the P4Runtime
- * server, false otherwise.
- */
- boolean isReachable(DeviceId deviceId);
-
+ extends GrpcClientController<P4RuntimeClientKey, P4RuntimeClient>,
+ ListenerService<P4RuntimeEvent, P4RuntimeEventListener> {
/**
* Adds a listener for device agent events for the given provider.
*
diff --git a/protocols/p4runtime/ctl/BUILD b/protocols/p4runtime/ctl/BUILD
index d6c0c7a..66aab43 100644
--- a/protocols/p4runtime/ctl/BUILD
+++ b/protocols/p4runtime/ctl/BUILD
@@ -1,6 +1,7 @@
COMPILE_DEPS = CORE_DEPS + KRYO + [
"//core/store/serializers:onos-core-serializers",
"//protocols/grpc/api:onos-protocols-grpc-api",
+ "//protocols/grpc/ctl:onos-protocols-grpc-ctl",
"//protocols/p4runtime/api:onos-protocols-p4runtime-api",
"//protocols/p4runtime/proto:onos-protocols-p4runtime-proto",
"@com_google_protobuf//:protobuf_java",
diff --git a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/ClientKey.java b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/ClientKey.java
deleted file mode 100644
index cc4bed0..0000000
--- a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/ClientKey.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.onosproject.p4runtime.ctl;
-
-import com.google.common.base.MoreObjects;
-import org.onosproject.net.DeviceId;
-
-import java.util.Objects;
-
-/**
- * Key that uniquely identifies a P4Runtime client.
- */
-final class ClientKey {
-
- private final DeviceId deviceId;
- private final String serverAddr;
- private final int serverPort;
- private final long p4DeviceId;
-
- /**
- * Creates a new client key.
- *
- * @param deviceId ONOS device ID
- * @param serverAddr P4Runtime server address
- * @param serverPort P4Runtime server port
- * @param p4DeviceId P4Runtime server-internal device ID
- */
- ClientKey(DeviceId deviceId, String serverAddr, int serverPort, long p4DeviceId) {
- this.deviceId = deviceId;
- this.serverAddr = serverAddr;
- this.serverPort = serverPort;
- this.p4DeviceId = p4DeviceId;
- }
-
- /**
- * Returns the device ID.
- *
- * @return device ID.
- */
- public DeviceId deviceId() {
- return deviceId;
- }
-
- /**
- * Returns the P4Runtime server address.
- *
- * @return P4Runtime server address
- */
- public String serverAddr() {
- return serverAddr;
- }
-
- /**
- * Returns the P4Runtime server port.
- *
- * @return P4Runtime server port
- */
- public int serverPort() {
- return serverPort;
- }
-
- /**
- * Returns the P4Runtime server-internal device ID.
- *
- * @return P4Runtime server-internal device ID
- */
- public long p4DeviceId() {
- return p4DeviceId;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(serverAddr, serverPort, p4DeviceId);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null || getClass() != obj.getClass()) {
- return false;
- }
- final ClientKey other = (ClientKey) obj;
- return Objects.equals(this.serverAddr, other.serverAddr)
- && Objects.equals(this.serverPort, other.serverPort)
- && Objects.equals(this.p4DeviceId, other.p4DeviceId);
- }
-
- @Override
- public String toString() {
- return MoreObjects.toStringHelper(this)
- .add("deviceId", deviceId)
- .add("serverAddr", serverAddr)
- .add("serverPort", serverPort)
- .add("p4DeviceId", p4DeviceId)
- .toString();
- }
-}
diff --git a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeClientImpl.java b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeClientImpl.java
index d806233..d5080ae 100644
--- a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeClientImpl.java
+++ b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeClientImpl.java
@@ -23,7 +23,6 @@
import com.google.common.collect.Sets;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
-import io.grpc.Context;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.Status;
@@ -32,9 +31,8 @@
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.StreamObserver;
import org.onlab.osgi.DefaultServiceDirectory;
-import org.onlab.util.SharedExecutors;
import org.onlab.util.Tools;
-import org.onosproject.net.DeviceId;
+import org.onosproject.grpc.ctl.AbstractGrpcClient;
import org.onosproject.net.pi.model.PiActionProfileId;
import org.onosproject.net.pi.model.PiCounterId;
import org.onosproject.net.pi.model.PiMeterId;
@@ -52,8 +50,8 @@
import org.onosproject.net.pi.runtime.PiTableEntry;
import org.onosproject.net.pi.service.PiPipeconfService;
import org.onosproject.p4runtime.api.P4RuntimeClient;
+import org.onosproject.p4runtime.api.P4RuntimeClientKey;
import org.onosproject.p4runtime.api.P4RuntimeEvent;
-import org.slf4j.Logger;
import p4.config.v1.P4InfoOuterClass.P4Info;
import p4.tmp.P4Config;
import p4.v1.P4RuntimeGrpc;
@@ -87,22 +85,13 @@
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
-import static org.onlab.util.Tools.groupedThreads;
-import static org.slf4j.LoggerFactory.getLogger;
import static p4.v1.P4RuntimeOuterClass.Entity.EntityCase.ACTION_PROFILE_GROUP;
import static p4.v1.P4RuntimeOuterClass.Entity.EntityCase.ACTION_PROFILE_MEMBER;
import static p4.v1.P4RuntimeOuterClass.Entity.EntityCase.PACKET_REPLICATION_ENGINE_ENTRY;
@@ -115,10 +104,7 @@
/**
* Implementation of a P4Runtime client.
*/
-final class P4RuntimeClientImpl implements P4RuntimeClient {
-
- // Timeout in seconds to obtain the request lock.
- private static final int LOCK_TIMEOUT = 60;
+final class P4RuntimeClientImpl extends AbstractGrpcClient implements P4RuntimeClient {
private static final Metadata.Key<com.google.rpc.Status> STATUS_DETAILS_KEY =
Metadata.Key.of("grpc-status-details-bin",
@@ -132,18 +118,9 @@
WriteOperationType.DELETE, Update.Type.DELETE
);
- private final Logger log = getLogger(getClass());
-
- private final Lock requestLock = new ReentrantLock();
- private final Context.CancellableContext cancellableContext =
- Context.current().withCancellation();
-
- private final DeviceId deviceId;
private final long p4DeviceId;
private final P4RuntimeControllerImpl controller;
private final P4RuntimeGrpc.P4RuntimeBlockingStub blockingStub;
- private final ExecutorService executorService;
- private final Executor contextExecutor;
private StreamChannelManager streamChannelManager;
// Used by this client for write requests.
@@ -154,70 +131,22 @@
/**
* Default constructor.
*
- * @param deviceId the ONOS device id
- * @param p4DeviceId the P4 device id
+ * @param clientKey the client key of this client
* @param channel gRPC channel
* @param controller runtime client controller
*/
- P4RuntimeClientImpl(DeviceId deviceId, long p4DeviceId, ManagedChannel channel,
+ P4RuntimeClientImpl(P4RuntimeClientKey clientKey, ManagedChannel channel,
P4RuntimeControllerImpl controller) {
- this.deviceId = deviceId;
- this.p4DeviceId = p4DeviceId;
+
+ super(clientKey);
+ this.p4DeviceId = clientKey.p4DeviceId();
this.controller = controller;
- this.executorService = Executors.newFixedThreadPool(15, groupedThreads(
- "onos-p4runtime-client-" + deviceId.toString(), "%d"));
- this.contextExecutor = this.cancellableContext.fixedContextExecutor(executorService);
+
//TODO Investigate use of stub deadlines instead of timeout in supplyInContext
this.blockingStub = P4RuntimeGrpc.newBlockingStub(channel);
this.streamChannelManager = new StreamChannelManager(channel);
}
- /**
- * Submits a task for async execution via the given executor. All tasks
- * submitted with this method will be executed sequentially.
- */
- private <U> CompletableFuture<U> supplyWithExecutor(
- Supplier<U> supplier, String opDescription, Executor executor) {
- return CompletableFuture.supplyAsync(() -> {
- // TODO: explore a more relaxed locking strategy.
- try {
- if (!requestLock.tryLock(LOCK_TIMEOUT, TimeUnit.SECONDS)) {
- log.error("LOCK TIMEOUT! This is likely a deadlock, "
- + "please debug (executing {})",
- opDescription);
- throw new IllegalThreadStateException("Lock timeout");
- }
- } catch (InterruptedException e) {
- log.warn("Thread interrupted while waiting for lock (executing {})",
- opDescription);
- throw new IllegalStateException(e);
- }
- try {
- return supplier.get();
- } catch (StatusRuntimeException ex) {
- log.warn("Unable to execute {} on {}: {}",
- opDescription, deviceId, ex.toString());
- throw ex;
- } catch (Throwable ex) {
- log.error("Exception in client of {}, executing {}",
- deviceId, opDescription, ex);
- throw ex;
- } finally {
- requestLock.unlock();
- }
- }, executor);
- }
-
- /**
- * Equivalent of supplyWithExecutor using the gRPC context executor of this
- * client, such that if the context is cancelled (e.g. client shutdown) the
- * RPC is automatically cancelled.
- */
- private <U> CompletableFuture<U> supplyInContext(
- Supplier<U> supplier, String opDescription) {
- return supplyWithExecutor(supplier, opDescription, contextExecutor);
- }
-
@Override
public CompletableFuture<Boolean> startStreamChannel() {
return supplyInContext(() -> sendMasterArbitrationUpdate(false),
@@ -225,12 +154,6 @@
}
@Override
- public CompletableFuture<Void> shutdown() {
- return supplyWithExecutor(this::doShutdown, "shutdown",
- SharedExecutors.getPoolThreadExecutor());
- }
-
- @Override
public CompletableFuture<Boolean> becomeMaster() {
return supplyInContext(() -> sendMasterArbitrationUpdate(true),
"becomeMaster");
@@ -1202,19 +1125,9 @@
.build();
}
- private Void doShutdown() {
- log.debug("Shutting down client for {}...", deviceId);
+ protected Void doShutdown() {
streamChannelManager.complete();
- cancellableContext.cancel(new InterruptedException(
- "Requested client shutdown"));
- this.executorService.shutdownNow();
- try {
- executorService.awaitTermination(5, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- log.warn("Executor service didn't shutdown in time.");
- Thread.currentThread().interrupt();
- }
- return null;
+ return super.doShutdown();
}
// Returns the collection of succesfully write entities.
diff --git a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeControllerImpl.java b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeControllerImpl.java
index a140491..abafaf5 100644
--- a/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeControllerImpl.java
+++ b/protocols/p4runtime/ctl/src/main/java/org/onosproject/p4runtime/ctl/P4RuntimeControllerImpl.java
@@ -19,36 +19,29 @@
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Striped;
import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
-import io.grpc.netty.NettyChannelBuilder;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
-import org.onosproject.event.AbstractListenerManager;
-import org.onosproject.grpc.api.GrpcChannelId;
-import org.onosproject.grpc.api.GrpcController;
+import org.onosproject.grpc.ctl.AbstractGrpcClientController;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceAgentEvent;
import org.onosproject.net.device.DeviceAgentListener;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.p4runtime.api.P4RuntimeClient;
+import org.onosproject.p4runtime.api.P4RuntimeClientKey;
import org.onosproject.p4runtime.api.P4RuntimeController;
import org.onosproject.p4runtime.api.P4RuntimeEvent;
import org.onosproject.p4runtime.api.P4RuntimeEventListener;
import org.onosproject.store.service.StorageService;
import org.slf4j.Logger;
-import java.io.IOException;
import java.math.BigInteger;
-import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
-import java.util.function.Supplier;
-import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
@@ -58,19 +51,12 @@
@Component(immediate = true)
@Service
public class P4RuntimeControllerImpl
- extends AbstractListenerManager<P4RuntimeEvent, P4RuntimeEventListener>
+ extends AbstractGrpcClientController
+ <P4RuntimeClientKey, P4RuntimeClient, P4RuntimeEvent, P4RuntimeEventListener>
implements P4RuntimeController {
- // Getting the pipeline config from the device can take tens of MBs.
- private static final int MAX_INBOUND_MSG_SIZE = 256; // Megabytes.
- private static final int MEGABYTES = 1024 * 1024;
-
private final Logger log = getLogger(getClass());
- private final Map<DeviceId, ClientKey> clientKeys = Maps.newHashMap();
- private final Map<ClientKey, P4RuntimeClient> clients = Maps.newHashMap();
- private final Map<DeviceId, GrpcChannelId> channelIds = Maps.newHashMap();
-
private final ConcurrentMap<DeviceId, ConcurrentMap<ProviderId, DeviceAgentListener>>
deviceAgentListeners = Maps.newConcurrentMap();
private final Striped<Lock> stripedLocks = Striped.lock(30);
@@ -78,151 +64,28 @@
private DistributedElectionIdGenerator electionIdGenerator;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
- private GrpcController grpcController;
-
- @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
private StorageService storageService;
@Activate
public void activate() {
+ super.activate();
eventDispatcher.addSink(P4RuntimeEvent.class, listenerRegistry);
electionIdGenerator = new DistributedElectionIdGenerator(storageService);
log.info("Started");
}
-
@Deactivate
public void deactivate() {
- clientKeys.keySet().forEach(this::removeClient);
- clientKeys.clear();
- clients.clear();
- channelIds.clear();
+ super.deactivate();
deviceAgentListeners.clear();
- grpcController = null;
electionIdGenerator.destroy();
electionIdGenerator = null;
- eventDispatcher.removeSink(P4RuntimeEvent.class);
log.info("Stopped");
}
@Override
- public boolean createClient(DeviceId deviceId, String serverAddr,
- int serverPort, long p4DeviceId) {
- checkNotNull(deviceId);
- checkNotNull(serverAddr);
- checkArgument(serverPort > 0, "Invalid server port");
-
- return withDeviceLock(() -> doCreateClient(
- deviceId, serverAddr, serverPort, p4DeviceId), deviceId);
- }
-
- private boolean doCreateClient(DeviceId deviceId, String serverAddr,
- int serverPort, long p4DeviceId) {
-
- ClientKey clientKey = new ClientKey(deviceId, serverAddr, serverPort, p4DeviceId);
-
- if (clientKeys.containsKey(deviceId)) {
- final ClientKey existingKey = clientKeys.get(deviceId);
- if (clientKey.equals(existingKey)) {
- log.debug("Not creating client for {} as it already exists (server={}:{}, p4DeviceId={})...",
- deviceId, serverAddr, serverPort, p4DeviceId);
- return true;
- } else {
- log.info("Requested client for {} with new " +
- "endpoint, removing old client (server={}:{}, " +
- "p4DeviceId={})...",
- deviceId, existingKey.serverAddr(),
- existingKey.serverPort(), existingKey.p4DeviceId());
- doRemoveClient(deviceId);
- }
- }
-
- log.info("Creating client for {} (server={}:{}, p4DeviceId={})...",
- deviceId, serverAddr, serverPort, p4DeviceId);
-
- GrpcChannelId channelId = GrpcChannelId.of(
- clientKey.deviceId(), "p4runtime-" + clientKey);
-
- ManagedChannelBuilder channelBuilder = NettyChannelBuilder
- .forAddress(serverAddr, serverPort)
- .maxInboundMessageSize(MAX_INBOUND_MSG_SIZE * MEGABYTES)
- .usePlaintext();
-
- ManagedChannel channel;
- try {
- channel = grpcController.connectChannel(channelId, channelBuilder);
- } catch (IOException e) {
- log.warn("Unable to connect to gRPC server of {}: {}",
- clientKey.deviceId(), e.getMessage());
- return false;
- }
-
- P4RuntimeClient client = new P4RuntimeClientImpl(
- clientKey.deviceId(), clientKey.p4DeviceId(), channel, this);
-
- clientKeys.put(clientKey.deviceId(), clientKey);
- clients.put(clientKey, client);
- channelIds.put(clientKey.deviceId(), channelId);
-
- return true;
- }
-
- @Override
- public P4RuntimeClient getClient(DeviceId deviceId) {
- if (deviceId == null) {
- return null;
- }
- return withDeviceLock(() -> doGetClient(deviceId), deviceId);
- }
-
- private P4RuntimeClient doGetClient(DeviceId deviceId) {
- if (!clientKeys.containsKey(deviceId)) {
- return null;
- } else {
- return clients.get(clientKeys.get(deviceId));
- }
- }
-
- @Override
- public void removeClient(DeviceId deviceId) {
- if (deviceId == null) {
- return;
- }
- withDeviceLock(() -> doRemoveClient(deviceId), deviceId);
- }
-
- private Void doRemoveClient(DeviceId deviceId) {
- if (clientKeys.containsKey(deviceId)) {
- final ClientKey clientKey = clientKeys.get(deviceId);
- clients.get(clientKey).shutdown();
- grpcController.disconnectChannel(channelIds.get(deviceId));
- clientKeys.remove(deviceId);
- clients.remove(clientKey);
- channelIds.remove(deviceId);
- }
- return null;
- }
-
- @Override
- public boolean hasClient(DeviceId deviceId) {
- return clientKeys.containsKey(deviceId);
- }
-
- @Override
- public boolean isReachable(DeviceId deviceId) {
- if (deviceId == null) {
- return false;
- }
- return withDeviceLock(() -> doIsReacheable(deviceId), deviceId);
- }
-
- private boolean doIsReacheable(DeviceId deviceId) {
- // FIXME: we're not checking for a P4Runtime server, it could be any gRPC service
- if (!clientKeys.containsKey(deviceId)) {
- log.debug("No client for {}, can't check for reachability", deviceId);
- return false;
- }
- return grpcController.isChannelOpen(channelIds.get(deviceId));
+ protected P4RuntimeClient createClientInstance(P4RuntimeClientKey clientKey, ManagedChannel channel) {
+ return new P4RuntimeClientImpl(clientKey, channel, this);
}
@Override
@@ -244,16 +107,6 @@
});
}
- private <U> U withDeviceLock(Supplier<U> task, DeviceId deviceId) {
- final Lock lock = stripedLocks.get(deviceId);
- lock.lock();
- try {
- return task.get();
- } finally {
- lock.unlock();
- }
- }
-
BigInteger newMasterElectionId(DeviceId deviceId) {
return electionIdGenerator.generate(deviceId);
}
diff --git a/protocols/p4runtime/ctl/src/test/java/org/onosproject/p4runtime/ctl/P4RuntimeGroupTest.java b/protocols/p4runtime/ctl/src/test/java/org/onosproject/p4runtime/ctl/P4RuntimeGroupTest.java
index 36e60ea..301d5e1 100644
--- a/protocols/p4runtime/ctl/src/test/java/org/onosproject/p4runtime/ctl/P4RuntimeGroupTest.java
+++ b/protocols/p4runtime/ctl/src/test/java/org/onosproject/p4runtime/ctl/P4RuntimeGroupTest.java
@@ -44,6 +44,7 @@
import org.onosproject.net.pi.runtime.PiActionGroupMember;
import org.onosproject.net.pi.runtime.PiActionGroupMemberId;
import org.onosproject.net.pi.runtime.PiActionParam;
+import org.onosproject.p4runtime.api.P4RuntimeClientKey;
import p4.v1.P4RuntimeOuterClass.ActionProfileGroup;
import p4.v1.P4RuntimeOuterClass.ActionProfileMember;
import p4.v1.P4RuntimeOuterClass.Entity;
@@ -100,6 +101,8 @@
private static final String GRPC_SERVER_NAME = "P4RuntimeGroupTest";
private static final long DEFAULT_TIMEOUT_TIME = 10;
private static final Uint128 DEFAULT_ELECTION_ID = Uint128.newBuilder().setLow(1).build();
+ private static final String P4R_IP = "127.0.0.1";
+ private static final int P4R_PORT = 50010;
private P4RuntimeClientImpl client;
private P4RuntimeControllerImpl controller;
@@ -152,9 +155,8 @@
@Before
public void setup() {
controller = niceMock(P4RuntimeControllerImpl.class);
- client = new P4RuntimeClientImpl(DEVICE_ID, P4_DEVICE_ID,
- grpcChannel,
- controller);
+ P4RuntimeClientKey clientKey = new P4RuntimeClientKey(DEVICE_ID, P4R_IP, P4R_PORT, P4_DEVICE_ID);
+ client = new P4RuntimeClientImpl(clientKey, grpcChannel, controller);
client.becomeMaster();
}