blob: b430d370d6a86095788d2fd920a5657093a6355c [file] [log] [blame]
Madan Jampanic27b6b22016-02-05 11:36:31 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Madan Jampanic27b6b22016-02-05 11:36:31 -08003 *
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.store.statistic.impl;
18
19import com.google.common.base.Objects;
Madan Jampanic27b6b22016-02-05 11:36:31 -080020import org.onlab.util.Tools;
sangyun-han9f0af2d2016-08-04 13:04:59 +090021import org.onosproject.cfg.ComponentConfigService;
Madan Jampanic27b6b22016-02-05 11:36:31 -080022import org.onosproject.cluster.ClusterService;
23import org.onosproject.cluster.NodeId;
24import org.onosproject.mastership.MastershipService;
25import org.onosproject.net.ConnectPoint;
26import org.onosproject.net.DeviceId;
27import org.onosproject.net.PortNumber;
28import org.onosproject.net.flow.FlowEntry;
29import org.onosproject.net.flow.FlowRule;
30import org.onosproject.net.flow.instructions.Instruction;
31import org.onosproject.net.flow.instructions.Instructions;
32import org.onosproject.net.statistic.FlowStatisticStore;
33import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Madan Jampani78be2492016-06-03 23:27:07 -070034import org.onosproject.store.cluster.messaging.MessageSubject;
Madan Jampanic27b6b22016-02-05 11:36:31 -080035import org.onosproject.store.serializers.KryoNamespaces;
Jordan Halterman2c83a102017-08-20 17:11:41 -070036import org.onosproject.store.service.Serializer;
sangyun-hanad84e0c2016-02-19 18:30:03 +090037import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070038import org.osgi.service.component.annotations.Activate;
39import org.osgi.service.component.annotations.Component;
40import org.osgi.service.component.annotations.Deactivate;
41import org.osgi.service.component.annotations.Modified;
42import org.osgi.service.component.annotations.Reference;
43import org.osgi.service.component.annotations.ReferenceCardinality;
Madan Jampanic27b6b22016-02-05 11:36:31 -080044import org.slf4j.Logger;
45
46import java.util.Collections;
sangyun-hanad84e0c2016-02-19 18:30:03 +090047import java.util.Dictionary;
Madan Jampanic27b6b22016-02-05 11:36:31 -080048import java.util.HashSet;
49import java.util.Map;
50import java.util.Optional;
sangyun-hanad84e0c2016-02-19 18:30:03 +090051import java.util.Properties;
Madan Jampanic27b6b22016-02-05 11:36:31 -080052import java.util.Set;
53import java.util.concurrent.ConcurrentHashMap;
54import java.util.concurrent.ExecutorService;
55import java.util.concurrent.Executors;
56import java.util.concurrent.TimeUnit;
57
sangyun-hanad84e0c2016-02-19 18:30:03 +090058import static com.google.common.base.Preconditions.checkArgument;
59import static com.google.common.base.Strings.isNullOrEmpty;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070060import static java.util.concurrent.Executors.newFixedThreadPool;
sangyun-hanad84e0c2016-02-19 18:30:03 +090061import static org.onlab.util.Tools.get;
Madan Jampanic27b6b22016-02-05 11:36:31 -080062import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyb5646e62018-10-16 11:42:18 -070063import static org.onosproject.store.OsgiPropertyConstants.DFS_MESSAGE_HANDLER_THREAD_POOL_SIZE;
64import static org.onosproject.store.OsgiPropertyConstants.DFS_MESSAGE_HANDLER_THREAD_POOL_SIZE_DEFAULT;
Madan Jampanic27b6b22016-02-05 11:36:31 -080065import static org.slf4j.LoggerFactory.getLogger;
66
67/**
68 * Maintains flow statistics using RPC calls to collect stats from remote instances
69 * on demand.
70 */
Ray Milkeyb5646e62018-10-16 11:42:18 -070071@Component(
72 immediate = true,
73 service = FlowStatisticStore.class,
74 property = {
Ray Milkey2d7bca12018-10-17 14:51:52 -070075 DFS_MESSAGE_HANDLER_THREAD_POOL_SIZE + ":Integer=" + DFS_MESSAGE_HANDLER_THREAD_POOL_SIZE_DEFAULT
Ray Milkeyb5646e62018-10-16 11:42:18 -070076 }
77)
Madan Jampanic27b6b22016-02-05 11:36:31 -080078public class DistributedFlowStatisticStore implements FlowStatisticStore {
79 private final Logger log = getLogger(getClass());
80
sangyun-hanad84e0c2016-02-19 18:30:03 +090081 private static final String FORMAT = "Setting: messageHandlerThreadPoolSize={}";
Madan Jampanic27b6b22016-02-05 11:36:31 -080082
Ray Milkeyd84f89b2018-08-17 14:54:17 -070083 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Madan Jampanic27b6b22016-02-05 11:36:31 -080084 protected MastershipService mastershipService;
85
Ray Milkeyd84f89b2018-08-17 14:54:17 -070086 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Madan Jampanic27b6b22016-02-05 11:36:31 -080087 protected ClusterCommunicationService clusterCommunicator;
88
Ray Milkeyd84f89b2018-08-17 14:54:17 -070089 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Madan Jampanic27b6b22016-02-05 11:36:31 -080090 protected ClusterService clusterService;
91
Ray Milkeyd84f89b2018-08-17 14:54:17 -070092 @Reference(cardinality = ReferenceCardinality.MANDATORY)
sangyun-han9f0af2d2016-08-04 13:04:59 +090093 protected ComponentConfigService cfgService;
94
Madan Jampanic27b6b22016-02-05 11:36:31 -080095 private Map<ConnectPoint, Set<FlowEntry>> previous =
96 new ConcurrentHashMap<>();
97
98 private Map<ConnectPoint, Set<FlowEntry>> current =
99 new ConcurrentHashMap<>();
100
Madan Jampani78be2492016-06-03 23:27:07 -0700101 public static final MessageSubject GET_CURRENT = new MessageSubject("peer-return-current");
102 public static final MessageSubject GET_PREVIOUS = new MessageSubject("peer-return-previous");
103
Jordan Halterman2c83a102017-08-20 17:11:41 -0700104 protected static final Serializer SERIALIZER = Serializer.using(KryoNamespaces.API);
Madan Jampanic27b6b22016-02-05 11:36:31 -0800105
106 private NodeId local;
107 private ExecutorService messageHandlingExecutor;
108
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700109 //@Property(name = "messageHandlerThreadPoolSize", intValue = DEFAULT_MESSAGE_HANDLER_THREAD_POOL_SIZE,
110 // label = "Size of thread pool to assign message handler")
Ray Milkeyb5646e62018-10-16 11:42:18 -0700111 private static int messageHandlerThreadPoolSize = DFS_MESSAGE_HANDLER_THREAD_POOL_SIZE_DEFAULT;
sangyun-hanad84e0c2016-02-19 18:30:03 +0900112
113
Madan Jampanic27b6b22016-02-05 11:36:31 -0800114 private static final long STATISTIC_STORE_TIMEOUT_MILLIS = 3000;
115
116 @Activate
sangyun-han9f0af2d2016-08-04 13:04:59 +0900117 public void activate(ComponentContext context) {
118 cfgService.registerProperties(getClass());
119
120 modified(context);
121
Madan Jampanic27b6b22016-02-05 11:36:31 -0800122 local = clusterService.getLocalNode().id();
123
124 messageHandlingExecutor = Executors.newFixedThreadPool(
sangyun-hanad84e0c2016-02-19 18:30:03 +0900125 messageHandlerThreadPoolSize,
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800126 groupedThreads("onos/store/statistic", "message-handlers", log));
Madan Jampanic27b6b22016-02-05 11:36:31 -0800127
128 clusterCommunicator.addSubscriber(
129 GET_CURRENT, SERIALIZER::decode, this::getCurrentStatisticInternal, SERIALIZER::encode,
130 messageHandlingExecutor);
131
132 clusterCommunicator.addSubscriber(
133 GET_CURRENT, SERIALIZER::decode, this::getPreviousStatisticInternal, SERIALIZER::encode,
134 messageHandlingExecutor);
135
136 log.info("Started");
137 }
138
139 @Deactivate
140 public void deactivate() {
sangyun-han9f0af2d2016-08-04 13:04:59 +0900141 cfgService.unregisterProperties(getClass(), false);
Madan Jampanic27b6b22016-02-05 11:36:31 -0800142 clusterCommunicator.removeSubscriber(GET_PREVIOUS);
143 clusterCommunicator.removeSubscriber(GET_CURRENT);
144 messageHandlingExecutor.shutdown();
145 log.info("Stopped");
146 }
147
sangyun-hanad84e0c2016-02-19 18:30:03 +0900148 @Modified
149 public void modified(ComponentContext context) {
150 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
151
152 int newMessageHandlerThreadPoolSize;
153
154 try {
155 String s = get(properties, "messageHandlerThreadPoolSize");
156
157 newMessageHandlerThreadPoolSize =
158 isNullOrEmpty(s) ? messageHandlerThreadPoolSize : Integer.parseInt(s.trim());
159
160 } catch (NumberFormatException e) {
161 log.warn(e.getMessage());
162 newMessageHandlerThreadPoolSize = messageHandlerThreadPoolSize;
163 }
164
165 // Any change in the following parameters implies thread pool restart
166 if (newMessageHandlerThreadPoolSize != messageHandlerThreadPoolSize) {
167 setMessageHandlerThreadPoolSize(newMessageHandlerThreadPoolSize);
168 restartMessageHandlerThreadPool();
169 }
170
171 log.info(FORMAT, messageHandlerThreadPoolSize);
172 }
173
Madan Jampanic27b6b22016-02-05 11:36:31 -0800174 @Override
175 public synchronized void removeFlowStatistic(FlowRule rule) {
176 ConnectPoint cp = buildConnectPoint(rule);
177 if (cp == null) {
178 return;
179 }
180
181 // remove this rule if present from current map
sangyun-hanad84e0c2016-02-19 18:30:03 +0900182 current.computeIfPresent(cp, (c, e) -> {
183 e.remove(rule);
184 return e;
185 });
Madan Jampanic27b6b22016-02-05 11:36:31 -0800186
187 // remove this on if present from previous map
sangyun-hanad84e0c2016-02-19 18:30:03 +0900188 previous.computeIfPresent(cp, (c, e) -> {
189 e.remove(rule);
190 return e;
191 });
Madan Jampanic27b6b22016-02-05 11:36:31 -0800192 }
193
194 @Override
195 public synchronized void addFlowStatistic(FlowEntry rule) {
196 ConnectPoint cp = buildConnectPoint(rule);
197 if (cp == null) {
198 return;
199 }
200
201 // create one if absent and add this rule
202 current.putIfAbsent(cp, new HashSet<>());
Ray Milkey88cc3432017-03-30 17:19:08 -0700203 current.computeIfPresent(cp, (c, e) -> {
204 e.add(rule); return e;
205 });
Madan Jampanic27b6b22016-02-05 11:36:31 -0800206
207 // remove previous one if present
Ray Milkey88cc3432017-03-30 17:19:08 -0700208 previous.computeIfPresent(cp, (c, e) -> {
209 e.remove(rule); return e;
210 });
Madan Jampanic27b6b22016-02-05 11:36:31 -0800211 }
212
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800213 @Override
Madan Jampanic27b6b22016-02-05 11:36:31 -0800214 public synchronized void updateFlowStatistic(FlowEntry rule) {
215 ConnectPoint cp = buildConnectPoint(rule);
216 if (cp == null) {
217 return;
218 }
219
220 Set<FlowEntry> curr = current.get(cp);
221 if (curr == null) {
222 addFlowStatistic(rule);
223 } else {
224 Optional<FlowEntry> f = curr.stream().filter(c -> rule.equals(c)).
225 findAny();
226 if (f.isPresent() && rule.bytes() < f.get().bytes()) {
227 log.debug("DistributedFlowStatisticStore:updateFlowStatistic():" +
228 " Invalid Flow Update! Will be removed!!" +
229 " curr flowId=" + Long.toHexString(rule.id().value()) +
230 ", prev flowId=" + Long.toHexString(f.get().id().value()) +
231 ", curr bytes=" + rule.bytes() + ", prev bytes=" + f.get().bytes() +
232 ", curr life=" + rule.life() + ", prev life=" + f.get().life() +
233 ", curr lastSeen=" + rule.lastSeen() + ", prev lastSeen=" + f.get().lastSeen());
234 // something is wrong! invalid flow entry, so delete it
235 removeFlowStatistic(rule);
236 return;
237 }
238 Set<FlowEntry> prev = previous.get(cp);
239 if (prev == null) {
240 prev = new HashSet<>();
241 previous.put(cp, prev);
242 }
243
244 // previous one is exist
245 if (f.isPresent()) {
246 // remove old one and add new one
247 prev.remove(rule);
248 if (!prev.add(f.get())) {
249 log.debug("DistributedFlowStatisticStore:updateFlowStatistic():" +
250 " flowId={}, add failed into previous.",
251 Long.toHexString(rule.id().value()));
252 }
253 }
254
255 // remove old one and add new one
256 curr.remove(rule);
257 if (!curr.add(rule)) {
258 log.debug("DistributedFlowStatisticStore:updateFlowStatistic():" +
259 " flowId={}, add failed into current.",
260 Long.toHexString(rule.id().value()));
261 }
262 }
263 }
264
265 @Override
266 public Set<FlowEntry> getCurrentFlowStatistic(ConnectPoint connectPoint) {
267 final DeviceId deviceId = connectPoint.deviceId();
268
269 NodeId master = mastershipService.getMasterFor(deviceId);
270 if (master == null) {
271 log.warn("No master for {}", deviceId);
272 return Collections.emptySet();
273 }
274
275 if (Objects.equal(local, master)) {
276 return getCurrentStatisticInternal(connectPoint);
277 } else {
278 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(
279 connectPoint,
280 GET_CURRENT,
281 SERIALIZER::encode,
282 SERIALIZER::decode,
283 master),
284 STATISTIC_STORE_TIMEOUT_MILLIS,
285 TimeUnit.MILLISECONDS,
286 Collections.emptySet());
287 }
288 }
289
290 private synchronized Set<FlowEntry> getCurrentStatisticInternal(ConnectPoint connectPoint) {
291 return current.get(connectPoint);
292 }
293
294 @Override
295 public Set<FlowEntry> getPreviousFlowStatistic(ConnectPoint connectPoint) {
296 final DeviceId deviceId = connectPoint.deviceId();
297
298 NodeId master = mastershipService.getMasterFor(deviceId);
299 if (master == null) {
300 log.warn("No master for {}", deviceId);
301 return Collections.emptySet();
302 }
303
304 if (Objects.equal(local, master)) {
305 return getPreviousStatisticInternal(connectPoint);
306 } else {
307 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(
308 connectPoint,
309 GET_PREVIOUS,
310 SERIALIZER::encode,
311 SERIALIZER::decode,
312 master),
313 STATISTIC_STORE_TIMEOUT_MILLIS,
314 TimeUnit.MILLISECONDS,
315 Collections.emptySet());
316 }
317 }
318
319 private synchronized Set<FlowEntry> getPreviousStatisticInternal(ConnectPoint connectPoint) {
320 return previous.get(connectPoint);
321 }
322
323 private ConnectPoint buildConnectPoint(FlowRule rule) {
324 PortNumber port = getOutput(rule);
325
326 if (port == null) {
327 return null;
328 }
329 ConnectPoint cp = new ConnectPoint(rule.deviceId(), port);
330 return cp;
331 }
332
333 private PortNumber getOutput(FlowRule rule) {
334 for (Instruction i : rule.treatment().allInstructions()) {
335 if (i.type() == Instruction.Type.OUTPUT) {
336 Instructions.OutputInstruction out = (Instructions.OutputInstruction) i;
337 return out.port();
338 }
Madan Jampanic27b6b22016-02-05 11:36:31 -0800339 }
340 return null;
341 }
sangyun-hanad84e0c2016-02-19 18:30:03 +0900342
343 /**
344 * Sets thread pool size of message handler.
345 *
346 * @param poolSize
347 */
348 private void setMessageHandlerThreadPoolSize(int poolSize) {
349 checkArgument(poolSize >= 0, "Message handler pool size must be 0 or more");
350 messageHandlerThreadPoolSize = poolSize;
351 }
352
353 /**
354 * Restarts thread pool of message handler.
355 */
356 private void restartMessageHandlerThreadPool() {
357 ExecutorService prevExecutor = messageHandlingExecutor;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700358 messageHandlingExecutor = newFixedThreadPool(getMessageHandlerThreadPoolSize(),
359 groupedThreads("DistFlowStats", "messageHandling-%d", log));
sangyun-hanad84e0c2016-02-19 18:30:03 +0900360 prevExecutor.shutdown();
361 }
362
363 /**
364 * Gets current thread pool size of message handler.
365 *
366 * @return messageHandlerThreadPoolSize
367 */
368 private int getMessageHandlerThreadPoolSize() {
369 return messageHandlerThreadPoolSize;
370 }
Sho SHIMIZU57f2efd2016-02-24 12:20:05 -0800371}