blob: 2bcb8091534126c80ac4a77b4cd509d404ee6fbb [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);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800131 executor = newFixedThreadPool(NUM_THREADS, namedThreads("onos-intent-monitor"));
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
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800649 List<IntentEvent> batchSuccess(BatchWrite batchWrite) {
650 // move on to next Batch
651 if (++currentBatch == batches.size()) {
652 return finalizeStates(batchWrite);
Brian O'Connor427a1762014-11-19 18:40:32 -0800653 }
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800654 return Collections.emptyList();
655 }
656
657 void batchFailed() {
658
659 // the current batch has failed, so recompile
660 // remove the current batch and all remaining
661 for (int i = currentBatch; i < batches.size(); i++) {
662 batches.remove(i);
663 }
664 if (oldIntent != null) {
665 executeWithdrawingPhase(this); // remove the old intent
666 }
667 if (newIntent != null) {
668 setInflightState(newIntent, FAILED);
669 batches.addAll(uninstallIntent(newIntent, newInstallables()));
670 }
671
672 // FIXME: should we try to recompile?
Brian O'Connor427a1762014-11-19 18:40:32 -0800673 }
674
675 // FIXME make sure this is called!!!
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800676 private List<IntentEvent> finalizeStates(BatchWrite batchWrite) {
677 // events to be triggered on successful write
678 List<IntentEvent> events = new ArrayList<>();
Brian O'Connor427a1762014-11-19 18:40:32 -0800679 for (Intent intent : stateMap.keySet()) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800680 switch (getInflightState(intent)) {
Brian O'Connor427a1762014-11-19 18:40:32 -0800681 case INSTALLING:
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800682 batchWrite.setState(intent, INSTALLED);
683 batchWrite.setInstallableIntents(newIntent.id(), newInstallables);
684 events.add(new IntentEvent(Type.INSTALLED, intent));
Brian O'Connor427a1762014-11-19 18:40:32 -0800685 break;
686 case WITHDRAWING:
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800687 batchWrite.setState(intent, WITHDRAWN);
688 events.add(new IntentEvent(Type.WITHDRAWN, intent));
689 batchWrite.removeInstalledIntents(intent.id());
690 batchWrite.removeIntent(intent.id());
Brian O'Connor427a1762014-11-19 18:40:32 -0800691 break;
692 case FAILED:
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800693 batchWrite.removeInstalledIntents(intent.id());
Brian O'Connor427a1762014-11-19 18:40:32 -0800694 break;
695
696 // FALLTHROUGH to default from here
697 case SUBMITTED:
698 case COMPILING:
699 case RECOMPILING:
700 case WITHDRAWN:
701 case INSTALLED:
702 default:
703 //FIXME clean this up (we shouldn't ever get here)
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800704 log.warn("Bad state: {} for {}", getInflightState(intent), intent);
Brian O'Connor427a1762014-11-19 18:40:32 -0800705 break;
706 }
707 }
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800708 return events;
Brian O'Connor427a1762014-11-19 18:40:32 -0800709 }
710
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700711 List<FlowRuleBatchOperation> batches() {
712 return batches;
713 }
714
Brian O'Connor427a1762014-11-19 18:40:32 -0800715 void addBatches(List<FlowRuleBatchOperation> batches) {
716 this.batches.addAll(batches);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700717 }
718
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800719 IntentState getInflightState(Intent intent) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700720 return stateMap.get(intent);
721 }
722
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800723
724 // set transient state during intent update process
725 void setInflightState(Intent intent, IntentState newState) {
726 // This method should be called for
727 // transition to non-parking or Failed only
728 EnumSet<IntentState> nonParkingOrFailed
729 = EnumSet.complementOf(EnumSet.of(SUBMITTED, INSTALLED, WITHDRAWN));
730 if (!nonParkingOrFailed.contains(newState)) {
731 log.error("Unexpected transition to {}", newState);
732 }
733
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700734 // TODO: clean this up, or set to debug
735 IntentState oldState = stateMap.get(intent);
Brian O'Connor427a1762014-11-19 18:40:32 -0800736 log.debug("intent id: {}, old state: {}, new state: {}",
Ray Milkeye97ede92014-11-20 10:43:12 -0800737 intent.id(), oldState, newState);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700738
739 stateMap.put(intent, newState);
740 IntentEvent event = store.setState(intent, newState);
741 if (event != null) {
742 eventDispatcher.post(event);
743 }
744 }
745
746 Map<Intent, IntentState> stateMap() {
747 return stateMap;
748 }
749 }
750
Brian O'Connorcb900f42014-10-07 21:55:33 -0700751 private class IntentInstallMonitor implements Runnable {
752
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800753 // TODO make this configurable
754 private static final int TIMEOUT_PER_OP = 500; // ms
Brian O'Connor427a1762014-11-19 18:40:32 -0800755 private static final int MAX_ATTEMPTS = 3;
Brian O'Connorcb900f42014-10-07 21:55:33 -0700756
Brian O'Connor427a1762014-11-19 18:40:32 -0800757 private final IntentOperations ops;
758 private final List<IntentUpdate> intentUpdates = Lists.newArrayList();
759
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800760 // future holding current FlowRuleBatch installation result
Brian O'Connor427a1762014-11-19 18:40:32 -0800761 private Future<CompletedBatchOperation> future;
762 private long startTime = System.currentTimeMillis();
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800763 private long endTime;
Brian O'Connor427a1762014-11-19 18:40:32 -0800764 private int installAttempt;
765
766 public IntentInstallMonitor(IntentOperations ops) {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700767 this.ops = ops;
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800768 resetTimeoutLimit();
769 }
770
771 private void resetTimeoutLimit() {
772 // FIXME compute reasonable timeouts
773 this.endTime = System.currentTimeMillis()
774 + ops.operations().size() * TIMEOUT_PER_OP;
Brian O'Connor427a1762014-11-19 18:40:32 -0800775 }
776
777 private void buildIntentUpdates() {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800778 BatchWrite batchWrite = store.newBatchWrite();
779
780 // create context and record new request to store
Brian O'Connor427a1762014-11-19 18:40:32 -0800781 for (IntentOperation op : ops.operations()) {
782 IntentUpdate update = new IntentUpdate(op);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800783 update.init(batchWrite);
Brian O'Connor427a1762014-11-19 18:40:32 -0800784 intentUpdates.add(update);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800785 }
786
787 if (!batchWrite.isEmpty()) {
788 store.batchWrite(batchWrite);
789 }
790
791 // start processing each Intents
792 for (IntentUpdate update : intentUpdates) {
793 if (update.newIntent() != null) {
794 IntentState state = store.getIntentState(update.newIntent().id());
795 if (state == SUBMITTED) {
796 eventDispatcher.post(new IntentEvent(Type.SUBMITTED, update.newIntent));
797 }
798 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800799 processIntentUpdate(update);
800 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700801 future = applyNextBatch();
Brian O'Connorcb900f42014-10-07 21:55:33 -0700802 }
803
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700804 /**
Brian O'Connor427a1762014-11-19 18:40:32 -0800805 * Builds and applies the next batch, and returns the future.
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700806 *
807 * @return Future for next batch
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700808 */
809 private Future<CompletedBatchOperation> applyNextBatch() {
Brian O'Connor427a1762014-11-19 18:40:32 -0800810 //TODO test this. (also, maybe save this batch)
811 FlowRuleBatchOperation batch = new FlowRuleBatchOperation(Collections.emptyList());
812 for (IntentUpdate update : intentUpdates) {
813 if (!update.isComplete()) {
814 batch.addAll(update.currentBatch());
815 }
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700816 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800817 return (batch.size() > 0) ? flowRuleService.applyBatch(batch) : null;
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700818 }
819
Brian O'Connor427a1762014-11-19 18:40:32 -0800820 private void updateBatches(CompletedBatchOperation completed) {
821 if (completed.isSuccess()) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800822 BatchWrite batchWrite = store.newBatchWrite();
823 List<IntentEvent> events = new ArrayList<>();
Brian O'Connor427a1762014-11-19 18:40:32 -0800824 for (IntentUpdate update : intentUpdates) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800825 events.addAll(update.batchSuccess(batchWrite));
826 }
827 if (!batchWrite.isEmpty()) {
828 store.batchWrite(batchWrite);
829 for (IntentEvent event : events) {
830 eventDispatcher.post(event);
831 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700832 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700833 } else {
Brian O'Connor427a1762014-11-19 18:40:32 -0800834 // entire batch has been reverted...
835 log.warn("Failed items: {}", completed.failedItems());
836
837 for (Long id : completed.failedIds()) {
838 IntentId targetId = IntentId.valueOf(id);
839 for (IntentUpdate update : intentUpdates) {
840 List<Intent> installables = Lists.newArrayList(update.newInstallables());
841 installables.addAll(update.oldInstallables());
842 for (Intent intent : installables) {
843 if (intent.id().equals(targetId)) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800844 update.batchFailed();
Brian O'Connor427a1762014-11-19 18:40:32 -0800845 break;
846 }
847 }
848 }
849 // don't increment the non-failed items, as they have been reverted.
850 }
851 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700852 }
853
854 /**
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700855 * Iterate through the pending futures, and remove them when they have completed.
856 */
857 private void processFutures() {
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700858 if (future == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800859 log.warn("I have no Future.");
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700860 return; //FIXME look at this
Brian O'Connorcb900f42014-10-07 21:55:33 -0700861 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700862 try {
863 CompletedBatchOperation completed = future.get(100, TimeUnit.NANOSECONDS);
Brian O'Connor427a1762014-11-19 18:40:32 -0800864 updateBatches(completed);
865 future = applyNextBatch();
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700866 } catch (TimeoutException | InterruptedException | ExecutionException te) {
867 //TODO look into error message
Brian O'Connor427a1762014-11-19 18:40:32 -0800868 log.debug("Installation of intents are still pending: {}", ops);
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700869 }
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700870 }
871
Brian O'Connor427a1762014-11-19 18:40:32 -0800872 private void retry() {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800873 log.debug("Execution timed out, retrying.");
Brian O'Connor427a1762014-11-19 18:40:32 -0800874 if (future.cancel(true)) { // cancel success; batch is reverted
875 // reset the timer
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800876 resetTimeoutLimit();
Brian O'Connor427a1762014-11-19 18:40:32 -0800877 if (installAttempt++ >= MAX_ATTEMPTS) {
878 log.warn("Install request timed out: {}", ops);
879 for (IntentUpdate update : intentUpdates) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800880 update.batchFailed();
Brian O'Connor427a1762014-11-19 18:40:32 -0800881 }
882 } // else just resubmit the work
883 future = applyNextBatch();
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800884 executor.submit(this);
Brian O'Connor427a1762014-11-19 18:40:32 -0800885 } else {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800886 log.error("Cancelling FlowRuleBatch failed.");
Brian O'Connor427a1762014-11-19 18:40:32 -0800887 // FIXME
888 // cancel failed... batch is broken; shouldn't happen!
889 // we could manually reverse everything
890 // ... or just core dump and send email to Ali
891 batchService.removeIntentOperations(ops);
892 }
893 }
894
895 boolean isComplete() {
896 // TODO: actually check with the intent update?
897 return future == null;
898 }
899
Brian O'Connorf2dbde52014-10-10 16:20:24 -0700900 @Override
901 public void run() {
Brian O'Connor427a1762014-11-19 18:40:32 -0800902 try {
903 if (intentUpdates.isEmpty()) {
904 // this should only be called on the first iteration
905 // note: this a "expensive", so it is not done in the constructor
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800906
907 // - creates per Intent installation context (IntentUpdate)
908 // - write Intents to store
909 // - process (compile, install, etc.) each Intents
910 // - generate FlowRuleBatch for this phase
Brian O'Connor427a1762014-11-19 18:40:32 -0800911 buildIntentUpdates();
912 }
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800913
914 // - peek if current FlowRuleBatch is complete
915 // -- If complete OK:
916 // step each IntentUpdate forward
917 // If phase left: generate next FlowRuleBatch
918 // If no more phase: write parking states
919 // -- If complete FAIL:
920 // Intent which failed: transition Intent to FAILED
921 // Other Intents: resubmit same FlowRuleBatch for this phase
Brian O'Connor427a1762014-11-19 18:40:32 -0800922 processFutures();
923 if (isComplete()) {
924 // there are no outstanding batches; we are done
925 batchService.removeIntentOperations(ops);
926 } else if (endTime < System.currentTimeMillis()) {
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800927 // - cancel current FlowRuleBatch and resubmit again
Brian O'Connor427a1762014-11-19 18:40:32 -0800928 retry();
929 } else {
930 // we are not done yet, yield the thread by resubmitting ourselves
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800931 executor.submit(this);
Brian O'Connor427a1762014-11-19 18:40:32 -0800932 }
933 } catch (Exception e) {
934 log.error("Error submitting batches:", e);
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800935 // FIXME incomplete Intents should be cleaned up
936 // (transition to FAILED, etc.)
Brian O'Connorcb900f42014-10-07 21:55:33 -0700937 }
938 }
939 }
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700940
941 private class InternalBatchDelegate implements IntentBatchDelegate {
942 @Override
943 public void execute(IntentOperations operations) {
Yuta HIGUCHIfe4367a2014-11-24 19:19:09 -0800944 log.info("Execute {} operation(s).", operations.operations().size());
945 log.debug("Execute operations: {}", operations.operations());
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700946 //FIXME: perhaps we want to track this task so that we can cancel it.
Yuta HIGUCHIc2bf3d82014-11-28 18:50:41 -0800947 executor.execute(new IntentInstallMonitor(operations));
Brian O'Connorfa81eae2014-10-30 13:20:05 -0700948 }
949
950 @Override
951 public void cancel(IntentOperations operations) {
952 //FIXME: implement this
953 log.warn("NOT IMPLEMENTED -- Cancel operations: {}", operations);
954 }
955 }
Ray Milkeye97ede92014-11-20 10:43:12 -0800956
Brian O'Connor66630c82014-10-02 21:08:19 -0700957}