blob: 538aa0e761738a0f4c58fa6da19d6738389f6b4d [file] [log] [blame]
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -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.net.intent.impl;
18
Andreas Papazois05548962016-11-23 11:36:55 +020019import com.google.common.collect.ImmutableSet;
20import com.google.common.annotations.Beta;
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -080021import com.google.common.base.MoreObjects;
22import com.google.common.base.MoreObjects.ToStringHelper;
Ray Milkeyfd724402016-05-26 14:45:46 -070023import com.google.common.collect.Lists;
Thomas Vachuska2980c972016-02-23 20:58:49 -080024import com.google.common.collect.Sets;
Andreas Papazois05548962016-11-23 11:36:55 +020025
26import org.apache.commons.lang3.tuple.Pair;
Thomas Vachuska2980c972016-02-23 20:58:49 -080027import org.onosproject.net.DeviceId;
Andreas Papazois05548962016-11-23 11:36:55 +020028import org.onosproject.net.behaviour.protection.ProtectedTransportEndpointDescription;
29import org.onosproject.net.behaviour.protection.ProtectionConfig;
30import org.onosproject.net.config.NetworkConfigService;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080031import org.onosproject.net.flow.FlowRule;
32import org.onosproject.net.flow.FlowRuleOperations;
33import org.onosproject.net.flow.FlowRuleOperationsContext;
34import org.onosproject.net.flow.FlowRuleService;
Yi Tseng38fc71e2017-02-03 14:50:47 -080035import org.onosproject.net.flowobjective.FilteringObjective;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080036import org.onosproject.net.flowobjective.FlowObjectiveService;
Yi Tseng38fc71e2017-02-03 14:50:47 -080037import org.onosproject.net.flowobjective.ForwardingObjective;
38import org.onosproject.net.flowobjective.NextObjective;
Thomas Vachuska2980c972016-02-23 20:58:49 -080039import org.onosproject.net.flowobjective.Objective;
40import org.onosproject.net.flowobjective.ObjectiveContext;
41import org.onosproject.net.flowobjective.ObjectiveError;
42import org.onosproject.net.intent.FlowObjectiveIntent;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080043import org.onosproject.net.intent.FlowRuleIntent;
44import org.onosproject.net.intent.Intent;
45import org.onosproject.net.intent.IntentData;
46import org.onosproject.net.intent.IntentStore;
Andreas Papazois05548962016-11-23 11:36:55 +020047import org.onosproject.net.intent.ProtectionEndpointIntent;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080048import org.slf4j.Logger;
49
Thomas Vachuska2980c972016-02-23 20:58:49 -080050import java.util.ArrayList;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080051import java.util.Collection;
Brian O'Connora78f0602016-09-22 10:56:08 -070052import java.util.Collections;
helenyrwue6aaa332016-08-05 15:41:42 -070053import java.util.Iterator;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080054import java.util.List;
55import java.util.Optional;
56import java.util.Set;
Andreas Papazois05548962016-11-23 11:36:55 +020057import java.util.concurrent.CompletableFuture;
58import java.util.concurrent.CopyOnWriteArrayList;
Yi Tseng38fc71e2017-02-03 14:50:47 -080059import java.util.concurrent.atomic.AtomicInteger;
Thomas Vachuska2980c972016-02-23 20:58:49 -080060import java.util.function.Consumer;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080061import java.util.stream.Collectors;
Yuta HIGUCHI3026c9b2017-01-30 13:28:49 -080062import java.util.stream.Stream;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080063
Andreas Papazois05548962016-11-23 11:36:55 +020064import static com.google.common.base.Preconditions.checkNotNull;
Thomas Vachuska2980c972016-02-23 20:58:49 -080065import static com.google.common.base.Preconditions.checkState;
Yi Tseng38fc71e2017-02-03 14:50:47 -080066import static org.onosproject.net.flowobjective.ObjectiveError.INSTALLATIONTHRESHOLDEXCEEDED;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080067import static org.onosproject.net.intent.IntentState.*;
68import static org.slf4j.LoggerFactory.getLogger;
69
70/**
71 * Auxiliary entity responsible for installing the intents into the environment.
72 */
73class IntentInstaller {
74
Brian O'Connorc590ebb2016-12-08 18:16:41 -080075 private static final Logger log = getLogger(IntentInstaller.class);
Yi Tseng38fc71e2017-02-03 14:50:47 -080076 private static final long OBJECTIVE_RETRY_THRESHOLD = 5;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080077
78 private IntentStore store;
79 private ObjectiveTrackerService trackerService;
80 private FlowRuleService flowRuleService;
81 private FlowObjectiveService flowObjectiveService;
Andreas Papazois05548962016-11-23 11:36:55 +020082 private NetworkConfigService networkConfigService;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080083
84 private enum Direction {
85 ADD,
86 REMOVE
87 }
88
89 /**
90 * Initializes the installer with references to required services.
91 *
92 * @param intentStore intent store
93 * @param trackerService objective tracking service
94 * @param flowRuleService flow rule service
95 * @param flowObjectiveService flow objective service
Andreas Papazois05548962016-11-23 11:36:55 +020096 * @param networkConfigService network configuration service
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080097 */
98 void init(IntentStore intentStore, ObjectiveTrackerService trackerService,
Andreas Papazois05548962016-11-23 11:36:55 +020099 FlowRuleService flowRuleService, FlowObjectiveService flowObjectiveService,
100 NetworkConfigService networkConfigService) {
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800101 this.store = intentStore;
102 this.trackerService = trackerService;
Andreas Papazois05548962016-11-23 11:36:55 +0200103 //TODO Various services should be plugged to the intent installer instead of being hardcoded
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800104 this.flowRuleService = flowRuleService;
105 this.flowObjectiveService = flowObjectiveService;
Andreas Papazois05548962016-11-23 11:36:55 +0200106 this.networkConfigService = networkConfigService;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800107 }
108
Thomas Vachuska2980c972016-02-23 20:58:49 -0800109 // FIXME: Intent Manager should have never become dependent on a specific intent type(s).
110 // This will be addressed in intent domains work; not now.
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800111
112 /**
113 * Applies the specified intent updates to the environment by uninstalling
114 * and installing the intents and updating the store references appropriately.
115 *
116 * @param toUninstall optional intent to uninstall
117 * @param toInstall optional intent to install
118 */
119 void apply(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) {
Andreas Papazois05548962016-11-23 11:36:55 +0200120 // Hook for handling success at intent installation level.
121 Consumer<IntentInstallationContext> successConsumer = (ctx) -> {
Thomas Vachuska2980c972016-02-23 20:58:49 -0800122 if (toInstall.isPresent()) {
123 IntentData installData = toInstall.get();
124 log.debug("Completed installing: {}", installData.key());
125 installData.setState(INSTALLED);
126 store.write(installData);
127 } else if (toUninstall.isPresent()) {
128 IntentData uninstallData = toUninstall.get();
129 log.debug("Completed withdrawing: {}", uninstallData.key());
130 switch (uninstallData.request()) {
131 case INSTALL_REQ:
132 uninstallData.setState(FAILED);
133 break;
134 case WITHDRAW_REQ:
135 default: //TODO "default" case should not happen
136 uninstallData.setState(WITHDRAWN);
137 break;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800138 }
Brian O'Connora78f0602016-09-22 10:56:08 -0700139 // Intent has been withdrawn; we can clear the installables
140 store.write(new IntentData(uninstallData, Collections.emptyList()));
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800141 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800142 };
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800143
Andreas Papazois05548962016-11-23 11:36:55 +0200144 // Hook for handling errors at intent installation level
145 Consumer<IntentInstallationContext> errorConsumer = (ctx) -> {
Thomas Vachuska2980c972016-02-23 20:58:49 -0800146 // if toInstall was cause of error, then recompile (manage/increment counter, when exceeded -> CORRUPT)
147 if (toInstall.isPresent()) {
148 IntentData installData = toInstall.get();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800149 installData.setState(CORRUPT);
150 installData.incrementErrorCount();
151 store.write(installData);
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800152 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800153 // if toUninstall was cause of error, then CORRUPT (another job will clean this up)
154 if (toUninstall.isPresent()) {
155 IntentData uninstallData = toUninstall.get();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800156 uninstallData.setState(CORRUPT);
157 uninstallData.incrementErrorCount();
158 store.write(uninstallData);
159 }
160 };
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800161
Andreas Papazois05548962016-11-23 11:36:55 +0200162 // Hooks at operation level
163 Consumer<OperationContext> successOperationConsumer = (ctx) -> {
164 ctx.intentContext.finishContext(ctx);
165 };
166 Consumer<OperationContext> errorOperationConsumer = (ctx) -> {
167 if (ctx.toInstall.isPresent()) {
168 IntentData installData = toInstall.get();
169 log.warn("Failed installation operation for: {} {} due to {}",
170 installData.key(), installData.intent(), ctx.error());
171 }
172 if (ctx.toUninstall.isPresent()) {
173 IntentData uninstallData = toUninstall.get();
174 log.warn("Failed withdrawal operation for: {} {} due to {}",
175 uninstallData.key(), uninstallData.intent(), ctx.error());
176 }
177 ctx.intentContext.handleError(ctx);
178 };
179
Thomas Vachuska2980c972016-02-23 20:58:49 -0800180 // Create a context for tracking the backing operations for applying
181 // the intents to the environment.
Andreas Papazois05548962016-11-23 11:36:55 +0200182 IntentInstallationContext intentContext =
183 new IntentInstallationContext(successConsumer, errorConsumer);
184 Set<OperationContext> contexts = createContext(intentContext, toUninstall, toInstall);
185 intentContext.pendingContexts = contexts;
186 contexts.forEach(ctx -> {
187 ctx.prepare(toUninstall, toInstall, successOperationConsumer, errorOperationConsumer);
188 ctx.apply();
189 });
Thomas Vachuska2980c972016-02-23 20:58:49 -0800190 }
191
Andreas Papazois05548962016-11-23 11:36:55 +0200192 // Context for applying and tracking multiple kinds of operation contexts
193 // related to specific intent data.
194 private final class IntentInstallationContext {
195 private Set<OperationContext> pendingContexts = Sets.newHashSet();
196 private Set<OperationContext> errorContexts = Sets.newHashSet();
197 private Consumer<IntentInstallationContext> successConsumer;
198 private Consumer<IntentInstallationContext> errorConsumer;
Thomas Vachuska2980c972016-02-23 20:58:49 -0800199
Andreas Papazois05548962016-11-23 11:36:55 +0200200 private IntentInstallationContext(Consumer<IntentInstallationContext> succesConsumer,
201 Consumer<IntentInstallationContext> errorConsumer) {
202 this.successConsumer = succesConsumer;
203 this.errorConsumer = errorConsumer;
204 }
205
206 private void handleError(OperationContext ctx) {
207 errorContexts.add(ctx);
208 finishContext(ctx);
209 }
210
211 private void finishContext(OperationContext ctx) {
212 synchronized (pendingContexts) {
213 pendingContexts.remove(ctx);
214 if (pendingContexts.isEmpty()) {
215 if (errorContexts.isEmpty()) {
216 successConsumer.accept(IntentInstallationContext.this);
217 } else {
218 errorConsumer.accept(IntentInstallationContext.this);
219 }
220 }
221 }
222 }
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -0800223
224 @Override
225 public String toString() {
226 return MoreObjects.toStringHelper(this)
227 .add("pendingContexts", pendingContexts)
228 .add("errorContexts", errorContexts)
229 .toString();
230 }
Andreas Papazois05548962016-11-23 11:36:55 +0200231 }
232
233 // --- Utilities to support various installable Intent ----
234
235 // Creates the set of contexts appropriate for tracking operations of the
Thomas Vachuska2980c972016-02-23 20:58:49 -0800236 // the specified intents.
Andreas Papazois05548962016-11-23 11:36:55 +0200237 private Set<OperationContext> createContext(IntentInstallationContext intentContext,
238 Optional<IntentData> toUninstall,
239 Optional<IntentData> toInstall) {
240
241 Set<OperationContext> contexts = Sets.newConcurrentHashSet();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800242 if (isInstallable(toUninstall, toInstall, FlowRuleIntent.class)) {
Andreas Papazois05548962016-11-23 11:36:55 +0200243 contexts.add(new FlowRuleOperationContext(intentContext));
Thomas Vachuska2980c972016-02-23 20:58:49 -0800244 }
245 if (isInstallable(toUninstall, toInstall, FlowObjectiveIntent.class)) {
Andreas Papazois05548962016-11-23 11:36:55 +0200246 contexts.add(new FlowObjectiveOperationContext(intentContext));
Thomas Vachuska2980c972016-02-23 20:58:49 -0800247 }
Andreas Papazois05548962016-11-23 11:36:55 +0200248 if (isInstallable(toUninstall, toInstall, ProtectionEndpointIntent.class)) {
249 contexts.add(new ProtectionConfigOperationContext(intentContext));
250 }
251
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -0800252 if (contexts.isEmpty()) {
253 log.warn("{} did not contain installable Intents", intentContext);
254 return ImmutableSet.of(new ErrorContext(intentContext));
255 }
256
257 return contexts;
Thomas Vachuska2980c972016-02-23 20:58:49 -0800258 }
259
Yuta HIGUCHI3026c9b2017-01-30 13:28:49 -0800260 /**
261 * Tests if one of {@code toUninstall} or {@code toInstall} contains
262 * installable Intent of type specified by {@code intentClass}.
263 *
264 * @param toUninstall IntentData to test
265 * @param toInstall IntentData to test
266 * @param intentClass installable Intent class
267 * @return true if at least one of IntentData contains installable specified.
268 */
Thomas Vachuska2980c972016-02-23 20:58:49 -0800269 private boolean isInstallable(Optional<IntentData> toUninstall, Optional<IntentData> toInstall,
270 Class<? extends Intent> intentClass) {
Yuta HIGUCHI3026c9b2017-01-30 13:28:49 -0800271
272 return Stream.concat(toInstall
273 .map(IntentData::installables)
274 .map(Collection::stream)
275 .orElse(Stream.empty()),
276 toUninstall
277 .map(IntentData::installables)
278 .map(Collection::stream)
279 .orElse(Stream.empty()))
280 .anyMatch(i -> intentClass.isAssignableFrom(i.getClass()));
Thomas Vachuska2980c972016-02-23 20:58:49 -0800281 }
282
283 // Base context for applying and tracking operations related to installable intents.
284 private abstract class OperationContext {
Andreas Papazois05548962016-11-23 11:36:55 +0200285 protected IntentInstallationContext intentContext;
Thomas Vachuska2980c972016-02-23 20:58:49 -0800286 protected Optional<IntentData> toUninstall;
287 protected Optional<IntentData> toInstall;
Yuta HIGUCHI4d19ab92016-10-27 16:27:15 -0700288 /**
289 * Implementation of {@link OperationContext} should call this on success.
290 */
Thomas Vachuska2980c972016-02-23 20:58:49 -0800291 protected Consumer<OperationContext> successConsumer;
Yuta HIGUCHI4d19ab92016-10-27 16:27:15 -0700292 /**
293 * Implementation of {@link OperationContext} should call this on error.
294 */
Thomas Vachuska2980c972016-02-23 20:58:49 -0800295 protected Consumer<OperationContext> errorConsumer;
296
Andreas Papazois05548962016-11-23 11:36:55 +0200297 protected OperationContext(IntentInstallationContext context) {
298 this.intentContext = context;
299 }
300
Yuta HIGUCHI4d19ab92016-10-27 16:27:15 -0700301 /**
302 * Applies the Intents specified by
303 * {@link #prepareIntents(List, Direction)} call(s) prior to this call.
304 */
Thomas Vachuska2980c972016-02-23 20:58:49 -0800305 abstract void apply();
306
Yuta HIGUCHI4d19ab92016-10-27 16:27:15 -0700307 /**
308 * Returns error state of the context.
309 * <p>
310 * Used for error logging purpose.
311 * Returned Object should have reasonable toString() implementation.
312 * @return context state, describing current error state
313 */
Thomas Vachuska2980c972016-02-23 20:58:49 -0800314 abstract Object error();
315
Yuta HIGUCHI4d19ab92016-10-27 16:27:15 -0700316 /**
317 * Prepares Intent(s) to {@link #apply() apply} in this operation.
318 * <p>
319 * Intents specified by {@code intentsToApply} in a single call
320 * can be applied to the Devices in arbitrary order.
321 * But group of Intents specified in consecutive {@link #prepareIntents(List, Direction)}
322 * calls must be applied in order. (e.g., guarded by barrier)
323 *
324 * @param intentsToApply {@link Intent}s to apply
325 * @param direction of operation
326 */
Thomas Vachuska2980c972016-02-23 20:58:49 -0800327 abstract void prepareIntents(List<Intent> intentsToApply, Direction direction);
328
329 void prepare(Optional<IntentData> toUninstall, Optional<IntentData> toInstall,
330 Consumer<OperationContext> successConsumer,
331 Consumer<OperationContext> errorConsumer) {
332 this.toUninstall = toUninstall;
333 this.toInstall = toInstall;
334 this.successConsumer = successConsumer;
335 this.errorConsumer = errorConsumer;
helenyrwue6aaa332016-08-05 15:41:42 -0700336 prepareIntentData(toUninstall, toInstall);
337 }
338
339 private void prepareIntentData(Optional<IntentData> uninstallData,
340 Optional<IntentData> installData) {
341 if (!installData.isPresent() && !uninstallData.isPresent()) {
342 return;
343 } else if (!installData.isPresent()) {
344 prepareIntentData(uninstallData, Direction.REMOVE);
345 } else if (!uninstallData.isPresent()) {
346 prepareIntentData(installData, Direction.ADD);
347 } else {
348 IntentData uninstall = uninstallData.get();
349 IntentData install = installData.get();
Brian O'Connor09d90f02016-09-13 11:06:14 -0700350 List<Intent> uninstallIntents = Lists.newArrayList(uninstall.installables());
351 List<Intent> installIntents = Lists.newArrayList(install.installables());
helenyrwue6aaa332016-08-05 15:41:42 -0700352
353 checkState(uninstallIntents.stream().allMatch(this::isSupported),
Yuta HIGUCHId5324f32017-01-27 14:35:13 -0800354 "Unsupported installable intents detected: %s", uninstallIntents);
helenyrwue6aaa332016-08-05 15:41:42 -0700355 checkState(installIntents.stream().allMatch(this::isSupported),
Yuta HIGUCHId5324f32017-01-27 14:35:13 -0800356 "Unsupported installable intents detected: %s", installIntents);
helenyrwue6aaa332016-08-05 15:41:42 -0700357
358 //TODO: Filter FlowObjective intents
359 // Filter out same intents and intents with same flow rules
360 Iterator<Intent> iterator = installIntents.iterator();
361 while (iterator.hasNext()) {
362 Intent installIntent = iterator.next();
363 uninstallIntents.stream().filter(uIntent -> {
364 if (uIntent.equals(installIntent)) {
365 return true;
366 } else if (uIntent instanceof FlowRuleIntent && installIntent instanceof FlowRuleIntent) {
Brian O'Connor09d90f02016-09-13 11:06:14 -0700367 //FIXME we can further optimize this by doing the filtering on a flow-by-flow basis
368 // (direction can be implied from intent state)
helenyrwue6aaa332016-08-05 15:41:42 -0700369 return ((FlowRuleIntent) uIntent).flowRules()
370 .containsAll(((FlowRuleIntent) installIntent).flowRules());
371 } else {
372 return false;
373 }
374 }).findFirst().ifPresent(common -> {
375 uninstallIntents.remove(common);
Brian O'Connor09d90f02016-09-13 11:06:14 -0700376 if (INSTALLED.equals(uninstall.state())) {
377 // only remove the install intent if the existing
378 // intent (i.e. the uninstall one) is already
379 // installed or installing
380 iterator.remove();
381 }
helenyrwue6aaa332016-08-05 15:41:42 -0700382 });
383 }
384
385 final IntentData newUninstall = new IntentData(uninstall, uninstallIntents);
386 final IntentData newInstall = new IntentData(install, installIntents);
387
388 trackerService.removeTrackedResources(newUninstall.key(), newUninstall.intent().resources());
389 uninstallIntents.forEach(installable ->
390 trackerService.removeTrackedResources(newUninstall.intent().key(),
391 installable.resources()));
392 trackerService.addTrackedResources(newInstall.key(), newInstall.intent().resources());
393 installIntents.forEach(installable ->
394 trackerService.addTrackedResources(newInstall.key(),
395 installable.resources()));
396 prepareIntents(uninstallIntents, Direction.REMOVE);
397 prepareIntents(installIntents, Direction.ADD);
398 }
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800399 }
400
Thomas Vachuska2980c972016-02-23 20:58:49 -0800401 /**
402 * Applies the specified intent data, if present, to the network using the
403 * specified context.
404 *
405 * @param intentData optional intent data; no-op if not present
406 * @param direction indicates adding or removal
407 */
408 private void prepareIntentData(Optional<IntentData> intentData, Direction direction) {
409 if (!intentData.isPresent()) {
410 return;
411 }
412
413 IntentData data = intentData.get();
414 List<Intent> intentsToApply = data.installables();
415 checkState(intentsToApply.stream().allMatch(this::isSupported),
Yuta HIGUCHId5324f32017-01-27 14:35:13 -0800416 "Unsupported installable intents detected: %s", intentsToApply);
Thomas Vachuska2980c972016-02-23 20:58:49 -0800417
418 if (direction == Direction.ADD) {
419 trackerService.addTrackedResources(data.key(), data.intent().resources());
420 intentsToApply.forEach(installable ->
421 trackerService.addTrackedResources(data.key(),
422 installable.resources()));
423 } else {
424 trackerService.removeTrackedResources(data.key(), data.intent().resources());
425 intentsToApply.forEach(installable ->
426 trackerService.removeTrackedResources(data.intent().key(),
427 installable.resources()));
428 }
429
430 prepareIntents(intentsToApply, direction);
431 }
432
433 private boolean isSupported(Intent intent) {
Andreas Papazois05548962016-11-23 11:36:55 +0200434 return intent instanceof FlowRuleIntent ||
435 intent instanceof FlowObjectiveIntent ||
436 intent instanceof ProtectionEndpointIntent;
Thomas Vachuska2980c972016-02-23 20:58:49 -0800437 }
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -0800438
439 protected ToStringHelper toStringHelper() {
440 return MoreObjects.toStringHelper(this)
441 .add("intentContext", intentContext)
442 .add("toUninstall", toUninstall)
443 .add("toInstall", toInstall);
444 }
445
446 @Override
447 public String toString() {
448 return toStringHelper()
449 .toString();
450 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800451 }
452
453
Andreas Papazois05548962016-11-23 11:36:55 +0200454 // Context for applying and tracking operations related to flow rule intents.
Thomas Vachuska2980c972016-02-23 20:58:49 -0800455 private class FlowRuleOperationContext extends OperationContext {
456 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
457 FlowRuleOperationsContext flowRuleOperationsContext;
458
Andreas Papazois05548962016-11-23 11:36:55 +0200459 FlowRuleOperationContext(IntentInstallationContext context) {
460 super(context);
461 }
462
Yuta HIGUCHI4d19ab92016-10-27 16:27:15 -0700463 @Override
Thomas Vachuska2980c972016-02-23 20:58:49 -0800464 void apply() {
465 flowRuleOperationsContext = new FlowRuleOperationsContext() {
466 @Override
467 public void onSuccess(FlowRuleOperations ops) {
468 successConsumer.accept(FlowRuleOperationContext.this);
469 }
470
471 @Override
472 public void onError(FlowRuleOperations ops) {
473 errorConsumer.accept(FlowRuleOperationContext.this);
474 }
475 };
476 FlowRuleOperations operations = builder.build(flowRuleOperationsContext);
477
478 if (log.isTraceEnabled()) {
479 log.trace("applying intent {} -> {} with {} rules: {}",
480 toUninstall.map(x -> x.key().toString()).orElse("<empty>"),
481 toInstall.map(x -> x.key().toString()).orElse("<empty>"),
482 operations.stages().stream().mapToLong(Set::size).sum(),
483 operations.stages());
484 }
485
486 flowRuleService.apply(operations);
487 }
488
489 @Override
490 public void prepareIntents(List<Intent> intentsToApply, Direction direction) {
491 // FIXME do FlowRuleIntents have stages??? Can we do uninstall work in parallel? I think so.
492 builder.newStage();
493
494 List<Collection<FlowRule>> stages = intentsToApply.stream()
Andreas Papazois05548962016-11-23 11:36:55 +0200495 .filter(x -> x instanceof FlowRuleIntent)
Thomas Vachuska2980c972016-02-23 20:58:49 -0800496 .map(x -> (FlowRuleIntent) x)
497 .map(FlowRuleIntent::flowRules)
498 .collect(Collectors.toList());
499
500 for (Collection<FlowRule> rules : stages) {
501 if (direction == Direction.ADD) {
502 rules.forEach(builder::add);
503 } else {
504 rules.forEach(builder::remove);
505 }
506 }
507
508 }
509
510 @Override
511 public Object error() {
512 return flowRuleOperationsContext;
513 }
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -0800514
515 @Override
516 protected ToStringHelper toStringHelper() {
517 return super.toStringHelper()
518 .omitNullValues()
519 .add("flowRuleOperationsContext", flowRuleOperationsContext);
520 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800521 }
522
523 // Context for applying and tracking operations related to flow objective intents.
524 private class FlowObjectiveOperationContext extends OperationContext {
Yi Tseng38fc71e2017-02-03 14:50:47 -0800525 private static final String UNSUPPORT_OBJ = "unsupported objective {}";
526 final List<ObjectiveContext> contexts = Lists.newArrayList();
527
528 final Set<ObjectiveContext> pendingContexts = Sets.newConcurrentHashSet();
529
530 // Second stage of pending contexts
531 final Set<ObjectiveContext> nextPendingContexts = Sets.newConcurrentHashSet();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800532 final Set<ObjectiveContext> errorContexts = Sets.newConcurrentHashSet();
533
Andreas Papazois05548962016-11-23 11:36:55 +0200534 FlowObjectiveOperationContext(IntentInstallationContext context) {
535 super(context);
536 }
537
Thomas Vachuska2980c972016-02-23 20:58:49 -0800538 @Override
539 public void prepareIntents(List<Intent> intentsToApply, Direction direction) {
Yi Tseng38fc71e2017-02-03 14:50:47 -0800540 intentsToApply
541 .stream()
542 .filter(intent -> intent instanceof FlowObjectiveIntent)
543 .map(intent -> buildObjectiveContexts((FlowObjectiveIntent) intent, direction))
544 .flatMap(Collection::stream)
545 .forEach(contexts::add);
546
547 // Two stage for different direction context
548 // We will apply REMOVE context first, and apply ADD context.
549 contexts.forEach(context -> {
550 switch (direction) {
551 case REMOVE:
552 pendingContexts.add(context);
553 break;
554 case ADD:
555 nextPendingContexts.add(context);
556 break;
557 default:
558 break;
559 }
560 });
Thomas Vachuska2980c972016-02-23 20:58:49 -0800561 }
562
563 // Builds the specified objective in the appropriate direction
Yi Tseng38fc71e2017-02-03 14:50:47 -0800564 private Set<? extends ObjectiveContext> buildObjectiveContexts(FlowObjectiveIntent intent,
565 Direction direction) {
566 Set<FlowObjectiveInstallationContext> contexts = Sets.newHashSet();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800567 int size = intent.objectives().size();
Yi Tseng38fc71e2017-02-03 14:50:47 -0800568 List<Objective> objectives = intent.objectives();
569 List<DeviceId> deviceIds = intent.devices();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800570
Yi Tseng38fc71e2017-02-03 14:50:47 -0800571 if (direction == Direction.ADD) {
572 for (int i = 0; i < size; i++) {
573 Objective objective = objectives.get(i);
574 DeviceId deviceId = deviceIds.get(i);
575 FlowObjectiveInstallationContext ctx =
576 buildObjectiveContext(objective, deviceId, direction);
577 contexts.add(ctx);
Thomas Vachuska2980c972016-02-23 20:58:49 -0800578 }
Yi Tseng38fc71e2017-02-03 14:50:47 -0800579 return contexts;
580 } else {
581 // we need to care about ordering here
582 // basic idea is to chain objective contexts
583 for (int i = 0; i < size; i++) {
584 Objective objective = intent.objectives().get(i);
585 DeviceId deviceId = intent.devices().get(i);
586
587 if (objective instanceof FilteringObjective) {
588 // don't need to care ordering of filtering objective
589 FlowObjectiveInstallationContext ctx =
590 buildObjectiveContext(objective, deviceId, direction);
591 contexts.add(ctx);
592 } else if (objective instanceof NextObjective) {
593 // need to removed after forwarding objective
594 // nothing to do here
595 } else if (objective instanceof ForwardingObjective) {
596 // forwarding objective, also find next objective if
597 // exist
598 FlowObjectiveInstallationContext fwdCtx =
599 buildObjectiveContext(objective, deviceId, direction);
600 ForwardingObjective fwd = (ForwardingObjective) objective;
601 NextObjective nxt = null;
602 Integer nextId = fwd.nextId();
603 if (nextId != null) {
604 for (int j = 0; j < size; j++) {
605 if (objectives.get(j).id() == nextId) {
606 nxt = (NextObjective) objectives.get(j);
607 break;
608 }
609 }
610 // if a next objective exists in the Intent
611 if (nxt != null) {
612 FlowObjectiveInstallationContext nxtCtx =
613 buildObjectiveContext(nxt, deviceId, direction);
614 fwdCtx.nextContext(nxtCtx);
615 }
616 }
617 contexts.add(fwdCtx);
618 } else {
619 // possible here?
620 log.warn(UNSUPPORT_OBJ, objective);
621 }
622 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800623 }
624 return contexts;
625 }
626
Yi Tseng38fc71e2017-02-03 14:50:47 -0800627 private FlowObjectiveInstallationContext buildObjectiveContext(Objective objective,
628 DeviceId deviceId,
629 Direction direction) {
630 Objective.Builder builder = objective.copy();
631 FlowObjectiveInstallationContext ctx = new FlowObjectiveInstallationContext();
632 switch (direction) {
633 case ADD:
634 objective = builder.add(ctx);
635 break;
636 case REMOVE:
637 objective = builder.remove(ctx);
638 break;
639 default:
640 break;
641 }
642 ctx.setObjective(objective, deviceId);
643 return ctx;
644 }
645
Thomas Vachuska2980c972016-02-23 20:58:49 -0800646 @Override
647 void apply() {
Yi Tseng38fc71e2017-02-03 14:50:47 -0800648 // If there is no pending contexts, try apply second stage
649 // pending contexts
650 if (pendingContexts.isEmpty()) {
651 pendingContexts.addAll(nextPendingContexts);
652 nextPendingContexts.clear();
653 }
654 final Set<ObjectiveContext> contextsToApply = Sets.newHashSet(pendingContexts);
655 contextsToApply.forEach(ctx -> {
656 FlowObjectiveInstallationContext foiCtx =
657 (FlowObjectiveInstallationContext) ctx;
658
659 flowObjectiveService.apply(foiCtx.deviceId, foiCtx.objective);
660 });
Thomas Vachuska2980c972016-02-23 20:58:49 -0800661 }
662
663 @Override
664 public Object error() {
665 return errorContexts;
666 }
667
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -0800668 @Override
669 protected ToStringHelper toStringHelper() {
670 return super.toStringHelper()
671 .add("contexts", contexts)
672 .add("pendingContexts", pendingContexts)
673 .add("errorContexts", errorContexts);
674 }
675
Thomas Vachuska2980c972016-02-23 20:58:49 -0800676 private class FlowObjectiveInstallationContext implements ObjectiveContext {
677 Objective objective;
678 DeviceId deviceId;
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700679 ObjectiveError error;
Yi Tseng38fc71e2017-02-03 14:50:47 -0800680 AtomicInteger retry;
681 FlowObjectiveInstallationContext nextContext;
Thomas Vachuska2980c972016-02-23 20:58:49 -0800682
683 void setObjective(Objective objective, DeviceId deviceId) {
Yi Tseng38fc71e2017-02-03 14:50:47 -0800684 // init function
Thomas Vachuska2980c972016-02-23 20:58:49 -0800685 this.objective = objective;
686 this.deviceId = deviceId;
Yi Tseng38fc71e2017-02-03 14:50:47 -0800687 this.error = null;
688 this.retry = new AtomicInteger(0);
689 this.nextContext = null;
Thomas Vachuska2980c972016-02-23 20:58:49 -0800690 }
691
Yi Tseng38fc71e2017-02-03 14:50:47 -0800692 int retryTimes() {
693 return this.retry.get();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800694 }
695
Yi Tseng38fc71e2017-02-03 14:50:47 -0800696 void increaseRetryValue() {
697 this.retry.incrementAndGet();
Thomas Vachuska2980c972016-02-23 20:58:49 -0800698 }
699
Yi Tseng38fc71e2017-02-03 14:50:47 -0800700 private void finished(ObjectiveError error) {
701
Thomas Vachuska2980c972016-02-23 20:58:49 -0800702 synchronized (pendingContexts) {
Yi Tseng38fc71e2017-02-03 14:50:47 -0800703 if (error != null) {
704 this.error = error;
705 handleObjectiveError(this, error);
706 } else {
707 // apply next context if exist
708 if (nextContext != null) {
709 pendingContexts.add(nextContext);
710 flowObjectiveService.apply(nextContext.deviceId,
711 nextContext.objective);
712 pendingContexts.remove(this);
Thomas Vachuska2980c972016-02-23 20:58:49 -0800713 } else {
Yi Tseng38fc71e2017-02-03 14:50:47 -0800714 pendingContexts.remove(this);
Thomas Vachuska2980c972016-02-23 20:58:49 -0800715 }
716 }
Yi Tseng38fc71e2017-02-03 14:50:47 -0800717 if (!pendingContexts.isEmpty()) {
718 return;
719 }
720 // Apply second stage pending contexts if it is not empty
721 if (!nextPendingContexts.isEmpty()) {
722 pendingContexts.addAll(nextPendingContexts);
723 nextPendingContexts.clear();
724 final Set<ObjectiveContext> contextsToApply =
725 Sets.newHashSet(pendingContexts);
726 contextsToApply.forEach(ctx -> {
727 FlowObjectiveInstallationContext foiCtx =
728 (FlowObjectiveInstallationContext) ctx;
729 flowObjectiveService.apply(foiCtx.deviceId,
730 foiCtx.objective);
731 });
732 return;
733 }
734 if (errorContexts.isEmpty()) {
735 successConsumer.accept(FlowObjectiveOperationContext.this);
736 } else {
737 errorConsumer.accept(FlowObjectiveOperationContext.this);
738 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800739 }
740 }
741
742 @Override
Yi Tseng38fc71e2017-02-03 14:50:47 -0800743 public void onSuccess(Objective objective) {
744 finished(null);
745 }
746
747 @Override
748 public void onError(Objective objective, ObjectiveError error) {
749 finished(error);
750 }
751
752 @Override
Thomas Vachuska2980c972016-02-23 20:58:49 -0800753 public String toString() {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700754 return String.format("(%s on %s for %s)", error, deviceId, objective);
Thomas Vachuska2980c972016-02-23 20:58:49 -0800755 }
Yi Tseng38fc71e2017-02-03 14:50:47 -0800756
757 public void nextContext(FlowObjectiveInstallationContext nextContext) {
758 this.nextContext = nextContext;
759 }
760 }
761
762 private void handleObjectiveError(FlowObjectiveInstallationContext ctx,
763 ObjectiveError error) {
764 log.debug("Got error(s) when install objective: {}, error: {}, retry: {}",
765 ctx.objective, ctx.error, ctx.retry);
766 if (ctx.retryTimes() > OBJECTIVE_RETRY_THRESHOLD) {
767 ctx.error = INSTALLATIONTHRESHOLDEXCEEDED;
768 errorContexts.add(ctx);
769 return;
770 }
771 // reset error
772 ctx.error = null;
773 // strategies for errors
774 switch (error) {
775 case GROUPEXISTS:
776 if (ctx.objective.op() == Objective.Operation.ADD) {
777 // Next group exists
778 // build new objective with new op ADD_TO_EXIST
779 NextObjective newObj =
780 ((NextObjective.Builder) ctx.objective.copy()).addToExisting(ctx);
781 ctx.setObjective(newObj, ctx.deviceId);
782 ctx.increaseRetryValue();
783 flowObjectiveService.apply(ctx.deviceId, ctx.objective);
784 } else {
785 pendingContexts.remove(ctx);
786 errorContexts.add(ctx);
787 }
788 break;
789 case GROUPINSTALLATIONFAILED:
790 // Group install failed, retry again
791 ctx.increaseRetryValue();
792 flowObjectiveService.apply(ctx.deviceId, ctx.objective);
793 break;
794 case GROUPMISSING:
795 if (ctx.objective.op() == Objective.Operation.ADD_TO_EXISTING) {
796 // Next group not exist, but we want to add new buckets
797 // build new objective with new op ADD
798 NextObjective newObj = (NextObjective) ctx.objective.copy().add(ctx);
799 ctx.setObjective(newObj, ctx.deviceId);
800 ctx.increaseRetryValue();
801 flowObjectiveService.apply(ctx.deviceId, ctx.objective);
802 } else if (ctx.objective.op() == Objective.Operation.REMOVE ||
803 ctx.objective.op() == Objective.Operation.REMOVE_FROM_EXISTING) {
804 // Already removed, no need to do anything
805 ctx.error = null;
806 pendingContexts.remove(ctx);
807 return;
808 } else {
809 // Next chaining group missing, try again.
810 ctx.increaseRetryValue();
811 flowObjectiveService.apply(ctx.deviceId, ctx.objective);
812 }
813 break;
814 case FLOWINSTALLATIONFAILED:
815 case GROUPREMOVALFAILED:
816 case INSTALLATIONTIMEOUT:
817 // Retry
818 ctx.increaseRetryValue();
819 flowObjectiveService.apply(ctx.deviceId, ctx.objective);
820 break;
821 default:
822 pendingContexts.remove(ctx);
823 errorContexts.add(ctx);
824 break;
825 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800826 }
827 }
828
829 private class ErrorContext extends OperationContext {
Andreas Papazois05548962016-11-23 11:36:55 +0200830 ErrorContext(IntentInstallationContext context) {
831 super(context);
832 }
Thomas Vachuska2980c972016-02-23 20:58:49 -0800833 @Override
834 void apply() {
835 throw new UnsupportedOperationException("Unsupported installable intent");
836 }
837
838 @Override
839 Object error() {
840 return null;
841 }
842
843 @Override
844 void prepareIntents(List<Intent> intentsToApply, Direction direction) {
845 }
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800846 }
Andreas Papazois05548962016-11-23 11:36:55 +0200847
848
849 /**
850 * Context for applying and tracking operations related to
851 * {@link ProtectionEndpointIntent}.
852 */
853 @Beta
854 private class ProtectionConfigOperationContext extends OperationContext {
855
856 ProtectionConfigOperationContext(IntentInstallationContext context) {
857 super(context);
858 }
859
860 /**
861 * Stage of installable Intents which can be processed in parallel.
862 */
863 private final class Stage {
864 // should it have progress state, how far it went?
865 private final Collection<Pair<ProtectionEndpointIntent, Direction>> ops;
866
867 Stage(Collection<Pair<ProtectionEndpointIntent, Direction>> ops) {
868 this.ops = checkNotNull(ops);
869 }
870
871 CompletableFuture<Void> apply() {
872 return ops.stream()
873 .map(op -> applyOp(op.getRight(), op.getLeft()))
874 .reduce(CompletableFuture.completedFuture(null),
875 (l, r) -> {
876 l.join();
877 return r;
878 });
879 }
880
881 private CompletableFuture<Void> applyOp(Direction dir, ProtectionEndpointIntent intent) {
882 log.trace("applying {}: {}", dir, intent);
883 if (dir == Direction.REMOVE) {
884 networkConfigService.removeConfig(intent.deviceId(), ProtectionConfig.class);
885 } else if (dir == Direction.ADD) {
886 ProtectedTransportEndpointDescription description = intent.description();
887
888 // Can't do following. Will trigger empty CONFIG_ADDED
889 //ProtectionConfig cfg = networkConfigService.addConfig(intent.deviceId(),
890 // ProtectionConfig.class);
891 ProtectionConfig cfg = new ProtectionConfig(intent.deviceId());
892 cfg.fingerprint(description.fingerprint());
893 cfg.peer(description.peer());
894 cfg.paths(description.paths());
895 //cfg.apply();
896
897 networkConfigService.applyConfig(intent.deviceId(),
898 ProtectionConfig.class,
899 cfg.node());
900 }
901 // TODO Should monitor progress and complete only after it's
902 // actually done.
903 return CompletableFuture.completedFuture(null);
904 }
905
906 @Override
907 public String toString() {
908 return ops.toString();
909 }
910 }
911
912 /**
913 * List of Stages which must be executed in order.
914 */
915 private final List<Stage> stages = new ArrayList<>();
916
917 private final List<Stage> failed = new CopyOnWriteArrayList<>();
918
919 @Override
920 synchronized void apply() {
921 for (Stage stage : stages) {
922 log.trace("applying Stage {}", stage);
923 CompletableFuture<Void> result = stage.apply();
924 // wait for stage completion
925 result.join();
926 if (result.isCompletedExceptionally()) {
927 log.error("Stage {} failed", stage);
928 failed.add(stage);
929 errorConsumer.accept(ProtectionConfigOperationContext.this);
930 return;
931 }
932 }
933 successConsumer.accept(ProtectionConfigOperationContext.this);
934 }
935
936 @Override
937 Object error() {
938 // Something to represent error state
939 return failed;
940 }
941
942 @Override
943 synchronized void prepareIntents(List<Intent> intentsToApply,
944 Direction direction) {
945
946 stages.add(new Stage(intentsToApply.stream()
947 .filter(i -> i instanceof ProtectionEndpointIntent)
948 .map(i -> Pair.of((ProtectionEndpointIntent) i, direction))
949 .collect(Collectors.toList())));
950 }
951
Yuta HIGUCHI63bbedd2017-01-30 10:49:29 -0800952 @Override
953 protected ToStringHelper toStringHelper() {
954 return super.toStringHelper()
955 .add("stages", stages)
956 .add("failed", failed);
957 }
Andreas Papazois05548962016-11-23 11:36:55 +0200958 }
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800959}