@Override public void refreshPackages() { FrameworkWiring wiring = felix.adapt(FrameworkWiring.class); final CountDownLatch latch = new CountDownLatch(1); wiring.refreshBundles(null, event -> { switch (event.getType()) { case FrameworkEvent.PACKAGES_REFRESHED: latch.countDown(); break; case FrameworkEvent.ERROR: log.log(Level.SEVERE, "ERROR FrameworkEvent received.", event.getThrowable()); break; } }); try { long TIMEOUT_SECONDS = 60L; if (!latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { log.warning("No PACKAGES_REFRESHED FrameworkEvent received within " + TIMEOUT_SECONDS + " seconds of calling FrameworkWiring.refreshBundles()"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
@Override public void start(BundleContext context) throws Exception { // keep track of the boot modules that should be installed Set<String> bootModuleLocations = new HashSet<>(); // make sure all boot modules are installed Set<Module> bootModules = new TreeSet<Module>((m1, m2) ->{return m1.getName().compareTo(m2.getName());}); bootModules.addAll(ModuleLayer.boot().modules()); for (Module module : bootModules) { bootModuleLocations.add(installBootModule(module, context)); } Set<Bundle> refresh = new HashSet<>(); for (Bundle b : context.getBundles()) { String bLoc = b.getLocation(); if (bLoc.startsWith(bootModuleLocationPrefix) && !bootModuleLocations.contains(b.getLocation())) { // something changed in VM configuration since last start; // must uninstall this boot module b.uninstall(); refresh.add(b); } } if (!refresh.isEmpty()) { CountDownLatch latch = new CountDownLatch(1); context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).adapt(FrameworkWiring.class).refreshBundles(refresh, (e) -> latch.countDown()); latch.await(10, TimeUnit.SECONDS); } }
public LayerFactoryImpl(Activator activator, BundleContext context, Module systemModule) { String layerTypeProp = context.getProperty("osgi.jpms.layer.type"); this.layerType = layerTypeProp == null ? LayerType.OneBundlePerLayerWithHierarchy : LayerType.valueOf(layerTypeProp); this.activator = activator; this.context = context; this.systemModule = systemModule; long startTime = System.nanoTime(); privatesCache = loadPrivatesCache(context, activator); System.out.println("Time loadPrivatesCache: " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startTime), TimeUnit.NANOSECONDS)); Bundle systemBundle = context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION); fwkWiring = systemBundle.adapt(FrameworkWiring.class); ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); layersWrite = lock.writeLock(); layersRead = lock.readLock(); BundleWiring systemWiring = systemBundle.adapt(BundleWiring.class); addToResolutionGraph(Collections.singleton(systemWiring)); wiringToModule.put(systemWiring, systemModule); }
private void refreshBundles(List<Bundle> bundles, SchemaHolder schemaHolder) { if (LOGGER.isInfoEnabled()) { for (Bundle bundle : bundles) { LOGGER.info("Refreshing wiring for bundle {}", bundle.getSymbolicName()); } } // we generate the entities bundle but not start it to avoid exceptions when the framework // will refresh bundles jarGeneratorService.regenerateMdsDataBundle(schemaHolder, false); FrameworkWiring framework = bundleContext.getBundle(0).adapt(FrameworkWiring.class); framework.refreshBundles(bundles); // give the framework 3 seconds to do a refresh ThreadSuspender.sleep(3000); // after refreshing all bundles we can start the entities bundle monitor.start(); }
private void clearModulesCache(String[] moduleNames) { for (String moduleName : moduleNames) { if (StringUtils.isNotBlank(moduleName)) { Bundle bundleToRefresh = WebBundleUtil.findBundleBySymbolicName(bundleContext, moduleName); Bundle frameworkBundle = bundleContext.getBundle(0); FrameworkWiring frameworkWiring = frameworkBundle.adapt(FrameworkWiring.class); Collection<Bundle> dependencyClosureBundles = frameworkWiring.getDependencyClosure(Arrays.asList(bundleToRefresh)); for (Bundle bundle : dependencyClosureBundles) { MdsBundleHelper.unregisterBundleJDOClasses(bundle); } } } ResourceBundle.clearCache(); }
public List<Long> getDependencyClosure(List<Long> bundleIds) { Bundle fw = m_bundleResourcesMap.get(0L).getBundle(); FrameworkWiring fwiring = fw.adapt(FrameworkWiring.class); List<Bundle> bundles = new ArrayList<Bundle>(); for (long bundleId : bundleIds) { Bundle bundle = m_bundleResourcesMap.get(bundleId).getBundle(); if (bundle != null) { bundles.add(bundle); } } Collection<Bundle> dependencyClosure = fwiring.getDependencyClosure(bundles); List<Long> dependencyClosureBundles = new ArrayList<Long>(); for (Bundle b : dependencyClosure) { dependencyClosureBundles.add(b.getBundleId()); } return dependencyClosureBundles; }
@Before public void setUp() { m_everest = new Everest(); // Create a fake bundle context. Bundle zero = mock(Bundle.class, RETURNS_MOCKS); BundleContext context = mock(BundleContext.class, RETURNS_MOCKS); when(zero.getBundleContext()).thenReturn(context); when(context.getBundle(0)).thenReturn(zero); when(context.getProperty(anyString())).thenReturn("Some Property"); when(zero.adapt(FrameworkWiring.class)).thenReturn(mock(FrameworkWiring.class)); when(zero.adapt(FrameworkStartLevel.class)).thenReturn(mock(FrameworkStartLevel.class)); m_osgi = new OsgiRootResource(context); m_everest.bindRootResource(m_osgi); }
public UpgradeProcess(final UpgradeServiceImpl bundleDeployerService, final BundleContext systemBundleContext) { this.bundleDeployerService = bundleDeployerService; this.systemBundleContext = systemBundleContext; // Refresh classes must be initialized first because they will be not available if the richconsole re-deploys // itself final AtomicBoolean refreshFinished = new AtomicBoolean(false); Lock refreshFinishLock = new ReentrantLock(); Condition refreshFinishCondition = refreshFinishLock.newCondition(); refreshListener = new FrameworkRefreshListener(refreshFinished, refreshFinishLock, refreshFinishCondition); Bundle systemBundle = systemBundleContext.getBundle(); frameworkWiring = systemBundle.adapt(FrameworkWiring.class); frameworkStartLevel = systemBundle.adapt(FrameworkStartLevel.class); originalFrameworkStartLevelValue = frameworkStartLevel.getStartLevel(); currentFrameworkStartLevelValue = originalFrameworkStartLevelValue; }
/** * Refreshes bundles using FrameworkWiring and current Bundle (<a * href="https://mail.osgi.org/pipermail/osgi-dev/2014-June/004459.html">reference</a>). */ public static void refreshBundles() { log.trace("Refreshing bundles..."); Bundle currentBundle = FrameworkUtil.getBundle(BundleUtils.class); if (currentBundle == null) { log.error("Could not obtain current bundle! Not refreshing Bundles."); return; } BundleContext bundleContext = currentBundle.getBundleContext(); if (bundleContext == null) { log.error("Could not obtain bundle context! Not refreshing Bundles."); return; } Bundle systemBundle = bundleContext.getBundle(0); if (systemBundle == null) { log.error("Could not obtain system bundle! Not refreshing Bundles."); return; } FrameworkWiring frameworkWiring = systemBundle.adapt(FrameworkWiring.class); if (frameworkWiring == null) { log.error("Could not obtain FrameworkWiring from system bundle! Not refreshing Bundles."); return; } frameworkWiring.refreshBundles(null); }
@Override public <A> A adaptTo(Class<A> clazz) { if (Bundle.class.equals(clazz)) { return (A) m_frameworkBundle; } else if (FrameworkWiring.class.equals(clazz)) { return (A) m_frameworkBundle.adapt(FrameworkWiring.class); } else if (FrameworkStartLevel.class.equals(clazz)) { return (A) m_frameworkBundle.adapt(FrameworkStartLevel.class); } else { return null; } }
public void refreshBundles(List<Long> bundleIds) { Bundle fw = m_bundleResourcesMap.get(0L).getBundle(); FrameworkWiring fwiring = fw.adapt(FrameworkWiring.class); List<Bundle> bundlesToRefresh = new ArrayList<Bundle>(); for (Long bundleId : bundleIds) { Bundle bundle = fw.getBundleContext().getBundle(bundleId); if (bundle != null) { bundlesToRefresh.add(bundle); } } fwiring.refreshBundles(bundlesToRefresh); }
public boolean resolveBundles(List<Long> bundleIds) { Bundle fw = m_bundleResourcesMap.get(0L).getBundle(); FrameworkWiring fwiring = fw.adapt(FrameworkWiring.class); List<Bundle> bundlesToResolve = new ArrayList<Bundle>(); for (Long bundleId : bundleIds) { Bundle bundle = fw.getBundleContext().getBundle(bundleId); if (bundle != null) { bundlesToResolve.add(bundle); } } return fwiring.resolveBundles(bundlesToResolve); }
@Deployment public static JavaArchive create() { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "refresh-test"); archive.addClasses(OSGiTestHelper.class); archive.setManifest(new Asset() { public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleSymbolicName(archive.getName()); builder.addBundleManifestVersion(2); builder.addImportPackages(OSGiRuntimeLocator.class, Runtime.class, Resource.class, FrameworkWiring.class); return builder.openStream(); } }); return archive; }
private void updateDependenciesState(Map<MavenArtifact, ArtifactLoader> artifact2loader, Set<PluginDescription> toInstall, Set<PluginDescription> toUninstall) { Objects.requireNonNull(artifact2loader); Objects.requireNonNull(toInstall); Objects.requireNonNull(toUninstall); LOGGER.fine(format("Update state: toInstall=%s, toUninstall=%s", toInstall, toUninstall)); IllegalStateException startExCollection = null; try { synchronized (lock) { try { performActions(computeActions(toInstall, toUninstall), artifact2loader); checkDependenciesState(); } finally { FrameworkWiring frameworkWiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class); CountDownLatch latch = new CountDownLatch(1); frameworkWiring.refreshBundles(null, event -> latch.countDown()); latch.await(); Set<Bundle> bundles = bundle2artifact.keySet(); frameworkWiring.resolveBundles(bundles); for (Bundle bundle : bundles) { if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING && (bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) == 0) { try { bundle.start(Bundle.START_ACTIVATION_POLICY); } catch (Throwable exStart) { LOGGER.log(Level.WARNING, format("Bundle %s couldn't start", bundle), exStart); if (startExCollection == null) startExCollection = new IllegalStateException("One or more bundles couldn't start"); startExCollection.addSuppressed(exStart); } } } } } } catch (Throwable ex) { LOGGER.log(Level.SEVERE, "Couldn't finish updating dependencies state", ex); IllegalStateException exToThrow = new IllegalStateException("Couldn't finish updating dependencies state", ex); if (startExCollection != null) exToThrow.addSuppressed(startExCollection); throw exToThrow; } if (startExCollection != null) throw startExCollection; }
@Override public void start(BundleContext context) throws Exception { try { LayerFactory factory = context.getService(context.getServiceReference(LayerFactory.class)); testBundleLayer(factory, context); Collection<Bundle> toRefresh = new ArrayList<>(); for (Bundle b : context.getBundles()) { if (b.getSymbolicName().startsWith("bundle.test.")) { toRefresh.add(b); } } // refresh the test bundles and test another layer CountDownLatch refreshed = new CountDownLatch(1); context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).adapt(FrameworkWiring.class).refreshBundles(toRefresh, (event) ->{ refreshed.countDown(); }); refreshed.await(); testBundleLayer(factory, context); Bundle aTest = context.installBundle("reference:file:" + context.getProperty("jpms.mods.path") + "/" + "jpms.test.a.jar"); aTest.start(); Module aModule = factory.getModules().get(aTest); System.out.println("JPMS Test module as a bundle."); tryUseFunctions(aModule.getLayer()); aTest.uninstall(); } catch (Throwable t) { t.printStackTrace(); } // shutdown framework at end of test new Thread(() -> { try { Thread.sleep(1000); //context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).stop(); } catch (Exception e) { } }).start(); }
/** * Constructor for Osgi root resource * * @param context bundle context of the everest-osgi bundle */ public OsgiRootResource(BundleContext context) { super(OSGI_ROOT, OSGI_DESCRIPTION); m_context = context; // Initialize subresource managers m_bundleResourceManager = BundleResourceManager.getInstance(); m_packageResourceManager = PackageResourceManager.getInstance(); m_serviceResourceManager = ServiceResourceManager.getInstance(); m_frameworkBundle = m_context.getBundle(0); FrameworkWiring fwiring = m_frameworkBundle.adapt(FrameworkWiring.class); BundleContext fwContext = m_frameworkBundle.getBundleContext(); // Construct static framework metadata ImmutableResourceMetadata.Builder metadataBuilder = new ImmutableResourceMetadata.Builder(super.getMetadata()); //TODO take some metadata from the framework metadataBuilder.set(Constants.FRAMEWORK_VERSION, fwContext.getProperty(Constants.FRAMEWORK_VERSION)); metadataBuilder.set(Constants.FRAMEWORK_VENDOR, fwContext.getProperty(Constants.FRAMEWORK_VENDOR)); metadataBuilder.set(Constants.FRAMEWORK_LANGUAGE, fwContext.getProperty(Constants.FRAMEWORK_LANGUAGE)); metadataBuilder.set(Constants.FRAMEWORK_PROCESSOR, fwContext.getProperty(Constants.FRAMEWORK_PROCESSOR)); metadataBuilder.set(Constants.FRAMEWORK_OS_NAME, fwContext.getProperty(Constants.FRAMEWORK_OS_NAME)); metadataBuilder.set(Constants.FRAMEWORK_OS_VERSION, fwContext.getProperty(Constants.FRAMEWORK_OS_VERSION)); metadataBuilder.set(Constants.FRAMEWORK_UUID, fwContext.getProperty(Constants.FRAMEWORK_UUID)); metadataBuilder.set(Constants.SUPPORTS_FRAMEWORK_EXTENSION, fwContext.getProperty(Constants.SUPPORTS_FRAMEWORK_EXTENSION)); metadataBuilder.set(Constants.SUPPORTS_FRAMEWORK_FRAGMENT, fwContext.getProperty(Constants.SUPPORTS_FRAMEWORK_FRAGMENT)); metadataBuilder.set(Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE, fwContext.getProperty(Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE)); metadataBuilder.set(Constants.SUPPORTS_BOOTCLASSPATH_EXTENSION, fwContext.getProperty(Constants.SUPPORTS_BOOTCLASSPATH_EXTENSION)); metadataBuilder.set(Constants.FRAMEWORK_BOOTDELEGATION, fwContext.getProperty(Constants.FRAMEWORK_BOOTDELEGATION)); metadataBuilder.set(Constants.FRAMEWORK_SYSTEMPACKAGES, fwContext.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES)); metadataBuilder.set(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, fwContext.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA)); m_metadata = metadataBuilder.build(); // Initialize bundle & service trackers int stateMask = Bundle.ACTIVE | Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING; Filter allServicesFilter = null; try { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(Constants.OBJECTCLASS); sb.append("=*)"); allServicesFilter = FrameworkUtil.createFilter(sb.toString()); } catch (InvalidSyntaxException e) { // Should never happen throw new RuntimeException(e.getMessage()); } m_configAdminTracker = new ServiceTracker(m_context, ConfigAdminTracker.clazz, new ConfigAdminTracker(this)); m_deploymentAdminTracker = new ServiceTracker(m_context, DeploymentAdminTracker.clazz,new DeploymentAdminTracker(this)); m_bundleTracker = new BundleTracker(m_context, stateMask, this); m_serviceTracker = new ServiceTracker(m_context, allServicesFilter, this); m_relations = new ArrayList<Relation>(); m_relations.add(new DefaultRelation(getPath(), Action.DELETE, FRAMEWORK_STOP_RELATION, "Stops the osgi framework")); m_relations.add(new DefaultRelation(getPath(), Action.UPDATE, FRAMEWORK_UPDATE_RELATION, "updates start level", new DefaultParameter() .name(STARTLEVEL_BUNDLE_PARAMETER) .description(STARTLEVEL_BUNDLE_PARAMETER) .type(Integer.class) .optional(true), new DefaultParameter() .name(STARTLEVEL_PARAMETER) .description(STARTLEVEL_PARAMETER) .type(Integer.class) .optional(true))); m_relations.add(new DefaultRelation(getPath(), Action.UPDATE, FRAMEWORK_RESTART_RELATION, "Restarts the osgi framework", new DefaultParameter() .name(FRAMEWORK_RESTART_PARAMETER) .description(FRAMEWORK_RESTART_PARAMETER) .type(Boolean.class) .optional(true))); }
private Framework startOSGiContainer(final String[] bundleLocations, final String tempDirPath) throws BundleException { FrameworkFactory frameworkFactory = ServiceLoader .load(FrameworkFactory.class).iterator().next(); Map<String, String> config = new HashMap<String, String>(); config.put("org.osgi.framework.system.packages", ""); config.put("osgi.configuration.area", tempDirPath); config.put("osgi.baseConfiguration.area", tempDirPath); config.put("osgi.sharedConfiguration.area", tempDirPath); config.put("osgi.instance.area", tempDirPath); config.put("osgi.user.area", tempDirPath); config.put("osgi.hook.configurators.exclude", "org.eclipse.core.runtime.internal.adaptor.EclipseLogHook"); Framework framework = frameworkFactory.newFramework(config); framework.init(); BundleContext systemBundleContext = framework.getBundleContext(); org.apache.maven.artifact.Artifact equinoxCompatibilityStateArtifact = pluginArtifactMap.get("org.eclipse.tycho:org.eclipse.osgi.compatibility.state"); URI compatibilityBundleURI = equinoxCompatibilityStateArtifact.getFile().toURI(); systemBundleContext.installBundle("reference:" + compatibilityBundleURI.toString()); framework.start(); for (String bundleLocation : bundleLocations) { try { systemBundleContext.installBundle(bundleLocation); } catch (BundleException e) { getLog().warn("Could not install bundle " + bundleLocation, e); } } FrameworkWiring frameworkWiring = framework .adapt(FrameworkWiring.class); frameworkWiring.resolveBundles(null); return framework; }