File size: 4,232 Bytes
19605ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use strict';

// Provides a stream to write to.
// When rotate is called, a new stream is provisioned.
// The original stream is closed and the file archived
// according to the archival rules.

var fs = require('fs');
var async = require('async');
var _ = require('lodash');
var zlib = require('zlib');
var EventEmitter = require('events').EventEmitter;
var NumberedFileOps = require('./numberedfileops');
var DateStampedFileOps = require('./datestampedfileops');

var _DEBUG = false;

function FileRotator(logpath, totalFiles, totalSize, gzip) {

    var base = new EventEmitter();

    var stream;
    var streamPath;

    var fileops = null;

    if (DateStampedFileOps.isDateStamped(logpath)) {
        fileops = DateStampedFileOps(logpath, totalFiles, totalSize, gzip);
    } else {
        fileops = NumberedFileOps(logpath, totalFiles, totalSize, gzip);
    }

    function gzipCurrentFile(next) {
        if (!gzip) {
            return next();
        }

        var unzippedPath = fileops.getStreamFilepath(false);
        var zippedPath = fileops.getStreamFilepath(true);

        fs.createReadStream(unzippedPath)
        .on('error', function (err) {
            base.emit('error', err);
            next();
        })
        .pipe(zlib.createGzip())
        .pipe(fs.createWriteStream(zippedPath))
        .on('finish', function () {
            fs.unlink(unzippedPath, next);
        })
    }

    function streamErrorHandler(err) {
        base.emit('error', err);
    };

    function initialiseNewFile(triggerinfo) {
        return function (next) {
            triggerinfo = triggerinfo || {};
            fileops.newStreamFilepath(triggerinfo, function (err, filePath) {
                if (err) {
                    return next(err);
                }

                stream = fs.createWriteStream(filePath,
                    {flags: 'a', encoding: 'utf8'});

                streamPath = filePath;

                stream.on('error', streamErrorHandler);

                stream.once('open', function () {
                    fs.stat(filePath, function (err, stats) {
                        if (err) {
                            base.emit('error', err);
                        } else {
                            base.emit('newfile', {
                                stream: stream,
                                logpath: streamPath,
                                stats: stats
                            });
                        }

                        if (next) {
                            next();
                        }
                    });
                });
            });
        };
    }

    function shutdownCurrentStream(next) {
        base.emit('closefile');
        if (stream) {
            var streamCopy = stream;
            stream.end(function () {
                streamCopy.removeListener('error', streamErrorHandler);
                if (next) {
                    next();
                }
            });
            stream = null;
        }
    };

    // Calling rotate gives us a new stream
    // Once called, the previous stream is not valid and
    // you won't get another one until the callback has been called.
    function rotate(triggerinfo, callback) {
        async.series([
            shutdownCurrentStream,
            gzipCurrentFile,
            fileops.moveIntermediateFiles,
            fileops.deleteFiles,
            initialiseNewFile(triggerinfo)
        ], function (err) {
            callback(err, stream, streamPath);
        });
    }

    // This gives us an initial stream.
    // If a file already exists, we'll just append to it.
    var initialised = false;
    function initialise(startNewFile, callback) {
        if (!initialised) {
            initialised = true;

            async.series([
                fileops.deleteFiles,
                initialiseNewFile({ startNewFile: startNewFile })
            ], function (err) {
                callback(err, stream, streamPath);
            });
        } else {
            callback();
        }
    }

    return _.extend({}, {
        initialise: initialise,
        rotate: rotate,
        end: shutdownCurrentStream
    }, base);
}

module.exports = FileRotator;