aboutsummaryrefslogtreecommitdiffstats
path: root/container-accesslogging/src/main/java/com/yahoo/container/logging/LogFileHandler.java
blob: 82c89276319e44c3347f7d0909cd62b386e494e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.logging;

import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.io.NativeIO;
import com.yahoo.log.LogFileDb;
import com.yahoo.system.ProcessExecuter;
import com.yahoo.yolean.Exceptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import java.util.zip.GZIPOutputStream;

/**
 * <p>Implements log file naming/rotating logic for container logs.</p>
 *
 * <p>Overridden methods: publish</p>
 *
 * <p>Added methods: setFilePattern, setRotationTimes, rotateNow (+ few others)</p>
 *
 * @author Bob Travis
 */
public class LogFileHandler extends StreamHandler {

    private final static Logger logger = Logger.getLogger(LogFileHandler.class.getName());
    private final boolean compressOnRotation;
    private long[] rotationTimes = {0}; //default to one log per day, at midnight
    private String filePattern = "./log.%T";  // default to current directory, ms time stamp
    private long nextRotationTime = 0;
    private FileOutputStream currentOutputStream = null;
    private String fileName;
    private String symlinkName = null;
    private ArrayBlockingQueue<LogRecord> logQueue = new ArrayBlockingQueue<>(100000);
    private LogRecord rotateCmd = new LogRecord(Level.SEVERE, "rotateNow");
    private ExecutorService executor = Executors.newCachedThreadPool(ThreadFactoryFactory.getDaemonThreadFactory("logfilehandler.compression"));
    private final NativeIO nativeIO = new NativeIO();
    private long lastDropPosition = 0;

    static private class LogThread extends Thread {
        LogFileHandler logFileHandler;
        long lastFlush = 0;
        LogThread(LogFileHandler logFile) {
            super("Logger");
            setDaemon(true);
            logFileHandler = logFile;
        }
        @Override
        public void run() {
            try {
                storeLogRecords();
            } catch (InterruptedException e) {
            } catch (Exception e) {
                com.yahoo.protect.Process.logAndDie("Failed storing log records", e);
            }

            logFileHandler.flush();
        }

        private void storeLogRecords() throws InterruptedException {
            while (!isInterrupted()) {
                LogRecord r = logFileHandler.logQueue.poll(100, TimeUnit.MILLISECONDS);
                if (r != null) {
                    if (r == logFileHandler.rotateCmd) {
                        logFileHandler.internalRotateNow();
                        lastFlush = System.nanoTime();
                    } else {
                        logFileHandler.internalPublish(r);
                    }
                    flushIfOld(3, TimeUnit.SECONDS);
                } else {
                    flushIfOld(100, TimeUnit.MILLISECONDS);
                }
            }
        }

        private void flushIfOld(long age, TimeUnit unit) {
            long now = System.nanoTime();
            if (TimeUnit.NANOSECONDS.toMillis(now - lastFlush) > unit.toMillis(age)) {
                logFileHandler.flush();
                lastFlush = now;
            }
        }
    }
    private final LogThread logThread;

    LogFileHandler() {
        this(false);
    }

    LogFileHandler(boolean compressOnRotation)
    {
        super();
        this.compressOnRotation = compressOnRotation;
        logThread = new LogThread(this);
        logThread.start();
    }

    /**
     * Sends logrecord to file, first rotating file if needed.
     *
     * @param r logrecord to publish
     */
    public void publish(LogRecord r) {
        try {
            logQueue.put(r);
        } catch (InterruptedException e) {
        }
    }

    @Override
    public synchronized void flush() {
        super.flush();
        try {
            if (currentOutputStream != null) {
                long newPos = currentOutputStream.getChannel().position();
                nativeIO.dropPartialFileFromCache(currentOutputStream.getFD(), lastDropPosition, newPos, true);
                lastDropPosition = newPos;
            }
        } catch (IOException e) {
            logger.warning("Failed dropping from cache : " + Exceptions.toMessageString(e));
        }
    }

