blob: fa7231fbd4f5ec7a785ea4640d90637cf6155bd8 [file] [log] [blame]
Yi Tseng59d5f3e2018-11-27 23:09:41 -08001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.drivers.gnmi;
18
19import com.google.common.collect.Maps;
Carmelo Casconeab5d41e2019-03-06 18:02:34 -080020import com.google.common.util.concurrent.Futures;
Yi Tseng59d5f3e2018-11-27 23:09:41 -080021import gnmi.Gnmi;
22import gnmi.Gnmi.GetRequest;
23import gnmi.Gnmi.GetResponse;
24import gnmi.Gnmi.Path;
25import org.apache.commons.lang3.tuple.Pair;
26import org.onosproject.net.DeviceId;
27import org.onosproject.net.Port;
28import org.onosproject.net.PortNumber;
29import org.onosproject.net.device.DefaultPortStatistics;
30import org.onosproject.net.device.PortStatistics;
31import org.onosproject.net.device.PortStatisticsDiscovery;
32
33import java.time.Duration;
34import java.time.temporal.ChronoUnit;
35import java.util.Collection;
36import java.util.Collections;
37import java.util.List;
38import java.util.Map;
39import java.util.stream.Collectors;
40
41/**
42 * Behaviour to get port statistics from device via gNMI.
43 */
44public class OpenConfigGnmiPortStatisticsDiscovery extends AbstractGnmiHandlerBehaviour
45 implements PortStatisticsDiscovery {
46
47 private static final Map<Pair<DeviceId, PortNumber>, Long> PORT_START_TIMES =
48 Maps.newConcurrentMap();
Carmelo Casconeab5d41e2019-03-06 18:02:34 -080049 private static final String LAST_CHANGE = "last-changed";
Yi Tseng59d5f3e2018-11-27 23:09:41 -080050
51 @Override
52 public Collection<PortStatistics> discoverPortStatistics() {
Carmelo Casconec32976e2019-04-08 14:50:52 -070053 if (!setupBehaviour("discoverPortStatistics()")) {
Yi Tseng59d5f3e2018-11-27 23:09:41 -080054 return Collections.emptyList();
55 }
56
57 Map<String, PortNumber> ifacePortNumberMapping = Maps.newHashMap();
58 List<Port> ports = deviceService.getPorts(deviceId);
59 GetRequest.Builder getRequest = GetRequest.newBuilder();
60 getRequest.setEncoding(Gnmi.Encoding.PROTO);
61
62 // Use this path to get all counters from specific interface(port)
63 // /interfaces/interface[port-name]/state/counters/[counter name]
64 ports.forEach(port -> {
65 String portName = port.number().name();
66 Path path = interfaceCounterPath(portName);
67 getRequest.addPath(path);
68 ifacePortNumberMapping.put(portName, port.number());
69 });
70
Carmelo Casconeab5d41e2019-03-06 18:02:34 -080071 GetResponse getResponse = Futures.getUnchecked(client.get(getRequest.build()));
Yi Tseng59d5f3e2018-11-27 23:09:41 -080072
73 Map<String, Long> inPkts = Maps.newHashMap();
74 Map<String, Long> outPkts = Maps.newHashMap();
75 Map<String, Long> inBytes = Maps.newHashMap();
76 Map<String, Long> outBytes = Maps.newHashMap();
77 Map<String, Long> inDropped = Maps.newHashMap();
78 Map<String, Long> outDropped = Maps.newHashMap();
79 Map<String, Long> inErrors = Maps.newHashMap();
80 Map<String, Long> outErrors = Maps.newHashMap();
81 Map<String, Duration> timestamps = Maps.newHashMap();
82
83 // Collect responses and sum {in,out,dropped} packets
84 getResponse.getNotificationList().forEach(notification -> {
85 notification.getUpdateList().forEach(update -> {
86 Path path = update.getPath();
87 String ifName = interfaceNameFromPath(path);
88 timestamps.putIfAbsent(ifName, Duration.ofNanos(notification.getTimestamp()));
89
90 // Last element is the counter name
91 String counterName = path.getElem(path.getElemCount() - 1).getName();
92 long counterValue = update.getVal().getUintVal();
93
94
95 switch (counterName) {
96 case "in-octets":
97 inBytes.put(ifName, counterValue);
98 break;
99 case "out-octets":
100 outBytes.put(ifName, counterValue);
101 break;
102 case "in-discards":
103 case "in-fcs-errors":
104 inDropped.compute(ifName, (k, v) -> v == null ? counterValue : v + counterValue);
105 break;
106 case "out-discards":
107 outDropped.put(ifName, counterValue);
108 break;
109 case "in-errors":
110 inErrors.put(ifName, counterValue);
111 break;
112 case "out-errors":
113 outErrors.put(ifName, counterValue);
114 break;
115 case "in-unicast-pkts":
116 case "in-broadcast-pkts":
117 case "in-multicast-pkts":
118 case "in-unknown-protos":
119 inPkts.compute(ifName, (k, v) -> v == null ? counterValue : v + counterValue);
120 break;
121 case "out-unicast-pkts":
122 case "out-broadcast-pkts":
123 case "out-multicast-pkts":
124 outPkts.compute(ifName, (k, v) -> v == null ? counterValue : v + counterValue);
125 break;
126 default:
127 log.warn("Unsupported counter name {}, ignored", counterName);
128 break;
129 }
130 });
131 });
132
133 // Build ONOS port stats map
134 return ifacePortNumberMapping.entrySet().stream()
135 .map(e -> {
136 String ifName = e.getKey();
137 PortNumber portNumber = e.getValue();
138 Duration portActive = getDurationActive(portNumber, timestamps.get(ifName));
139 return DefaultPortStatistics.builder()
140 .setDeviceId(deviceId)
141 .setPort(portNumber)
142 .setDurationSec(portActive.getSeconds())
143 .setDurationNano(portActive.getNano())
144 .setPacketsSent(outPkts.getOrDefault(ifName, 0L))
145 .setPacketsReceived(inPkts.getOrDefault(ifName, 0L))
146 .setPacketsTxDropped(outDropped.getOrDefault(ifName, 0L))
147 .setPacketsRxDropped(inDropped.getOrDefault(ifName, 0L))
148 .setBytesSent(outBytes.getOrDefault(ifName, 0L))
149 .setBytesReceived(inBytes.getOrDefault(ifName, 0L))
150 .setPacketsTxErrors(outErrors.getOrDefault(ifName, 0L))
151 .setPacketsRxErrors(inErrors.getOrDefault(ifName, 0L))
152 .build();
153 })
154 .collect(Collectors.toList());
155
156 }
157
158 private String interfaceNameFromPath(Path path) {
159 // /interfaces/interface[name=iface-name]
160 return path.getElem(1).getKeyOrDefault("name", null);
161 }
162
163 private Path interfaceCounterPath(String portName) {
164 // /interfaces/interface[name=port-name]/state/counters
165 return Path.newBuilder()
166 .addElem(Gnmi.PathElem.newBuilder().setName("interfaces").build())
167 .addElem(Gnmi.PathElem.newBuilder().setName("interface")
168 .putKey("name", portName).build())
169 .addElem(Gnmi.PathElem.newBuilder().setName("state").build())
170 .addElem(Gnmi.PathElem.newBuilder().setName("counters").build())
171 .build();
172 }
173
174 private Duration getDurationActive(PortNumber portNumber, Duration timestamp) {
175 Port port = deviceService.getPort(deviceId, portNumber);
176 if (port == null || !port.isEnabled()) {
177 //FIXME log
178 return Duration.ZERO;
179 }
180 String lastChangedStr = port.annotations().value(LAST_CHANGE);
181 if (lastChangedStr == null) {
182 //FIXME log
183 // Falling back to the hack...
184 // FIXME: This is a workaround since we cannot determine the port
185 // duration from gNMI now
186 final long now = System.currentTimeMillis() / 1000;
187 final Long startTime = PORT_START_TIMES.putIfAbsent(
188 Pair.of(deviceId, portNumber), now);
189 return Duration.ofSeconds(startTime == null ? now : now - startTime);
190 }
191
192 try {
193 long lastChanged = Long.parseLong(lastChangedStr);
194 return timestamp.minus(lastChanged, ChronoUnit.NANOS);
195 } catch (NullPointerException | NumberFormatException ex) {
196 //FIXME log
197 return Duration.ZERO;
198 }
199 }
200}