blob: 7b79f952a9060eac7b26ea844ebd6c3b305e1cb4 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
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
Brian O'Connor66630c82014-10-02 21:08:19 -070018import org.apache.felix.scr.annotations.Activate;
19import org.apache.felix.scr.annotations.Component;
20import org.apache.felix.scr.annotations.Deactivate;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -080021import org.apache.felix.scr.annotations.Modified;
22import org.apache.felix.scr.annotations.Property;
Brian O'Connor66630c82014-10-02 21:08:19 -070023import org.apache.felix.scr.annotations.Reference;
24import org.apache.felix.scr.annotations.ReferenceCardinality;
25import org.apache.felix.scr.annotations.Service;
Sho SHIMIZUe0981722016-01-14 16:02:48 -080026import org.onlab.util.Tools;
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -080027import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080028import org.onosproject.core.CoreService;
29import org.onosproject.core.IdGenerator;
Sho SHIMIZU98c0a392016-01-14 18:40:53 -080030import org.onosproject.event.AbstractListenerManager;
helenyrwu2a674902016-07-20 09:48:04 -070031import org.onosproject.net.DeviceId;
Andreas Papazois05548962016-11-23 11:36:55 +020032import org.onosproject.net.config.NetworkConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.net.flow.FlowRuleService;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080034import org.onosproject.net.flowobjective.FlowObjectiveService;
helenyrwu2a674902016-07-20 09:48:04 -070035import org.onosproject.net.group.GroupKey;
36import org.onosproject.net.group.GroupService;
Brian O'Connorabafb502014-12-02 22:26:20 -080037import org.onosproject.net.intent.Intent;
38import org.onosproject.net.intent.IntentBatchDelegate;
Brian O'Connorabafb502014-12-02 22:26:20 -080039import org.onosproject.net.intent.IntentCompiler;
Brian O'Connorcff03322015-02-03 15:28:59 -080040import org.onosproject.net.intent.IntentData;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.net.intent.IntentEvent;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.intent.IntentExtensionService;
Brian O'Connorabafb502014-12-02 22:26:20 -080043import org.onosproject.net.intent.IntentListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080044import org.onosproject.net.intent.IntentService;
45import org.onosproject.net.intent.IntentState;
46import org.onosproject.net.intent.IntentStore;
Brian O'Connorabafb502014-12-02 22:26:20 -080047import org.onosproject.net.intent.IntentStoreDelegate;
Ray Milkeyf9af43c2015-02-09 16:45:48 -080048import org.onosproject.net.intent.Key;
helenyrwu2a674902016-07-20 09:48:04 -070049import org.onosproject.net.intent.PointToPointIntent;
50import org.onosproject.net.intent.impl.compiler.PointToPointIntentCompiler;
Sho SHIMIZU36a8a6e2015-02-13 15:38:45 -080051import org.onosproject.net.intent.impl.phase.FinalIntentProcessPhase;
Sho SHIMIZUce49b602015-02-23 19:15:49 -080052import org.onosproject.net.intent.impl.phase.IntentProcessPhase;
Brian O'Connorc590ebb2016-12-08 18:16:41 -080053import org.onosproject.net.intent.impl.phase.Skipped;
Luca Pretede10c782017-01-05 17:23:08 -080054import org.onosproject.net.resource.ResourceConsumer;
Sho SHIMIZUe18cb122016-02-22 21:04:56 -080055import org.onosproject.net.resource.ResourceService;
Luca Pretede10c782017-01-05 17:23:08 -080056import org.osgi.service.component.ComponentContext;
Brian O'Connor66630c82014-10-02 21:08:19 -070057import org.slf4j.Logger;
58
Brian O'Connorf0c5a052015-04-27 00:34:53 -070059import java.util.Collection;
60import java.util.EnumSet;
61import java.util.List;
62import java.util.Map;
Sho SHIMIZUab541a52016-01-13 23:29:32 -080063import java.util.Objects;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070064import java.util.Optional;
Sho SHIMIZUad8ab272016-01-13 22:08:58 -080065import java.util.concurrent.CompletableFuture;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070066import java.util.concurrent.ExecutorService;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070067import java.util.stream.Collectors;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070068
Brian O'Connorfa81eae2014-10-30 13:20:05 -070069import static com.google.common.base.Preconditions.checkNotNull;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -080070import static com.google.common.base.Strings.isNullOrEmpty;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080071import static java.util.concurrent.Executors.newFixedThreadPool;
Brian O'Connordb15b042015-02-04 14:59:28 -080072import static java.util.concurrent.Executors.newSingleThreadExecutor;
Brian O'Connorbdc7f002015-02-18 20:49:41 -080073import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080074import static org.onosproject.net.intent.IntentState.*;
Jonathan Hart96c5a4a2015-07-31 14:23:33 -070075import static org.onosproject.net.intent.constraint.PartialFailureConstraint.intentAllowsPartialFailure;
Sho SHIMIZUce49b602015-02-23 19:15:49 -080076import static org.onosproject.net.intent.impl.phase.IntentProcessPhase.newInitialPhase;
Changhoon Yoon541ef712015-05-23 17:18:34 +090077import static org.onosproject.security.AppGuard.checkPermission;
Sho SHIMIZU98c0a392016-01-14 18:40:53 -080078import static org.onosproject.security.AppPermission.Type.INTENT_READ;
79import static org.onosproject.security.AppPermission.Type.INTENT_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070080import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090081
Brian O'Connor66630c82014-10-02 21:08:19 -070082/**
Brian O'Connorce2d8b52015-07-29 16:24:13 -070083 * An implementation of intent service.
Brian O'Connor66630c82014-10-02 21:08:19 -070084 */
85@Component(immediate = true)
86@Service
87public class IntentManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070088 extends AbstractListenerManager<IntentEvent, IntentListener>
Brian O'Connor66630c82014-10-02 21:08:19 -070089 implements IntentService, IntentExtensionService {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070090
Sho SHIMIZU8b5051d2014-11-05 11:24:13 -080091 private static final Logger log = getLogger(IntentManager.class);
Brian O'Connor66630c82014-10-02 21:08:19 -070092
Sho SHIMIZU17c09da2016-03-31 12:54:17 -070093 private static final String INTENT_NULL = "Intent cannot be null";
94 private static final String INTENT_ID_NULL = "Intent key cannot be null";
Brian O'Connor66630c82014-10-02 21:08:19 -070095
Brian O'Connor7a71d5d2014-12-02 00:12:27 -080096 private static final EnumSet<IntentState> RECOMPILE
97 = EnumSet.of(INSTALL_REQ, FAILED, WITHDRAW_REQ);
Jonathan Hart96c5a4a2015-07-31 14:23:33 -070098 private static final EnumSet<IntentState> WITHDRAW
99 = EnumSet.of(WITHDRAW_REQ, WITHDRAWING, WITHDRAWN);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800100
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800101 private static final boolean DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL = false;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800102 @Property(name = "skipReleaseResourcesOnWithdrawal",
103 boolValue = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL,
104 label = "Indicates whether skipping resource releases on withdrawal is enabled or not")
105 private boolean skipReleaseResourcesOnWithdrawal = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL;
Brian O'Connor7a71d5d2014-12-02 00:12:27 -0800106
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800107 private static final int DEFAULT_NUM_THREADS = 12;
108 @Property(name = "numThreads",
109 intValue = DEFAULT_NUM_THREADS,
110 label = "Number of worker threads")
111 private int numThreads = DEFAULT_NUM_THREADS;
112
Brian O'Connor520c0522014-11-23 23:50:47 -0800113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 protected CoreService coreService;
Brian O'Connor66630c82014-10-02 21:08:19 -0700115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
117 protected IntentStore store;
118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tom85258ee2014-10-07 00:10:02 -0700120 protected ObjectiveTrackerService trackerService;
tom95329eb2014-10-06 08:40:06 -0700121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sho SHIMIZU214ac322015-02-23 19:30:15 -0800123 protected FlowRuleService flowRuleService;
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700124
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800126 protected FlowObjectiveService flowObjectiveService;
127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800129 protected ResourceService resourceService;
130
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
132 protected ComponentConfigService configService;
133
helenyrwu2a674902016-07-20 09:48:04 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected GroupService groupService;
136
Andreas Papazois05548962016-11-23 11:36:55 +0200137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
138 private NetworkConfigService networkConfigService;
139
140
Brian O'Connordb15b042015-02-04 14:59:28 -0800141 private ExecutorService batchExecutor;
142 private ExecutorService workerExecutor;
Brian O'Connor520c0522014-11-23 23:50:47 -0800143
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800144 private final IntentInstaller intentInstaller = new IntentInstaller();
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800145 private final CompilerRegistry compilerRegistry = new CompilerRegistry();
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800146 private final InternalIntentProcessor processor = new InternalIntentProcessor();
Brian O'Connor520c0522014-11-23 23:50:47 -0800147 private final IntentStoreDelegate delegate = new InternalStoreDelegate();
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800148 private final IntentStoreDelegate testOnlyDelegate = new TestOnlyIntentStoreDelegate();
Brian O'Connor520c0522014-11-23 23:50:47 -0800149 private final TopologyChangeDelegate topoDelegate = new InternalTopoChangeDelegate();
150 private final IntentBatchDelegate batchDelegate = new InternalBatchDelegate();
151 private IdGenerator idGenerator;
152
Brian O'Connorb499b352015-02-03 16:46:15 -0800153 private final IntentAccumulator accumulator = new IntentAccumulator(batchDelegate);
Brian O'Connorcff03322015-02-03 15:28:59 -0800154
Brian O'Connor66630c82014-10-02 21:08:19 -0700155 @Activate
156 public void activate() {
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800157 configService.registerProperties(getClass());
158
Andreas Papazois05548962016-11-23 11:36:55 +0200159 intentInstaller.init(store, trackerService, flowRuleService, flowObjectiveService,
160 networkConfigService);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800161 if (skipReleaseResourcesOnWithdrawal) {
162 store.setDelegate(testOnlyDelegate);
163 } else {
164 store.setDelegate(delegate);
165 }
tom95329eb2014-10-06 08:40:06 -0700166 trackerService.setDelegate(topoDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700167 eventDispatcher.addSink(IntentEvent.class, listenerRegistry);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700168 batchExecutor = newSingleThreadExecutor(groupedThreads("onos/intent", "batch", log));
169 workerExecutor = newFixedThreadPool(numThreads, groupedThreads("onos/intent", "worker-%d", log));
Brian O'Connor520c0522014-11-23 23:50:47 -0800170 idGenerator = coreService.getIdGenerator("intent-ids");
Thomas Vachuska23235962017-02-03 11:44:15 -0800171 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor520c0522014-11-23 23:50:47 -0800172 Intent.bindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700173 log.info("Started");
174 }
175
176 @Deactivate
177 public void deactivate() {
Andreas Papazois05548962016-11-23 11:36:55 +0200178 intentInstaller.init(null, null, null, null, null);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800179 if (skipReleaseResourcesOnWithdrawal) {
180 store.unsetDelegate(testOnlyDelegate);
181 } else {
182 store.unsetDelegate(delegate);
183 }
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800184 configService.unregisterProperties(getClass(), false);
tom95329eb2014-10-06 08:40:06 -0700185 trackerService.unsetDelegate(topoDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700186 eventDispatcher.removeSink(IntentEvent.class);
Brian O'Connordb15b042015-02-04 14:59:28 -0800187 batchExecutor.shutdown();
Brian O'Connor3c58e962015-04-28 23:21:51 -0700188 workerExecutor.shutdown();
Brian O'Connor520c0522014-11-23 23:50:47 -0800189 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700190 log.info("Stopped");
191 }
192
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800193 @Modified
194 public void modified(ComponentContext context) {
195 if (context == null) {
196 skipReleaseResourcesOnWithdrawal = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL;
197 logConfig("Default config");
198 return;
199 }
200
201 String s = Tools.get(context.getProperties(), "skipReleaseResourcesOnWithdrawal");
202 boolean newTestEnabled = isNullOrEmpty(s) ? skipReleaseResourcesOnWithdrawal : Boolean.parseBoolean(s.trim());
203 if (skipReleaseResourcesOnWithdrawal && !newTestEnabled) {
204 store.unsetDelegate(testOnlyDelegate);
205 store.setDelegate(delegate);
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800206 skipReleaseResourcesOnWithdrawal = false;
207 logConfig("Reconfigured skip release resources on withdrawal");
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800208 } else if (!skipReleaseResourcesOnWithdrawal && newTestEnabled) {
209 store.unsetDelegate(delegate);
210 store.setDelegate(testOnlyDelegate);
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800211 skipReleaseResourcesOnWithdrawal = true;
212 logConfig("Reconfigured skip release resources on withdrawal");
213 }
214
215 s = Tools.get(context.getProperties(), "numThreads");
216 int newNumThreads = isNullOrEmpty(s) ? numThreads : Integer.parseInt(s);
217 if (newNumThreads != numThreads) {
218 numThreads = newNumThreads;
219 ExecutorService oldWorkerExecutor = workerExecutor;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800220 workerExecutor = newFixedThreadPool(numThreads, groupedThreads("onos/intent", "worker-%d", log));
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800221 if (oldWorkerExecutor != null) {
222 oldWorkerExecutor.shutdown();
223 }
224 logConfig("Reconfigured number of worker threads");
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800225 }
226 }
227
228 private void logConfig(String prefix) {
229 log.info("{} with skipReleaseResourcesOnWithdrawal = {}", prefix, skipReleaseResourcesOnWithdrawal);
230 }
231
Brian O'Connor66630c82014-10-02 21:08:19 -0700232 @Override
233 public void submit(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900234 checkPermission(INTENT_WRITE);
Brian O'Connor66630c82014-10-02 21:08:19 -0700235 checkNotNull(intent, INTENT_NULL);
Brian O'Connorcff03322015-02-03 15:28:59 -0800236 IntentData data = new IntentData(intent, IntentState.INSTALL_REQ, null);
Brian O'Connorcff03322015-02-03 15:28:59 -0800237 store.addPending(data);
Brian O'Connor66630c82014-10-02 21:08:19 -0700238 }
239
240 @Override
241 public void withdraw(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900242 checkPermission(INTENT_WRITE);
Brian O'Connor66630c82014-10-02 21:08:19 -0700243 checkNotNull(intent, INTENT_NULL);
Brian O'Connorcff03322015-02-03 15:28:59 -0800244 IntentData data = new IntentData(intent, IntentState.WITHDRAW_REQ, null);
Brian O'Connorcff03322015-02-03 15:28:59 -0800245 store.addPending(data);
Brian O'Connor66630c82014-10-02 21:08:19 -0700246 }
247
Brian O'Connor66630c82014-10-02 21:08:19 -0700248 @Override
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700249 public void purge(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900250 checkPermission(INTENT_WRITE);
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700251 checkNotNull(intent, INTENT_NULL);
252 IntentData data = new IntentData(intent, IntentState.PURGE_REQ, null);
253 store.addPending(data);
helenyrwu2a674902016-07-20 09:48:04 -0700254
255 // remove associated group if there is one
256 if (intent instanceof PointToPointIntent) {
257 PointToPointIntent pointIntent = (PointToPointIntent) intent;
258 DeviceId deviceId = pointIntent.ingressPoint().deviceId();
259 GroupKey groupKey = PointToPointIntentCompiler.makeGroupKey(intent.id());
260 groupService.removeGroup(deviceId, groupKey,
261 intent.appId());
262 }
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700263 }
264
265 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800266 public Intent getIntent(Key key) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900267 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800268 return store.getIntent(key);
269 }
270
271 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700272 public Iterable<Intent> getIntents() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900273 checkPermission(INTENT_READ);
Brian O'Connor66630c82014-10-02 21:08:19 -0700274 return store.getIntents();
275 }
276
277 @Override
Brian O'Connor38224302016-08-02 22:03:01 -0700278 public void addPending(IntentData intentData) {
279 checkPermission(INTENT_WRITE);
280 checkNotNull(intentData, INTENT_NULL);
281 //TODO we might consider further checking / assertions
282 store.addPending(intentData);
283 }
284
285 @Override
Thomas Vachuskac46af202015-06-03 16:43:27 -0700286 public Iterable<IntentData> getIntentData() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900287 checkPermission(INTENT_READ);
Thomas Vachuskac46af202015-06-03 16:43:27 -0700288 return store.getIntentData(false, 0);
289 }
290
291 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700292 public long getIntentCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900293 checkPermission(INTENT_READ);
Brian O'Connor66630c82014-10-02 21:08:19 -0700294 return store.getIntentCount();
295 }
296
297 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800298 public IntentState getIntentState(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900299 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800300 checkNotNull(intentKey, INTENT_ID_NULL);
301 return store.getIntentState(intentKey);
Brian O'Connor66630c82014-10-02 21:08:19 -0700302 }
303
304 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800305 public List<Intent> getInstallableIntents(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900306 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800307 checkNotNull(intentKey, INTENT_ID_NULL);
308 return store.getInstallableIntents(intentKey);
Thomas Vachuska10d4abc2014-10-21 12:47:26 -0700309 }
310
311 @Override
Brian O'Connorbe28a872015-02-19 21:44:37 -0800312 public boolean isLocal(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900313 checkPermission(INTENT_READ);
Brian O'Connorbe28a872015-02-19 21:44:37 -0800314 return store.isMaster(intentKey);
315 }
316
317 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700318 public <T extends Intent> void registerCompiler(Class<T> cls, IntentCompiler<T> compiler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900319 checkPermission(INTENT_WRITE);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800320 compilerRegistry.registerCompiler(cls, compiler);
Brian O'Connor66630c82014-10-02 21:08:19 -0700321 }
322
323 @Override
324 public <T extends Intent> void unregisterCompiler(Class<T> cls) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900325 checkPermission(INTENT_WRITE);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800326 compilerRegistry.unregisterCompiler(cls);
Brian O'Connor66630c82014-10-02 21:08:19 -0700327 }
328
329 @Override
330 public Map<Class<? extends Intent>, IntentCompiler<? extends Intent>> getCompilers() {
Heedo Kang4a47a302016-02-29 17:40:23 +0900331 checkPermission(INTENT_READ);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800332 return compilerRegistry.getCompilers();
Brian O'Connor66630c82014-10-02 21:08:19 -0700333 }
334
335 @Override
Jonathan Hart34f1e382015-02-24 16:52:23 -0800336 public Iterable<Intent> getPending() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900337 checkPermission(INTENT_READ);
Jonathan Hart34f1e382015-02-24 16:52:23 -0800338 return store.getPending();
339 }
340
Brian O'Connor66630c82014-10-02 21:08:19 -0700341 // Store delegate to re-post events emitted from the store.
342 private class InternalStoreDelegate implements IntentStoreDelegate {
343 @Override
344 public void notify(IntentEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700345 post(event);
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800346 switch (event.type()) {
347 case WITHDRAWN:
Luca Pretede10c782017-01-05 17:23:08 -0800348 if (!skipReleaseResourcesOnWithdrawal) {
349 releaseResources(event.subject());
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800350 }
351 break;
352 default:
353 break;
354 }
Brian O'Connor66630c82014-10-02 21:08:19 -0700355 }
Brian O'Connorea4d7d12015-01-28 16:37:46 -0800356
357 @Override
Brian O'Connorcff03322015-02-03 15:28:59 -0800358 public void process(IntentData data) {
359 accumulator.add(data);
Brian O'Connorea4d7d12015-01-28 16:37:46 -0800360 }
Thomas Vachuskac46af202015-06-03 16:43:27 -0700361
362 @Override
363 public void onUpdate(IntentData intentData) {
364 trackerService.trackIntent(intentData);
365 }
Luca Pretede10c782017-01-05 17:23:08 -0800366
367 private void releaseResources(Intent intent) {
368 // If a resource group is set on the intent, the resource consumer is
369 // set equal to it. Otherwise it's set to the intent key
370 ResourceConsumer resourceConsumer =
371 intent.resourceGroup() != null ? intent.resourceGroup() : intent.key();
372
373 // By default the resource doesn't get released
374 boolean removeResource = false;
375
376 if (intent.resourceGroup() == null) {
377 // If the intent doesn't have a resource group, it means the
378 // resource was registered using the intent key, so it can be
379 // released
380 removeResource = true;
381 } else {
382 // When a resource group is set, we make sure there are no other
383 // intents using the same resource group, before deleting the
384 // related resources.
385 Long remainingIntents =
386 Tools.stream(store.getIntents())
387 .filter(i -> i.resourceGroup().equals(intent.resourceGroup()))
388 .count();
389 if (remainingIntents == 0) {
390 removeResource = true;
391 }
392 }
393
394 if (removeResource) {
395 // Release resources allocated to withdrawn intent
396 if (!resourceService.release(resourceConsumer)) {
397 log.error("Failed to release resources allocated to {}", resourceConsumer);
398 }
399 }
400 }
Brian O'Connor66630c82014-10-02 21:08:19 -0700401 }
402
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800403 // Store delegate enabled only when performing intent throughput tests
404 private class TestOnlyIntentStoreDelegate implements IntentStoreDelegate {
405 @Override
406 public void process(IntentData data) {
407 accumulator.add(data);
408 }
409
410 @Override
411 public void onUpdate(IntentData data) {
412 trackerService.trackIntent(data);
413 }
414
415 @Override
416 public void notify(IntentEvent event) {
417 post(event);
418 }
419 }
420
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800421 private void buildAndSubmitBatches(Iterable<Key> intentKeys,
Brian O'Connor72a034c2014-11-26 18:24:23 -0800422 boolean compileAllFailed) {
Brian O'Connor72a034c2014-11-26 18:24:23 -0800423 // Attempt recompilation of the specified intents first.
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800424 for (Key key : intentKeys) {
425 Intent intent = store.getIntent(key);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800426 if (intent == null) {
427 continue;
428 }
Brian O'Connor03406a42015-02-03 17:28:57 -0800429 submit(intent);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800430 }
431
Jonathan Hart0cca3e82015-09-23 17:54:11 -0700432 if (compileAllFailed) {
433 // If required, compile all currently failed intents.
434 for (Intent intent : getIntents()) {
435 IntentState state = getIntentState(intent.key());
436 if (RECOMPILE.contains(state) || intentAllowsPartialFailure(intent)) {
437 if (WITHDRAW.contains(state)) {
438 withdraw(intent);
439 } else {
440 submit(intent);
441 }
Brian O'Connor72a034c2014-11-26 18:24:23 -0800442 }
443 }
444 }
Brian O'Connor72a034c2014-11-26 18:24:23 -0800445 }
446
tom95329eb2014-10-06 08:40:06 -0700447 // Topology change delegate
448 private class InternalTopoChangeDelegate implements TopologyChangeDelegate {
449 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800450 public void triggerCompile(Iterable<Key> intentKeys,
tom85258ee2014-10-07 00:10:02 -0700451 boolean compileAllFailed) {
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800452 buildAndSubmitBatches(intentKeys, compileAllFailed);
tom95329eb2014-10-06 08:40:06 -0700453 }
tom95329eb2014-10-06 08:40:06 -0700454 }
tom85258ee2014-10-07 00:10:02 -0700455
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700456 private class InternalBatchDelegate implements IntentBatchDelegate {
457 @Override
Brian O'Connorb499b352015-02-03 16:46:15 -0800458 public void execute(Collection<IntentData> operations) {
Brian O'Connorab8ef822015-02-17 18:08:54 -0800459 log.debug("Execute {} operation(s).", operations.size());
460 log.trace("Execute operations: {}", operations);
Sho SHIMIZU94b03b12015-04-10 14:53:13 -0700461
462 // batchExecutor is single-threaded, so only one batch is in flight at a time
Sho SHIMIZU489aa9b2016-01-14 17:19:32 -0800463 CompletableFuture.runAsync(() -> {
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800464 // process intent until the phase reaches one of the final phases
465 List<CompletableFuture<IntentData>> futures = operations.stream()
466 .map(x -> CompletableFuture.completedFuture(x)
467 .thenApply(IntentManager.this::createInitialPhase)
Sho SHIMIZU4a141852016-01-14 18:55:40 -0800468 .thenApplyAsync(IntentProcessPhase::process, workerExecutor)
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800469 .thenApply(FinalIntentProcessPhase::data)
470 .exceptionally(e -> {
Pier Luigi13b287f2017-01-10 15:07:52 -0800471 // When the future fails, we update the Intent to simulate the failure of
472 // the installation/withdrawal phase and we save in the current map. In
473 // the next round the CleanUp Thread will pick this Intent again.
474 log.warn("Future failed", e);
475 log.warn("Intent {} - state {} - request {}",
476 x.key(), x.state(), x.request());
477 switch (x.state()) {
478 case INSTALL_REQ:
479 case INSTALLING:
480 case WITHDRAW_REQ:
481 case WITHDRAWING:
482 x.setState(FAILED);
483 IntentData current = store.getIntentData(x.key());
484 return new IntentData(x, current.installables());
485 default:
486 return null;
487 }
Brian O'Connorc590ebb2016-12-08 18:16:41 -0800488 }))
489 .collect(Collectors.toList());
Sho SHIMIZU62bbc602016-01-13 16:54:35 -0800490
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800491 // write multiple data to store in order
492 store.batchWrite(Tools.allOf(futures).join().stream()
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800493 .filter(Objects::nonNull)
494 .collect(Collectors.toList()));
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800495 }, batchExecutor).exceptionally(e -> {
496 log.error("Error submitting batches:", e);
497 // FIXME incomplete Intents should be cleaned up
498 // (transition to FAILED, etc.)
499
500 // the batch has failed
501 // TODO: maybe we should do more?
502 log.error("Walk the plank, matey...");
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800503 return null;
504 }).thenRun(accumulator::ready);
505
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700506 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700507 }
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800508
Sho SHIMIZUc88b85e2016-01-14 18:45:14 -0800509 private IntentProcessPhase createInitialPhase(IntentData data) {
Brian O'Connorc590ebb2016-12-08 18:16:41 -0800510 IntentData pending = store.getPendingData(data.key());
511 if (pending == null || pending.version().isNewerThan(data.version())) {
512 /*
513 If the pending map is null, then this intent was compiled by a
514 previous batch iteration, so we can skip it.
515 If the pending map has a newer request, it will get compiled as
516 part of the next batch, so we can skip it.
517 */
518 return Skipped.getPhase();
519 }
Sho SHIMIZUc88b85e2016-01-14 18:45:14 -0800520 IntentData current = store.getIntentData(data.key());
521 return newInitialPhase(processor, data, current);
522 }
523
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800524 private class InternalIntentProcessor implements IntentProcessor {
525 @Override
526 public List<Intent> compile(Intent intent, List<Intent> previousInstallables) {
527 return compilerRegistry.compile(intent, previousInstallables);
528 }
529
530 @Override
Brian O'Connorf0c5a052015-04-27 00:34:53 -0700531 public void apply(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) {
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800532 intentInstaller.apply(toUninstall, toInstall);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800533 }
Ray Milkeyfd7931d2015-03-30 13:58:38 -0700534 }
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800535
Brian O'Connor66630c82014-10-02 21:08:19 -0700536}