    private void internalPublish(LogRecord r) {
        // first check to see if new file needed.
        // if so, use this.internalRotateNow() to do it

        long now = System.currentTimeMillis();
        if (nextRotationTime <= 0) {
            nextRotationTime = getNextRotationTime(now); // lazy initialization
        }
        if (now > nextRotationTime || currentOutputStream == null) {
            internalRotateNow();
        }
        super.publish(r);
    }

    /**
     * Assign pattern for generating (rotating) file names.
     *
     * @param pattern See LogFormatter for definition
     */
    void setFilePattern ( String pattern ) {
        filePattern = pattern;
    }

    /**
     * Assign times for rotating output files.
     *
     * @param timesOfDay in millis, from midnight
     *
     */
    void setRotationTimes ( long[] timesOfDay ) {
        rotationTimes = timesOfDay;
    }

    /** Assign time for rotating output files
     *
     * @param prescription string form of times, in minutes
     */
    void setRotationTimes ( String prescription ) {
        setRotationTimes(calcTimesMinutes(prescription));
    }

    /**
     * Find next rotation after specified time.
     *
     * @param now the specified time; if zero, current time is used.
     * @return the next rotation time
     */
    long getNextRotationTime (long now) {
        if (now <= 0) {
            now = System.currentTimeMillis();
        }
        long nowTod = timeOfDayMillis(now);
        long next = 0;
        for (long rotationTime : rotationTimes) {
            if (nowTod < rotationTime) {
                next = rotationTime-nowTod + now;
                break;
            }
        }
        if (next == 0) { // didn't find one -- use 1st time 'tomorrow'
            next = rotationTimes[0]+lengthOfDayMillis-nowTod + now;
        }

        return next;
    }

