blob: d8c2dcd512d3da96521b492f4778597f27ffcfe1 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connor66630c82014-10-02 21:08:19 -070016package org.onlab.onos.net.intent.impl;
17
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080018import com.google.common.collect.ImmutableList;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Lists;
21import com.google.common.collect.Maps;
Brian O'Connor66630c82014-10-02 21:08:19 -070022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
25import org.apache.felix.scr.annotations.Reference;
26import org.apache.felix.scr.annotations.ReferenceCardinality;
27import org.apache.felix.scr.annotations.Service;
Brian O'Connor72a034c2014-11-26 18:24:23 -080028import org.onlab.onos.core.ApplicationId;
Brian O'Connor520c0522014-11-23 23:50:47 -080029import org.onlab.onos.core.CoreService;
30import org.onlab.onos.core.IdGenerator;
Brian O'Connor66630c82014-10-02 21:08:19 -070031import org.onlab.onos.event.AbstractListenerRegistry;
32import org.onlab.onos.event.EventDeliveryService;
Brian O'Connorcb900f42014-10-07 21:55:33 -070033import org.onlab.onos.net.flow.CompletedBatchOperation;
Brian O'Connorf2dbde52014-10-10 16:20:24 -070034import org.onlab.onos.net.flow.FlowRuleBatchOperation;
35import org.onlab.onos.net.flow.FlowRuleService;
Brian O'Connor66630c82014-10-02 21:08:19 -070036import org.onlab.onos.net.intent.Intent;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070037import org.onlab.onos.net.intent.IntentBatchDelegate;
38import org.onlab.onos.net.intent.IntentBatchService;
Brian O'Connor66630c82014-10-02 21:08:19 -070039import org.onlab.onos.net.intent.IntentCompiler;
40import org.onlab.onos.net.intent.IntentEvent;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080041import org.onlab.onos.net.intent.IntentEvent.Type;
Brian O'Connor66630c82014-10-02 21:08:19 -070042import org.onlab.onos.net.intent.IntentException;
43import org.onlab.onos.net.intent.IntentExtensionService;
44import org.onlab.onos.net.intent.IntentId;
45import org.onlab.onos.net.intent.IntentInstaller;
46import org.onlab.onos.net.intent.IntentListener;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070047import org.onlab.onos.net.intent.IntentOperation;
Brian O'Connor66630c82014-10-02 21:08:19 -070048import org.onlab.onos.net.intent.IntentOperations;
49import org.onlab.onos.net.intent.IntentService;
50import org.onlab.onos.net.intent.IntentState;
51import org.onlab.onos.net.intent.IntentStore;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080052import org.onlab.onos.net.intent.IntentStore.BatchWrite;
Brian O'Connor66630c82014-10-02 21:08:19 -070053import org.onlab.onos.net.intent.IntentStoreDelegate;
54import org.slf4j.Logger;
55
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080056import java.util.ArrayList;
57import java.util.Collections;
58import java.util.EnumSet;
59import java.util.List;
60import java.util.Map;
61import java.util.concurrent.ConcurrentHashMap;
62import java.util.concurrent.ConcurrentMap;
63import java.util.concurrent.ExecutionException;
64import java.util.concurrent.ExecutorService;
65import java.util.concurrent.Future;
66import java.util.concurrent.TimeUnit;
67import java.util.concurrent.TimeoutException;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070068
69import static com.google.common.base.Preconditions.checkArgument;
70import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080071import static java.util.concurrent.Executors.newFixedThreadPool;
72import static org.onlab.onos.net.intent.IntentState.*;
Brian O'Connorfa81eae2014-10-30 13:20:05 -070073import static org.onlab.util.Tools.namedThreads;
74import static org.slf4j.LoggerFactory.getLogger;
Brian O'Connor66630c82014-10-02 21:08:19 -070075
76/**
77 * An implementation of Intent Manager.
78 */
79@Component(immediate = true)
80@Service
81public class IntentManager
82 implements IntentService, IntentExtensionService {
Sho SHIMIZU8b5051d2014-11-05 11:24:13 -080083 private static final Logger log = getLogger(IntentManager.class);
Brian O'Connor66630c82014-10-02 21:08:19 -070084
85 public static final String INTENT_NULL = "Intent cannot be null";
86 public static final String INTENT_ID_NULL = "Intent ID cannot be null";
87
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -080088 private static final int NUM_THREADS = 12;
89
Brian O'Connor66630c82014-10-02 21:08:19 -070090 // Collections for compiler, installer, and listener are ONOS instance local
91 private final ConcurrentMap<Class<? extends Intent>,
92 IntentCompiler<? extends Intent>> compilers = new ConcurrentHashMap<>();
Thomas Vachuskab97cf282014-10-20 23:31:12 -070093 private final ConcurrentMap<Class<? extends Intent>,
94 IntentInstaller<? extends Intent>> installers = new ConcurrentHashMap<>();
Brian O'Connor66630c82014-10-02 21:08:19 -070095
96 private final AbstractListenerRegistry<IntentEvent, IntentListener>
tom95329eb2014-10-06 08:40:06 -070097 listenerRegistry = new AbstractListenerRegistry<>();
Brian O'Connor66630c82014-10-02 21:08:19 -070098
Brian O'Connor520c0522014-11-23 23:50:47 -080099 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
100 protected CoreService coreService;
Brian O'Connor66630c82014-10-02 21:08:19 -0700101
102 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
103 protected IntentStore store;
104
105 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700106 protected IntentBatchService batchService;
107
108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tom85258ee2014-10-07 00:10:02 -0700109 protected ObjectiveTrackerService trackerService;
tom95329eb2014-10-06 08:40:06 -0700110
111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Brian O'Connor66630c82014-10-02 21:08:19 -0700112 protected EventDeliveryService eventDispatcher;
113
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 protected FlowRuleService flowRuleService;
116
Brian O'Connor520c0522014-11-23 23:50:47 -0800117
118 private ExecutorService executor;
Brian O'Connor520c0522014-11-23 23:50:47 -0800119
120 private final IntentStoreDelegate delegate = new InternalStoreDelegate();
121 private final TopologyChangeDelegate topoDelegate = new InternalTopoChangeDelegate();
122 private final IntentBatchDelegate batchDelegate = new InternalBatchDelegate();
123 private IdGenerator idGenerator;
124
Brian O'Connor66630c82014-10-02 21:08:19 -0700125 @Activate
126 public void activate() {
127 store.setDelegate(delegate);
tom95329eb2014-10-06 08:40:06 -0700128 trackerService.setDelegate(topoDelegate);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700129 batchService.setDelegate(batchDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700130 eventDispatcher.addSink(IntentEvent.class, listenerRegistry);
alshabiba9819bf2014-11-30 18:15:52 -0800131 executor = newFixedThreadPool(NUM_THREADS, namedThreads("onos-intent"));
Brian O'Connor520c0522014-11-23 23:50:47 -0800132 idGenerator = coreService.getIdGenerator("intent-ids");
133 Intent.bindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700134 log.info("Started");
135 }
136
137 @Deactivate
138 public void deactivate() {
139 store.unsetDelegate(delegate);
tom95329eb2014-10-06 08:40:06 -0700140 trackerService.unsetDelegate(topoDelegate);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700141 batchService.unsetDelegate(batchDelegate);
Brian O'Connor66630c82014-10-02 21:08:19 -0700142 eventDispatcher.removeSink(IntentEvent.class);
Brian O'Connorcb900f42014-10-07 21:55:33 -0700143 executor.shutdown();
Brian O'Connor520c0522014-11-23 23:50:47 -0800144 Intent.unbindIdGenerator(idGenerator);
Brian O'Connor66630c82014-10-02 21:08:19 -0700145 log.info("Stopped");
146 }
147
148 @Override
149 public void submit(Intent intent) {
150 checkNotNull(intent, INTENT_NULL);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800151 execute(IntentOperations.builder(intent.appId())
152 .addSubmitOperation(intent).build());
Brian O'Connor66630c82014-10-02 21:08:19 -0700153 }
154
155 @Override
156 public void withdraw(Intent intent) {
157 checkNotNull(intent, INTENT_NULL);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800158 execute(IntentOperations.builder(intent.appId())
159 .addWithdrawOperation(intent.id()).build());
Brian O'Connor66630c82014-10-02 21:08:19 -0700160 }
161
Brian O'Connor66630c82014-10-02 21:08:19 -0700162 @Override
Thomas Vachuska83e090e2014-10-22 14:25:35 -0700163 public void replace(IntentId oldIntentId, Intent newIntent) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700164 checkNotNull(oldIntentId, INTENT_ID_NULL);
165 checkNotNull(newIntent, INTENT_NULL);
Brian O'Connor72a034c2014-11-26 18:24:23 -0800166 execute(IntentOperations.builder(newIntent.appId())
Ray Milkeye97ede92014-11-20 10:43:12 -0800167 .addReplaceOperation(oldIntentId, newIntent)
168 .build());
Thomas Vachuska83e090e2014-10-22 14:25:35 -0700169 }
170
Thomas Vachuska83e090e2014-10-22 14:25:35 -0700171 @Override
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700172 public void execute(IntentOperations operations) {
Brian O'Connore2ff25a2014-11-18 19:25:43 -0800173 if (operations.operations().isEmpty()) {
174 return;
175 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700176 batchService.addIntentOperations(operations);
Brian O'Connor66630c82014-10-02 21:08:19 -0700177 }
178
179 @Override
180 public Iterable<Intent> getIntents() {
181 return store.getIntents();
182 }
183
184 @Override
185 public long getIntentCount() {
186 return store.getIntentCount();
187 }
188
189 @Override
190 public Intent getIntent(IntentId id) {
191 checkNotNull(id, INTENT_ID_NULL);
192 return store.getIntent(id);
193 }
194
195 @Override
196 public IntentState getIntentState(IntentId id) {
197 checkNotNull(id, INTENT_ID_NULL);
198 return store.getIntentState(id);
199 }
200
201 @Override
Thomas Vachuska10d4abc2014-10-21 12:47:26 -0700202 public List<Intent> getInstallableIntents(IntentId intentId) {
203 checkNotNull(intentId, INTENT_ID_NULL);
204 return store.getInstallableIntents(intentId);
205 }
206
207 @Override
Brian O'Connor66630c82014-10-02 21:08:19 -0700208 public void addListener(IntentListener listener) {
209 listenerRegistry.addListener(listener);
210 }
211
212 @Override
213 public void removeListener(IntentListener listener) {
214 listenerRegistry.removeListener(listener);
215 }
216
217 @Override
218 public <T extends Intent> void registerCompiler(Class<T> cls, IntentCompiler<T> compiler) {
219 compilers.put(cls, compiler);
220 }
221
222 @Override
223 public <T extends Intent> void unregisterCompiler(Class<T> cls) {
224 compilers.remove(cls);
225 }
226
227 @Override
228 public Map<Class<? extends Intent>, IntentCompiler<? extends Intent>> getCompilers() {
229 return ImmutableMap.copyOf(compilers);
230 }
231
232 @Override
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700233 public <T extends Intent> void registerInstaller(Class<T> cls, IntentInstaller<T> installer) {
Brian O'Connor66630c82014-10-02 21:08:19 -0700234 installers.put(cls, installer);
235 }
236
237 @Override
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700238 public <T extends Intent> void unregisterInstaller(Class<T> cls) {
Brian O'Connor66630c82014-10-02 21:08:19 -0700239 installers.remove(cls);
240 }
241
242 @Override
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700243 public Map<Class<? extends Intent>, IntentInstaller<? extends Intent>> getInstallers() {
Brian O'Connor66630c82014-10-02 21:08:19 -0700244 return ImmutableMap.copyOf(installers);
245 }
246
247 /**
Brian O'Connor66630c82014-10-02 21:08:19 -0700248 * Returns the corresponding intent compiler to the specified intent.
249 *
250 * @param intent intent
tom95329eb2014-10-06 08:40:06 -0700251 * @param <T> the type of intent
Brian O'Connor66630c82014-10-02 21:08:19 -0700252 * @return intent compiler corresponding to the specified intent
253 */
254 private <T extends Intent> IntentCompiler<T> getCompiler(T intent) {
255 @SuppressWarnings("unchecked")
256 IntentCompiler<T> compiler = (IntentCompiler<T>) compilers.get(intent.getClass());
257 if (compiler == null) {
258 throw new IntentException("no compiler for class " + intent.getClass());
259 }
260 return compiler;
261 }
262
263 /**
264 * Returns the corresponding intent installer to the specified installable intent.
tom95329eb2014-10-06 08:40:06 -0700265 *
Brian O'Connor66630c82014-10-02 21:08:19 -0700266 * @param intent intent
tom95329eb2014-10-06 08:40:06 -0700267 * @param <T> the type of installable intent
Brian O'Connor66630c82014-10-02 21:08:19 -0700268 * @return intent installer corresponding to the specified installable intent
269 */
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700270 private <T extends Intent> IntentInstaller<T> getInstaller(T intent) {
Brian O'Connor66630c82014-10-02 21:08:19 -0700271 @SuppressWarnings("unchecked")
272 IntentInstaller<T> installer = (IntentInstaller<T>) installers.get(intent.getClass());
273 if (installer == null) {
274 throw new IntentException("no installer for class " + intent.getClass());
275 }
276 return installer;
277 }
278
279 /**
tom85258ee2014-10-07 00:10:02 -0700280 * Compiles the specified intent.
Brian O'Connor66630c82014-10-02 21:08:19 -0700281 *
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700282 * @param update intent update
Brian O'Connor66630c82014-10-02 21:08:19 -0700283 */
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700284 private void executeCompilingPhase(IntentUpdate update) {
285 Intent intent = update.newIntent();
tom85258ee2014-10-07 00:10:02 -0700286 // Indicate that the intent is entering the compiling phase.
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800287 update.setInflightState(intent, COMPILING);
tom85258ee2014-10-07 00:10:02 -0700288
289 try {
290 // Compile the intent into installable derivatives.
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700291 List<Intent> installables = compileIntent(intent, update);
tom85258ee2014-10-07 00:10:02 -0700292
293 // If all went well, associate the resulting list of installable
294 // intents with the top-level intent and proceed to install.
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700295 update.setInstallables(installables);
296 } catch (IntentException e) {
Jonathan Hart11096402014-10-20 17:31:49 -0700297 log.warn("Unable to compile intent {} due to:", intent.id(), e);
tom53945d52014-10-07 11:01:36 -0700298
tom85258ee2014-10-07 00:10:02 -0700299 // If compilation failed, mark the intent as failed.
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800300 update.setInflightState(intent, FAILED);
tom85258ee2014-10-07 00:10:02 -0700301 }
302 }
303
Brian O'Connorcb900f42014-10-07 21:55:33 -0700304 /**
305 * Compiles an intent recursively.
306 *
307 * @param intent intent
308 * @return result of compilation
309 */
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700310 private List<Intent> compileIntent(Intent intent, IntentUpdate update) {
Thomas Vachuska4926c1b2014-10-21 00:44:10 -0700311 if (intent.isInstallable()) {
312 return ImmutableList.of(intent);
Brian O'Connor66630c82014-10-02 21:08:19 -0700313 }
Brian O'Connorcb900f42014-10-07 21:55:33 -0700314
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700315 registerSubclassCompilerIfNeeded(intent);
316 List<Intent> previous = update.oldInstallables();
317 // FIXME: get previous resources
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700318 List<Intent> installable = new ArrayList<>();
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700319 for (Intent compiled : getCompiler(intent).compile(intent, previous, null)) {
320 installable.addAll(compileIntent(compiled, update));
Brian O'Connorcb900f42014-10-07 21:55:33 -0700321 }
tom85258ee2014-10-07 00:10:02 -0700322 return installable;
Brian O'Connor66630c82014-10-02 21:08:19 -0700323 }
324
325 /**
tom85258ee2014-10-07 00:10:02 -0700326 * Installs all installable intents associated with the specified top-level
327 * intent.
Brian O'Connor66630c82014-10-02 21:08:19 -0700328 *
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700329 * @param update intent update
Brian O'Connor66630c82014-10-02 21:08:19 -0700330 */
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700331 private void executeInstallingPhase(IntentUpdate update) {
332 if (update.newInstallables() == null) {
333 //no failed intents allowed past this point...
334 return;
tom85258ee2014-10-07 00:10:02 -0700335 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700336 // Indicate that the intent is entering the installing phase.
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800337 update.setInflightState(update.newIntent(), INSTALLING);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700338
339 List<FlowRuleBatchOperation> batches = Lists.newArrayList();
340 for (Intent installable : update.newInstallables()) {
341 registerSubclassInstallerIfNeeded(installable);
342 trackerService.addTrackedResources(update.newIntent().id(),
343 installable.resources());
344 try {
345 batches.addAll(getInstaller(installable).install(installable));
346 } catch (IntentException e) {
347 log.warn("Unable to install intent {} due to:", update.newIntent().id(), e);
Brian O'Connor427a1762014-11-19 18:40:32 -0800348 trackerService.removeTrackedResources(update.newIntent().id(),
349 installable.resources());
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700350 //FIXME we failed... intent should be recompiled
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700351 }
352 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800353 update.addBatches(batches);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700354 }
355
356 /**
357 * Uninstalls the specified intent by uninstalling all of its associated
358 * installable derivatives.
359 *
360 * @param update intent update
361 */
362 private void executeWithdrawingPhase(IntentUpdate update) {
363 if (!update.oldIntent().equals(update.newIntent())) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800364 update.setInflightState(update.oldIntent(), WITHDRAWING);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700365 } // else newIntent is FAILED
Brian O'Connor427a1762014-11-19 18:40:32 -0800366 update.addBatches(uninstallIntent(update.oldIntent(), update.oldInstallables()));
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700367 }
368
369 /**
370 * Uninstalls all installable intents associated with the given intent.
371 *
Brian O'Connor427a1762014-11-19 18:40:32 -0800372 * @param intent intent
373 * @param installables installable intents
374 * @return list of batches to uninstall intent
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700375 */
Brian O'Connor427a1762014-11-19 18:40:32 -0800376 private List<FlowRuleBatchOperation> uninstallIntent(Intent intent, List<Intent> installables) {
377 if (installables == null) {
378 return Collections.emptyList();
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700379 }
380 List<FlowRuleBatchOperation> batches = Lists.newArrayList();
Brian O'Connor427a1762014-11-19 18:40:32 -0800381 for (Intent installable : installables) {
382 trackerService.removeTrackedResources(intent.id(),
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700383 installable.resources());
384 try {
385 batches.addAll(getInstaller(installable).uninstall(installable));
386 } catch (IntentException e) {
Brian O'Connor427a1762014-11-19 18:40:32 -0800387 log.warn("Unable to uninstall intent {} due to:", intent.id(), e);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700388 // TODO: this should never happen. but what if it does?
389 }
390 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800391 return batches;
tom85258ee2014-10-07 00:10:02 -0700392 }
393
394 /**
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700395 * Withdraws the old intent and installs the new intent as one operation.
tom85258ee2014-10-07 00:10:02 -0700396 *
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700397 * @param update intent update
tom85258ee2014-10-07 00:10:02 -0700398 */
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700399 private void executeReplacementPhase(IntentUpdate update) {
400 checkArgument(update.oldInstallables().size() == update.newInstallables().size(),
401 "Old and New Intent must have equivalent installable intents.");
402 if (!update.oldIntent().equals(update.newIntent())) {
403 // only set the old intent's state if it is different
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800404 update.setInflightState(update.oldIntent(), WITHDRAWING);
tom53945d52014-10-07 11:01:36 -0700405 }
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800406 update.setInflightState(update.newIntent(), INSTALLING);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700407
408 List<FlowRuleBatchOperation> batches = Lists.newArrayList();
409 for (int i = 0; i < update.oldInstallables().size(); i++) {
410 Intent oldInstallable = update.oldInstallables().get(i);
411 Intent newInstallable = update.newInstallables().get(i);
Brian O'Connor427a1762014-11-19 18:40:32 -0800412 //FIXME revisit this
413// if (oldInstallable.equals(newInstallable)) {
414// continue;
415// }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700416 checkArgument(oldInstallable.getClass().equals(newInstallable.getClass()),
417 "Installable Intent type mismatch.");
418 trackerService.removeTrackedResources(update.oldIntent().id(), oldInstallable.resources());
419 trackerService.addTrackedResources(update.newIntent().id(), newInstallable.resources());
420 try {
421 batches.addAll(getInstaller(newInstallable).replace(oldInstallable, newInstallable));
422 } catch (IntentException e) {
423 log.warn("Unable to update intent {} due to:", update.oldIntent().id(), e);
424 //FIXME... we failed. need to uninstall (if same) or revert (if different)
Brian O'Connor427a1762014-11-19 18:40:32 -0800425 trackerService.removeTrackedResources(update.newIntent().id(), newInstallable.resources());
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800426 update.setInflightState(update.newIntent(), FAILED);
Brian O'Connor427a1762014-11-19 18:40:32 -0800427 batches = uninstallIntent(update.oldIntent(), update.oldInstallables());
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700428 }
429 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800430 update.addBatches(batches);
tom53945d52014-10-07 11:01:36 -0700431 }
432
433 /**
Brian O'Connor66630c82014-10-02 21:08:19 -0700434 * Registers an intent compiler of the specified intent if an intent compiler
435 * for the intent is not registered. This method traverses the class hierarchy of
436 * the intent. Once an intent compiler for a parent type is found, this method
437 * registers the found intent compiler.
438 *
439 * @param intent intent
440 */
441 private void registerSubclassCompilerIfNeeded(Intent intent) {
442 if (!compilers.containsKey(intent.getClass())) {
443 Class<?> cls = intent.getClass();
444 while (cls != Object.class) {
445 // As long as we're within the Intent class descendants
446 if (Intent.class.isAssignableFrom(cls)) {
447 IntentCompiler<?> compiler = compilers.get(cls);
448 if (compiler != null) {
449 compilers.put(intent.getClass(), compiler);
450 return;
451 }
452 }
453 cls = cls.getSuperclass();
454 }
455 }
456 }
457
458 /**
459 * Registers an intent installer of the specified intent if an intent installer
460 * for the intent is not registered. This method traverses the class hierarchy of
461 * the intent. Once an intent installer for a parent type is found, this method
462 * registers the found intent installer.
463 *
464 * @param intent intent
465 */
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700466 private void registerSubclassInstallerIfNeeded(Intent intent) {
Brian O'Connor66630c82014-10-02 21:08:19 -0700467 if (!installers.containsKey(intent.getClass())) {
468 Class<?> cls = intent.getClass();
469 while (cls != Object.class) {
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700470 // As long as we're within the Intent class descendants
471 if (Intent.class.isAssignableFrom(cls)) {
Brian O'Connor66630c82014-10-02 21:08:19 -0700472 IntentInstaller<?> installer = installers.get(cls);
473 if (installer != null) {
474 installers.put(intent.getClass(), installer);
475 return;
476 }
477 }
478 cls = cls.getSuperclass();
479 }
480 }
481 }
482
Brian O'Connor66630c82014-10-02 21:08:19 -0700483 // Store delegate to re-post events emitted from the store.
484 private class InternalStoreDelegate implements IntentStoreDelegate {
485 @Override
486 public void notify(IntentEvent event) {
tom85258ee2014-10-07 00:10:02 -0700487 eventDispatcher.post(event);
Brian O'Connor66630c82014-10-02 21:08:19 -0700488 }
489 }
490
Brian O'Connor72a034c2014-11-26 18:24:23 -0800491 private void buildAndSubmitBatches(Iterable<IntentId> intentIds,
492 boolean compileAllFailed) {
493 Map<ApplicationId, IntentOperations.Builder> batches = Maps.newHashMap();
494 // Attempt recompilation of the specified intents first.
495 for (IntentId id : intentIds) {
496 Intent intent = store.getIntent(id);
497 if (intent == null) {
498 continue;
499 }
500 IntentOperations.Builder builder = batches.get(intent.appId());
501 if (builder == null) {
502 builder = IntentOperations.builder(intent.appId());
503 batches.put(intent.appId(), builder);
504 }
505 builder.addUpdateOperation(id);
506 }
507
508 if (compileAllFailed) {
509 // If required, compile all currently failed intents.
510 for (Intent intent : getIntents()) {
511 if (getIntentState(intent.id()) == FAILED) {
512 IntentOperations.Builder builder = batches.get(intent.appId());
513 if (builder == null) {
514 builder = IntentOperations.builder(intent.appId());
515 batches.put(intent.appId(), builder);
516 }
517 builder.addUpdateOperation(intent.id());
518 }
519 }
520 }
521
522 for (ApplicationId appId : batches.keySet()) {
523 if (batchService.isLocalLeader(appId)) {
524 execute(batches.get(appId).build());
525 }
526 }
527 }
528
tom95329eb2014-10-06 08:40:06 -0700529 // Topology change delegate
530 private class InternalTopoChangeDelegate implements TopologyChangeDelegate {
531 @Override
tom85258ee2014-10-07 00:10:02 -0700532 public void triggerCompile(Iterable<IntentId> intentIds,
533 boolean compileAllFailed) {
Brian O'Connor72a034c2014-11-26 18:24:23 -0800534 buildAndSubmitBatches(intentIds, compileAllFailed);
tom95329eb2014-10-06 08:40:06 -0700535 }
tom95329eb2014-10-06 08:40:06 -0700536 }
tom85258ee2014-10-07 00:10:02 -0700537
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800538 // TODO move this inside IntentUpdate?
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700539 /**
Brian O'Connor427a1762014-11-19 18:40:32 -0800540 * TODO. rename this...
541 * @param update intent update
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700542 */
Brian O'Connor427a1762014-11-19 18:40:32 -0800543 private void processIntentUpdate(IntentUpdate update) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700544
Brian O'Connor427a1762014-11-19 18:40:32 -0800545 // check to see if the intent needs to be compiled or recompiled
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700546 if (update.newIntent() != null) {
547 executeCompilingPhase(update);
548 }
549
550 if (update.oldInstallables() != null && update.newInstallables() != null) {
551 executeReplacementPhase(update);
552 } else if (update.newInstallables() != null) {
553 executeInstallingPhase(update);
554 } else if (update.oldInstallables() != null) {
555 executeWithdrawingPhase(update);
556 } else {
Brian O'Connor427a1762014-11-19 18:40:32 -0800557 if (update.oldIntent() != null &&
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800558 !update.oldIntent().equals(update.newIntent())) {
Brian O'Connor427a1762014-11-19 18:40:32 -0800559 // removing failed intent
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800560 update.setInflightState(update.oldIntent(), WITHDRAWING);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700561 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800562// if (update.newIntent() != null) {
563// // TODO assert that next state is failed
564// }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700565 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700566 }
567
568 // TODO comments...
569 private class IntentUpdate {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700570 private final Intent oldIntent;
571 private final Intent newIntent;
572 private final Map<Intent, IntentState> stateMap = Maps.newHashMap();
573
574 private final List<Intent> oldInstallables;
575 private List<Intent> newInstallables;
Brian O'Connor427a1762014-11-19 18:40:32 -0800576 private final List<FlowRuleBatchOperation> batches = Lists.newLinkedList();
577 private int currentBatch = 0; // TODO: maybe replace with an iterator
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700578
579 IntentUpdate(IntentOperation op) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700580 switch (op.type()) {
581 case SUBMIT:
582 newIntent = op.intent();
583 oldIntent = null;
584 break;
585 case WITHDRAW:
586 newIntent = null;
587 oldIntent = store.getIntent(op.intentId());
588 break;
589 case REPLACE:
590 newIntent = op.intent();
591 oldIntent = store.getIntent(op.intentId());
592 break;
593 case UPDATE:
594 oldIntent = store.getIntent(op.intentId());
Brian O'Connor427a1762014-11-19 18:40:32 -0800595 newIntent = oldIntent;
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700596 break;
597 default:
598 oldIntent = null;
599 newIntent = null;
600 break;
601 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700602 // fetch the old intent's installables from the store
603 if (oldIntent != null) {
604 oldInstallables = store.getInstallableIntents(oldIntent.id());
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700605 } else {
606 oldInstallables = null;
607 }
608 }
609
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800610 void init(BatchWrite batchWrite) {
611 // add new intent to store (if required)
612 if (newIntent != null) {
613 batchWrite.createIntent(newIntent);
614 }
615 }
616
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700617 Intent oldIntent() {
618 return oldIntent;
619 }
620
621 Intent newIntent() {
622 return newIntent;
623 }
624
625 List<Intent> oldInstallables() {
626 return oldInstallables;
627 }
628
629 List<Intent> newInstallables() {
630 return newInstallables;
631 }
632
633 void setInstallables(List<Intent> installables) {
634 newInstallables = installables;
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800635 //FIXME batch this
636
637 //store.setInstallableIntents(newIntent.id(), installables);
638
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700639 }
640
Brian O'Connor427a1762014-11-19 18:40:32 -0800641 boolean isComplete() {
642 return currentBatch >= batches.size();
643 }
644
645 FlowRuleBatchOperation currentBatch() {
646 return !isComplete() ? batches.get(currentBatch) : null;
647 }
648
alshabiba9819bf2014-11-30 18:15:52 -0800649 void batchSuccess(BatchWrite batchWrite) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800650 // move on to next Batch
651 if (++currentBatch == batches.size()) {
alshabiba9819bf2014-11-30 18:15:52 -0800652 finalizeStates(batchWrite);
Brian O'Connor427a1762014-11-19 18:40:32 -0800653 }
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800654 }
655
656 void batchFailed() {
657
658 // the current batch has failed, so recompile
659 // remove the current batch and all remaining
660 for (int i = currentBatch; i < batches.size(); i++) {
661 batches.remove(i);
662 }
663 if (oldIntent != null) {
664 executeWithdrawingPhase(this); // remove the old intent
665 }
666 if (newIntent != null) {
667 setInflightState(newIntent, FAILED);
668 batches.addAll(uninstallIntent(newIntent, newInstallables()));
669 }
670
671 // FIXME: should we try to recompile?
Brian O'Connor427a1762014-11-19 18:40:32 -0800672 }
673
674 // FIXME make sure this is called!!!
alshabiba9819bf2014-11-30 18:15:52 -0800675 private void finalizeStates(BatchWrite batchWrite) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800676 // events to be triggered on successful write
Brian O'Connor427a1762014-11-19 18:40:32 -0800677 for (Intent intent : stateMap.keySet()) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800678 switch (getInflightState(intent)) {
Brian O'Connor427a1762014-11-19 18:40:32 -0800679 case INSTALLING:
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800680 batchWrite.setState(intent, INSTALLED);
681 batchWrite.setInstallableIntents(newIntent.id(), newInstallables);
Brian O'Connor427a1762014-11-19 18:40:32 -0800682 break;
683 case WITHDRAWING:
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800684 batchWrite.setState(intent, WITHDRAWN);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800685 batchWrite.removeInstalledIntents(intent.id());
686 batchWrite.removeIntent(intent.id());
Brian O'Connor427a1762014-11-19 18:40:32 -0800687 break;
688 case FAILED:
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800689 batchWrite.removeInstalledIntents(intent.id());
Brian O'Connor427a1762014-11-19 18:40:32 -0800690 break;
691
692 // FALLTHROUGH to default from here
693 case SUBMITTED:
694 case COMPILING:
695 case RECOMPILING:
696 case WITHDRAWN:
697 case INSTALLED:
698 default:
699 //FIXME clean this up (we shouldn't ever get here)
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800700 log.warn("Bad state: {} for {}", getInflightState(intent), intent);
Brian O'Connor427a1762014-11-19 18:40:32 -0800701 break;
702 }
703 }
704 }
705
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700706 List<FlowRuleBatchOperation> batches() {
707 return batches;
708 }
709
Brian O'Connor427a1762014-11-19 18:40:32 -0800710 void addBatches(List<FlowRuleBatchOperation> batches) {
711 this.batches.addAll(batches);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700712 }
713
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800714 IntentState getInflightState(Intent intent) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700715 return stateMap.get(intent);
716 }
717
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800718
719 // set transient state during intent update process
720 void setInflightState(Intent intent, IntentState newState) {
721 // This method should be called for
722 // transition to non-parking or Failed only
723 EnumSet<IntentState> nonParkingOrFailed
724 = EnumSet.complementOf(EnumSet.of(SUBMITTED, INSTALLED, WITHDRAWN));
725 if (!nonParkingOrFailed.contains(newState)) {
726 log.error("Unexpected transition to {}", newState);
727 }
728
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700729 // TODO: clean this up, or set to debug
730 IntentState oldState = stateMap.get(intent);
Brian O'Connor427a1762014-11-19 18:40:32 -0800731 log.debug("intent id: {}, old state: {}, new state: {}",
Ray Milkeye97ede92014-11-20 10:43:12 -0800732 intent.id(), oldState, newState);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700733
734 stateMap.put(intent, newState);
alshabiba9819bf2014-11-30 18:15:52 -0800735// IntentEvent event = store.setState(intent, newState);
736// if (event != null) {
737// eventDispatcher.post(event);
738// }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700739 }
740
741 Map<Intent, IntentState> stateMap() {
742 return stateMap;
743 }
744 }
745
Brian O'Connorcb900f42014-10-07 21:55:33 -0700746 private class IntentInstallMonitor implements Runnable {
747
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800748 // TODO make this configurable
749 private static final int TIMEOUT_PER_OP = 500; // ms
Brian O'Connor427a1762014-11-19 18:40:32 -0800750 private static final int MAX_ATTEMPTS = 3;
Brian O'Connorcb900f42014-10-07 21:55:33 -0700751
Brian O'Connor427a1762014-11-19 18:40:32 -0800752 private final IntentOperations ops;
753 private final List<IntentUpdate> intentUpdates = Lists.newArrayList();
754
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800755 // future holding current FlowRuleBatch installation result
Brian O'Connor427a1762014-11-19 18:40:32 -0800756 private Future<CompletedBatchOperation> future;
757 private long startTime = System.currentTimeMillis();
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800758 private long endTime;
Brian O'Connor427a1762014-11-19 18:40:32 -0800759 private int installAttempt;
760
761 public IntentInstallMonitor(IntentOperations ops) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700762 this.ops = ops;
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800763 resetTimeoutLimit();
764 }
765
766 private void resetTimeoutLimit() {
767 // FIXME compute reasonable timeouts
768 this.endTime = System.currentTimeMillis()
769 + ops.operations().size() * TIMEOUT_PER_OP;
Brian O'Connor427a1762014-11-19 18:40:32 -0800770 }
771
772 private void buildIntentUpdates() {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800773 BatchWrite batchWrite = store.newBatchWrite();
774
775 // create context and record new request to store
Brian O'Connor427a1762014-11-19 18:40:32 -0800776 for (IntentOperation op : ops.operations()) {
777 IntentUpdate update = new IntentUpdate(op);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800778 update.init(batchWrite);
Brian O'Connor427a1762014-11-19 18:40:32 -0800779 intentUpdates.add(update);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800780 }
781
782 if (!batchWrite.isEmpty()) {
783 store.batchWrite(batchWrite);
784 }
785
786 // start processing each Intents
787 for (IntentUpdate update : intentUpdates) {
788 if (update.newIntent() != null) {
789 IntentState state = store.getIntentState(update.newIntent().id());
790 if (state == SUBMITTED) {
791 eventDispatcher.post(new IntentEvent(Type.SUBMITTED, update.newIntent));
792 }
793 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800794 processIntentUpdate(update);
795 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700796 future = applyNextBatch();
Brian O'Connorcb900f42014-10-07 21:55:33 -0700797 }
798
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700799 /**
Brian O'Connor427a1762014-11-19 18:40:32 -0800800 * Builds and applies the next batch, and returns the future.
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700801 *
802 * @return Future for next batch
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700803 */
804 private Future<CompletedBatchOperation> applyNextBatch() {
Brian O'Connor427a1762014-11-19 18:40:32 -0800805 //TODO test this. (also, maybe save this batch)
806 FlowRuleBatchOperation batch = new FlowRuleBatchOperation(Collections.emptyList());
807 for (IntentUpdate update : intentUpdates) {
808 if (!update.isComplete()) {
809 batch.addAll(update.currentBatch());
810 }
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700811 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800812 return (batch.size() > 0) ? flowRuleService.applyBatch(batch) : null;
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700813 }
814
Brian O'Connor427a1762014-11-19 18:40:32 -0800815 private void updateBatches(CompletedBatchOperation completed) {
816 if (completed.isSuccess()) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800817 BatchWrite batchWrite = store.newBatchWrite();
818 List<IntentEvent> events = new ArrayList<>();
Brian O'Connor427a1762014-11-19 18:40:32 -0800819 for (IntentUpdate update : intentUpdates) {
alshabiba9819bf2014-11-30 18:15:52 -0800820 update.batchSuccess(batchWrite);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800821 }
822 if (!batchWrite.isEmpty()) {
823 store.batchWrite(batchWrite);
824 for (IntentEvent event : events) {
825 eventDispatcher.post(event);
826 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700827 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700828 } else {
Brian O'Connor427a1762014-11-19 18:40:32 -0800829 // entire batch has been reverted...
830 log.warn("Failed items: {}", completed.failedItems());
831
832 for (Long id : completed.failedIds()) {
833 IntentId targetId = IntentId.valueOf(id);
834 for (IntentUpdate update : intentUpdates) {
835 List<Intent> installables = Lists.newArrayList(update.newInstallables());
836 installables.addAll(update.oldInstallables());
837 for (Intent intent : installables) {
838 if (intent.id().equals(targetId)) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800839 update.batchFailed();
Brian O'Connor427a1762014-11-19 18:40:32 -0800840 break;
841 }
842 }
843 }
844 // don't increment the non-failed items, as they have been reverted.
845 }
846 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700847 }
848
849 /**
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700850 * Iterate through the pending futures, and remove them when they have completed.
851 */
852 private void processFutures() {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700853 if (future == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800854 log.warn("I have no Future.");
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700855 return; //FIXME look at this
Brian O'Connorcb900f42014-10-07 21:55:33 -0700856 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700857 try {
858 CompletedBatchOperation completed = future.get(100, TimeUnit.NANOSECONDS);
Brian O'Connor427a1762014-11-19 18:40:32 -0800859 updateBatches(completed);
860 future = applyNextBatch();
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700861 } catch (TimeoutException | InterruptedException | ExecutionException te) {
862 //TODO look into error message
Brian O'Connor427a1762014-11-19 18:40:32 -0800863 log.debug("Installation of intents are still pending: {}", ops);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700864 }
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700865 }
866
Brian O'Connor427a1762014-11-19 18:40:32 -0800867 private void retry() {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800868 log.debug("Execution timed out, retrying.");
Brian O'Connor427a1762014-11-19 18:40:32 -0800869 if (future.cancel(true)) { // cancel success; batch is reverted
870 // reset the timer
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800871 resetTimeoutLimit();
Brian O'Connor427a1762014-11-19 18:40:32 -0800872 if (installAttempt++ >= MAX_ATTEMPTS) {
873 log.warn("Install request timed out: {}", ops);
874 for (IntentUpdate update : intentUpdates) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800875 update.batchFailed();
Brian O'Connor427a1762014-11-19 18:40:32 -0800876 }
877 } // else just resubmit the work
878 future = applyNextBatch();
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800879 executor.submit(this);
Brian O'Connor427a1762014-11-19 18:40:32 -0800880 } else {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800881 log.error("Cancelling FlowRuleBatch failed.");
Brian O'Connor427a1762014-11-19 18:40:32 -0800882 // FIXME
883 // cancel failed... batch is broken; shouldn't happen!
884 // we could manually reverse everything
885 // ... or just core dump and send email to Ali
886 batchService.removeIntentOperations(ops);
887 }
888 }
889
890 boolean isComplete() {
891 // TODO: actually check with the intent update?
892 return future == null;
893 }
894
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700895 @Override
896 public void run() {
Brian O'Connor427a1762014-11-19 18:40:32 -0800897 try {
898 if (intentUpdates.isEmpty()) {
899 // this should only be called on the first iteration
900 // note: this a "expensive", so it is not done in the constructor
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800901
902 // - creates per Intent installation context (IntentUpdate)
903 // - write Intents to store
904 // - process (compile, install, etc.) each Intents
905 // - generate FlowRuleBatch for this phase
Brian O'Connor427a1762014-11-19 18:40:32 -0800906 buildIntentUpdates();
907 }
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800908
909 // - peek if current FlowRuleBatch is complete
910 // -- If complete OK:
911 // step each IntentUpdate forward
912 // If phase left: generate next FlowRuleBatch
913 // If no more phase: write parking states
914 // -- If complete FAIL:
915 // Intent which failed: transition Intent to FAILED
916 // Other Intents: resubmit same FlowRuleBatch for this phase
Brian O'Connor427a1762014-11-19 18:40:32 -0800917 processFutures();
918 if (isComplete()) {
919 // there are no outstanding batches; we are done
920 batchService.removeIntentOperations(ops);
921 } else if (endTime < System.currentTimeMillis()) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800922 // - cancel current FlowRuleBatch and resubmit again
Brian O'Connor427a1762014-11-19 18:40:32 -0800923 retry();
924 } else {
925 // we are not done yet, yield the thread by resubmitting ourselves
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800926 executor.submit(this);
Brian O'Connor427a1762014-11-19 18:40:32 -0800927 }
928 } catch (Exception e) {
929 log.error("Error submitting batches:", e);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800930 // FIXME incomplete Intents should be cleaned up
931 // (transition to FAILED, etc.)
Brian O'Connorcb900f42014-10-07 21:55:33 -0700932 }
933 }
934 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700935
936 private class InternalBatchDelegate implements IntentBatchDelegate {
937 @Override
938 public void execute(IntentOperations operations) {
Yuta HIGUCHIfe4367a2014-11-24 19:19:09 -0800939 log.info("Execute {} operation(s).", operations.operations().size());
940 log.debug("Execute operations: {}", operations.operations());
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700941 //FIXME: perhaps we want to track this task so that we can cancel it.
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800942 executor.execute(new IntentInstallMonitor(operations));
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700943 }
944
945 @Override
946 public void cancel(IntentOperations operations) {
947 //FIXME: implement this
948 log.warn("NOT IMPLEMENTED -- Cancel operations: {}", operations);
949 }
950 }
Ray Milkeye97ede92014-11-20 10:43:12 -0800951
Brian O'Connor66630c82014-10-02 21:08:19 -0700952}