blob: ed596993e86ee5afcd16decca3be1fea9b414e52 [file] [log] [blame]
Charles Chanf7b1b4b2019-01-16 15:30:39 -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.portloadbalancer.app;
18
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Sets;
21import org.osgi.service.component.annotations.Activate;
22import org.osgi.service.component.annotations.Component;
23import org.osgi.service.component.annotations.Deactivate;
24import org.osgi.service.component.annotations.Reference;
25import org.osgi.service.component.annotations.ReferenceCardinality;
26import org.onlab.util.KryoNamespace;
27import org.onosproject.cluster.ClusterService;
28import org.onosproject.cluster.LeadershipService;
29import org.onosproject.cluster.NodeId;
30import org.onosproject.core.ApplicationId;
31import org.onosproject.core.CoreService;
32import org.onosproject.portloadbalancer.api.PortLoadBalancer;
33import org.onosproject.portloadbalancer.api.PortLoadBalancerData;
34import org.onosproject.portloadbalancer.api.PortLoadBalancerEvent;
35import org.onosproject.portloadbalancer.api.PortLoadBalancerAdminService;
36import org.onosproject.portloadbalancer.api.PortLoadBalancerId;
37import org.onosproject.portloadbalancer.api.PortLoadBalancerListener;
38import org.onosproject.portloadbalancer.api.PortLoadBalancerMode;
39import org.onosproject.portloadbalancer.api.PortLoadBalancerService;
40import org.onosproject.mastership.MastershipService;
41import org.onosproject.net.DeviceId;
42import org.onosproject.net.PortNumber;
43import org.onosproject.net.device.DeviceEvent;
44import org.onosproject.net.device.DeviceListener;
45import org.onosproject.net.device.DeviceService;
46import org.onosproject.net.flow.DefaultTrafficSelector;
47import org.onosproject.net.flow.DefaultTrafficTreatment;
48import org.onosproject.net.flow.TrafficSelector;
49import org.onosproject.net.flow.TrafficTreatment;
50import org.onosproject.net.flow.instructions.Instruction;
51import org.onosproject.net.flow.instructions.Instructions;
52import org.onosproject.net.flowobjective.DefaultNextObjective;
53import org.onosproject.net.flowobjective.DefaultNextTreatment;
54import org.onosproject.net.flowobjective.FlowObjectiveService;
55import org.onosproject.net.flowobjective.NextObjective;
56import org.onosproject.net.flowobjective.Objective;
57import org.onosproject.net.flowobjective.ObjectiveContext;
58import org.onosproject.net.flowobjective.ObjectiveError;
59import org.onosproject.store.serializers.KryoNamespaces;
60import org.onosproject.store.service.ConsistentMap;
61import org.onosproject.store.service.MapEvent;
62import org.onosproject.store.service.MapEventListener;
63import org.onosproject.store.service.Serializer;
64import org.onosproject.store.service.StorageService;
65import org.onosproject.store.service.Versioned;
66import org.slf4j.Logger;
67
68import java.util.Collection;
69import java.util.Map;
70import java.util.Set;
71import java.util.concurrent.ExecutorService;
72import java.util.concurrent.Executors;
73import java.util.stream.Collectors;
74
75import static org.onlab.util.Tools.groupedThreads;
76import static org.slf4j.LoggerFactory.getLogger;
77
78@Component(
79 immediate = true,
80 service = { PortLoadBalancerService.class, PortLoadBalancerAdminService.class }
81)
82public class PortLoadBalancerManager implements PortLoadBalancerService, PortLoadBalancerAdminService {
83
84 @Reference(cardinality = ReferenceCardinality.MANDATORY)
85 private CoreService coreService;
86
87 @Reference(cardinality = ReferenceCardinality.MANDATORY)
88 private StorageService storageService;
89
90 @Reference(cardinality = ReferenceCardinality.MANDATORY)
91 private FlowObjectiveService flowObjService;
92
93 @Reference(cardinality = ReferenceCardinality.MANDATORY)
94 private MastershipService mastershipService;
95
96 @Reference(cardinality = ReferenceCardinality.MANDATORY)
97 private LeadershipService leadershipService;
98
99 @Reference(cardinality = ReferenceCardinality.MANDATORY)
100 private ClusterService clusterService;
101
102 @Reference(cardinality = ReferenceCardinality.MANDATORY)
103 private DeviceService deviceService;
104
105 private static final Logger log = getLogger(PortLoadBalancerManager.class);
106 private static final String APP_NAME = "org.onosproject.portloadbalancer";
107
108 private ApplicationId appId;
109 private ConsistentMap<PortLoadBalancerId, PortLoadBalancer> portLoadBalancerStore;
110 private ConsistentMap<PortLoadBalancerId, Integer> portLoadBalancerNextStore;
111 // TODO Evaluate if ResourceService is a better option
112 private ConsistentMap<PortLoadBalancerId, ApplicationId> portLoadBalancerResStore;
113 private Set<PortLoadBalancerListener> listeners = Sets.newConcurrentHashSet();
114
115 private ExecutorService portLoadBalancerEventExecutor;
116 private ExecutorService portLoadBalancerProvExecutor;
117 private ExecutorService deviceEventExecutor;
118
119 private MapEventListener<PortLoadBalancerId, PortLoadBalancer> portLoadBalancerStoreListener;
120 // TODO build CLI to view and clear the next store
121 private MapEventListener<PortLoadBalancerId, Integer> portLoadBalancerNextStoreListener;
122 private MapEventListener<PortLoadBalancerId, ApplicationId> portLoadBalancerResStoreListener;
123 private final DeviceListener deviceListener = new InternalDeviceListener();
124
125 @Activate
126 public void activate() {
127 appId = coreService.registerApplication(APP_NAME);
128
129 portLoadBalancerEventExecutor = Executors.newSingleThreadExecutor(
130 groupedThreads("portloadbalancer-event", "%d", log));
131 portLoadBalancerProvExecutor = Executors.newSingleThreadExecutor(
132 groupedThreads("portloadbalancer-prov", "%d", log));
133 deviceEventExecutor = Executors.newSingleThreadScheduledExecutor(
134 groupedThreads("portloadbalancer-dev-event", "%d", log));
135 portLoadBalancerStoreListener = new PortLoadBalancerStoreListener();
136 portLoadBalancerNextStoreListener = new PortLoadBalancerNextStoreListener();
137 portLoadBalancerResStoreListener = new PortLoadBalancerResStoreListener();
138
139 KryoNamespace serializer = KryoNamespace.newBuilder()
140 .register(KryoNamespaces.API)
141 .register(PortLoadBalancer.class)
142 .register(PortLoadBalancerId.class)
143 .register(PortLoadBalancerMode.class)
144 .build();
145 portLoadBalancerStore = storageService.<PortLoadBalancerId, PortLoadBalancer>consistentMapBuilder()
146 .withName("onos-portloadbalancer-store")
147 .withRelaxedReadConsistency()
148 .withSerializer(Serializer.using(serializer))
149 .build();
150 portLoadBalancerStore.addListener(portLoadBalancerStoreListener);
151 portLoadBalancerNextStore = storageService.<PortLoadBalancerId, Integer>consistentMapBuilder()
152 .withName("onos-portloadbalancer-next-store")
153 .withRelaxedReadConsistency()
154 .withSerializer(Serializer.using(serializer))
155 .build();
156 portLoadBalancerNextStore.addListener(portLoadBalancerNextStoreListener);
157 portLoadBalancerResStore = storageService.<PortLoadBalancerId, ApplicationId>consistentMapBuilder()
158 .withName("onos-portloadbalancer-res-store")
159 .withRelaxedReadConsistency()
160 .withSerializer(Serializer.using(serializer))
161 .build();
162 portLoadBalancerResStore.addListener(portLoadBalancerResStoreListener);
163
164 deviceService.addListener(deviceListener);
165
166 log.info("Started");
167 }
168
169 @Deactivate
170 public void deactivate() {
171 portLoadBalancerStore.removeListener(portLoadBalancerStoreListener);
172 portLoadBalancerNextStore.removeListener(portLoadBalancerNextStoreListener);
173
174 portLoadBalancerEventExecutor.shutdown();
175 portLoadBalancerProvExecutor.shutdown();
176 deviceEventExecutor.shutdown();
177
178 log.info("Stopped");
179 }
180
181 @Override
182 public void addListener(PortLoadBalancerListener listener) {
183 listeners.add(listener);
184 }
185
186 @Override
187 public void removeListener(PortLoadBalancerListener listener) {
188 listeners.remove(listener);
189 }
190
191 @Override
192 public PortLoadBalancer createOrUpdate(PortLoadBalancerId portLoadBalancerId, Set<PortNumber> ports,
193 PortLoadBalancerMode mode) {
194 log.debug("Putting {} -> {} {} into port load balancer store", portLoadBalancerId, mode, ports);
195 return Versioned.valueOrNull(portLoadBalancerStore.put(portLoadBalancerId,
196 new PortLoadBalancer(portLoadBalancerId, ports, mode)));
197 }
198
199 @Override
200 public PortLoadBalancer remove(PortLoadBalancerId portLoadBalancerId) {
201 ApplicationId reservation = Versioned.valueOrNull(portLoadBalancerResStore.get(portLoadBalancerId));
202 // Remove only if it is not used - otherwise it is necessary to release first
203 if (reservation == null) {
204 log.debug("Removing {} from port load balancer store", portLoadBalancerId);
205 return Versioned.valueOrNull(portLoadBalancerStore.remove(portLoadBalancerId));
206 }
207 log.warn("Removal {} from port load balancer store was not possible " +
208 "due to a previous reservation", portLoadBalancerId);
209 return null;
210 }
211
212 @Override
213 public Map<PortLoadBalancerId, PortLoadBalancer> getPortLoadBalancers() {
214 return ImmutableMap.copyOf(portLoadBalancerStore.asJavaMap());
215 }
216
217 @Override
218 public PortLoadBalancer getPortLoadBalancer(PortLoadBalancerId portLoadBalancerId) {
219 return Versioned.valueOrNull(portLoadBalancerStore.get(portLoadBalancerId));
220 }
221
222 @Override
223 public Map<PortLoadBalancerId, Integer> getPortLoadBalancerNexts() {
224 return ImmutableMap.copyOf(portLoadBalancerNextStore.asJavaMap());
225 }
226
227 @Override
228 public int getPortLoadBalancerNext(PortLoadBalancerId portLoadBalancerId) {
229 return Versioned.valueOrNull(portLoadBalancerNextStore.get(portLoadBalancerId));
230 }
231
232 @Override
233 public boolean reserve(PortLoadBalancerId portLoadBalancerId, ApplicationId appId) {
234 // Check if the resource is available
235 ApplicationId reservation = Versioned.valueOrNull(portLoadBalancerResStore.get(portLoadBalancerId));
236 PortLoadBalancer portLoadBalancer = Versioned.valueOrNull(portLoadBalancerStore.get(portLoadBalancerId));
237 if (reservation == null && portLoadBalancer != null) {
238 log.debug("Reserving {} -> {} into port load balancer reservation store", portLoadBalancerId, appId);
239 return portLoadBalancerResStore.put(portLoadBalancerId, appId) == null;
240 } else if (reservation != null && reservation.equals(appId)) {
241 // App try to reserve the resource a second time
242 log.debug("Already reserved {} -> {} skip reservation", portLoadBalancerId, appId);
243 return true;
244 }
245 log.warn("Reservation failed {} -> {}", portLoadBalancerId, appId);
246 return false;
247 }
248
249 @Override
250 public boolean release(PortLoadBalancerId portLoadBalancerId, ApplicationId appId) {
251 // Check if the resource is reserved
252 ApplicationId reservation = Versioned.valueOrNull(portLoadBalancerResStore.get(portLoadBalancerId));
253 if (reservation != null && reservation.equals(appId)) {
254 log.debug("Removing {} -> {} from port load balancer reservation store", portLoadBalancerId, appId);
255 return portLoadBalancerResStore.remove(portLoadBalancerId) != null;
256 }
257 log.warn("Release failed {} -> {}", portLoadBalancerId, appId);
258 return false;
259 }
260
261 @Override
262 public ApplicationId getReservation(PortLoadBalancerId portLoadBalancerId) {
263 return Versioned.valueOrNull(portLoadBalancerResStore.get(portLoadBalancerId));
264 }
265
266 @Override
267 public Map<PortLoadBalancerId, ApplicationId> getReservations() {
268 return portLoadBalancerResStore.asJavaMap();
269 }
270
271 private class PortLoadBalancerStoreListener implements MapEventListener<PortLoadBalancerId, PortLoadBalancer> {
272 public void event(MapEvent<PortLoadBalancerId, PortLoadBalancer> event) {
273 switch (event.type()) {
274 case INSERT:
275 log.debug("PortLoadBalancer {} insert new={}, old={}", event.key(), event.newValue(),
276 event.oldValue());
277 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.ADDED, event.newValue().value().data(),
278 null));
279 populatePortLoadBalancer(event.newValue().value());
280 break;
281 case REMOVE:
282 log.debug("PortLoadBalancer {} remove new={}, old={}", event.key(), event.newValue(),
283 event.oldValue());
284 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.REMOVED, null,
285 event.oldValue().value().data()));
286 revokePortLoadBalancer(event.oldValue().value());
287 break;
288 case UPDATE:
289 log.debug("PortLoadBalancer {} update new={}, old={}", event.key(), event.newValue(),
290 event.oldValue());
291 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.UPDATED, event.newValue().value().data(),
292 event.oldValue().value().data()));
293 updatePortLoadBalancer(event.newValue().value(), event.oldValue().value());
294 break;
295 default:
296 break;
297 }
298 }
299 }
300
301 private class PortLoadBalancerNextStoreListener implements MapEventListener<PortLoadBalancerId, Integer> {
302 public void event(MapEvent<PortLoadBalancerId, Integer> event) {
303 switch (event.type()) {
304 case INSERT:
305 log.debug("PortLoadBalancer next {} insert new={}, old={}", event.key(), event.newValue(),
306 event.oldValue());
307 break;
308 case REMOVE:
309 log.debug("PortLoadBalancer next {} remove new={}, old={}", event.key(), event.newValue(),
310 event.oldValue());
311 break;
312 case UPDATE:
313 log.debug("PortLoadBalancer next {} update new={}, old={}", event.key(), event.newValue(),
314 event.oldValue());
315 break;
316 default:
317 break;
318 }
319 }
320 }
321
322 private class PortLoadBalancerResStoreListener implements MapEventListener<PortLoadBalancerId, ApplicationId> {
323 public void event(MapEvent<PortLoadBalancerId, ApplicationId> event) {
324 switch (event.type()) {
325 case INSERT:
326 log.debug("PortLoadBalancer reservation {} insert new={}, old={}", event.key(), event.newValue(),
327 event.oldValue());
328 break;
329 case REMOVE:
330 log.debug("PortLoadBalancer reservation {} remove new={}, old={}", event.key(), event.newValue(),
331 event.oldValue());
332 break;
333 case UPDATE:
334 log.debug("PortLoadBalancer reservation {} update new={}, old={}", event.key(), event.newValue(),
335 event.oldValue());
336 break;
337 default:
338 break;
339 }
340 }
341 }
342
343 private class InternalDeviceListener implements DeviceListener {
344 // We want to manage only a subset of events and if we are the leader
345 @Override
346 public void event(DeviceEvent event) {
347 deviceEventExecutor.execute(() -> {
348 DeviceId deviceId = event.subject().id();
349 if (!isLocalLeader(deviceId)) {
350 log.debug("Not the leader of {}. Skip event {}", deviceId, event);
351 return;
352 }
353 // Populate or revoke according to the device availability
354 if (deviceService.isAvailable(deviceId)) {
355 init(deviceId);
356 } else {
357 cleanup(deviceId);
358 }
359 });
360 }
361 // Some events related to the devices are skipped
362 @Override
363 public boolean isRelevant(DeviceEvent event) {
364 return event.type() == DeviceEvent.Type.DEVICE_ADDED ||
365 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
366 event.type() == DeviceEvent.Type.DEVICE_UPDATED;
367 }
368 }
369
370 private void post(PortLoadBalancerEvent portLoadBalancerEvent) {
371 portLoadBalancerEventExecutor.execute(() -> {
372 for (PortLoadBalancerListener l : listeners) {
373 if (l.isRelevant(portLoadBalancerEvent)) {
374 l.event(portLoadBalancerEvent);
375 }
376 }
377 });
378 }
379
380 private void init(DeviceId deviceId) {
381 portLoadBalancerStore.entrySet().stream()
382 .filter(portLoadBalancerEntry -> portLoadBalancerEntry.getKey().deviceId().equals(deviceId))
383 .forEach(portLoadBalancerEntry -> populatePortLoadBalancer(portLoadBalancerEntry.getValue().value()));
384 }
385
386 private void cleanup(DeviceId deviceId) {
387 portLoadBalancerStore.entrySet().stream()
388 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
389 .forEach(entry -> portLoadBalancerNextStore.remove(entry.getKey()));
390 log.debug("{} is removed from portLoadBalancerNextStore", deviceId);
391 }
392
393 private void populatePortLoadBalancer(PortLoadBalancer portLoadBalancer) {
394 DeviceId deviceId = portLoadBalancer.portLoadBalancerId().deviceId();
395 if (!isLocalLeader(deviceId)) {
396 log.debug("Not the leader of {}. Skip populatePortLoadBalancer {}", deviceId,
397 portLoadBalancer.portLoadBalancerId());
398 return;
399 }
400
401 portLoadBalancerProvExecutor.execute(() -> {
402 Integer nextid = Versioned.valueOrNull(portLoadBalancerNextStore
403 .get(portLoadBalancer.portLoadBalancerId()));
404 if (nextid == null) {
405 // Build a new context and new next objective
406 PortLoadBalancerObjectiveContext context =
407 new PortLoadBalancerObjectiveContext(portLoadBalancer.portLoadBalancerId());
408 NextObjective nextObj = nextObjBuilder(portLoadBalancer.portLoadBalancerId(),
409 portLoadBalancer.ports(), nextid).add(context);
410 // Finally submit, store, and register the resource
411 flowObjService.next(deviceId, nextObj);
412 portLoadBalancerNextStore.put(portLoadBalancer.portLoadBalancerId(), nextObj.id());
413 } else {
414 log.info("NextObj for {} already exists. Skip populatePortLoadBalancer",
415 portLoadBalancer.portLoadBalancerId());
416 }
417 });
418 }
419
420 private void revokePortLoadBalancer(PortLoadBalancer portLoadBalancer) {
421 DeviceId deviceId = portLoadBalancer.portLoadBalancerId().deviceId();
422 if (!isLocalLeader(deviceId)) {
423 log.debug("Not the leader of {}. Skip revokePortLoadBalancer {}", deviceId,
424 portLoadBalancer.portLoadBalancerId());
425 return;
426 }
427
428 portLoadBalancerProvExecutor.execute(() -> {
429 Integer nextid = Versioned.valueOrNull(portLoadBalancerNextStore.get(portLoadBalancer
430 .portLoadBalancerId()));
431 if (nextid != null) {
432 // Build a new context and remove old next objective
433 PortLoadBalancerObjectiveContext context =
434 new PortLoadBalancerObjectiveContext(portLoadBalancer.portLoadBalancerId());
435 NextObjective nextObj = nextObjBuilder(portLoadBalancer.portLoadBalancerId(), portLoadBalancer.ports(),
436 nextid).remove(context);
437 // Finally submit and invalidate the store
438 flowObjService.next(deviceId, nextObj);
439 portLoadBalancerNextStore.remove(portLoadBalancer.portLoadBalancerId());
440 } else {
441 log.info("NextObj for {} does not exist. Skip revokePortLoadBalancer",
442 portLoadBalancer.portLoadBalancerId());
443 }
444 });
445 }
446
447 private void updatePortLoadBalancer(PortLoadBalancer newPortLoadBalancer, PortLoadBalancer oldPortLoadBalancer) {
448 DeviceId deviceId = newPortLoadBalancer.portLoadBalancerId().deviceId();
449 if (!isLocalLeader(deviceId)) {
450 log.debug("Not the leader of {}. Skip updatePortLoadBalancer {}", deviceId,
451 newPortLoadBalancer.portLoadBalancerId());
452 return;
453 }
454
455 portLoadBalancerProvExecutor.execute(() -> {
456 Integer nextid = Versioned.valueOrNull(portLoadBalancerNextStore
457 .get(newPortLoadBalancer.portLoadBalancerId()));
458 if (nextid != null) {
459 // Compute modifications and context
460 PortLoadBalancerObjectiveContext context =
461 new PortLoadBalancerObjectiveContext(newPortLoadBalancer.portLoadBalancerId());
462 Set<PortNumber> portsToBeAdded =
463 Sets.difference(newPortLoadBalancer.ports(), oldPortLoadBalancer.ports());
464 Set<PortNumber> portsToBeRemoved =
465 Sets.difference(oldPortLoadBalancer.ports(), newPortLoadBalancer.ports());
466 // and send them to the flowobj subsystem
467 if (!portsToBeAdded.isEmpty()) {
468 flowObjService.next(deviceId, nextObjBuilder(newPortLoadBalancer.portLoadBalancerId(),
469 portsToBeAdded, nextid)
470 .addToExisting(context));
471 } else {
472 log.debug("NextObj for {} nothing to add", newPortLoadBalancer.portLoadBalancerId());
473
474 }
475 if (!portsToBeRemoved.isEmpty()) {
476 flowObjService.next(deviceId, nextObjBuilder(newPortLoadBalancer.portLoadBalancerId(),
477 portsToBeRemoved, nextid)
478 .removeFromExisting(context));
479 } else {
480 log.debug("NextObj for {} nothing to remove", newPortLoadBalancer.portLoadBalancerId());
481 }
482 } else {
483 log.info("NextObj for {} does not exist. Skip updatePortLoadBalancer",
484 newPortLoadBalancer.portLoadBalancerId());
485 }
486 });
487 }
488
489 private NextObjective.Builder nextObjBuilder(PortLoadBalancerId portLoadBalancerId, Set<PortNumber> ports,
490 Integer nextId) {
491 if (nextId == null) {
492 nextId = flowObjService.allocateNextId();
493 }
494 // This metadata is used to pass the key to the driver.
495 // Some driver, e.g. OF-DPA, will use that information while creating load balancing group.
496 // TODO This is not an actual LAG port. In the future, we should extend metadata structure to carry
497 // generic information. We should avoid using in_port in the metadata once generic metadata is available.
498 TrafficSelector meta = DefaultTrafficSelector.builder()
499 .matchInPort(PortNumber.portNumber(portLoadBalancerId.key())).build();
500 NextObjective.Builder nextObjBuilder = DefaultNextObjective.builder()
501 .withId(nextId)
502 .withMeta(meta)
503 .withType(NextObjective.Type.HASHED)
504 .fromApp(appId);
505 ports.forEach(port -> {
506 TrafficTreatment treatment = DefaultTrafficTreatment.builder().setOutput(port).build();
507 nextObjBuilder.addTreatment(DefaultNextTreatment.of(treatment));
508 });
509 return nextObjBuilder;
510 }
511
512 // Custom-built function, when the device is not available we need a fallback mechanism
513 private boolean isLocalLeader(DeviceId deviceId) {
514 if (!mastershipService.isLocalMaster(deviceId)) {
515 // When the device is available we just check the mastership
516 if (deviceService.isAvailable(deviceId)) {
517 return false;
518 }
519 // Fallback with Leadership service - device id is used as topic
520 NodeId leader = leadershipService.runForLeadership(
521 deviceId.toString()).leaderNodeId();
522 // Verify if this node is the leader
523 return clusterService.getLocalNode().id().equals(leader);
524 }
525 return true;
526 }
527
528 private final class PortLoadBalancerObjectiveContext implements ObjectiveContext {
529 private final PortLoadBalancerId portLoadBalancerId;
530
531 private PortLoadBalancerObjectiveContext(PortLoadBalancerId portLoadBalancerId) {
532 this.portLoadBalancerId = portLoadBalancerId;
533 }
534
535 @Override
536 public void onSuccess(Objective objective) {
537 NextObjective nextObj = (NextObjective) objective;
538 log.debug("Successfully {} nextobj {} for port load balancer {}. NextObj={}",
539 nextObj.op(), nextObj.id(), portLoadBalancerId, nextObj);
540 portLoadBalancerProvExecutor.execute(() -> onSuccessHandler(nextObj, portLoadBalancerId));
541 }
542
543 @Override
544 public void onError(Objective objective, ObjectiveError error) {
545 NextObjective nextObj = (NextObjective) objective;
546 log.warn("Failed to {} nextobj {} for port load balancer {} due to {}. NextObj={}",
547 nextObj.op(), nextObj.id(), portLoadBalancerId, error, nextObj);
548 portLoadBalancerProvExecutor.execute(() -> onErrorHandler(nextObj, portLoadBalancerId));
549 }
550 }
551
552 private void onSuccessHandler(NextObjective nextObjective, PortLoadBalancerId portLoadBalancerId) {
553 // Operation done
554 PortLoadBalancerData oldPortLoadBalancerData = new PortLoadBalancerData(portLoadBalancerId);
555 PortLoadBalancerData newPortLoadBalancerData = new PortLoadBalancerData(portLoadBalancerId);
556 // Other operations will not lead to a generation of an event
557 switch (nextObjective.op()) {
558 case ADD:
559 newPortLoadBalancerData.setNextId(nextObjective.id());
560 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.INSTALLED, newPortLoadBalancerData,
561 oldPortLoadBalancerData));
562 break;
563 case REMOVE:
564 oldPortLoadBalancerData.setNextId(nextObjective.id());
565 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.UNINSTALLED, newPortLoadBalancerData,
566 oldPortLoadBalancerData));
567 break;
568 default:
569 break;
570 }
571 }
572
573 private void onErrorHandler(NextObjective nextObjective, PortLoadBalancerId portLoadBalancerId) {
574 // There was a failure
575 PortLoadBalancerData portLoadBalancerData = new PortLoadBalancerData(portLoadBalancerId);
576 // send FAILED event;
577 switch (nextObjective.op()) {
578 case ADD:
579 // If ADD is failing apps do not know the next id; let's update the store
580 portLoadBalancerNextStore.remove(portLoadBalancerId);
581 portLoadBalancerResStore.remove(portLoadBalancerId);
582 portLoadBalancerStore.remove(portLoadBalancerId);
583 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.FAILED, portLoadBalancerData,
584 portLoadBalancerData));
585 break;
586 case ADD_TO_EXISTING:
587 // If ADD_TO_EXISTING is failing let's remove the failed ports
588 Collection<PortNumber> addedPorts = nextObjective.next().stream()
589 .flatMap(t -> t.allInstructions().stream())
590 .filter(i -> i.type() == Instruction.Type.OUTPUT)
591 .map(i -> ((Instructions.OutputInstruction) i).port())
592 .collect(Collectors.toList());
593 portLoadBalancerStore.compute(portLoadBalancerId, (key, value) -> {
594 if (value != null && value.ports() != null && !value.ports().isEmpty()) {
595 value.ports().removeAll(addedPorts);
596 }
597 return value;
598 });
599 portLoadBalancerData.setNextId(nextObjective.id());
600 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.FAILED, portLoadBalancerData,
601 portLoadBalancerData));
602 break;
603 case REMOVE_FROM_EXISTING:
604 // If REMOVE_TO_EXISTING is failing let's re-add the failed ports
605 Collection<PortNumber> removedPorts = nextObjective.next().stream()
606 .flatMap(t -> t.allInstructions().stream())
607 .filter(i -> i.type() == Instruction.Type.OUTPUT)
608 .map(i -> ((Instructions.OutputInstruction) i).port())
609 .collect(Collectors.toList());
610 portLoadBalancerStore.compute(portLoadBalancerId, (key, value) -> {
611 if (value != null && value.ports() != null) {
612 value.ports().addAll(removedPorts);
613 }
614 return value;
615 });
616 portLoadBalancerData.setNextId(nextObjective.id());
617 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.FAILED, portLoadBalancerData,
618 portLoadBalancerData));
619 break;
620 case VERIFY:
621 case REMOVE:
622 // If ADD/REMOVE_TO_EXISTING, REMOVE and VERIFY are failing let's send
623 // also the info about the next id
624 portLoadBalancerData.setNextId(nextObjective.id());
625 post(new PortLoadBalancerEvent(PortLoadBalancerEvent.Type.FAILED, portLoadBalancerData,
626 portLoadBalancerData));
627 break;
628 default:
629 break;
630 }
631
632 }
633}