mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

opends
28.11.2006 eda79366f0bdacebb6fca64c8e472538c9b16798
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2006 Sun Microsystems, Inc.
 */
package org.opends.server.loggers;
 
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.logging.ErrorManager;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
 
import org.opends.server.api.InvokableComponent;
import org.opends.server.core.DirectoryException;
import org.opends.server.config.ConfigAttribute;
import org.opends.server.config.ConfigEntry;
import org.opends.server.types.DN;
import org.opends.server.types.InvokableMethod;
import org.opends.server.types.ResultCode;
import org.opends.server.util.TimeThread;
 
import static org.opends.server.config.ConfigConstants.*;
import static org.opends.server.messages.ConfigMessages.*;
import static org.opends.server.messages.MessageHandler.*;
 
/**
 * Simple file logging <tt>Handler</tt>.
 * The <tt>DirectoryFileHandler</tt> can write to a specified file,
 * and can handle rotating the file based on predefined policies.
 */
public class DirectoryFileHandler extends Handler
        implements LoggerAlarmHandler, InvokableComponent
{
  private Writer writer;
  private MeteredStream meter;
  private boolean append;
  private String filename;
  private int bufferSize = 65536;
  private long limit = 0;
  private File file;
  private ArrayList<ActionType> actions;
  private ConfigEntry configEntry;
 
 
  /**
   * Initialize a DirectoryFileHandler to write to the given filename.
   *
   * @param configEntry The configuration entry for the associated logger.
   * @param filename  the name of the output file.
   * @param bufferSize the buffer size before flushing data to the file.
   * @exception  IOException if there are IO problems opening the files.
   * @exception  SecurityException  if a security manager exists and if
   *          the caller does not have <tt>LoggingPermission("control")</tt>.
   */
  public DirectoryFileHandler(ConfigEntry configEntry,
                              String filename, int bufferSize)
         throws IOException, SecurityException
  {
    this.configEntry = configEntry;
    this.bufferSize = bufferSize;
    configure();
    this.filename = filename;
    openFile();
  }
 
  /**
   * Initialize a DirectoryFileHandler to write to the given filename,
   * with optional append.
   *
   * @param configEntry The configuration entry for the associated logger.
   * @param filename  the name of the output file
   * @param append  specifies append mode
   * @param bufferSize the buffer size before flushing data to the file.
   * @exception  IOException if there are IO problems opening the files.
   * @exception  SecurityException  if a security manager exists and if
   *          the caller does not have <tt>LoggingPermission("control")</tt>.
   */
  public DirectoryFileHandler(ConfigEntry configEntry,
                              String filename, boolean append, int bufferSize)
         throws IOException, SecurityException
  {
    this.configEntry = configEntry;
    this.bufferSize = bufferSize;
    configure();
    this.filename = filename;
    this.append = append;
    openFile();
  }
 
 
  /**
   * Set the maximum file size limit.
   *
   * @param limit The maximum file size.
   */
  public void setFileSize(long limit)
  {
    this.limit = limit;
  }
 
 
  /**
   * Private method to open the set of output files, based on the
   * configured instance variables.
   *
   * @exception IOException        If there was an error while opening the file.
   * @exception SecurityException  If a security manager exists and if
   *                               the caller does not have LoggingPermission.
   */
  private void openFile() throws IOException, SecurityException
  {
    // We register our own ErrorManager during initialization
    // so we can record exceptions.
    InitializationErrorManager em = new InitializationErrorManager();
    setErrorManager(em);
 
    file = new File(filename);
 
    // Create the initial log file.
    if (append)
    {
      open(file, true);
    } else
    {
      // FIXME - Should we rotate?
      open(file, false);
    }
 
    // Did we detect any exceptions during initialization?
    Exception ex = em.lastException;
    if (ex != null)
    {
      if (ex instanceof IOException)
      {
        throw (IOException) ex;
      } else if (ex instanceof SecurityException)
      {
        throw (SecurityException) ex;
      } else
      {
        throw new IOException("Exception: " + ex);
      }
    }
 
    // Install the normal default ErrorManager.
    setErrorManager(new ErrorManager());
  }
 
 
  /**
   * Rotate the current file to the specified new file name.
   * @param newFile The name of the new file to rotate to.
   */
  public void rotate(String newFile)
  {
    close();
    File f1 = file;
    File f2 = new File(newFile);
    if (f1.exists())
    {
      if (f2.exists())
      {
        System.err.println("File:" + f2 + " already exists. Renaming...");
        File f3 = new File(newFile + ".sav");
        f2.renameTo(f3);
      }
      f1.renameTo(f2);
    }
    try
    {
      open(file, false);
    } catch (IOException ix)
    {
      // We don't want to throw an exception here, but we
      // report the exception to any registered ErrorManager.
      reportError(null, ix, ErrorManager.OPEN_FAILURE);
    }
  }
 
  /**
   * Format and publish a <tt>LogRecord</tt>.
   *
   * @param  record  Description of the log event. A null record is
   *         silently ignored and is not published.
   *
   */
  public void publish(LogRecord record)
  {
    String msg;
    try
    {
      msg = getFormatter().format(record);
    } catch (Exception ex)
    {
      reportError(null, ex, ErrorManager.WRITE_FAILURE);
      return;
    }
 
    synchronized(this)
    {
      try
      {
        writer.write(msg);
      } catch (Exception ex)
      {
        reportError(null, ex, ErrorManager.WRITE_FAILURE);
        return;
      }
 
      if(limit > 0 && meter.written >= limit)
      {
        rollover();
      }
    }
  }
 
 
  /**
   * Return the number of bytes written to the current file.
   *
   * @return  The number of bytes written to the current file.
   */
  public long getFileSize()
  {
    return meter.written;
  }
 
  /**
  * This method is called from by the logger thread when a
  * file rotation needs to happen.
  */
  public void rollover()
  {
    String newfilename = filename + "." + getFileExtension();
    rotate(newfilename);
 
    RotationActionThread rotThread =
      new RotationActionThread(newfilename, actions, configEntry);
    rotThread.start();
 
  }
 
  /**
   * This method sets the actions that need to be executed after rotation.
   *
   * @param actions An array of actions that need to be executed on rotation.
   */
  public void setPostRotationActions(ArrayList<ActionType> actions)
  {
    this.actions = actions;
  }
 
 
  /**
   * Retrieves the DN of the configuration entry with which this component is
   * associated.
   *
   * @return  The DN of the configuration entry with which this component is
   *          associated.
   */
  public DN getInvokableComponentEntryDN()
  {
    return configEntry.getDN();
  }
 
 
 
  /**
   * Retrieves a list of the methods that may be invoked for this component.
   *
   * @return  A list of the methods that may be invoked for this component.
   */
  public InvokableMethod[] getOperationSignatures()
  {
    InvokableMethod[] methods = new InvokableMethod[1];
    methods[0] = new InvokableMethod("rotateNow",
                                     "Rotate the log file immediately",
                                     null, "void", true, true);
    return methods;
  }
 
 
 
  /**
   * Invokes the specified method with the provided arguments.
   *
   * @param  methodName  The name of the method to invoke.
   * @param  arguments   The set of configuration attributes holding the
   *                     arguments to use for the method.
   *
   * @return  The return value for the method, or <CODE>null</CODE> if it did
   *          not return a value.
   *
   * @throws  DirectoryException  If there was no such method, or if an error
   *                              occurred while attempting to invoke it.
   */
  public Object invokeMethod(String methodName, ConfigAttribute[] arguments)
         throws DirectoryException
  {
    if(!methodName.equals("rotateNow"))
    {
      int msgID = MSGID_CONFIG_JMX_NO_METHOD;
      throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
                                   getMessage(msgID), msgID);
    }
 
    rollover();
 
    return null;
  }
 
 
  /**
   * Close the current output stream.
   *
   */
  public void close()
  {
    flushAndClose();
  }
 
 
  /**
   * Return the extension for the target filename for the rotated file.
   *
   * @return  The extension for the target filename for the rotated file.
   */
  private String getFileExtension()
  {
    return TimeThread.getUTCTime();
  }
 
 
  /**
   * Open the file and set the appropriate output stream.
   *
   * @param  fname   The path and name of the file to be written.
   * @param  append  Indicates whether to append to the existing file or to
   *                 overwrite it.
   *
   * @throws  IOException  If a problem occurs while opening the file.
   */
  private void open(File fname, boolean append) throws IOException
  {
    long len = 0;
    if (append)
    {
      len = fname.length();
    }
    FileOutputStream fout = new FileOutputStream(fname, append);
    BufferedOutputStream bout = null;
    if(bufferSize <= 0)
    {
      bout = new BufferedOutputStream(fout);
    } else
    {
      bout = new BufferedOutputStream(fout, bufferSize);
    }
    meter = new MeteredStream(bout, len);
    // flushAndClose();
    writer = new BufferedWriter(new OutputStreamWriter(meter));
  }
 
 
  /**
   * Private method to configure a DirectoryFileHandler
   * with default values.
   */
  private void configure()
  {
    setLevel(Level.ALL);
    this.append = true;
  }
 
 
  /**
   * Flush any buffered messages and close the output stream.
   */
  private void flushAndClose()
  {
    if (writer != null)
    {
      try
      {
        writer.flush();
        writer.close();
      } catch (Exception ex) {
        // We don't want to throw an exception here, but we
        // report the exception to any registered ErrorManager.
        reportError(null, ex, ErrorManager.CLOSE_FAILURE);
      }
      writer = null;
    }
 
  }
 
  /**
   * Flush any buffered messages.
   */
  public void flush()
  {
    if (writer != null)
    {
      try
      {
        writer.flush();
      } catch (Exception ex) {
        // We don't want to throw an exception here, but we
        // report the exception to any registered ErrorManager.
        reportError(null, ex, ErrorManager.FLUSH_FAILURE);
      }
    }
  }
 
 
}