blob: 7ea40d4fc082f183fa5f07584c74bd1731056976 [file] [log] [blame]
Thomas Vachuska02aeb032015-01-06 22:36:30 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Thomas Vachuska02aeb032015-01-06 22:36:30 -08003 *
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 */
16package org.onosproject.app.impl;
17
Arnav Jainefb57e52019-07-09 14:24:10 -070018import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.fasterxml.jackson.databind.node.ArrayNode;
21import com.fasterxml.jackson.databind.node.ObjectNode;
Madan Jampani015d3a32016-06-16 18:25:11 -070022import com.google.common.cache.Cache;
23import com.google.common.cache.CacheBuilder;
Jonathan Hartc32585f2016-06-16 14:01:27 -070024import com.google.common.collect.HashMultimap;
Arnav Jainefb57e52019-07-09 14:24:10 -070025import com.google.common.collect.ImmutableList;
26import com.google.common.collect.ImmutableSet;
Jonathan Hartc32585f2016-06-16 14:01:27 -070027import com.google.common.collect.Multimap;
Madan Jampani015d3a32016-06-16 18:25:11 -070028import com.google.common.util.concurrent.Uninterruptibles;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080029import org.apache.karaf.features.Feature;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080030import org.apache.karaf.features.FeaturesService;
31import org.onosproject.app.ApplicationAdminService;
32import org.onosproject.app.ApplicationEvent;
33import org.onosproject.app.ApplicationListener;
34import org.onosproject.app.ApplicationService;
35import org.onosproject.app.ApplicationState;
36import org.onosproject.app.ApplicationStore;
37import org.onosproject.app.ApplicationStoreDelegate;
38import org.onosproject.core.Application;
39import org.onosproject.core.ApplicationId;
Arnav Jainefb57e52019-07-09 14:24:10 -070040import org.onosproject.core.DefaultApplication;
41import org.onosproject.core.DefaultApplicationId;
42import org.onosproject.core.Version;
43import org.onosproject.core.VersionService;
Thomas Vachuskac65dd712015-11-04 17:19:10 -080044import org.onosproject.event.AbstractListenerManager;
Changhoon Yoonb856b812015-08-10 03:47:19 +090045import org.onosproject.security.Permission;
46import org.onosproject.security.SecurityUtil;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070047import org.osgi.service.component.annotations.Activate;
48import org.osgi.service.component.annotations.Component;
49import org.osgi.service.component.annotations.Deactivate;
50import org.osgi.service.component.annotations.Reference;
51import org.osgi.service.component.annotations.ReferenceCardinality;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080052import org.slf4j.Logger;
53
Arnav Jainefb57e52019-07-09 14:24:10 -070054import java.io.IOException;
Jonathan Hartc32585f2016-06-16 14:01:27 -070055import java.io.InputStream;
Arnav Jainefb57e52019-07-09 14:24:10 -070056import java.net.HttpURLConnection;
57import java.net.MalformedURLException;
58import java.net.URL;
59import java.util.Iterator;
Jonathan Hartc32585f2016-06-16 14:01:27 -070060import java.util.Set;
Madan Jampani015d3a32016-06-16 18:25:11 -070061import java.util.concurrent.CountDownLatch;
62import java.util.concurrent.TimeUnit;
Madan Jampania0c4bdb2016-06-17 11:02:38 -070063import java.util.function.Consumer;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080064
65import static com.google.common.base.Preconditions.checkNotNull;
Arnav Jainefb57e52019-07-09 14:24:10 -070066import static org.onosproject.app.ApplicationEvent.Type.*;
Changhoon Yoon541ef712015-05-23 17:18:34 +090067import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac65dd712015-11-04 17:19:10 -080068import static org.onosproject.security.AppPermission.Type.APP_READ;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080069import static org.slf4j.LoggerFactory.getLogger;
70
71/**
72 * Implementation of the application management service.
73 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -070074@Component(immediate = true, service = {ApplicationService.class, ApplicationAdminService.class})
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070075public class ApplicationManager
76 extends AbstractListenerManager<ApplicationEvent, ApplicationListener>
77 implements ApplicationService, ApplicationAdminService {
Thomas Vachuska02aeb032015-01-06 22:36:30 -080078
79 private final Logger log = getLogger(getClass());
80
Arnav Jainefb57e52019-07-09 14:24:10 -070081 private static final String APP_REGISTRY_URL = "http://api.onosproject.org:8080/api/applications";
82
Thomas Vachuska02aeb032015-01-06 22:36:30 -080083 private static final String APP_ID_NULL = "Application ID cannot be null";
Madan Jampani015d3a32016-06-16 18:25:11 -070084 private static final long DEFAULT_OPERATION_TIMEOUT_MILLIS = 2000;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080085 private final ApplicationStoreDelegate delegate = new InternalStoreDelegate();
86
Ray Milkeyd84f89b2018-08-17 14:54:17 -070087 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska02aeb032015-01-06 22:36:30 -080088 protected ApplicationStore store;
89
Ray Milkeyd84f89b2018-08-17 14:54:17 -070090 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska02aeb032015-01-06 22:36:30 -080091 protected FeaturesService featuresService;
92
Arnav Jainefb57e52019-07-09 14:24:10 -070093 @Reference(cardinality = ReferenceCardinality.MANDATORY)
94 protected VersionService versionService;
95
Thomas Vachuskac65dd712015-11-04 17:19:10 -080096 // Application supplied hooks for pre-activation processing.
Jonathan Hartc32585f2016-06-16 14:01:27 -070097 private final Multimap<String, Runnable> deactivateHooks = HashMultimap.create();
Madan Jampania0c4bdb2016-06-17 11:02:38 -070098 private final Cache<ApplicationId, CountDownLatch> pendingOperations =
Madan Jampani015d3a32016-06-16 18:25:11 -070099 CacheBuilder.newBuilder()
Arnav Jainefb57e52019-07-09 14:24:10 -0700100 .expireAfterWrite(DEFAULT_OPERATION_TIMEOUT_MILLIS * 2, TimeUnit.MILLISECONDS)
101 .build();
Thomas Vachuskac65dd712015-11-04 17:19:10 -0800102
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800103 @Activate
104 public void activate() {
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800105 eventDispatcher.addSink(ApplicationEvent.class, listenerRegistry);
Thomas Vachuska8dc1a692015-03-31 01:01:37 -0700106 store.setDelegate(delegate);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800107 log.info("Started");
108 }
109
110 @Deactivate
111 public void deactivate() {
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800112 eventDispatcher.removeSink(ApplicationEvent.class);
Thomas Vachuska8dc1a692015-03-31 01:01:37 -0700113 store.unsetDelegate(delegate);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800114 log.info("Stopped");
115 }
116
117 @Override
118 public Set<Application> getApplications() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900119 checkPermission(APP_READ);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800120 return store.getApplications();
121 }
122
123 @Override
124 public ApplicationId getId(String name) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900125 checkPermission(APP_READ);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800126 checkNotNull(name, "Name cannot be null");
127 return store.getId(name);
128 }
129
130 @Override
131 public Application getApplication(ApplicationId appId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900132 checkPermission(APP_READ);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800133 checkNotNull(appId, APP_ID_NULL);
134 return store.getApplication(appId);
135 }
136
137 @Override
138 public ApplicationState getState(ApplicationId appId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900139 checkPermission(APP_READ);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800140 checkNotNull(appId, APP_ID_NULL);
141 return store.getState(appId);
142 }
143
144 @Override
145 public Set<Permission> getPermissions(ApplicationId appId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900146 checkPermission(APP_READ);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800147 checkNotNull(appId, APP_ID_NULL);
148 return store.getPermissions(appId);
149 }
150
151 @Override
Thomas Vachuskac65dd712015-11-04 17:19:10 -0800152 public void registerDeactivateHook(ApplicationId appId, Runnable hook) {
153 checkPermission(APP_READ);
154 checkNotNull(appId, APP_ID_NULL);
155 checkNotNull(hook, "Hook cannot be null");
156 deactivateHooks.put(appId.name(), hook);
157 }
158
159 @Override
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800160 public Application install(InputStream appDescStream) {
161 checkNotNull(appDescStream, "Application archive stream cannot be null");
Changhoon Yoonb856b812015-08-10 03:47:19 +0900162 Application app = store.create(appDescStream);
163 SecurityUtil.register(app.id());
164 return app;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800165 }
166
167 @Override
168 public void uninstall(ApplicationId appId) {
169 checkNotNull(appId, APP_ID_NULL);
Madan Jampania0c4bdb2016-06-17 11:02:38 -0700170 updateStoreAndWaitForNotificationHandling(appId, store::remove);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800171 }
172
173 @Override
174 public void activate(ApplicationId appId) {
175 checkNotNull(appId, APP_ID_NULL);
Changhoon Yoonb856b812015-08-10 03:47:19 +0900176 if (!SecurityUtil.isAppSecured(appId)) {
177 return;
178 }
Madan Jampania0c4bdb2016-06-17 11:02:38 -0700179 updateStoreAndWaitForNotificationHandling(appId, store::activate);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800180 }
181
182 @Override
183 public void deactivate(ApplicationId appId) {
184 checkNotNull(appId, APP_ID_NULL);
Madan Jampania0c4bdb2016-06-17 11:02:38 -0700185 updateStoreAndWaitForNotificationHandling(appId, store::deactivate);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800186 }
187
188 @Override
189 public void setPermissions(ApplicationId appId, Set<Permission> permissions) {
190 checkNotNull(appId, APP_ID_NULL);
191 checkNotNull(permissions, "Permissions cannot be null");
192 store.setPermissions(appId, permissions);
193 }
194
Thomas Vachuska08b4dec2017-08-31 15:20:17 -0700195 @Override
196 public InputStream getApplicationArchive(ApplicationId appId) {
197 checkNotNull(appId, APP_ID_NULL);
198 return store.getApplicationArchive(appId);
199 }
200
Madan Jampania0c4bdb2016-06-17 11:02:38 -0700201 private void updateStoreAndWaitForNotificationHandling(ApplicationId appId,
202 Consumer<ApplicationId> storeUpdateTask) {
203 CountDownLatch latch = new CountDownLatch(1);
204 try {
205 pendingOperations.put(appId, latch);
206 storeUpdateTask.accept(appId);
207 } catch (Exception e) {
208 pendingOperations.invalidate(appId);
209 latch.countDown();
210 log.warn("Failed to update store for {}", appId.name(), e);
211 }
212 Uninterruptibles.awaitUninterruptibly(latch, DEFAULT_OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
213 }
214
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800215 private class InternalStoreDelegate implements ApplicationStoreDelegate {
216 @Override
217 public void notify(ApplicationEvent event) {
218 ApplicationEvent.Type type = event.type();
219 Application app = event.subject();
Madan Jampania0c4bdb2016-06-17 11:02:38 -0700220 CountDownLatch latch = pendingOperations.getIfPresent(app.id());
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800221 try {
222 if (type == APP_ACTIVATED) {
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700223 if (installAppFeatures(app)) {
224 log.info("Application {} has been activated", app.id().name());
225 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800226
227 } else if (type == APP_DEACTIVATED) {
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700228 if (uninstallAppFeatures(app)) {
229 log.info("Application {} has been deactivated", app.id().name());
230 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800231
232 } else if (type == APP_INSTALLED) {
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700233 if (installAppArtifacts(app)) {
234 log.info("Application {} has been installed", app.id().name());
235 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800236
237 } else if (type == APP_UNINSTALLED) {
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700238 if (uninstallAppFeatures(app) || uninstallAppArtifacts(app)) {
239 log.info("Application {} has been uninstalled", app.id().name());
240 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800241
242 }
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700243 post(event);
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800244 } catch (Exception e) {
245 log.warn("Unable to perform operation on application " + app.id().name(), e);
Madan Jampani015d3a32016-06-16 18:25:11 -0700246 } finally {
247 if (latch != null) {
248 latch.countDown();
Madan Jampania0c4bdb2016-06-17 11:02:38 -0700249 pendingOperations.invalidate(app.id());
Madan Jampani015d3a32016-06-16 18:25:11 -0700250 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800251 }
252 }
253 }
254
Thomas Vachuska0d6af8d2015-03-23 15:54:47 -0700255 // The following methods are fully synchronized to guard against remote vs.
256 // locally induced feature service interactions.
257
Thomas Vachuska761f0042015-11-11 19:10:17 -0800258 // Installs all feature repositories required by the specified app.
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700259 private synchronized boolean installAppArtifacts(Application app) throws Exception {
260 if (app.featuresRepo().isPresent() &&
261 featuresService.getRepository(app.featuresRepo().get()) == null) {
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800262 featuresService.addRepository(app.featuresRepo().get());
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700263 return true;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800264 }
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700265 return false;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800266 }
267
Thomas Vachuska761f0042015-11-11 19:10:17 -0800268 // Uninstalls all the feature repositories required by the specified app.
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700269 private synchronized boolean uninstallAppArtifacts(Application app) throws Exception {
270 if (app.featuresRepo().isPresent() &&
271 featuresService.getRepository(app.featuresRepo().get()) != null) {
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800272 featuresService.removeRepository(app.featuresRepo().get());
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700273 return true;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800274 }
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700275 return false;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800276 }
277
Thomas Vachuska761f0042015-11-11 19:10:17 -0800278 // Installs all features that define the specified app.
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700279 private synchronized boolean installAppFeatures(Application app) throws Exception {
280 boolean changed = false;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800281 for (String name : app.features()) {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800282 Feature feature = featuresService.getFeature(name);
Thomas Vachuskab56b9172015-11-24 11:24:23 -0800283
284 // If we see an attempt at activation of a non-existent feature
285 // attempt to install the app artifacts first and then retry.
286 // This can be triggered by a race condition between different ONOS
287 // instances "installing" the apps from disk at their own pace.
288 // Perhaps there is a more elegant solution to be explored in the
289 // future.
290 if (feature == null) {
291 installAppArtifacts(app);
292 feature = featuresService.getFeature(name);
293 }
294
Thomas Vachuska62f04a42015-04-22 14:38:34 -0700295 if (feature != null && !featuresService.isInstalled(feature)) {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800296 featuresService.installFeature(name);
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700297 changed = true;
Thomas Vachuskab56b9172015-11-24 11:24:23 -0800298 } else if (feature == null) {
Thomas Vachuska62f04a42015-04-22 14:38:34 -0700299 log.warn("Feature {} not found", name);
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800300 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800301 }
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700302 return changed;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800303 }
304
Thomas Vachuska761f0042015-11-11 19:10:17 -0800305 // Uninstalls all features that define the specified app.
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700306 private synchronized boolean uninstallAppFeatures(Application app) throws Exception {
307 boolean changed = false;
Jonathan Hartc32585f2016-06-16 14:01:27 -0700308 deactivateHooks.removeAll(app.id().name()).forEach(hook -> invokeHook(hook, app.id()));
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800309 for (String name : app.features()) {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800310 Feature feature = featuresService.getFeature(name);
Thomas Vachuska62f04a42015-04-22 14:38:34 -0700311 if (feature != null && featuresService.isInstalled(feature)) {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800312 featuresService.uninstallFeature(name);
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700313 changed = true;
Thomas Vachuska62f04a42015-04-22 14:38:34 -0700314 } else if (feature == null) {
315 log.warn("Feature {} not found", name);
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800316 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800317 }
Thomas Vachuska9ff88a92015-05-13 13:57:18 -0700318 return changed;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800319 }
320
Thomas Vachuskac65dd712015-11-04 17:19:10 -0800321 // Invokes the specified function, if not null.
Arnav Jainefb57e52019-07-09 14:24:10 -0700322 @java.lang.SuppressWarnings("squid:S1217")
323 // We really do mean to call run()
Thomas Vachuskac65dd712015-11-04 17:19:10 -0800324 private void invokeHook(Runnable hook, ApplicationId appId) {
325 if (hook != null) {
326 try {
327 hook.run();
328 } catch (Exception e) {
329 log.warn("Deactivate hook for application {} encountered an error",
330 appId.name(), e);
331 }
332 }
333 }
334
Arnav Jainefb57e52019-07-09 14:24:10 -0700335 @Override
336 public Set<Application> getRegisteredApplications() {
337 ImmutableSet.Builder<Application> builder = ImmutableSet.builder();
338 ObjectMapper mapper = new ObjectMapper();
339
340 // Get input stream from the URL
341 try {
342 URL githubUrl = new URL(APP_REGISTRY_URL + "?onosVersion=" + versionService.version().toString());
343 HttpURLConnection githubHttp = (HttpURLConnection) githubUrl.openConnection();
344 InputStream githubStream = githubHttp.getInputStream();
345
346 // Read input stream into an ArrayNode
347 ArrayNode rootTree = (ArrayNode) mapper.readTree(githubStream);
348
349 // Iterate over the array node for each object add each version as application object to the set
350 rootTree.forEach(n -> {
351 mapObject(builder, (ObjectNode) n);
352 });
353
354 //Iterate through Builder to remove unnecessary apps
355 Set<Application> apps = builder.build();
356
357 return apps;
358 } catch (MalformedURLException e) {
359 throw new IllegalStateException("Bad URL " + APP_REGISTRY_URL, e);
360 } catch (IOException e) {
361 throw new IllegalStateException("Unable to fetch URL " + APP_REGISTRY_URL, e);
362 }
363 }
364
365 private void mapObject(ImmutableSet.Builder<Application> apps, ObjectNode node) {
366 String appIDs = node.get("id").asText();
367 ApplicationId appID = new DefaultApplicationId(1, appIDs);
368 String title = node.get("title").asText();
369 String readme = node.get("readme").asText();
370 String category = node.get("category").asText();
371 String url = node.get("url").asText();
372 String origin = node.get("maintainer").asText();
373 JsonNode it = node.get("versions");
374 Iterator iterate = it.iterator();
375 while (iterate.hasNext()) {
376 DefaultApplication.Builder app = new DefaultApplication.Builder();
377 JsonNode jsonNode = (JsonNode) iterate.next();
378 URL imageUrl = null;
379 try {
380 imageUrl = new URL(jsonNode.get("oarURL").asText());
381 } catch (MalformedURLException e) {
382 e.printStackTrace();
383 }
384 Version version1 = Version.version(jsonNode.get("onosVersion").asText());
385 app.withImageUrl(imageUrl)
386 .withAppId(new DefaultApplicationId(1, node.get("id").asText()))
387 .withVersion(version1)
388 .withAppId(appID)
389 .withReadme(readme)
390 .withDescription(readme)
391 .withTitle(title)
392 .withFeatures(ImmutableList.of("none"))
393 .withCategory(category)
394 .withUrl(url)
395 .withOrigin(origin);
396 apps.add(app.build());
397 }
398 }
399}