blob: 38d7a5b0323ff9621e3de17abac9fd27a70c29ab [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.net.intent.impl;
Brian O'Connor66630c82014-10-02 21:08:19 -070017
Sho SHIMIZUe0981722016-01-14 16:02:48 -080018import org.onlab.util.Tools;
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -080019import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080020import org.onosproject.core.CoreService;
21import org.onosproject.core.IdGenerator;
Sho SHIMIZU98c0a392016-01-14 18:40:53 -080022import org.onosproject.event.AbstractListenerManager;
helenyrwu2a674902016-07-20 09:48:04 -070023import org.onosproject.net.DeviceId;
Andreas Papazois05548962016-11-23 11:36:55 +020024import org.onosproject.net.config.NetworkConfigService;
Andreas Papazoisf00087c2016-11-23 11:36:55 +020025import org.onosproject.net.domain.DomainIntentService;
Brian O'Connorabafb502014-12-02 22:26:20 -080026import org.onosproject.net.flow.FlowRuleService;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080027import org.onosproject.net.flowobjective.FlowObjectiveService;
helenyrwu2a674902016-07-20 09:48:04 -070028import org.onosproject.net.group.GroupKey;
29import org.onosproject.net.group.GroupService;
Brian O'Connorabafb502014-12-02 22:26:20 -080030import org.onosproject.net.intent.Intent;
31import org.onosproject.net.intent.IntentBatchDelegate;
Brian O'Connorabafb502014-12-02 22:26:20 -080032import org.onosproject.net.intent.IntentCompiler;
Brian O'Connorcff03322015-02-03 15:28:59 -080033import org.onosproject.net.intent.IntentData;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.net.intent.IntentEvent;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.net.intent.IntentExtensionService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070036import org.onosproject.net.intent.IntentInstallCoordinator;
Yi Tsengc927a062017-05-02 15:02:37 -070037import org.onosproject.net.intent.IntentInstaller;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.intent.IntentListener;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070039import org.onosproject.net.intent.IntentOperationContext;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.intent.IntentService;
41import org.onosproject.net.intent.IntentState;
42import org.onosproject.net.intent.IntentStore;
Brian O'Connorabafb502014-12-02 22:26:20 -080043import org.onosproject.net.intent.IntentStoreDelegate;
Ray Milkeyf9af43c2015-02-09 16:45:48 -080044import org.onosproject.net.intent.Key;
Yi Tseng24d9be72017-05-12 11:28:13 -070045import org.onosproject.net.intent.ObjectiveTrackerService;
helenyrwu2a674902016-07-20 09:48:04 -070046import org.onosproject.net.intent.PointToPointIntent;
Yi Tseng24d9be72017-05-12 11:28:13 -070047import org.onosproject.net.intent.TopologyChangeDelegate;
helenyrwu2a674902016-07-20 09:48:04 -070048import org.onosproject.net.intent.impl.compiler.PointToPointIntentCompiler;
Sho SHIMIZU36a8a6e2015-02-13 15:38:45 -080049import org.onosproject.net.intent.impl.phase.FinalIntentProcessPhase;
Sho SHIMIZUce49b602015-02-23 19:15:49 -080050import org.onosproject.net.intent.impl.phase.IntentProcessPhase;
Brian O'Connorc590ebb2016-12-08 18:16:41 -080051import org.onosproject.net.intent.impl.phase.Skipped;
Luca Pretede10c782017-01-05 17:23:08 -080052import org.onosproject.net.resource.ResourceConsumer;
Sho SHIMIZUe18cb122016-02-22 21:04:56 -080053import org.onosproject.net.resource.ResourceService;
Luca Pretede10c782017-01-05 17:23:08 -080054import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070055import org.osgi.service.component.annotations.Activate;
56import org.osgi.service.component.annotations.Component;
57import org.osgi.service.component.annotations.Deactivate;
58import org.osgi.service.component.annotations.Modified;
59import org.osgi.service.component.annotations.Reference;
60import org.osgi.service.component.annotations.ReferenceCardinality;
Brian O'Connor66630c82014-10-02 21:08:19 -070061import org.slf4j.Logger;
62
Brian O'Connorf0c5a052015-04-27 00:34:53 -070063import java.util.Collection;
64import java.util.EnumSet;
65import java.util.List;
66import java.util.Map;
Sho SHIMIZUab541a52016-01-13 23:29:32 -080067import java.util.Objects;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070068import java.util.Optional;
Sho SHIMIZUad8ab272016-01-13 22:08:58 -080069import java.util.concurrent.CompletableFuture;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070070import java.util.concurrent.ExecutorService;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070071import java.util.stream.Collectors;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070072
Brian O'Connorfa81eae2014-10-30 13:20:05 -070073import static com.google.common.base.Preconditions.checkNotNull;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -080074import static com.google.common.base.Strings.isNullOrEmpty;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080075import static java.util.concurrent.Executors.newFixedThreadPool;
Brian O'Connordb15b042015-02-04 14:59:28 -080076import static java.util.concurrent.Executors.newSingleThreadExecutor;
Brian O'Connorbdc7f002015-02-18 20:49:41 -080077import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070078import static org.onosproject.net.OsgiPropertyConstants.IM_NUM_THREADS;
79import static org.onosproject.net.OsgiPropertyConstants.IM_NUM_THREADS_DEFAULT;
80import static org.onosproject.net.OsgiPropertyConstants.IM_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL;
81import static org.onosproject.net.OsgiPropertyConstants.IM_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL_DEFAULT;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070082import static org.onosproject.net.intent.IntentState.FAILED;
83import static org.onosproject.net.intent.IntentState.INSTALL_REQ;
84import static org.onosproject.net.intent.IntentState.WITHDRAWING;
85import static org.onosproject.net.intent.IntentState.WITHDRAWN;
86import static org.onosproject.net.intent.IntentState.WITHDRAW_REQ;
Jonathan Hart96c5a4a2015-07-31 14:23:33 -070087import static org.onosproject.net.intent.constraint.PartialFailureConstraint.intentAllowsPartialFailure;
Sho SHIMIZUce49b602015-02-23 19:15:49 -080088import static org.onosproject.net.intent.impl.phase.IntentProcessPhase.newInitialPhase;
Changhoon Yoon541ef712015-05-23 17:18:34 +090089import static org.onosproject.security.AppGuard.checkPermission;
Sho SHIMIZU98c0a392016-01-14 18:40:53 -080090import static org.onosproject.security.AppPermission.Type.INTENT_READ;
91import static org.onosproject.security.AppPermission.Type.INTENT_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070092import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090093
Brian O'Connor66630c82014-10-02 21:08:19 -070094/**
Brian O'Connorce2d8b52015-07-29 16:24:13 -070095 * An implementation of intent service.
Brian O'Connor66630c82014-10-02 21:08:19 -070096 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070097@Component(
98 immediate = true,
99 service = {
100 IntentService.class,
101 IntentExtensionService.class,
102 IntentInstallCoordinator.class
103 },
104 property = {
Ray Milkey2d7bca12018-10-17 14:51:52 -0700105 IM_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL + ":Boolean=" + IM_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL_DEFAULT,
106 IM_NUM_THREADS + ":Integer=" + IM_NUM_THREADS_DEFAULT
Ray Milkeyd04e2272018-10-16 18:20:18 -0700107 }
108)
Brian O'Connor66630c82014-10-02 21:08:19 -0700109public class IntentManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700110 extends AbstractListenerManager<IntentEvent, IntentListener>
Yi Tsengc927a062017-05-02 15:02:37 -0700111 implements IntentService, IntentExtensionService, IntentInstallCoordinator {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700112
Sho SHIMIZU8b5051d2014-11-05 11:24:13 -0800113 private static final Logger log = getLogger(IntentManager.class);
Brian O'Connor66630c82014-10-02 21:08:19 -0700114
Sho SHIMIZU17c09da2016-03-31 12:54:17 -0700115 private static final String INTENT_NULL = "Intent cannot be null";
116 private static final String INTENT_ID_NULL = "Intent key cannot be null";
Brian O'Connor66630c82014-10-02 21:08:19 -0700117
Brian O'Connor7a71d5d2014-12-02 00:12:27 -0800118 private static final EnumSet<IntentState> RECOMPILE
119 = EnumSet.of(INSTALL_REQ, FAILED, WITHDRAW_REQ);
Jonathan Hart96c5a4a2015-07-31 14:23:33 -0700120 private static final EnumSet<IntentState> WITHDRAW
121 = EnumSet.of(WITHDRAW_REQ, WITHDRAWING, WITHDRAWN);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800122
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700123 //@Property(name = "skipReleaseResourcesOnWithdrawal",
124 // boolValue = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL,
125 // label = "Indicates whether skipping resource releases on withdrawal is enabled or not")
Ray Milkeyd04e2272018-10-16 18:20:18 -0700126 private boolean skipReleaseResourcesOnWithdrawal = IM_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL_DEFAULT;
Brian O'Connor7a71d5d2014-12-02 00:12:27 -0800127
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700128 //@Property(name = "numThreads",
129 // intValue = DEFAULT_NUM_THREADS,
130 // label = "Number of worker threads")
Ray Milkeyd04e2272018-10-16 18:20:18 -0700131 private int numThreads = IM_NUM_THREADS_DEFAULT;
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800132
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700133 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Brian O'Connor520c0522014-11-23 23:50:47 -0800134 protected CoreService coreService;
Brian O'Connor66630c82014-10-02 21:08:19 -0700135
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Brian O'Connor66630c82014-10-02 21:08:19 -0700137 protected IntentStore store;
138
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700139 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom85258ee2014-10-07 00:10:02 -0700140 protected ObjectiveTrackerService trackerService;
tom95329eb2014-10-06 08:40:06 -0700141
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700142 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sho SHIMIZU214ac322015-02-23 19:30:15 -0800143 protected FlowRuleService flowRuleService;
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700144
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700145 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800146 protected FlowObjectiveService flowObjectiveService;
147
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andreas Papazoisf00087c2016-11-23 11:36:55 +0200149 protected DomainIntentService domainIntentService;
150
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700151 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800152 protected ResourceService resourceService;
153
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800155 protected ComponentConfigService configService;
156
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY)
helenyrwu2a674902016-07-20 09:48:04 -0700158 protected GroupService groupService;
159
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700160 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andreas Papazois05548962016-11-23 11:36:55 +0200161 private NetworkConfigService networkConfigService;
162
Brian O'Connordb15b042015-02-04 14:59:28 -0800163 private ExecutorService batchExecutor;
164 private ExecutorService workerExecutor;
Brian O'Connor520c0522014-11-23 23:50:47 -0800165
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800166 private final CompilerRegistry compilerRegistry = new CompilerRegistry();
Yi Tsengc927a062017-05-02 15:02:37 -0700167 private final InstallerRegistry installerRegistry = new InstallerRegistry();
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800168 private final InternalIntentProcessor processor = new InternalIntentProcessor();
Brian O'Connor520c0522014-11-23 23:50:47 -0800169 private final IntentStoreDelegate delegate = new InternalStoreDelegate();
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800170 private final IntentStoreDelegate testOnlyDelegate = new TestOnlyIntentStoreDelegate();
Brian O'Connor520c0522014-11-23 23:50:47 -0800171 private final TopologyChangeDelegate topoDelegate = new InternalTopoChangeDelegate();
172 private final IntentBatchDelegate batchDelegate = new InternalBatchDelegate();
Yi Tsengc927a062017-05-02 15:02:37 -0700173 private InstallCoordinator installCoordinator;
Brian O'Connor520c0522014-11-23 23:50:47 -0800174 private IdGenerator idGenerator;
175
Brian O'Connorb499b352015-02-03 16:46:15 -0800176 private final IntentAccumulator accumulator = new IntentAccumulator(batchDelegate);
Brian O'Connorcff03322015-02-03 15:28:59 -0800177
Brian O'Connor66630c82014-10-02 21:08:19 -0700178 @Activate
179 public void activate() {
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800180 configService.registerProperties(getClass());
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800181 if (skipReleaseResourcesOnWithdrawal) {
182 store.setDelegate(testOnlyDelegate);
183 } else {
184 store.setDelegate(delegate);
185 }
tom95329eb2014-10-06 08:40:06 -0700186 trackerService.setDelegate(topoDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700187 eventDispatcher.addSink(IntentEvent.class, listenerRegistry);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700188 batchExecutor = newSingleThreadExecutor(groupedThreads("onos/intent", "batch", log));
189 workerExecutor = newFixedThreadPool(numThreads, groupedThreads("onos/intent", "worker-%d", log));
Brian O'Connor520c0522014-11-23 23:50:47 -0800190 idGenerator = coreService.getIdGenerator("intent-ids");
Thomas Vachuska23235962017-02-03 11:44:15 -0800191 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor520c0522014-11-23 23:50:47 -0800192 Intent.bindIdGenerator(idGenerator);
Yi Tsengc927a062017-05-02 15:02:37 -0700193 installCoordinator = new InstallCoordinator(installerRegistry, store);
Brian O'Connor66630c82014-10-02 21:08:19 -0700194 log.info("Started");
195 }
196
197 @Deactivate
198 public void deactivate() {
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800199 if (skipReleaseResourcesOnWithdrawal) {
200 store.unsetDelegate(testOnlyDelegate);
201 } else {
202 store.unsetDelegate(delegate);
203 }
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800204 configService.unregisterProperties(getClass(), false);
tom95329eb2014-10-06 08:40:06 -0700205 trackerService.unsetDelegate(topoDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700206 eventDispatcher.removeSink(IntentEvent.class);
Brian O'Connordb15b042015-02-04 14:59:28 -0800207 batchExecutor.shutdown();
Brian O'Connor3c58e962015-04-28 23:21:51 -0700208 workerExecutor.shutdown();
Brian O'Connor520c0522014-11-23 23:50:47 -0800209 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700210 log.info("Stopped");
211 }
212
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800213 @Modified
214 public void modified(ComponentContext context) {
215 if (context == null) {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700216 skipReleaseResourcesOnWithdrawal = IM_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL_DEFAULT;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800217 logConfig("Default config");
218 return;
219 }
220
221 String s = Tools.get(context.getProperties(), "skipReleaseResourcesOnWithdrawal");
222 boolean newTestEnabled = isNullOrEmpty(s) ? skipReleaseResourcesOnWithdrawal : Boolean.parseBoolean(s.trim());
223 if (skipReleaseResourcesOnWithdrawal && !newTestEnabled) {
224 store.unsetDelegate(testOnlyDelegate);
225 store.setDelegate(delegate);
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800226 skipReleaseResourcesOnWithdrawal = false;
227 logConfig("Reconfigured skip release resources on withdrawal");
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800228 } else if (!skipReleaseResourcesOnWithdrawal && newTestEnabled) {
229 store.unsetDelegate(delegate);
230 store.setDelegate(testOnlyDelegate);
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800231 skipReleaseResourcesOnWithdrawal = true;
232 logConfig("Reconfigured skip release resources on withdrawal");
233 }
234
235 s = Tools.get(context.getProperties(), "numThreads");
236 int newNumThreads = isNullOrEmpty(s) ? numThreads : Integer.parseInt(s);
237 if (newNumThreads != numThreads) {
238 numThreads = newNumThreads;
239 ExecutorService oldWorkerExecutor = workerExecutor;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800240 workerExecutor = newFixedThreadPool(numThreads, groupedThreads("onos/intent", "worker-%d", log));
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800241 if (oldWorkerExecutor != null) {
242 oldWorkerExecutor.shutdown();
243 }
244 logConfig("Reconfigured number of worker threads");
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800245 }
246 }
247
248 private void logConfig(String prefix) {
249 log.info("{} with skipReleaseResourcesOnWithdrawal = {}", prefix, skipReleaseResourcesOnWithdrawal);
250 }
251
Brian O'Connor66630c82014-10-02 21:08:19 -0700252 @Override
253 public void submit(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900254 checkPermission(INTENT_WRITE);
Brian O'Connor66630c82014-10-02 21:08:19 -0700255 checkNotNull(intent, INTENT_NULL);
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700256 IntentData data = IntentData.submit(intent);
Brian O'Connorcff03322015-02-03 15:28:59 -0800257 store.addPending(data);
Brian O'Connor66630c82014-10-02 21:08:19 -0700258 }
259
260 @Override
261 public void withdraw(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900262 checkPermission(INTENT_WRITE);
Brian O'Connor66630c82014-10-02 21:08:19 -0700263 checkNotNull(intent, INTENT_NULL);
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700264 IntentData data = IntentData.withdraw(intent);
Brian O'Connorcff03322015-02-03 15:28:59 -0800265 store.addPending(data);
Brian O'Connor66630c82014-10-02 21:08:19 -0700266 }
267
Brian O'Connor66630c82014-10-02 21:08:19 -0700268 @Override
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700269 public void purge(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900270 checkPermission(INTENT_WRITE);
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700271 checkNotNull(intent, INTENT_NULL);
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700272 IntentData data = IntentData.purge(intent);
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700273 store.addPending(data);
helenyrwu2a674902016-07-20 09:48:04 -0700274
275 // remove associated group if there is one
276 if (intent instanceof PointToPointIntent) {
277 PointToPointIntent pointIntent = (PointToPointIntent) intent;
Ray Milkeya2cf3a12018-02-15 16:13:56 -0800278 DeviceId deviceId = pointIntent.filteredIngressPoint().connectPoint().deviceId();
helenyrwu2a674902016-07-20 09:48:04 -0700279 GroupKey groupKey = PointToPointIntentCompiler.makeGroupKey(intent.id());
280 groupService.removeGroup(deviceId, groupKey,
281 intent.appId());
282 }
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700283 }
284
285 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800286 public Intent getIntent(Key key) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900287 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800288 return store.getIntent(key);
289 }
290
291 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700292 public Iterable<Intent> getIntents() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900293 checkPermission(INTENT_READ);
Brian O'Connor66630c82014-10-02 21:08:19 -0700294 return store.getIntents();
295 }
296
297 @Override
Brian O'Connor38224302016-08-02 22:03:01 -0700298 public void addPending(IntentData intentData) {
299 checkPermission(INTENT_WRITE);
300 checkNotNull(intentData, INTENT_NULL);
301 //TODO we might consider further checking / assertions
302 store.addPending(intentData);
303 }
304
305 @Override
Thomas Vachuskac46af202015-06-03 16:43:27 -0700306 public Iterable<IntentData> getIntentData() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900307 checkPermission(INTENT_READ);
Thomas Vachuskac46af202015-06-03 16:43:27 -0700308 return store.getIntentData(false, 0);
309 }
310
311 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700312 public long getIntentCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900313 checkPermission(INTENT_READ);
Brian O'Connor66630c82014-10-02 21:08:19 -0700314 return store.getIntentCount();
315 }
316
317 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800318 public IntentState getIntentState(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900319 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800320 checkNotNull(intentKey, INTENT_ID_NULL);
321 return store.getIntentState(intentKey);
Brian O'Connor66630c82014-10-02 21:08:19 -0700322 }
323
324 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800325 public List<Intent> getInstallableIntents(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900326 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800327 checkNotNull(intentKey, INTENT_ID_NULL);
328 return store.getInstallableIntents(intentKey);
Thomas Vachuska10d4abc2014-10-21 12:47:26 -0700329 }
330
331 @Override
Brian O'Connorbe28a872015-02-19 21:44:37 -0800332 public boolean isLocal(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900333 checkPermission(INTENT_READ);
Brian O'Connorbe28a872015-02-19 21:44:37 -0800334 return store.isMaster(intentKey);
335 }
336
337 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700338 public <T extends Intent> void registerCompiler(Class<T> cls, IntentCompiler<T> compiler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900339 checkPermission(INTENT_WRITE);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800340 compilerRegistry.registerCompiler(cls, compiler);
Brian O'Connor66630c82014-10-02 21:08:19 -0700341 }
342
343 @Override
344 public <T extends Intent> void unregisterCompiler(Class<T> cls) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900345 checkPermission(INTENT_WRITE);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800346 compilerRegistry.unregisterCompiler(cls);
Brian O'Connor66630c82014-10-02 21:08:19 -0700347 }
348
349 @Override
350 public Map<Class<? extends Intent>, IntentCompiler<? extends Intent>> getCompilers() {
Heedo Kang4a47a302016-02-29 17:40:23 +0900351 checkPermission(INTENT_READ);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800352 return compilerRegistry.getCompilers();
Brian O'Connor66630c82014-10-02 21:08:19 -0700353 }
354
355 @Override
Yi Tsengc927a062017-05-02 15:02:37 -0700356 public <T extends Intent> void registerInstaller(Class<T> cls, IntentInstaller<T> installer) {
357 installerRegistry.registerInstaller(cls, installer);
358 }
359
360 @Override
361 public <T extends Intent> void unregisterInstaller(Class<T> cls) {
362 installerRegistry.unregisterInstaller(cls);
363 }
364
365 @Override
366 public Map<Class<? extends Intent>, IntentInstaller<? extends Intent>> getInstallers() {
367 return installerRegistry.getInstallers();
368 }
369
370 @Override
371 @SuppressWarnings("unchecked")
372 public <T extends Intent> IntentInstaller<T> getInstaller(Class<T> cls) {
373 return (IntentInstaller<T>) installerRegistry.getInstallers().get(cls);
374 }
375
376 @Override
Jonathan Hart34f1e382015-02-24 16:52:23 -0800377 public Iterable<Intent> getPending() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900378 checkPermission(INTENT_READ);
Jonathan Hart34f1e382015-02-24 16:52:23 -0800379 return store.getPending();
380 }
381
Yi Tsengc927a062017-05-02 15:02:37 -0700382 @Override
383 public void intentInstallSuccess(IntentOperationContext context) {
384 installCoordinator.success(context);
385 }
386
387 @Override
388 public void intentInstallFailed(IntentOperationContext context) {
389 installCoordinator.failed(context);
390 }
391
Brian O'Connor66630c82014-10-02 21:08:19 -0700392 // Store delegate to re-post events emitted from the store.
393 private class InternalStoreDelegate implements IntentStoreDelegate {
394 @Override
395 public void notify(IntentEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700396 post(event);
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800397 switch (event.type()) {
398 case WITHDRAWN:
Luca Pretede10c782017-01-05 17:23:08 -0800399 if (!skipReleaseResourcesOnWithdrawal) {
400 releaseResources(event.subject());
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800401 }
402 break;
403 default:
404 break;
405 }
Brian O'Connor66630c82014-10-02 21:08:19 -0700406 }
Brian O'Connorea4d7d12015-01-28 16:37:46 -0800407
408 @Override
Brian O'Connorcff03322015-02-03 15:28:59 -0800409 public void process(IntentData data) {
410 accumulator.add(data);
Brian O'Connorea4d7d12015-01-28 16:37:46 -0800411 }
Thomas Vachuskac46af202015-06-03 16:43:27 -0700412
413 @Override
414 public void onUpdate(IntentData intentData) {
415 trackerService.trackIntent(intentData);
416 }
Luca Pretede10c782017-01-05 17:23:08 -0800417
418 private void releaseResources(Intent intent) {
419 // If a resource group is set on the intent, the resource consumer is
420 // set equal to it. Otherwise it's set to the intent key
421 ResourceConsumer resourceConsumer =
422 intent.resourceGroup() != null ? intent.resourceGroup() : intent.key();
423
424 // By default the resource doesn't get released
425 boolean removeResource = false;
426
427 if (intent.resourceGroup() == null) {
428 // If the intent doesn't have a resource group, it means the
429 // resource was registered using the intent key, so it can be
430 // released
431 removeResource = true;
432 } else {
433 // When a resource group is set, we make sure there are no other
434 // intents using the same resource group, before deleting the
435 // related resources.
436 Long remainingIntents =
437 Tools.stream(store.getIntents())
Yi Tseng2ef80142017-02-17 15:56:32 -0800438 .filter(i -> {
439 return i.resourceGroup() != null
440 && i.resourceGroup().equals(intent.resourceGroup());
441 })
Luca Pretede10c782017-01-05 17:23:08 -0800442 .count();
443 if (remainingIntents == 0) {
444 removeResource = true;
445 }
446 }
447
448 if (removeResource) {
449 // Release resources allocated to withdrawn intent
450 if (!resourceService.release(resourceConsumer)) {
451 log.error("Failed to release resources allocated to {}", resourceConsumer);
452 }
453 }
454 }
Brian O'Connor66630c82014-10-02 21:08:19 -0700455 }
456
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800457 // Store delegate enabled only when performing intent throughput tests
458 private class TestOnlyIntentStoreDelegate implements IntentStoreDelegate {
459 @Override
460 public void process(IntentData data) {
461 accumulator.add(data);
462 }
463
464 @Override
465 public void onUpdate(IntentData data) {
466 trackerService.trackIntent(data);
467 }
468
469 @Override
470 public void notify(IntentEvent event) {
471 post(event);
472 }
473 }
474
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800475 private void buildAndSubmitBatches(Iterable<Key> intentKeys,
Brian O'Connor72a034c2014-11-26 18:24:23 -0800476 boolean compileAllFailed) {
Brian O'Connor72a034c2014-11-26 18:24:23 -0800477 // Attempt recompilation of the specified intents first.
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800478 for (Key key : intentKeys) {
Yi Tseng49a2b2e2017-05-11 14:32:16 -0700479 if (!store.isMaster(key)) {
480 continue;
481 }
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800482 Intent intent = store.getIntent(key);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800483 if (intent == null) {
484 continue;
485 }
jaegonkimb914fcb2018-05-20 16:04:06 +0900486 if (store.getPendingData(key) != null) {
487 continue;
488 }
Brian O'Connor03406a42015-02-03 17:28:57 -0800489 submit(intent);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800490 }
491
Jonathan Hart0cca3e82015-09-23 17:54:11 -0700492 if (compileAllFailed) {
493 // If required, compile all currently failed intents.
494 for (Intent intent : getIntents()) {
Yi Tseng49a2b2e2017-05-11 14:32:16 -0700495 if (!store.isMaster(intent.key())) {
496 continue;
497 }
jaegonkimb914fcb2018-05-20 16:04:06 +0900498 if (store.getPendingData(intent.key()) != null) {
499 continue;
500 }
Jonathan Hart0cca3e82015-09-23 17:54:11 -0700501 IntentState state = getIntentState(intent.key());
502 if (RECOMPILE.contains(state) || intentAllowsPartialFailure(intent)) {
503 if (WITHDRAW.contains(state)) {
504 withdraw(intent);
505 } else {
506 submit(intent);
507 }
Brian O'Connor72a034c2014-11-26 18:24:23 -0800508 }
509 }
510 }
Brian O'Connor72a034c2014-11-26 18:24:23 -0800511 }
512
tom95329eb2014-10-06 08:40:06 -0700513 // Topology change delegate
514 private class InternalTopoChangeDelegate implements TopologyChangeDelegate {
515 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800516 public void triggerCompile(Iterable<Key> intentKeys,
tom85258ee2014-10-07 00:10:02 -0700517 boolean compileAllFailed) {
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700518 // TODO figure out who is making excessive calls?
Jon Hall274cecb2017-08-09 12:15:48 -0700519 log.trace("submitting {} + all?:{} for compilation", intentKeys, compileAllFailed);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800520 buildAndSubmitBatches(intentKeys, compileAllFailed);
tom95329eb2014-10-06 08:40:06 -0700521 }
tom95329eb2014-10-06 08:40:06 -0700522 }
tom85258ee2014-10-07 00:10:02 -0700523
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700524 private class InternalBatchDelegate implements IntentBatchDelegate {
525 @Override
Brian O'Connorb499b352015-02-03 16:46:15 -0800526 public void execute(Collection<IntentData> operations) {
Brian O'Connorab8ef822015-02-17 18:08:54 -0800527 log.debug("Execute {} operation(s).", operations.size());
528 log.trace("Execute operations: {}", operations);
Sho SHIMIZU94b03b12015-04-10 14:53:13 -0700529
530 // batchExecutor is single-threaded, so only one batch is in flight at a time
Sho SHIMIZU489aa9b2016-01-14 17:19:32 -0800531 CompletableFuture.runAsync(() -> {
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800532 // process intent until the phase reaches one of the final phases
533 List<CompletableFuture<IntentData>> futures = operations.stream()
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700534 .map(data -> {
535 log.debug("Start processing of {} {}@{}", data.request(), data.key(), data.version());
536 return data;
537 })
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800538 .map(x -> CompletableFuture.completedFuture(x)
539 .thenApply(IntentManager.this::createInitialPhase)
Sho SHIMIZU4a141852016-01-14 18:55:40 -0800540 .thenApplyAsync(IntentProcessPhase::process, workerExecutor)
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800541 .thenApply(FinalIntentProcessPhase::data)
542 .exceptionally(e -> {
Pier Luigi13b287f2017-01-10 15:07:52 -0800543 // When the future fails, we update the Intent to simulate the failure of
544 // the installation/withdrawal phase and we save in the current map. In
545 // the next round the CleanUp Thread will pick this Intent again.
546 log.warn("Future failed", e);
547 log.warn("Intent {} - state {} - request {}",
548 x.key(), x.state(), x.request());
549 switch (x.state()) {
550 case INSTALL_REQ:
551 case INSTALLING:
552 case WITHDRAW_REQ:
553 case WITHDRAWING:
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700554 // TODO should we swtich based on current
Pier Luigi13b287f2017-01-10 15:07:52 -0800555 IntentData current = store.getIntentData(x.key());
Yuta HIGUCHI4f8a3772017-05-16 20:23:49 -0700556 return IntentData.nextState(current, FAILED);
Pier Luigi13b287f2017-01-10 15:07:52 -0800557 default:
558 return null;
559 }
Brian O'Connorc590ebb2016-12-08 18:16:41 -0800560 }))
561 .collect(Collectors.toList());
Sho SHIMIZU62bbc602016-01-13 16:54:35 -0800562
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800563 // write multiple data to store in order
564 store.batchWrite(Tools.allOf(futures).join().stream()
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800565 .filter(Objects::nonNull)
566 .collect(Collectors.toList()));
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800567 }, batchExecutor).exceptionally(e -> {
568 log.error("Error submitting batches:", e);
569 // FIXME incomplete Intents should be cleaned up
570 // (transition to FAILED, etc.)
571
572 // the batch has failed
573 // TODO: maybe we should do more?
574 log.error("Walk the plank, matey...");
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800575 return null;
576 }).thenRun(accumulator::ready);
577
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700578 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700579 }
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800580
Sho SHIMIZUc88b85e2016-01-14 18:45:14 -0800581 private IntentProcessPhase createInitialPhase(IntentData data) {
Brian O'Connorc590ebb2016-12-08 18:16:41 -0800582 IntentData pending = store.getPendingData(data.key());
583 if (pending == null || pending.version().isNewerThan(data.version())) {
584 /*
585 If the pending map is null, then this intent was compiled by a
586 previous batch iteration, so we can skip it.
587 If the pending map has a newer request, it will get compiled as
588 part of the next batch, so we can skip it.
589 */
590 return Skipped.getPhase();
591 }
Sho SHIMIZUc88b85e2016-01-14 18:45:14 -0800592 IntentData current = store.getIntentData(data.key());
593 return newInitialPhase(processor, data, current);
594 }
595
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800596 private class InternalIntentProcessor implements IntentProcessor {
597 @Override
598 public List<Intent> compile(Intent intent, List<Intent> previousInstallables) {
599 return compilerRegistry.compile(intent, previousInstallables);
600 }
601
602 @Override
Brian O'Connorf0c5a052015-04-27 00:34:53 -0700603 public void apply(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) {
Yi Tsengc927a062017-05-02 15:02:37 -0700604 installCoordinator.installIntents(toUninstall, toInstall);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800605 }
Ray Milkeyfd7931d2015-03-30 13:58:38 -0700606 }
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800607
Brian O'Connor66630c82014-10-02 21:08:19 -0700608}