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        SharedResourceLoader loader = 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                    loader.addURL(oldURL);
176                }
177            }
178        }
179        if (urlsToAdd != null) {
180            for (URL newURL : urlsToAdd) {
181                loader.addURL(newURL);
182            }
183        }
184        if (resourceLoader != null) {
185            // properly close the previous resource ClassLoader, otherwise any leak of an InputStream from it
186            // will keep the JAR available in the internal sun.net.www.protocol.jar JarFileFactory cache
187            // used by sun.net.www.protocol.jar.JarURLConnection, which will cause subsequent references
188            // to use the old JAR.
189            try {
190                resourceLoader.close();
191            } catch (IOException e) {
192                log.error("Failed to close previous resource loader", e);
193            }
194        }
195        resourceLoader = loader;
196    }
197
198    public static void shutdown() throws InterruptedException {
199        if (runtime == null) {
200            throw new IllegalStateException("runtime not exist");
201        }
202        try {
203            runtime.stop();
204        } finally {
205            runtime = null;
206        }
207    }
208
209    /**
210     * Tests whether or not the runtime was initialized.
211     *
212     * @return true if the runtime was initialized, false otherwise
213     */
214    public static synchronized boolean isInitialized() {
215        return runtime != null;
216    }
217
218    public static SharedResourceLoader getResourceLoader() {
219        return resourceLoader;
220    }
221
222    /**
223     * Gets the runtime service instance.
224     *
225     * @return the runtime service instance
226     */
227    public static RuntimeService getRuntime() {
228        return runtime;
229    }
230
231    /**
232     * Gets a service given its class.
233     */
234    public static <T> T getService(Class<T> serviceClass) {
235        ServiceProvider provider = DefaultServiceProvider.getProvider();
236        if (provider != null) {
237            return provider.getService(serviceClass);
238        }
239        checkRuntimeInitialized();
240        // TODO impl a runtime service provider
241        return runtime.getService(serviceClass);
242    }
243
244    /**
245     * Gets a service given its class.
246     *
247     * @deprecated since 9.10, use {@link #getService} instead
248     */
249    @Deprecated
250    public static <T> T getLocalService(Class<T> serviceClass) {
251        return getService(serviceClass);
252    }
253
254    /**
255     * Lookup a registered object given its key.
256     */
257    public static Object lookup(String key) {
258        return null; // TODO
259    }
260
261    /**
262     * Runs the given {@link Runnable} while logged in as a system user.
263     *
264     * @param runnable what to run
265     * @since 8.4
266     */
267    public static void doPrivileged(Runnable runnable) {
268        try {
269            LoginContext loginContext = login();
270            try {
271                runnable.run();
272            } finally {
273                if (loginContext != null) { // may be null in tests
274                    loginContext.logout();
275                }
276            }
277        } catch (LoginException e) {
278            throw new RuntimeException(e);
279        }
280    }
281
282    /**
283     * Calls the given {@link Supplier} while logged in as a system user and returns its result.
284     *
285     * @param supplier what to call
286     * @return the supplier's result
287     * @since 8.4
288     */
289    public static <T> T doPrivileged(Supplier<T> supplier) {
290        try {
291            LoginContext loginContext = login();
292            try {
293                return supplier.get();
294            } finally {
295                if (loginContext != null) { // may be null in tests
296                    loginContext.logout();
297                }
298            }
299        } catch (LoginException e) {
300            throw new RuntimeException(e);
301        }
302    }
303
304    /**
305     * Login in the system as the system user (a pseudo-user having all privileges).
306     *
307     * @return the login session if successful. Never returns null.
308     * @throws LoginException on login failure
309     */
310    public static LoginContext login() throws LoginException {
311        checkRuntimeInitialized();
312        LoginService loginService = runtime.getService(LoginService.class);
313        if (loginService != null) {
314            return loginService.login();
315        }
316        return null;
317    }
318
319    /**
320     * Login in the system as the system user (a pseudo-user having all privileges). The given username will be used to
321     * identify the user id that called this method.
322     *
323     * @param username the originating user id
324     * @return the login session if successful. Never returns null.
325     * @throws LoginException on login failure
326     */
327    public static LoginContext loginAs(String username) throws LoginException {
328        checkRuntimeInitialized();
329        LoginService loginService = runtime.getService(LoginService.class);
330        if (loginService != null) {
331            return loginService.loginAs(username);
332        }
333        return null;
334    }
335
336    /**
337     * Login in the system as the given user without checking the password.
338     *
339     * @param username the user name to login as.
340     * @return the login context
341     * @throws LoginException if any error occurs
342     * @since 5.4.2
343     */
344    public static LoginContext loginAsUser(String username) throws LoginException {
345        return getService(LoginAs.class).loginAs(username);
346    }
347
348    /**
349     * Login in the system as the given user using the given password.
350     *
351     * @param username the username to login
352     * @param password the password
353     * @return a login session if login was successful. Never returns null.
354     * @throws LoginException if login failed
355     */
356    public static LoginContext login(String username, Object password) throws LoginException {
357        checkRuntimeInitialized();
358        LoginService loginService = runtime.getService(LoginService.class);
359        if (loginService != null) {
360            return loginService.login(username, password);
361        }
362        return null;
363    }
364
365    /**
366     * Login in the system using the given callback handler for login info resolution.
367     *
368     * @param cbHandler used to fetch the login info
369     * @return the login context
370     * @throws LoginException
371     */
372    public static LoginContext login(CallbackHandler cbHandler) throws LoginException {
373        checkRuntimeInitialized();
374        LoginService loginService = runtime.getService(LoginService.class);
375        if (loginService != null) {
376            return loginService.login(cbHandler);
377        }
378        return null;
379    }
380
381    public static void sendEvent(RuntimeServiceEvent event) {
382        Object[] listenersArray = listeners.getListeners();
383        for (Object listener : listenersArray) {
384            ((RuntimeServiceListener) listener).handleEvent(event);
385        }
386    }
387
388    /**
389     * Registers a listener to be notified about runtime events.
390     * <p>
391     * If the listener is already registered, do nothing.
392     *
393     * @param listener the listener to register
394     */
395    public static void addListener(RuntimeServiceListener listener) {
396        listeners.add(listener);
397    }
398
399    /**
400     * Removes the given listener.
401     * <p>
402     * If the listener is not registered, do nothing.
403     *
404     * @param listener the listener to remove
405     */
406    public static void removeListener(RuntimeServiceListener listener) {
407        listeners.remove(listener);
408    }
409
410    /**
411     * Gets the given property value if any, otherwise null.
412     * <p>
413     * The framework properties will be searched first then if any matching property is found the system properties are
414     * searched too.
415     *
416     * @param key the property key
417     * @return the property value if any or null otherwise
418     */
419    public static String getProperty(String key) {
420        return getProperty(key, null);
421    }
422
423    /**
424     * Gets the given property value if any, otherwise returns the given default value.
425     * <p>
426     * The framework properties will be searched first then if any matching property is found the system properties are
427     * searched too.
428     *
429     * @param key the property key
430     * @param defValue the default value to use
431     * @return the property value if any otherwise the default value
432     */
433    public static String getProperty(String key, String defValue) {
434        checkRuntimeInitialized();
435        return runtime.getProperty(key, defValue);
436    }
437
438    /**
439     * Gets all the framework properties. The system properties are not included in the returned map.
440     *
441     * @return the framework properties map. Never returns null.
442     */
443    public static Properties getProperties() {
444        checkRuntimeInitialized();
445        return runtime.getProperties();
446    }
447
448    /**
449     * Expands any variable found in the given expression with the value of the corresponding framework property.
450     * <p>
451     * The variable format is ${property_key}.
452     * <p>
453     * System properties are also expanded.
454     */
455    public static String expandVars(String expression) {
456        checkRuntimeInitialized();
457        return runtime.expandVars(expression);
458    }
459
460    public static boolean isOSGiServiceSupported() {
461        if (isOSGiServiceSupported == null) {
462            isOSGiServiceSupported = Boolean.valueOf(isBooleanPropertyTrue("ecr.osgi.services"));
463        }
464        return isOSGiServiceSupported.booleanValue();
465    }
466
467    /**
468     * Returns true if dev mode is set.
469     * <p>
470     * Activating this mode, some of the code may not behave as it would in production, to ease up debugging and working
471     * on developing the application.
472     * <p>
473     * For instance, it'll enable hot-reload if some packages are installed while the framework is running. It will also
474     * reset some caches when that happens.
475     */
476    public static boolean isDevModeSet() {
477        return isBooleanPropertyTrue(NUXEO_DEV_SYSTEM_PROP);
478    }
479
480    /**
481     * Returns true if test mode is set.
482     * <p>
483     * Activating this mode, some of the code may not behave as it would in production, to ease up testing.
484     */
485    public static boolean isTestModeSet() {
486        return isBooleanPropertyTrue(NUXEO_TESTING_SYSTEM_PROP);
487    }
488
489    /**
490     * Returns true if given property is false when compared to a boolean value. Returns false if given property in
491     * unset.
492     * <p>
493     * Checks for the system properties if property is not found in the runtime properties.
494     *
495     * @since 5.8
496     */
497    public static boolean isBooleanPropertyFalse(String propName) {
498        String v = getProperty(propName);
499        if (v == null) {
500            v = System.getProperty(propName);
501        }
502        if (StringUtils.isBlank(v)) {
503            return false;
504        }
505        return !Boolean.parseBoolean(v);
506    }
507
508    /**
509     * Returns true if given property is true when compared to a boolean value.
510     * <p>
511     * Checks for the system properties if property is not found in the runtime properties.
512     *
513     * @since 5.6
514     */
515    public static boolean isBooleanPropertyTrue(String propName) {
516        String v = getProperty(propName);
517        if (v == null) {
518            v = System.getProperty(propName);
519        }
520        return Boolean.parseBoolean(v);
521    }
522
523    /**
524     * @see FileEventTracker
525     * @param aFile The file to delete
526     * @param aMarker the marker Object
527     */
528    public static void trackFile(File aFile, Object aMarker) {
529        FileEvent.onFile(Framework.class, aFile, aMarker).send();
530    }
531
532    /**
533     * Strategy is not customizable anymore.
534     *
535     * @deprecated
536     * @since 6.0
537     * @see #trackFile(File, Object)
538     * @see org.nuxeo.runtime.trackers.files.FileEventTracker.SafeFileDeleteStrategy
539     * @param file The file to delete
540     * @param marker the marker Object
541     * @param fileDeleteStrategy ignored deprecated parameter
542     */
543    @Deprecated
544    public static void trackFile(File file, Object marker, FileDeleteStrategy fileDeleteStrategy) {
545        trackFile(file, marker);
546    }
547
548    /**
549     * @since 6.0
550     */
551    protected static void checkRuntimeInitialized() {
552        if (runtime == null) {
553            throw new IllegalStateException("Runtime not initialized");
554        }
555    }
556
557    /**
558     * Creates an empty file in the framework temporary-file directory ({@code nuxeo.tmp.dir} vs {@code java.io.tmpdir}
559     * ), using the given prefix and suffix to generate its name.
560     * <p>
561     * Invoking this method is equivalent to invoking
562     * <code>{@link File#createTempFile(java.lang.String, java.lang.String, java.io.File)
563     * File.createTempFile(prefix,&nbsp;suffix,&nbsp;Environment.getDefault().getTemp())}</code>.
564     * <p>
565     * The {@link #createTempFilePath(String, String, FileAttribute...)} method provides an alternative method to create
566     * an empty file in the framework temporary-file directory. Files created by that method may have more restrictive
567     * access permissions to files created by this method and so may be more suited to security-sensitive applications.
568     *
569     * @param prefix The prefix string to be used in generating the file's name; must be at least three characters long
570     * @param suffix The suffix string to be used in generating the file's name; may be <code>null</code>, in which case
571     *            the suffix <code>".tmp"</code> will be used
572     * @return An abstract pathname denoting a newly-created empty file
573     * @throws IllegalArgumentException If the <code>prefix</code> argument contains fewer than three characters
574     * @throws IOException If a file could not be created
575     * @throws SecurityException If a security manager exists and its <code>
576     *             {@link java.lang.SecurityManager#checkWrite(java.lang.String)}</code> method does not allow a file to
577     *             be created
578     * @since 8.1
579     * @see File#createTempFile(String, String, File)
580     * @see Environment#getTemp()
581     * @see #createTempFilePath(String, String, FileAttribute...)
582     * @see #createTempDirectory(String, FileAttribute...)
583     */
584    public static File createTempFile(String prefix, String suffix) throws IOException {
585        try {
586            return File.createTempFile(prefix, suffix, getTempDir());
587        } catch (IOException e) {
588            throw new IOException("Could not create temp file in " + getTempDir(), e);
589        }
590    }
591
592    /**
593     * @return the Nuxeo temp dir returned by {@link Environment#getTemp()}. If the Environment fails to initialize,
594     *         then returns the File denoted by {@code "nuxeo.tmp.dir"} System property, or {@code "java.io.tmpdir"}.
595     * @since 8.1
596     */
597    private static File getTempDir() {
598        Environment env = Environment.getDefault();
599        File temp = env != null ? env.getTemp()
600                : new File(System.getProperty("nuxeo.tmp.dir", System.getProperty("java.io.tmpdir")));
601        temp.mkdirs();
602        return temp;
603    }
604
605    /**
606     * Creates an empty file in the framework temporary-file directory ({@code nuxeo.tmp.dir} vs {@code java.io.tmpdir}
607     * ), using the given prefix and suffix to generate its name. The resulting {@code Path} is associated with the
608     * default {@code FileSystem}.
609     * <p>
610     * Invoking this method is equivalent to invoking
611     * {@link Files#createTempFile(Path, String, String, FileAttribute...)
612     * Files.createTempFile(Environment.getDefault().getTemp().toPath(),&nbsp;prefix,&nbsp;suffix,&nbsp;attrs)}.
613     *
614     * @param prefix the prefix string to be used in generating the file's name; may be {@code null}
615     * @param suffix the suffix string to be used in generating the file's name; may be {@code null}, in which case "
616     *            {@code .tmp}" is used
617     * @param attrs an optional list of file attributes to set atomically when creating the file
618     * @return the path to the newly created file that did not exist before this method was invoked
619     * @throws IllegalArgumentException if the prefix or suffix parameters cannot be used to generate a candidate file
620     *             name
621     * @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically when
622     *             creating the directory
623     * @throws IOException if an I/O error occurs or the temporary-file directory does not exist
624     * @throws SecurityException In the case of the default provider, and a security manager is installed, the
625     *             {@link SecurityManager#checkWrite(String) checkWrite} method is invoked to check write access to the
626     *             file.
627     * @since 8.1
628     * @see Files#createTempFile(Path, String, String, FileAttribute...)
629     * @see Environment#getTemp()
630     * @see #createTempFile(String, String)
631     */
632    public static Path createTempFilePath(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException {
633        try {
634            return Files.createTempFile(getTempDir().toPath(), prefix, suffix, attrs);
635        } catch (IOException e) {
636            throw new IOException("Could not create temp file in " + getTempDir(), e);
637        }
638    }
639
640    /**
641     * Creates a new directory in the framework temporary-file directory ({@code nuxeo.tmp.dir} vs
642     * {@code java.io.tmpdir}), using the given prefix to generate its name. The resulting {@code Path} is associated
643     * with the default {@code FileSystem}.
644     * <p>
645     * Invoking this method is equivalent to invoking {@link Files#createTempDirectory(Path, String, FileAttribute...)
646     * Files.createTempDirectory(Environment.getDefault().getTemp().toPath(),&nbsp;prefix,&nbsp;suffix,&nbsp;attrs)}.
647     *
648     * @param prefix the prefix string to be used in generating the directory's name; may be {@code null}
649     * @param attrs an optional list of file attributes to set atomically when creating the directory
650     * @return the path to the newly created directory that did not exist before this method was invoked
651     * @throws IllegalArgumentException if the prefix cannot be used to generate a candidate directory name
652     * @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically when
653     *             creating the directory
654     * @throws IOException if an I/O error occurs or the temporary-file directory does not exist
655     * @throws SecurityException In the case of the default provider, and a security manager is installed, the
656     *             {@link SecurityManager#checkWrite(String) checkWrite} method is invoked to check write access when
657     *             creating the directory.
658     * @since 8.1
659     * @see Files#createTempDirectory(Path, String, FileAttribute...)
660     * @see Environment#getTemp()
661     * @see #createTempFile(String, String)
662     */
663    public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException {
664        try {
665            return Files.createTempDirectory(getTempDir().toPath(), prefix, attrs);
666        } catch (IOException e) {
667            throw new IOException("Could not create temp directory in " + getTempDir(), e);
668        }
669    }
670
671}