    void waitDrained() {
        while(! logQueue.isEmpty()) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
            }
        }
        flush();
    }

    private void checkAndCreateDir(String pathname) {
      int lastSlash = pathname.lastIndexOf("/");
      if (lastSlash > -1) {
          String pathExcludingFilename = pathname.substring(0, lastSlash);
          File filepath = new File(pathExcludingFilename);
          if (!filepath.exists()) {
            filepath.mkdirs();
          }
      }
    }

    /**
     * Force file rotation now, independent of schedule.
     */
    void rotateNow () {
        publish(rotateCmd);
    }

    // Throw InterruptedException upwards rather than relying on isInterrupted to stop the thread as
    // isInterrupted() returns false after interruption in p.waitFor
    private void internalRotateNow() {
        // figure out new file name, then
        // use super.setOutputStream to switch to a new file

        String oldFileName = fileName;
        long now = System.currentTimeMillis();
        fileName = LogFormatter.insertDate(filePattern, now);
        flush();
        super.close();

        try {
            checkAndCreateDir(fileName);
            FileOutputStream os = new FileOutputStream(fileName, true); // append mode, for safety
            super.setOutputStream(os);
            currentOutputStream = os;
            lastDropPosition = 0;
            LogFileDb.nowLoggingTo(fileName);
        }
        catch (IOException e) {
            throw new RuntimeException("Couldn't open log file '" + fileName + "'", e);
        }

        createSymlinkToCurrentFile();

        nextRotationTime = 0; //figure it out later (lazy evaluation)
        if ((oldFileName != null)) {
            File oldFile = new File(oldFileName);
            if (oldFile.exists()) {
                if (compressOnRotation) {
                    executor.execute(() -> runCompression(oldFile));
                } else {
                    nativeIO.dropFileFromCache(oldFile);
                }
            }
        }
    }


    static void runCompression(File oldFile) {
        File gzippedFile = new File(oldFile.getPath() + ".gz");
        try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
             FileInputStream inputStream = new FileInputStream(oldFile))
        {
            byte [] buffer = new byte[0x400000]; // 4M buffer

            long totalBytesRead = 0;
            NativeIO nativeIO = new NativeIO();
            for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
                compressor.write(buffer, 0, read);
                nativeIO.dropPartialFileFromCache(inputStream.getFD(), totalBytesRead, read, false);
                totalBytesRead += read;
            }
            compressor.finish();
            compressor.flush();

            oldFile.delete();
            nativeIO.dropFileFromCache(gzippedFile);
        } catch (IOException e) {
            logger.warning("Got '" + e + "' while compressing '" + oldFile.getPath() + "'.");
        }
    }

    /** Name files by date - create a symlink with a constant name to the newest file */
    private void createSymlinkToCurrentFile() {
        if (symlinkName == null) return;
        File f = new File(fileName);
        File f2 = new File(f.getParent(), symlinkName);
        String canonicalPath;
        try {
            canonicalPath = f.getCanonicalPath();
        } catch (IOException e) {
            logger.warning("Got '" + e + "' while doing f.getCanonicalPath() on file '" + f.getPath() + "'.");
            return;
        }
        String [] cmd = new String[]{"/bin/ln", "-sf", canonicalPath, f2.getPath()};
        try {
            int retval = new ProcessExecuter().exec(cmd).getFirst();
            // Detonator pattern: Think of all the fun we can have if ln isn't what we
            // think it is, if it doesn't return, etc, etc
            if (retval != 0) {
                logger.warning("Command '" + Arrays.toString(cmd) + "' + failed with exitcode=" + retval);
            }
        } catch (IOException e) {
            logger.warning("Got '" + e + "' while doing'" + Arrays.toString(cmd) + "'.");
        }
    }

    /**
     * Calculate rotation times array, given times in minutes, as "0 60 ..."
     *
     */
    private static long[] calcTimesMinutes(String times) {
        ArrayList<Long> list = new ArrayList<>(50);
        int i = 0;
        boolean etc = false;

        while (i < times.length()) {
            if (times.charAt(i) == ' ') { i++; continue; } // skip spaces
            int j = i; // start of string
            i = times.indexOf(' ', i);
            if (i == -1) i = times.length();
            if (times.charAt(j) == '.' && times.substring(j,i).equals("...")) { // ...
                etc = true;
                break;
            }
            list.add(Long.valueOf(times.substring(j,i)));
        }

        int size = list.size();
        long[] longtimes = new long[size];
        for (i = 0; i<size; i++) {
            longtimes[i] = list.get(i)   // pick up value in minutes past midnight
                           * 60000;                          // and multiply to get millis
        }

        if (etc) { // fill out rest of day, same as final interval
            long endOfDay = 24*60*60*1000;
            long lasttime = longtimes[size-1];
            long interval = lasttime - longtimes[size-2];
            long moreneeded = (endOfDay - lasttime)/interval;
            if (moreneeded > 0) {
                int newsize = size + (int)moreneeded;
                long[] temp = new long[newsize];
                for (i=0; i<size; i++) {
                    temp[i] = longtimes[i];
                }
                while (size < newsize) {
                    lasttime += interval;
                    temp[size++] = lasttime;
                }
                longtimes = temp;
            }
        }

        return longtimes;
    }

    // Support staff :-)
    private static final long lengthOfDayMillis = 24*60*60*1000;  // ? is this close enough ?

    private static long timeOfDayMillis ( long time ) {
        return time % lengthOfDayMillis;
    }

    void setSymlinkName(String symlinkName) {
        this.symlinkName = symlinkName;
    }

    /**
     * Flushes all queued messages, interrupts the log thread in this and
     * waits for it to end before returning
     */
    public void shutdown() {
        logThread.interrupt();
        try {
            logThread.join();
            executor.shutdown();
            executor.awaitTermination(600, TimeUnit.SECONDS);
        }
        catch (InterruptedException e) {
        }
    }

    /**
     * Only for unit testing. Do not use.
     */
    public String getFileName() {
        return fileName;
    }

}