Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f02747a716fb0a96043d6211711fd2e607507988 (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
/*******************************************************************************
 * Copyright (c) 2006, 2018 IBM Corporation and others.
 * 
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - Jeff Briggs, Henry Hughes, Ryan Morse
 *     Red Hat - ongoing maintenance
 *******************************************************************************/

package org.eclipse.linuxtools.systemtap.structures;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.linuxtools.internal.systemtap.structures.Localization;
import org.eclipse.linuxtools.systemtap.structures.listeners.IGobblerListener;

/**
 * A utility for saving script output to a log file as it runs.
 */
public class LoggingStreamDaemon implements IGobblerListener {
    private static final int BUFFER_SIZE = 1024;
    private static final Set<LoggingStreamDaemon> allLogs = new HashSet<>();

    protected StringBuilder output;
    protected File outputFile;
    protected FileWriter writer;
    private boolean saveLog = false;

    /**
     * Sets up a new logger. Log contents will be saved to a temporary file
     * until {@link #saveLog} is used to save the log to a specified file.
     */
    public LoggingStreamDaemon() {
        output = new StringBuilder();
        try {
            outputFile = File.createTempFile(this.toString(), ".tmp"); //$NON-NLS-1$
            writer = new FileWriter(outputFile, true);
        } catch (IOException ioe) {
            outputFile = null;
            writer = null;
        }
    }

    /**
     * Pushes output to log.
     */
    private void pushData() {
        try {
            // Recreate the log if it was deleted
            if (!outputFile.exists()) {
                startRestoredLog();
            }
            writer.write(output.toString());
            output.setLength(0);
            writer.flush();
        } catch (IOException ioe) {}
    }

    /**
     * Outputs one line.
     */
    @Override
    public void handleDataEvent(String line) {
        if (isReady()) {
            output.append(line);
            pushData();
        }
    }

    /**
     * Reads in and returns the output produced.
     * @return The logged data.
     */
    public String getOutput() {
        if (!isReady()) {
            return null;
        }
        if (output.length() > 0) {
            pushData();
        }
        try (FileReader reader = new FileReader(outputFile)) {
            char[] buffer = new char[BUFFER_SIZE];
            int count;
            StringBuilder builder = new StringBuilder();
            while (-1 != (count = reader.read(buffer))) {
                builder.append(buffer, 0, count);
            }
            return builder.toString();
        } catch (IOException ioe) {
            return null;
        }
    }

    /**
     * Sets the logging stream to be continuously saved to a file.
     * @param file The file to save the log data to. Must not be <code>null</code>.
     * @return <code>true</code> if the save was successful, <code>false</code> otherwise.
     */
    public boolean saveLog(File file) {
        if (!isReady()) {
            return false;
        }
        // If saving to the same file that's already being saved to,
        // either do nothing if it exists, or restore it if it doesn't.
        if (file.equals(outputFile)) {
            if (!outputFile.exists()) {
                try {
                    startRestoredLog();
                } catch (IOException e) {
                    return false;
                }
            }
            return true;
        }
        // If saving to a file used by another active log,
        // quit to avoid write conflicts.
        for (LoggingStreamDaemon log : allLogs) {
            if (!log.equals(this) && file.equals(log.outputFile)) {
                return false;
            }
        }

        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileWriter w = new FileWriter(file, false);
            try (FileReader r = new FileReader(outputFile)) {
                char[] buffer = new char[BUFFER_SIZE];
                int count;
                while (-1 != (count = r.read(buffer))) {
                    w.write(new String(buffer, 0, count));
                }
            }
            w.flush();
            writer.close();
            writer = w;
        } catch (IOException ioe) {
            return false;
        }
        outputFile.delete();
        outputFile = file;
        saveLog = true;
        allLogs.add(this);
        return true;
    }

    private void startRestoredLog() throws IOException {
        outputFile.createNewFile();
        output.insert(0, Localization.getString("LoggingStreamDaemon.ResumedLog") + '\n'); //$NON-NLS-1$
        writer.close();
        writer = new FileWriter(outputFile, false);
    }

    public void dispose() {
        if (outputFile != null) {
            if (!saveLog) {
                outputFile.delete();
            }
            outputFile = null;
        }

        if (writer != null) {
            try {
                writer.close();
            } catch(IOException ioe) {}
            writer = null;
        }

        if (output != null) {
            output.setLength(0);
            output = null;
        }

        allLogs.remove(this);
    }

    private boolean isReady() {
        return writer != null && outputFile != null;
    }
}

Back to the top