001/*
002 * (C) Copyright 2006-2017 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *     Kevin Leturc <kleturc@nuxeo.com>
019 */
020package org.nuxeo.runtime.api;
021
022import java.io.File;
023import java.io.IOException;
024import java.net.MalformedURLException;
025import java.net.URL;
026import java.nio.file.Files;
027import java.nio.file.Path;
028import java.nio.file.attribute.FileAttribute;
029import java.util.List;
030import java.util.Properties;
031import java.util.function.Supplier;
032
033import javax.security.auth.callback.CallbackHandler;
034import javax.security.auth.login.LoginContext;
035import javax.security.auth.login.LoginException;
036
037import org.apache.commons.io.FileDeleteStrategy;
038import org.apache.commons.lang3.StringUtils;
039import org.apache.commons.logging.Log;
040import org.apache.commons.logging.LogFactory;
041import org.nuxeo.common.Environment;
042import org.nuxeo.common.collections.ListenerList;
043import org.nuxeo.runtime.RuntimeService;
044import org.nuxeo.runtime.RuntimeServiceEvent;
045import org.nuxeo.runtime.RuntimeServiceException;
046import org.nuxeo.runtime.RuntimeServiceListener;
047import org.nuxeo.runtime.api.login.LoginAs;
048import org.nuxeo.runtime.api.login.LoginService;
049import org.nuxeo.runtime.trackers.files.FileEvent;
050import org.nuxeo.runtime.trackers.files.FileEventTracker;
051
052/**
053 * This class is the main entry point to a Nuxeo runtime application.
054 * <p>
055 * It offers an easy way to create new sessions, to access system services and other resources.
056 * <p>
057 * There are two type of services:
058 * <ul>
059 * <li>Global Services - these services are uniquely defined by a service class, and there is an unique instance of the
060 * service in the system per class.
061 * <li>Local Services - these services are defined by a class and an URI. This type of service allows multiple service
062 * instances for the same class of services. Each instance is uniquely defined in the system by an URI.
063 * </ul>
064 *
065 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
066 */
067public final class Framework {
068
069    private static final Log log = LogFactory.getLog(Framework.class);
070
071    private static Boolean testModeSet;
072
073    /**
074     * Global dev property
075     *
076     * @since 5.6
077     * @see #isDevModeSet()
078     */
079    public static final String NUXEO_DEV_SYSTEM_PROP = "org.nuxeo.dev";
080
081    /**
082     * Global testing property
083     *
084     * @since 5.6
085     * @see #isTestModeSet()
086     */
087    public static final String NUXEO_TESTING_SYSTEM_PROP = "org.nuxeo.runtime.testing";
088
089    /**
090     * Property to control strict runtime mode
091     *
092     * @since 5.6
093     * @see #handleDevError(Throwable)
094     * @deprecated since 9.1 This property is not documented and doesn't work.
095     */
096    @Deprecated
097    public static final String NUXEO_STRICT_RUNTIME_SYSTEM_PROP = "org.nuxeo.runtime.strict";
098
099    /**
100     * The runtime instance.
101     */
102    private static RuntimeService runtime;
103
104    private static final ListenerList listeners = new ListenerList();
105
106    /**
107     * A class loader used to share resources between all bundles.
108     * <p>
109     * This is useful to put resources outside any bundle (in a directory on the file system) and then refer them from
110     * XML contributions.
111     * <p>
112     * The resource directory used by this loader is ${nuxeo_data_dir}/resources whee ${nuxeo_data_dir} is usually
113     * ${nuxeo_home}/data
114     */
115    protected static SharedResourceLoader resourceLoader;
116
117    /**
118     * Whether or not services should be exported as OSGI services. This is controlled by the ${ecr.osgi.services}
119     * property. The default is false.
120     */
121    protected static Boolean isOSGiServiceSupported;
122
123    // Utility class.
124    private Framework() {
125    }
126
127    public static void initialize(RuntimeService runtimeService) {
128        if (runtime != null) {
129            throw new RuntimeServiceException("Nuxeo Framework was already initialized");
130        }
131        runtime = runtimeService;
132        reloadResourceLoader();
133        runtime.start();
134    }
135
136    public static void reloadResourceLoader() {
137        File rs = new File(Environment.getDefault().getData(), "resources");
138        rs.mkdirs();
139        URL url;
140        try {
141            url = rs.toURI().toURL();
142        } catch (MalformedURLException e) {
143            throw new RuntimeServiceException(e);
144        }
145        resourceLoader = new SharedResourceLoader(new URL[] { url }, Framework.class.getClassLoader());
146    }
147
148    /**
149     * Reload the resources loader, keeping URLs already tracked, and adding possibility to add or remove some URLs.
150     * <p>
151     * Useful for hot reload of jars.
152     *
153     * @since 5.6
154     */
155    public static void reloadResourceLoader(List<URL> urlsToAdd, List<URL> urlsToRemove) {
156        File rs = new File(Environment.getDefault().getData(), "resources");
157        rs.mkdirs();
158        URL[] existing = null;
159        if (resourceLoader != null) {
160            existing = resourceLoader.getURLs();
161        }
162        // reinit
163        URL url;
164        try {
165            url = rs.toURI().toURL();
166        } catch (MalformedURLException e) {
167            throw new RuntimeException(e);
168        }
169        resourceLoader = new SharedResourceLoader(new URL[] { url }, Framework.class.getClassLoader());
170        // add back existing urls unless they should be removed, and add new
171        // urls
172        if (existing != null) {
173            for (URL oldURL : existing) {
174                if (urlsToRemove == null || !urlsToRemove.contains(oldURL)) {
175                    resourceLoader.addURL(oldURL);
176                }
177            }
178        }
179        if (urlsToAdd != null) {
180            for (URL newURL : urlsToAdd) {
181                resourceLoader.addURL(newURL);
182            }
183        }
184    }
185
186    public static void shutdown() throws InterruptedException {
187        if (runtime == null) {
188            throw new IllegalStateException("runtime not exist");
189        }
190        try {
191            runtime.stop();
192        } finally {
193            runtime = null;
194        }
195    }
196
197    /**
198     * Tests whether or not the runtime was initialized.
199     *
200     * @return true if the runtime was initialized, false otherwise
201     */
202    public static synchronized boolean isInitialized() {
203        return runtime != null;
204    }
205
206    public static SharedResourceLoader getResourceLoader() {
207        return resourceLoader;
208    }
209
210    /**
211     * Gets the runtime service instance.
212     *
213     * @return the runtime service instance
214     */
215    public static RuntimeService getRuntime() {
216        return runtime;
217    }
218
219    /**
220     * Gets a service given its class.
221     */
222    public static <T> T getService(Class<T> serviceClass) {
223        ServiceProvider provider = DefaultServiceProvider.getProvider();
224        if (provider != null) {
225            return provider.getService(serviceClass);
226        }
227        checkRuntimeInitialized();
228        // TODO impl a runtime service provider
229        return runtime.getService(serviceClass);
230    }
231
232    /**
233     * Gets a service given its class.
234     *
235     * @deprecated since 9.10, use {@link #getService} instead
236     */
237    @Deprecated
238    public static <T> T getLocalService(Class<T> serviceClass) {
239        return getService(serviceClass);
240    }
241
242    /**
243     * Lookup a registered object given its key.
244     */
245    public static Object lookup(String key) {
246        return null; // TODO
247    }
248
249    /**
250     * Runs the given {@link Runnable} while logged in as a system user.
251     *
252     * @param runnable what to run
253     * @since 8.4
254     */
255    public static void doPrivileged(Runnable runnable) {
256        try {
257            LoginContext loginContext = login();
258            try {
259                runnable.run();
260            } finally {
261                if (loginContext != null) { // may be null in tests
262                    loginContext.logout();
263                }
264            }
265        } catch (LoginException e) {
266            throw new RuntimeException(e);
267        }
268    }
269
270    /**
271     * Calls the given {@link Supplier} while logged in as a system user and returns its result.
272     *
273     * @param supplier what to call
274     * @return the supplier's result
275     * @since 8.4
276     */
277    public static <T> T doPrivileged(Supplier<T> supplier) {
278        try {
279            LoginContext loginContext = login();
280            try {
281                return supplier.get();
282            } finally {
283                if (loginContext != null) { // may be null in tests
284                    loginContext.logout();
285                }
286            }
287        } catch (LoginException e) {
288            throw new RuntimeException(e);
289        }
290    }
291
292    /**
293     * Login in the system as the system user (a pseudo-user having all privileges).
294     *
295     * @return the login session if successful. Never returns null.
296     * @throws LoginException on login failure
297     */
298    public static LoginContext login() throws LoginException {
299        checkRuntimeInitialized();
300        LoginService loginService = runtime.getService(LoginService.class);
301        if (loginService != null) {
302            return loginService.login();
303        }
304        return null;
305    }
306
307    /**
308     * Login in the system as the system user (a pseudo-user having all privileges). The given username will be used to
309     * identify the user id that called this method.
310     *
311     * @param username the originating user id
312     * @return the login session if successful. Never returns null.
313     * @throws LoginException on login failure
314     */
315    public static LoginContext loginAs(String username) throws LoginException {
316        checkRuntimeInitialized();
317        LoginService loginService = runtime.getService(LoginService.class);
318        if (loginService != null) {
319            return loginService.loginAs(username);
320        }
321        return null;
322    }
323
324    /**
325     * Login in the system as the given user without checking the password.
326     *
327     * @param username the user name to login as.
328     * @return the login context
329     * @throws LoginException if any error occurs
330     * @since 5.4.2
331     */
332    public static LoginContext loginAsUser(String username) throws LoginException {
333        return getService(LoginAs.class).loginAs(username);
334    }
335
336    /**
337     * Login in the system as the given user using the given password.
338     *
339     * @param username the username to login
340     * @param password the password
341     * @return a login session if login was successful. Never returns null.
342     * @throws LoginException if login failed
343     */
344    public static LoginContext login(String username, Object password) throws LoginException {
345        checkRuntimeInitialized();
346        LoginService loginService = runtime.getService(LoginService.class);
347        if (loginService != null) {
348            return loginService.login(username, password);
349        }
350        return null;
351    }
352
353    /**
354     * Login in the system using the given callback handler for login info resolution.
355     *
356     * @param cbHandler used to fetch the login info
357     * @return the login context
358     * @throws LoginException
359     */
360    public static LoginContext login(CallbackHandler cbHandler) throws LoginException {
361        checkRuntimeInitialized();
362        LoginService loginService = runtime.getService(LoginService.class);
363        if (loginService != null) {
364            return loginService.login(cbHandler);
365        }
366        return null;
367    }
368
369    public static void sendEvent(RuntimeServiceEvent event) {
370        Object[] listenersArray = listeners.getListeners();
371        for (Object listener : listenersArray) {
372            ((RuntimeServiceListener) listener).handleEvent(event);
373        }
374    }
375
376    /**
377     * Registers a listener to be notified about runtime events.
378     * <p>
379     * If the listener is already registered, do nothing.
380     *
381     * @param listener the listener to register
382     */
383    public static void addListener(RuntimeServiceListener listener) {
384        listeners.add(listener);
385    }
386
387    /**
388     * Removes the given listener.
389     * <p>
390     * If the listener is not registered, do nothing.
391     *
392     * @param listener the listener to remove
393     */
394    public static void removeListener(RuntimeServiceListener listener) {
395        listeners.remove(listener);
396    }
397
398    /**
399     * Gets the given property value if any, otherwise null.
400     * <p>
401     * The framework properties will be searched first then if any matching property is found the system properties are
402     * searched too.
403     *
404     * @param key the property key
405     * @return the property value if any or null otherwise
406     */
407    public static String getProperty(String key) {
408        return getProperty(key, null);
409    }
410
411    /**
412     * Gets the given property value if any, otherwise returns the given default value.
413     * <p>
414     * The framework properties will be searched first then if any matching property is found the system properties are
415     * searched too.
416     *
417     * @param key the property key
418     * @param defValue the default value to use
419     * @return the property value if any otherwise the default value
420     */
421    public static String getProperty(String key, String defValue) {
422        checkRuntimeInitialized();
423        return runtime.getProperty(key, defValue);
424    }
425
426    /**
427     * Gets all the framework properties. The system properties are not included in the returned map.
428     *
429     * @return the framework properties map. Never returns null.
430     */
431    public static Properties getProperties() {
432        checkRuntimeInitialized();
433        return runtime.getProperties();
434    }
435
436    /**
437     * Expands any variable found in the given expression with the value of the corresponding framework property.
438     * <p>
439     * The variable format is ${property_key}.
440     * <p>
441     * System properties are also expanded.
442     */
443    public static String expandVars(String expression) {
444        checkRuntimeInitialized();
445        return runtime.expandVars(expression);
446    }
447
448    public static boolean isOSGiServiceSupported() {
449        if (isOSGiServiceSupported == null) {
450            isOSGiServiceSupported = Boolean.valueOf(isBooleanPropertyTrue("ecr.osgi.services"));
451        }
452        return isOSGiServiceSupported.booleanValue();
453    }
454
455    /**
456     * Returns true if dev mode is set.
457     * <p>
458     * Activating this mode, some of the code may not behave as it would in production, to ease up debugging and working
459     * on developing the application.
460     * <p>
461     * For instance, it'll enable hot-reload if some packages are installed while the framework is running. It will also
462     * reset some caches when that happens.
463     */
464    public static boolean isDevModeSet() {
465        return isBooleanPropertyTrue(NUXEO_DEV_SYSTEM_PROP);
466    }
467
468    /**
469     * Returns true if test mode is set.
470     * <p>
471     * Activating this mode, some of the code may not behave as it would in production, to ease up testing.
472     */
473    public static boolean isTestModeSet() {
474        if (testModeSet == null) {
475            testModeSet = isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP);
476        }
477        return testModeSet;
478    }
479
480    /**
481     * Returns true if given property is false when compared to a boolean value. Returns false if given property in
482     * unset.
483     * <p>
484     * Checks for the system properties if property is not found in the runtime properties.
485     *
486     * @since 5.8
487     */
488    public static boolean isBooleanPropertyFalse(String propName) {
489        String v = getProperty(propName);
490        if (v == null) {
491            v = System.getProperty(propName);
492        }
493        if (StringUtils.isBlank(v)) {
494            return false;
495        }
496        return !Boolean.parseBoolean(v);
497    }
498
499    /**
500     * Returns true if given property is true when compared to a boolean value.
501     * <p>
502     * Checks for the system properties if property is not found in the runtime properties.
503     *
504     * @since 5.6
505     */
506    public static boolean isBooleanPropertyTrue(String propName) {
507        String v = getProperty(propName);
508        if (v == null) {
509            v = System.getProperty(propName);
510        }
511        return Boolean.parseBoolean(v);
512    }
513
514    /**
515     * Since 5.6, this method stops the application if property {@link #NUXEO_STRICT_RUNTIME_SYSTEM_PROP} is set to
516     * true, and one of the following errors occurred during startup.
517     * <ul>
518     * <li>Component XML parse error.
519     * <li>Contribution to an unknown extension point.
520     * <li>Component with an unknown implementation class (the implementation entry exists in the XML descriptor but
521     * cannot be resolved to a class).
522     * <li>Uncatched exception on extension registration / unregistration (either in framework or user component code)
523     * <li>Uncatched exception on component activation / deactivation (either in framework or user component code)
524     * <li>Broken Nuxeo-Component MANIFEST entry. (i.e. the entry cannot be resolved to a resource)
525     * </ul>
526     * <p>
527     * Before 5.6, this method stopped the application if development mode was enabled (i.e. org.nuxeo.dev system
528     * property is set) but this is not the case anymore to handle a dev mode that does not stop the runtime framework
529     * when using hot reload.
530     *
531     * @param t the exception or null if none
532     * @deprecated since 9.1 DON'T USE THIS METHOD ANYMORE, its behavior is not documented. It also seems to not work.
533     *             If you want to stop server startup add error messages to {@link RuntimeService#getMessageHandler()}.
534     */
535    @Deprecated
536    public static void handleDevError(Throwable t) {
537        if (isBooleanPropertyTrue(NUXEO_STRICT_RUNTIME_SYSTEM_PROP)) {
538            System.err.println("Fatal error caught in strict runtime mode => exiting.");
539            if (t != null) {
540                t.printStackTrace();
541            }
542            System.exit(1);
543        } else if (t != null) {
544            log.error(t, t);
545        }
546    }
547
548    /**
549     * @see FileEventTracker
550     * @param aFile The file to delete
551     * @param aMarker the marker Object
552     */
553    public static void trackFile(File aFile, Object aMarker) {
554        FileEvent.onFile(Framework.class, aFile, aMarker).send();
555    }
556
557    /**
558     * Strategy is not customizable anymore.
559     *
560     * @deprecated
561     * @since 6.0
562     * @see #trackFile(File, Object)
563     * @see org.nuxeo.runtime.trackers.files.FileEventTracker.SafeFileDeleteStrategy
564     * @param file The file to delete
565     * @param marker the marker Object
566     * @param fileDeleteStrategy ignored deprecated parameter
567     */
568    @Deprecated
569    public static void trackFile(File file, Object marker, FileDeleteStrategy fileDeleteStrategy) {
570        trackFile(file, marker);
571    }
572
573    /**
574     * @since 6.0
575     */
576    protected static void checkRuntimeInitialized() {
577        if (runtime == null) {
578            throw new IllegalStateException("Runtime not initialized");
579        }
580    }
581
582    /**
583     * Creates an empty file in the framework temporary-file directory ({@code nuxeo.tmp.dir} vs {@code java.io.tmpdir}
584     * ), using the given prefix and suffix to generate its name.
585     * <p>
586     * Invoking this method is equivalent to invoking
587     * <code>{@link File#createTempFile(java.lang.String, java.lang.String, java.io.File)
588     * File.createTempFile(prefix,&nbsp;suffix,&nbsp;Environment.getDefault().getTemp())}</code>.
589     * <p>
590     * The {@link #createTempFilePath(String, String, FileAttribute...)} method provides an alternative method to create
591     * an empty file in the framework temporary-file directory. Files created by that method may have more restrictive
592     * access permissions to files created by this method and so may be more suited to security-sensitive applications.
593     *
594     * @param prefix The prefix string to be used in generating the file's name; must be at least three characters long
595     * @param suffix The suffix string to be used in generating the file's name; may be <code>null</code>, in which case
596     *            the suffix <code>".tmp"</code> will be used
597     * @return An abstract pathname denoting a newly-created empty file
598     * @throws IllegalArgumentException If the <code>prefix</code> argument contains fewer than three characters
599     * @throws IOException If a file could not be created
600     * @throws SecurityException If a security manager exists and its <code>
601     *             {@link java.lang.SecurityManager#checkWrite(java.lang.String)}</code> method does not allow a file to
602     *             be created
603     * @since 8.1
604     * @see File#createTempFile(String, String, File)
605     * @see Environment#getTemp()
606     * @see #createTempFilePath(String, String, FileAttribute...)
607     * @see #createTempDirectory(String, FileAttribute...)
608     */
609    public static File createTempFile(String prefix, String suffix) throws IOException {
610        try {
611            return File.createTempFile(prefix, suffix, getTempDir());
612        } catch (IOException e) {
613            throw new IOException("Could not create temp file in " + getTempDir(), e);
614        }
615    }
616
617    /**
618     * @return the Nuxeo temp dir returned by {@link Environment#getTemp()}. If the Environment fails to initialize,
619     *         then returns the File denoted by {@code "nuxeo.tmp.dir"} System property, or {@code "java.io.tmpdir"}.
620     * @since 8.1
621     */
622    private static File getTempDir() {
623        Environment env = Environment.getDefault();
624        File temp = env != null ? env.getTemp()
625                : new File(System.getProperty("nuxeo.tmp.dir", System.getProperty("java.io.tmpdir")));
626        temp.mkdirs();
627        return temp;
628    }
629
630    /**
631     * Creates an empty file in the framework temporary-file directory ({@code nuxeo.tmp.dir} vs {@code java.io.tmpdir}
632     * ), using the given prefix and suffix to generate its name. The resulting {@code Path} is associated with the
633     * default {@code FileSystem}.
634     * <p>
635     * Invoking this method is equivalent to invoking
636     * {@link Files#createTempFile(Path, String, String, FileAttribute...)
637     * Files.createTempFile(Environment.getDefault().getTemp().toPath(),&nbsp;prefix,&nbsp;suffix,&nbsp;attrs)}.
638     *
639     * @param prefix the prefix string to be used in generating the file's name; may be {@code null}
640     * @param suffix the suffix string to be used in generating the file's name; may be {@code null}, in which case "
641     *            {@code .tmp}" is used
642     * @param attrs an optional list of file attributes to set atomically when creating the file
643     * @return the path to the newly created file that did not exist before this method was invoked
644     * @throws IllegalArgumentException if the prefix or suffix parameters cannot be used to generate a candidate file
645     *             name
646     * @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically when
647     *             creating the directory
648     * @throws IOException if an I/O error occurs or the temporary-file directory does not exist
649     * @throws SecurityException In the case of the default provider, and a security manager is installed, the
650     *             {@link SecurityManager#checkWrite(String) checkWrite} method is invoked to check write access to the
651     *             file.
652     * @since 8.1
653     * @see Files#createTempFile(Path, String, String, FileAttribute...)
654     * @see Environment#getTemp()
655     * @see #createTempFile(String, String)
656     */
657    public static Path createTempFilePath(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException {
658        try {
659            return Files.createTempFile(getTempDir().toPath(), prefix, suffix, attrs);
660        } catch (IOException e) {
661            throw new IOException("Could not create temp file in " + getTempDir(), e);
662        }
663    }
664
665    /**
666     * Creates a new directory in the framework temporary-file directory ({@code nuxeo.tmp.dir} vs
667     * {@code java.io.tmpdir}), using the given prefix to generate its name. The resulting {@code Path} is associated
668     * with the default {@code FileSystem}.
669     * <p>
670     * Invoking this method is equivalent to invoking {@link Files#createTempDirectory(Path, String, FileAttribute...)
671     * Files.createTempDirectory(Environment.getDefault().getTemp().toPath(),&nbsp;prefix,&nbsp;suffix,&nbsp;attrs)}.
672     *
673     * @param prefix the prefix string to be used in generating the directory's name; may be {@code null}
674     * @param attrs an optional list of file attributes to set atomically when creating the directory
675     * @return the path to the newly created directory that did not exist before this method was invoked
676     * @throws IllegalArgumentException if the prefix cannot be used to generate a candidate directory name
677     * @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically when
678     *             creating the directory
679     * @throws IOException if an I/O error occurs or the temporary-file directory does not exist
680     * @throws SecurityException In the case of the default provider, and a security manager is installed, the
681     *             {@link SecurityManager#checkWrite(String) checkWrite} method is invoked to check write access when
682     *             creating the directory.
683     * @since 8.1
684     * @see Files#createTempDirectory(Path, String, FileAttribute...)
685     * @see Environment#getTemp()
686     * @see #createTempFile(String, String)
687     */
688    public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException {
689        try {
690            return Files.createTempDirectory(getTempDir().toPath(), prefix, attrs);
691        } catch (IOException e) {
692            throw new IOException("Could not create temp directory in " + getTempDir(), e);
693        }
694    }
695
696}