OptimisticTypesPersistence.java revision 1093:3fa7d5c6ed92
1/*
2 * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25package jdk.nashorn.internal.codegen;
26
27import java.io.BufferedInputStream;
28import java.io.BufferedOutputStream;
29import java.io.DataInputStream;
30import java.io.DataOutputStream;
31import java.io.File;
32import java.io.FileInputStream;
33import java.io.FileOutputStream;
34import java.io.IOException;
35import java.io.InputStream;
36import java.net.URL;
37import java.nio.file.Files;
38import java.nio.file.Path;
39import java.security.AccessController;
40import java.security.MessageDigest;
41import java.security.PrivilegedAction;
42import java.text.SimpleDateFormat;
43import java.util.Base64;
44import java.util.Date;
45import java.util.Map;
46import java.util.Timer;
47import java.util.TimerTask;
48import java.util.concurrent.TimeUnit;
49import java.util.concurrent.atomic.AtomicBoolean;
50import java.util.function.Function;
51import java.util.function.IntFunction;
52import java.util.function.Predicate;
53import java.util.stream.Stream;
54import jdk.nashorn.internal.codegen.types.Type;
55import jdk.nashorn.internal.runtime.Context;
56import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
57import jdk.nashorn.internal.runtime.Source;
58import jdk.nashorn.internal.runtime.logging.DebugLogger;
59import jdk.nashorn.internal.runtime.options.Options;
60
61/**
62 * Static utility that encapsulates persistence of type information for functions compiled with optimistic
63 * typing. With this feature enabled, when a JavaScript function is recompiled because it gets deoptimized,
64 * the type information for deoptimization is stored in a cache file. If the same function is compiled in a
65 * subsequent JVM invocation, the type information is used for initial compilation, thus allowing the system
66 * to skip a lot of intermediate recompilations and immediately emit a version of the code that has its
67 * optimistic types at (or near) the steady state.
68 * </p><p>
69 * Normally, the type info persistence feature is disabled. When the {@code nashorn.typeInfo.maxFiles} system
70 * property is specified with a value greater than 0, it is enabled and operates in an operating-system
71 * specific per-user cache directory. You can override the directory by specifying it in the
72 * {@code nashorn.typeInfo.cacheDir} directory. The maximum number of files is softly enforced by a task that
73 * cleans up the directory periodically on a separate thread. It is run after some delay after a new file is
74 * added to the cache. The default delay is 20 seconds, and can be set using the
75 * {@code nashorn.typeInfo.cleanupDelaySeconds} system property. You can also specify the word
76 * {@code unlimited} as the value for {@code nashorn.typeInfo.maxFiles} in which case the type info cache is
77 * allowed to grow without limits.
78 */
79public final class OptimisticTypesPersistence {
80    // Default is 0, for disabling the feature when not specified. A reasonable default when enabled is
81    // dependent on the application; setting it to e.g. 20000 is probably good enough for most uses and will
82    // usually cap the cache directory to about 80MB presuming a 4kB filesystem allocation unit. There is one
83    // file per JavaScript function.
84    private static final int DEFAULT_MAX_FILES = 0;
85    // Constants for signifying that the cache should not be limited
86    private static final int UNLIMITED_FILES = -1;
87    // Maximum number of files that should be cached on disk. The maximum will be softly enforced.
88    private static final int MAX_FILES = getMaxFiles();
89    // Number of seconds to wait between adding a new file to the cache and running a cleanup process
90    private static final int DEFAULT_CLEANUP_DELAY = 20;
91    private static final int CLEANUP_DELAY = Math.max(0, Options.getIntProperty(
92            "nashorn.typeInfo.cleanupDelaySeconds", DEFAULT_CLEANUP_DELAY));
93    // The name of the default subdirectory within the system cache directory where we store type info.
94    private static final String DEFAULT_CACHE_SUBDIR_NAME = "com.oracle.java.NashornTypeInfo";
95    // The directory where we cache type info
96    private static final File baseCacheDir = createBaseCacheDir();
97    private static final File cacheDir = createCacheDir(baseCacheDir);
98    // In-process locks to make sure we don't have a cross-thread race condition manipulating any file.
99    private static final Object[] locks = cacheDir == null ? null : createLockArray();
100    // Only report one read/write error every minute
101    private static final long ERROR_REPORT_THRESHOLD = 60000L;
102
103    private static volatile long lastReportedError;
104    private static final AtomicBoolean scheduledCleanup;
105    private static final Timer cleanupTimer;
106    static {
107        if (baseCacheDir == null || MAX_FILES == UNLIMITED_FILES) {
108            scheduledCleanup = null;
109            cleanupTimer = null;
110        } else {
111            scheduledCleanup = new AtomicBoolean();
112            cleanupTimer = new Timer(true);
113        }
114    }
115    /**
116     * Retrieves an opaque descriptor for the persistence location for a given function. It should be passed
117     * to {@link #load(Object)} and {@link #store(Object, Map)} methods.
118     * @param source the source where the function comes from
119     * @param functionId the unique ID number of the function within the source
120     * @param paramTypes the types of the function parameters (as persistence is per parameter type
121     * specialization).
122     * @return an opaque descriptor for the persistence location. Can be null if persistence is disabled.
123     */
124    public static Object getLocationDescriptor(final Source source, final int functionId, final Type[] paramTypes) {
125        if(cacheDir == null) {
126            return null;
127        }
128        final StringBuilder b = new StringBuilder(48);
129        // Base64-encode the digest of the source, and append the function id.
130        b.append(source.getDigest()).append('-').append(functionId);
131        // Finally, if this is a parameter-type specialized version of the function, add the parameter types
132        // to the file name.
133        if(paramTypes != null && paramTypes.length > 0) {
134            b.append('-');
135            for(final Type t: paramTypes) {
136                b.append(Type.getShortSignatureDescriptor(t));
137            }
138        }
139        return new LocationDescriptor(new File(cacheDir, b.toString()));
140    }
141
142    private static final class LocationDescriptor {
143        private final File file;
144
145        LocationDescriptor(final File file) {
146            this.file = file;
147        }
148    }
149
150
151    /**
152     * Stores the map of optimistic types for a given function.
153     * @param locationDescriptor the opaque persistence location descriptor, retrieved by calling
154     * {@link #getLocationDescriptor(Source, int, Type[])}.
155     * @param optimisticTypes the map of optimistic types.
156     */
157    @SuppressWarnings("resource")
158    public static void store(final Object locationDescriptor, final Map<Integer, Type> optimisticTypes) {
159        if(locationDescriptor == null || optimisticTypes.isEmpty()) {
160            return;
161        }
162        final File file = ((LocationDescriptor)locationDescriptor).file;
163
164        AccessController.doPrivileged(new PrivilegedAction<Void>() {
165            @Override
166            public Void run() {
167                synchronized(getFileLock(file)) {
168                    if (!file.exists()) {
169                        // If the file already exists, we aren't increasing the number of cached files, so
170                        // don't schedule cleanup.
171                        scheduleCleanup();
172                    }
173                    try (final FileOutputStream out = new FileOutputStream(file)) {
174                        out.getChannel().lock(); // lock exclusive
175                        final DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(out));
176                        Type.writeTypeMap(optimisticTypes, dout);
177                        dout.flush();
178                    } catch(final Exception e) {
179                        reportError("write", file, e);
180                    }
181                }
182                return null;
183            }
184        });
185    }
186
187    /**
188     * Loads the map of optimistic types for a given function.
189     * @param locationDescriptor the opaque persistence location descriptor, retrieved by calling
190     * {@link #getLocationDescriptor(Source, int, Type[])}.
191     * @return the map of optimistic types, or null if persisted type information could not be retrieved.
192     */
193    @SuppressWarnings("resource")
194    public static Map<Integer, Type> load(final Object locationDescriptor) {
195        if (locationDescriptor == null) {
196            return null;
197        }
198        final File file = ((LocationDescriptor)locationDescriptor).file;
199        return AccessController.doPrivileged(new PrivilegedAction<Map<Integer, Type>>() {
200            @Override
201            public Map<Integer, Type> run() {
202                try {
203                    if(!file.isFile()) {
204                        return null;
205                    }
206                    synchronized(getFileLock(file)) {
207                        try (final FileInputStream in = new FileInputStream(file)) {
208                            in.getChannel().lock(0, Long.MAX_VALUE, true); // lock shared
209                            final DataInputStream din = new DataInputStream(new BufferedInputStream(in));
210                            return Type.readTypeMap(din);
211                        }
212                    }
213                } catch (final Exception e) {
214                    reportError("read", file, e);
215                    return null;
216                }
217            }
218        });
219    }
220
221    private static void reportError(final String msg, final File file, final Exception e) {
222        final long now = System.currentTimeMillis();
223        if(now - lastReportedError > ERROR_REPORT_THRESHOLD) {
224            getLogger().warning(String.format("Failed to %s %s", msg, file), e);
225            lastReportedError = now;
226        }
227    }
228
229    private static File createBaseCacheDir() {
230        if(MAX_FILES == 0 || Options.getBooleanProperty("nashorn.typeInfo.disabled")) {
231            return null;
232        }
233        try {
234            return createBaseCacheDirPrivileged();
235        } catch(final Exception e) {
236            getLogger().warning("Failed to create cache dir", e);
237            return null;
238        }
239    }
240
241    private static File createBaseCacheDirPrivileged() {
242        return AccessController.doPrivileged(new PrivilegedAction<File>() {
243            @Override
244            public File run() {
245                final String explicitDir = System.getProperty("nashorn.typeInfo.cacheDir");
246                final File dir;
247                if(explicitDir != null) {
248                    dir = new File(explicitDir);
249                } else {
250                    // When no directory is explicitly specified, get an operating system specific cache
251                    // directory, and create "com.oracle.java.NashornTypeInfo" in it.
252                    final File systemCacheDir = getSystemCacheDir();
253                    dir = new File(systemCacheDir, DEFAULT_CACHE_SUBDIR_NAME);
254                    if (isSymbolicLink(dir)) {
255                        return null;
256                    }
257                }
258                return dir;
259            }
260        });
261    }
262
263    private static File createCacheDir(final File baseDir) {
264        if (baseDir == null) {
265            return null;
266        }
267        try {
268            return createCacheDirPrivileged(baseDir);
269        } catch(final Exception e) {
270            getLogger().warning("Failed to create cache dir", e);
271            return null;
272        }
273    }
274
275    private static File createCacheDirPrivileged(final File baseDir) {
276        return AccessController.doPrivileged(new PrivilegedAction<File>() {
277            @Override
278            public File run() {
279                final String versionDirName;
280                try {
281                    versionDirName = getVersionDirName();
282                } catch(final Exception e) {
283                    getLogger().warning("Failed to calculate version dir name", e);
284                    return null;
285                }
286                final File versionDir = new File(baseDir, versionDirName);
287                if (isSymbolicLink(versionDir)) {
288                    return null;
289                }
290                versionDir.mkdirs();
291                if (versionDir.isDirectory()) {
292                    getLogger().info("Optimistic type persistence directory is " + versionDir);
293                    return versionDir;
294                }
295                getLogger().warning("Could not create optimistic type persistence directory " + versionDir);
296                return null;
297            }
298        });
299    }
300
301    /**
302     * Returns an operating system specific root directory for cache files.
303     * @return an operating system specific root directory for cache files.
304     */
305    private static File getSystemCacheDir() {
306        final String os = System.getProperty("os.name", "generic");
307        if("Mac OS X".equals(os)) {
308            // Mac OS X stores caches in ~/Library/Caches
309            return new File(new File(System.getProperty("user.home"), "Library"), "Caches");
310        } else if(os.startsWith("Windows")) {
311            // On Windows, temp directory is the best approximation of a cache directory, as its contents
312            // persist across reboots and various cleanup utilities know about it. java.io.tmpdir normally
313            // points to a user-specific temp directory, %HOME%\LocalSettings\Temp.
314            return new File(System.getProperty("java.io.tmpdir"));
315        } else {
316            // In other cases we're presumably dealing with a UNIX flavor (Linux, Solaris, etc.); "~/.cache"
317            return new File(System.getProperty("user.home"), ".cache");
318        }
319    }
320
321    /**
322     * In order to ensure that changes in Nashorn code don't cause corruption in the data, we'll create a
323     * per-code-version directory. Normally, this will create the SHA-1 digest of the nashorn.jar. In case the classpath
324     * for nashorn is local directory (e.g. during development), this will create the string "dev-" followed by the
325     * timestamp of the most recent .class file.
326     *
327     * @return digest of currently running nashorn
328     * @throws Exception if digest could not be created
329     */
330    public static String getVersionDirName() throws Exception {
331        final URL url = OptimisticTypesPersistence.class.getResource("");
332        final String protocol = url.getProtocol();
333        if (protocol.equals("jar")) {
334            // Normal deployment: nashorn.jar
335            final String jarUrlFile = url.getFile();
336            final String filePath = jarUrlFile.substring(0, jarUrlFile.indexOf('!'));
337            final URL file = new URL(filePath);
338            try (final InputStream in = file.openStream()) {
339                final byte[] buf = new byte[128*1024];
340                final MessageDigest digest = MessageDigest.getInstance("SHA-1");
341                for(;;) {
342                    final int l = in.read(buf);
343                    if(l == -1) {
344                        return Base64.getUrlEncoder().withoutPadding().encodeToString(digest.digest());
345                    }
346                    digest.update(buf, 0, l);
347                }
348            }
349        } else if(protocol.equals("file")) {
350            // Development
351            final String fileStr = url.getFile();
352            final String className = OptimisticTypesPersistence.class.getName();
353            final int packageNameLen = className.lastIndexOf('.');
354            final String dirStr = fileStr.substring(0, fileStr.length() - packageNameLen - 1);
355            final File dir = new File(dirStr);
356            return "dev-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(getLastModifiedClassFile(
357                    dir, 0L)));
358        } else {
359            throw new AssertionError();
360        }
361    }
362
363    private static long getLastModifiedClassFile(final File dir, final long max) {
364        long currentMax = max;
365        for(final File f: dir.listFiles()) {
366            if(f.getName().endsWith(".class")) {
367                final long lastModified = f.lastModified();
368                if (lastModified > currentMax) {
369                    currentMax = lastModified;
370                }
371            } else if (f.isDirectory()) {
372                final long lastModified = getLastModifiedClassFile(f, currentMax);
373                if (lastModified > currentMax) {
374                    currentMax = lastModified;
375                }
376            }
377        }
378        return currentMax;
379    }
380
381    /**
382     * Returns true if the specified file is a symbolic link, and also logs a warning if it is.
383     * @param file the file
384     * @return true if file is a symbolic link, false otherwise.
385     */
386    private static boolean isSymbolicLink(final File file) {
387        if (Files.isSymbolicLink(file.toPath())) {
388            getLogger().warning("Directory " + file + " is a symlink");
389            return true;
390        }
391        return false;
392    }
393
394    private static Object[] createLockArray() {
395        final Object[] lockArray = new Object[Runtime.getRuntime().availableProcessors() * 2];
396        for (int i = 0; i < lockArray.length; ++i) {
397            lockArray[i] = new Object();
398        }
399        return lockArray;
400    }
401
402    private static Object getFileLock(final File file) {
403        return locks[(file.hashCode() & Integer.MAX_VALUE) % locks.length];
404    }
405
406    private static DebugLogger getLogger() {
407        try {
408            return Context.getContext().getLogger(RecompilableScriptFunctionData.class);
409        } catch (final Exception e) {
410            e.printStackTrace();
411            return DebugLogger.DISABLED_LOGGER;
412        }
413    }
414
415    private static void scheduleCleanup() {
416        if (MAX_FILES != UNLIMITED_FILES && scheduledCleanup.compareAndSet(false, true)) {
417            cleanupTimer.schedule(new TimerTask() {
418                @Override
419                public void run() {
420                    scheduledCleanup.set(false);
421                    try {
422                        doCleanup();
423                    } catch (final IOException e) {
424                        // Ignore it. While this is unfortunate, we don't have good facility for reporting
425                        // this, as we're running in a thread that has no access to Context, so we can't grab
426                        // a DebugLogger.
427                    }
428                }
429            }, TimeUnit.SECONDS.toMillis(CLEANUP_DELAY));
430        }
431    }
432
433    private static void doCleanup() throws IOException {
434        final Path[] files = getAllRegularFilesInLastModifiedOrder();
435        final int nFiles = files.length;
436        final int filesToDelete = Math.max(0, nFiles - MAX_FILES);
437        int filesDeleted = 0;
438        for (int i = 0; i < nFiles && filesDeleted < filesToDelete; ++i) {
439            try {
440                Files.deleteIfExists(files[i]);
441                // Even if it didn't exist, we increment filesDeleted; it existed a moment earlier; something
442                // else deleted it for us; that's okay with us.
443                filesDeleted++;
444            } catch (final Exception e) {
445                // does not increase filesDeleted
446            }
447            files[i] = null; // gc eligible
448        }
449    }
450
451    private static Path[] getAllRegularFilesInLastModifiedOrder() throws IOException {
452        try (final Stream<Path> filesStream = Files.walk(baseCacheDir.toPath())) {
453            // TODO: rewrite below once we can use JDK8 syntactic constructs
454            return filesStream
455            .filter(new Predicate<Path>() {
456                @Override
457                public boolean test(final Path path) {
458                    return !Files.isDirectory(path);
459                }
460            })
461            .map(new Function<Path, PathAndTime>() {
462                @Override
463                public PathAndTime apply(final Path path) {
464                    return new PathAndTime(path);
465                }
466            })
467            .sorted()
468            .map(new Function<PathAndTime, Path>() {
469                @Override
470                public Path apply(final PathAndTime pathAndTime) {
471                    return pathAndTime.path;
472                }
473            })
474            .toArray(new IntFunction<Path[]>() { // Replace with Path::new
475                @Override
476                public Path[] apply(final int length) {
477                    return new Path[length];
478                }
479            });
480        }
481    }
482
483    private static class PathAndTime implements Comparable<PathAndTime> {
484        private final Path path;
485        private final long time;
486
487        PathAndTime(final Path path) {
488            this.path = path;
489            this.time = getTime(path);
490        }
491
492        @Override
493        public int compareTo(final PathAndTime other) {
494            return Long.compare(time, other.time);
495        }
496
497        private static long getTime(final Path path) {
498            try {
499                return Files.getLastModifiedTime(path).toMillis();
500            } catch (final IOException e) {
501                // All files for which we can't retrieve the last modified date will be considered oldest.
502                return -1L;
503            }
504        }
505    }
506
507    private static int getMaxFiles() {
508        final String str = Options.getStringProperty("nashorn.typeInfo.maxFiles", null);
509        if (str == null) {
510            return DEFAULT_MAX_FILES;
511        } else if ("unlimited".equals(str)) {
512            return UNLIMITED_FILES;
513        }
514        return Math.max(0, Integer.parseInt(str));
515    }
516}
517