blob: 6f2ed1329725af041257845609ffda3a3ceafc74 [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;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -080054import org.osgi.service.component.ComponentContext;
Sho SHIMIZUe18cb122016-02-22 21:04:56 -080055import org.onosproject.net.resource.ResourceService;
Brian O'Connor66630c82014-10-02 21:08:19 -070056import org.slf4j.Logger;
57
Brian O'Connorf0c5a052015-04-27 00:34:53 -070058import java.util.Collection;
59import java.util.EnumSet;
60import java.util.List;
61import java.util.Map;
Sho SHIMIZUab541a52016-01-13 23:29:32 -080062import java.util.Objects;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070063import java.util.Optional;
Sho SHIMIZUad8ab272016-01-13 22:08:58 -080064import java.util.concurrent.CompletableFuture;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070065import java.util.concurrent.ExecutorService;
Brian O'Connorf0c5a052015-04-27 00:34:53 -070066import java.util.stream.Collectors;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070067
Brian O'Connorfa81eae2014-10-30 13:20:05 -070068import static com.google.common.base.Preconditions.checkNotNull;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -080069import static com.google.common.base.Strings.isNullOrEmpty;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080070import static java.util.concurrent.Executors.newFixedThreadPool;
Brian O'Connordb15b042015-02-04 14:59:28 -080071import static java.util.concurrent.Executors.newSingleThreadExecutor;
Brian O'Connorbdc7f002015-02-18 20:49:41 -080072import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -080073import static org.onosproject.net.intent.IntentState.*;
Jonathan Hart96c5a4a2015-07-31 14:23:33 -070074import static org.onosproject.net.intent.constraint.PartialFailureConstraint.intentAllowsPartialFailure;
Sho SHIMIZUce49b602015-02-23 19:15:49 -080075import static org.onosproject.net.intent.impl.phase.IntentProcessPhase.newInitialPhase;
Changhoon Yoon541ef712015-05-23 17:18:34 +090076import static org.onosproject.security.AppGuard.checkPermission;
Sho SHIMIZU98c0a392016-01-14 18:40:53 -080077import static org.onosproject.security.AppPermission.Type.INTENT_READ;
78import static org.onosproject.security.AppPermission.Type.INTENT_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070079import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090080
Brian O'Connor66630c82014-10-02 21:08:19 -070081/**
Brian O'Connorce2d8b52015-07-29 16:24:13 -070082 * An implementation of intent service.
Brian O'Connor66630c82014-10-02 21:08:19 -070083 */
84@Component(immediate = true)
85@Service
86public class IntentManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070087 extends AbstractListenerManager<IntentEvent, IntentListener>
Brian O'Connor66630c82014-10-02 21:08:19 -070088 implements IntentService, IntentExtensionService {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070089
Sho SHIMIZU8b5051d2014-11-05 11:24:13 -080090 private static final Logger log = getLogger(IntentManager.class);
Brian O'Connor66630c82014-10-02 21:08:19 -070091
Sho SHIMIZU17c09da2016-03-31 12:54:17 -070092 private static final String INTENT_NULL = "Intent cannot be null";
93 private static final String INTENT_ID_NULL = "Intent key cannot be null";
Brian O'Connor66630c82014-10-02 21:08:19 -070094
Brian O'Connor7a71d5d2014-12-02 00:12:27 -080095 private static final EnumSet<IntentState> RECOMPILE
96 = EnumSet.of(INSTALL_REQ, FAILED, WITHDRAW_REQ);
Jonathan Hart96c5a4a2015-07-31 14:23:33 -070097 private static final EnumSet<IntentState> WITHDRAW
98 = EnumSet.of(WITHDRAW_REQ, WITHDRAWING, WITHDRAWN);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -080099
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800100 private static final boolean DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL = false;
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800101 @Property(name = "skipReleaseResourcesOnWithdrawal",
102 boolValue = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL,
103 label = "Indicates whether skipping resource releases on withdrawal is enabled or not")
104 private boolean skipReleaseResourcesOnWithdrawal = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL;
Brian O'Connor7a71d5d2014-12-02 00:12:27 -0800105
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800106 private static final int DEFAULT_NUM_THREADS = 12;
107 @Property(name = "numThreads",
108 intValue = DEFAULT_NUM_THREADS,
109 label = "Number of worker threads")
110 private int numThreads = DEFAULT_NUM_THREADS;
111
Brian O'Connor520c0522014-11-23 23:50:47 -0800112 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
113 protected CoreService coreService;
Brian O'Connor66630c82014-10-02 21:08:19 -0700114
115 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
116 protected IntentStore store;
117
118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tom85258ee2014-10-07 00:10:02 -0700119 protected ObjectiveTrackerService trackerService;
tom95329eb2014-10-06 08:40:06 -0700120
121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sho SHIMIZU214ac322015-02-23 19:30:15 -0800122 protected FlowRuleService flowRuleService;
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700123
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800125 protected FlowObjectiveService flowObjectiveService;
126
127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800128 protected ResourceService resourceService;
129
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected ComponentConfigService configService;
132
helenyrwu2a674902016-07-20 09:48:04 -0700133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
134 protected GroupService groupService;
135
Andreas Papazois05548962016-11-23 11:36:55 +0200136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 private NetworkConfigService networkConfigService;
138
139
Brian O'Connordb15b042015-02-04 14:59:28 -0800140 private ExecutorService batchExecutor;
141 private ExecutorService workerExecutor;
Brian O'Connor520c0522014-11-23 23:50:47 -0800142
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800143 private final IntentInstaller intentInstaller = new IntentInstaller();
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800144 private final CompilerRegistry compilerRegistry = new CompilerRegistry();
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800145 private final InternalIntentProcessor processor = new InternalIntentProcessor();
Brian O'Connor520c0522014-11-23 23:50:47 -0800146 private final IntentStoreDelegate delegate = new InternalStoreDelegate();
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800147 private final IntentStoreDelegate testOnlyDelegate = new TestOnlyIntentStoreDelegate();
Brian O'Connor520c0522014-11-23 23:50:47 -0800148 private final TopologyChangeDelegate topoDelegate = new InternalTopoChangeDelegate();
149 private final IntentBatchDelegate batchDelegate = new InternalBatchDelegate();
150 private IdGenerator idGenerator;
151
Brian O'Connorb499b352015-02-03 16:46:15 -0800152 private final IntentAccumulator accumulator = new IntentAccumulator(batchDelegate);
Brian O'Connorcff03322015-02-03 15:28:59 -0800153
Brian O'Connor66630c82014-10-02 21:08:19 -0700154 @Activate
155 public void activate() {
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800156 configService.registerProperties(getClass());
157
Andreas Papazois05548962016-11-23 11:36:55 +0200158 intentInstaller.init(store, trackerService, flowRuleService, flowObjectiveService,
159 networkConfigService);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800160 if (skipReleaseResourcesOnWithdrawal) {
161 store.setDelegate(testOnlyDelegate);
162 } else {
163 store.setDelegate(delegate);
164 }
tom95329eb2014-10-06 08:40:06 -0700165 trackerService.setDelegate(topoDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700166 eventDispatcher.addSink(IntentEvent.class, listenerRegistry);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700167 batchExecutor = newSingleThreadExecutor(groupedThreads("onos/intent", "batch", log));
168 workerExecutor = newFixedThreadPool(numThreads, groupedThreads("onos/intent", "worker-%d", log));
Brian O'Connor520c0522014-11-23 23:50:47 -0800169 idGenerator = coreService.getIdGenerator("intent-ids");
Thomas Vachuska23235962017-02-03 11:44:15 -0800170 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor520c0522014-11-23 23:50:47 -0800171 Intent.bindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700172 log.info("Started");
173 }
174
175 @Deactivate
176 public void deactivate() {
Andreas Papazois05548962016-11-23 11:36:55 +0200177 intentInstaller.init(null, null, null, null, null);
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800178 if (skipReleaseResourcesOnWithdrawal) {
179 store.unsetDelegate(testOnlyDelegate);
180 } else {
181 store.unsetDelegate(delegate);
182 }
Sho SHIMIZUd5bf1062016-02-25 10:26:02 -0800183 configService.unregisterProperties(getClass(), false);
tom95329eb2014-10-06 08:40:06 -0700184 trackerService.unsetDelegate(topoDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700185 eventDispatcher.removeSink(IntentEvent.class);
Brian O'Connordb15b042015-02-04 14:59:28 -0800186 batchExecutor.shutdown();
Brian O'Connor3c58e962015-04-28 23:21:51 -0700187 workerExecutor.shutdown();
Brian O'Connor520c0522014-11-23 23:50:47 -0800188 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700189 log.info("Stopped");
190 }
191
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800192 @Modified
193 public void modified(ComponentContext context) {
194 if (context == null) {
195 skipReleaseResourcesOnWithdrawal = DEFAULT_SKIP_RELEASE_RESOURCES_ON_WITHDRAWAL;
196 logConfig("Default config");
197 return;
198 }
199
200 String s = Tools.get(context.getProperties(), "skipReleaseResourcesOnWithdrawal");
201 boolean newTestEnabled = isNullOrEmpty(s) ? skipReleaseResourcesOnWithdrawal : Boolean.parseBoolean(s.trim());
202 if (skipReleaseResourcesOnWithdrawal && !newTestEnabled) {
203 store.unsetDelegate(testOnlyDelegate);
204 store.setDelegate(delegate);
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800205 skipReleaseResourcesOnWithdrawal = false;
206 logConfig("Reconfigured skip release resources on withdrawal");
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800207 } else if (!skipReleaseResourcesOnWithdrawal && newTestEnabled) {
208 store.unsetDelegate(delegate);
209 store.setDelegate(testOnlyDelegate);
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800210 skipReleaseResourcesOnWithdrawal = true;
211 logConfig("Reconfigured skip release resources on withdrawal");
212 }
213
214 s = Tools.get(context.getProperties(), "numThreads");
215 int newNumThreads = isNullOrEmpty(s) ? numThreads : Integer.parseInt(s);
216 if (newNumThreads != numThreads) {
217 numThreads = newNumThreads;
218 ExecutorService oldWorkerExecutor = workerExecutor;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800219 workerExecutor = newFixedThreadPool(numThreads, groupedThreads("onos/intent", "worker-%d", log));
Thomas Vachuskabdbdd242016-03-01 01:55:55 -0800220 if (oldWorkerExecutor != null) {
221 oldWorkerExecutor.shutdown();
222 }
223 logConfig("Reconfigured number of worker threads");
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800224 }
225 }
226
227 private void logConfig(String prefix) {
228 log.info("{} with skipReleaseResourcesOnWithdrawal = {}", prefix, skipReleaseResourcesOnWithdrawal);
229 }
230
Brian O'Connor66630c82014-10-02 21:08:19 -0700231 @Override
232 public void submit(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900233 checkPermission(INTENT_WRITE);
Brian O'Connor66630c82014-10-02 21:08:19 -0700234 checkNotNull(intent, INTENT_NULL);
Brian O'Connorcff03322015-02-03 15:28:59 -0800235 IntentData data = new IntentData(intent, IntentState.INSTALL_REQ, null);
Brian O'Connorcff03322015-02-03 15:28:59 -0800236 store.addPending(data);
Brian O'Connor66630c82014-10-02 21:08:19 -0700237 }
238
239 @Override
240 public void withdraw(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900241 checkPermission(INTENT_WRITE);
Brian O'Connor66630c82014-10-02 21:08:19 -0700242 checkNotNull(intent, INTENT_NULL);
Brian O'Connorcff03322015-02-03 15:28:59 -0800243 IntentData data = new IntentData(intent, IntentState.WITHDRAW_REQ, null);
Brian O'Connorcff03322015-02-03 15:28:59 -0800244 store.addPending(data);
Brian O'Connor66630c82014-10-02 21:08:19 -0700245 }
246
Brian O'Connor66630c82014-10-02 21:08:19 -0700247 @Override
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700248 public void purge(Intent intent) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900249 checkPermission(INTENT_WRITE);
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700250 checkNotNull(intent, INTENT_NULL);
251 IntentData data = new IntentData(intent, IntentState.PURGE_REQ, null);
252 store.addPending(data);
helenyrwu2a674902016-07-20 09:48:04 -0700253
254 // remove associated group if there is one
255 if (intent instanceof PointToPointIntent) {
256 PointToPointIntent pointIntent = (PointToPointIntent) intent;
257 DeviceId deviceId = pointIntent.ingressPoint().deviceId();
258 GroupKey groupKey = PointToPointIntentCompiler.makeGroupKey(intent.id());
259 groupService.removeGroup(deviceId, groupKey,
260 intent.appId());
261 }
Ray Milkey8c6d00e2015-03-13 14:14:34 -0700262 }
263
264 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800265 public Intent getIntent(Key key) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900266 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800267 return store.getIntent(key);
268 }
269
270 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700271 public Iterable<Intent> getIntents() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900272 checkPermission(INTENT_READ);
Brian O'Connor66630c82014-10-02 21:08:19 -0700273 return store.getIntents();
274 }
275
276 @Override
Brian O'Connor38224302016-08-02 22:03:01 -0700277 public void addPending(IntentData intentData) {
278 checkPermission(INTENT_WRITE);
279 checkNotNull(intentData, INTENT_NULL);
280 //TODO we might consider further checking / assertions
281 store.addPending(intentData);
282 }
283
284 @Override
Thomas Vachuskac46af202015-06-03 16:43:27 -0700285 public Iterable<IntentData> getIntentData() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900286 checkPermission(INTENT_READ);
Thomas Vachuskac46af202015-06-03 16:43:27 -0700287 return store.getIntentData(false, 0);
288 }
289
290 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700291 public long getIntentCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900292 checkPermission(INTENT_READ);
Brian O'Connor66630c82014-10-02 21:08:19 -0700293 return store.getIntentCount();
294 }
295
296 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800297 public IntentState getIntentState(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900298 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800299 checkNotNull(intentKey, INTENT_ID_NULL);
300 return store.getIntentState(intentKey);
Brian O'Connor66630c82014-10-02 21:08:19 -0700301 }
302
303 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800304 public List<Intent> getInstallableIntents(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900305 checkPermission(INTENT_READ);
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800306 checkNotNull(intentKey, INTENT_ID_NULL);
307 return store.getInstallableIntents(intentKey);
Thomas Vachuska10d4abc2014-10-21 12:47:26 -0700308 }
309
310 @Override
Brian O'Connorbe28a872015-02-19 21:44:37 -0800311 public boolean isLocal(Key intentKey) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900312 checkPermission(INTENT_READ);
Brian O'Connorbe28a872015-02-19 21:44:37 -0800313 return store.isMaster(intentKey);
314 }
315
316 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700317 public <T extends Intent> void registerCompiler(Class<T> cls, IntentCompiler<T> compiler) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900318 checkPermission(INTENT_WRITE);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800319 compilerRegistry.registerCompiler(cls, compiler);
Brian O'Connor66630c82014-10-02 21:08:19 -0700320 }
321
322 @Override
323 public <T extends Intent> void unregisterCompiler(Class<T> cls) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900324 checkPermission(INTENT_WRITE);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800325 compilerRegistry.unregisterCompiler(cls);
Brian O'Connor66630c82014-10-02 21:08:19 -0700326 }
327
328 @Override
329 public Map<Class<? extends Intent>, IntentCompiler<? extends Intent>> getCompilers() {
Heedo Kang4a47a302016-02-29 17:40:23 +0900330 checkPermission(INTENT_READ);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800331 return compilerRegistry.getCompilers();
Brian O'Connor66630c82014-10-02 21:08:19 -0700332 }
333
334 @Override
Jonathan Hart34f1e382015-02-24 16:52:23 -0800335 public Iterable<Intent> getPending() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900336 checkPermission(INTENT_READ);
Jonathan Hart34f1e382015-02-24 16:52:23 -0800337 return store.getPending();
338 }
339
Brian O'Connor66630c82014-10-02 21:08:19 -0700340 // Store delegate to re-post events emitted from the store.
341 private class InternalStoreDelegate implements IntentStoreDelegate {
342 @Override
343 public void notify(IntentEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700344 post(event);
Naoki Shiotabbc7ead2016-01-20 14:10:38 -0800345 switch (event.type()) {
346 case WITHDRAWN:
347 // release resources allocated to withdrawn intent
348 if (!resourceService.release(event.subject().id())) {
349 log.error("Failed to release resources allocated to {}", event.subject().id());
350 }
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 }
Brian O'Connor66630c82014-10-02 21:08:19 -0700366 }
367
Sho SHIMIZU4cee50f2016-02-23 16:24:42 -0800368 // Store delegate enabled only when performing intent throughput tests
369 private class TestOnlyIntentStoreDelegate implements IntentStoreDelegate {
370 @Override
371 public void process(IntentData data) {
372 accumulator.add(data);
373 }
374
375 @Override
376 public void onUpdate(IntentData data) {
377 trackerService.trackIntent(data);
378 }
379
380 @Override
381 public void notify(IntentEvent event) {
382 post(event);
383 }
384 }
385
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800386 private void buildAndSubmitBatches(Iterable<Key> intentKeys,
Brian O'Connor72a034c2014-11-26 18:24:23 -0800387 boolean compileAllFailed) {
Brian O'Connor72a034c2014-11-26 18:24:23 -0800388 // Attempt recompilation of the specified intents first.
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800389 for (Key key : intentKeys) {
390 Intent intent = store.getIntent(key);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800391 if (intent == null) {
392 continue;
393 }
Brian O'Connor03406a42015-02-03 17:28:57 -0800394 submit(intent);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800395 }
396
Jonathan Hart0cca3e82015-09-23 17:54:11 -0700397 if (compileAllFailed) {
398 // If required, compile all currently failed intents.
399 for (Intent intent : getIntents()) {
400 IntentState state = getIntentState(intent.key());
401 if (RECOMPILE.contains(state) || intentAllowsPartialFailure(intent)) {
402 if (WITHDRAW.contains(state)) {
403 withdraw(intent);
404 } else {
405 submit(intent);
406 }
Brian O'Connor72a034c2014-11-26 18:24:23 -0800407 }
408 }
409 }
Brian O'Connor72a034c2014-11-26 18:24:23 -0800410 }
411
tom95329eb2014-10-06 08:40:06 -0700412 // Topology change delegate
413 private class InternalTopoChangeDelegate implements TopologyChangeDelegate {
414 @Override
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800415 public void triggerCompile(Iterable<Key> intentKeys,
tom85258ee2014-10-07 00:10:02 -0700416 boolean compileAllFailed) {
Ray Milkeyf9af43c2015-02-09 16:45:48 -0800417 buildAndSubmitBatches(intentKeys, compileAllFailed);
tom95329eb2014-10-06 08:40:06 -0700418 }
tom95329eb2014-10-06 08:40:06 -0700419 }
tom85258ee2014-10-07 00:10:02 -0700420
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700421 private class InternalBatchDelegate implements IntentBatchDelegate {
422 @Override
Brian O'Connorb499b352015-02-03 16:46:15 -0800423 public void execute(Collection<IntentData> operations) {
Brian O'Connorab8ef822015-02-17 18:08:54 -0800424 log.debug("Execute {} operation(s).", operations.size());
425 log.trace("Execute operations: {}", operations);
Sho SHIMIZU94b03b12015-04-10 14:53:13 -0700426
427 // batchExecutor is single-threaded, so only one batch is in flight at a time
Sho SHIMIZU489aa9b2016-01-14 17:19:32 -0800428 CompletableFuture.runAsync(() -> {
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800429 // process intent until the phase reaches one of the final phases
430 List<CompletableFuture<IntentData>> futures = operations.stream()
431 .map(x -> CompletableFuture.completedFuture(x)
432 .thenApply(IntentManager.this::createInitialPhase)
Sho SHIMIZU4a141852016-01-14 18:55:40 -0800433 .thenApplyAsync(IntentProcessPhase::process, workerExecutor)
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800434 .thenApply(FinalIntentProcessPhase::data)
435 .exceptionally(e -> {
Pier Luigi13b287f2017-01-10 15:07:52 -0800436 // When the future fails, we update the Intent to simulate the failure of
437 // the installation/withdrawal phase and we save in the current map. In
438 // the next round the CleanUp Thread will pick this Intent again.
439 log.warn("Future failed", e);
440 log.warn("Intent {} - state {} - request {}",
441 x.key(), x.state(), x.request());
442 switch (x.state()) {
443 case INSTALL_REQ:
444 case INSTALLING:
445 case WITHDRAW_REQ:
446 case WITHDRAWING:
447 x.setState(FAILED);
448 IntentData current = store.getIntentData(x.key());
449 return new IntentData(x, current.installables());
450 default:
451 return null;
452 }
Brian O'Connorc590ebb2016-12-08 18:16:41 -0800453 }))
454 .collect(Collectors.toList());
Sho SHIMIZU62bbc602016-01-13 16:54:35 -0800455
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800456 // write multiple data to store in order
457 store.batchWrite(Tools.allOf(futures).join().stream()
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800458 .filter(Objects::nonNull)
459 .collect(Collectors.toList()));
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800460 }, batchExecutor).exceptionally(e -> {
461 log.error("Error submitting batches:", e);
462 // FIXME incomplete Intents should be cleaned up
463 // (transition to FAILED, etc.)
464
465 // the batch has failed
466 // TODO: maybe we should do more?
467 log.error("Walk the plank, matey...");
Sho SHIMIZU8f2b7772016-01-14 18:17:44 -0800468 return null;
469 }).thenRun(accumulator::ready);
470
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700471 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700472 }
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800473
Sho SHIMIZUc88b85e2016-01-14 18:45:14 -0800474 private IntentProcessPhase createInitialPhase(IntentData data) {
Brian O'Connorc590ebb2016-12-08 18:16:41 -0800475 IntentData pending = store.getPendingData(data.key());
476 if (pending == null || pending.version().isNewerThan(data.version())) {
477 /*
478 If the pending map is null, then this intent was compiled by a
479 previous batch iteration, so we can skip it.
480 If the pending map has a newer request, it will get compiled as
481 part of the next batch, so we can skip it.
482 */
483 return Skipped.getPhase();
484 }
Sho SHIMIZUc88b85e2016-01-14 18:45:14 -0800485 IntentData current = store.getIntentData(data.key());
486 return newInitialPhase(processor, data, current);
487 }
488
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800489 private class InternalIntentProcessor implements IntentProcessor {
490 @Override
491 public List<Intent> compile(Intent intent, List<Intent> previousInstallables) {
492 return compilerRegistry.compile(intent, previousInstallables);
493 }
494
495 @Override
Brian O'Connorf0c5a052015-04-27 00:34:53 -0700496 public void apply(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) {
Thomas Vachuskaf6ec97b2016-02-22 10:59:23 -0800497 intentInstaller.apply(toUninstall, toInstall);
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800498 }
Ray Milkeyfd7931d2015-03-30 13:58:38 -0700499 }
Sho SHIMIZUb0a47d42015-02-19 13:26:30 -0800500
Brian O'Connor66630c82014-10-02 21:08:19 -0700501}