/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) Ericsson AB, 2004-2008. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.jvnet.glassfish.comms.admin.reporter;
import com.ericsson.ssa.container.reporter.Reporter;
import com.ericsson.ssa.container.sim.SipServletFacade;
import com.ericsson.ssa.sip.Layer;
import com.ericsson.ssa.config.ConfigFactory;
import com.ericsson.ssa.config.annotations.Configuration;
import com.ericsson.ssa.config.annotations.UpdatePolicy;
import com.ericsson.ssa.sip.SipServletRequestImpl;
import com.ericsson.ssa.sip.SipServletResponseImpl;
import com.ericsson.ssa.sip.Header;
import com.sun.enterprise.util.SystemPropertyConstants;
import com.sun.enterprise.web.accesslog.AccessLogFormatter;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.LinkedList;
import java.util.Date;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Date;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Servlet;
import org.apache.catalina.Request;
import org.apache.catalina.Response;
import org.jvnet.glassfish.comms.util.LogUtil;
public class AccessLog extends AccessLogFormatter {
private static AccessLog instance = new AccessLog();
private static Logger _logger = LogUtil.SMI_LOGGER.getLogger();
private static final String QUOTE = "\"";
private final static int MIN_BUFFER_SIZE = 4096;
private final static long DEFAULT_SIP_ACCESS_LOG_SIZE = 2000000;
private static long logStartTime;
private boolean accessLogEnabled = false;
private String pattern;
private boolean logRotationEnabled;
private int logRotationTime; // default 15 minutes
private String logRotationSuffix;
private String accessLogDir;
private long logRotationFileSize = DEFAULT_SIP_ACCESS_LOG_SIZE;
private static FileChannel fileChannel;
private static FileOutputStream fos;
private final static String SIP_ACCESS_LOG_NAME = "sip_access_log";
/*
* Supported access log entry tokens
*/
private static final String CLIENT_NAME = "client.name";
private static final String AUTH_USER_NAME = "auth-user-name";
private static final String DATE_TIME = "datetime";
private static final String REQUEST = "request";
private static final String STATUS = "status";
private static final String RESPONSE_LENGTH = "response.length";
private static final String MAX_FORWARDS = "max.forwards";
private static final String FROM = "from";
private static final String CSEQ = "cseq";
private static final String CONTACT = "contact";
private static final String TO = "to";
private static final String CONTENT_TYPE = "content.type";
private static final String VIA = "via";
private static final String CALL_ID = "call.id";
/**
* List of access log pattern components
*/
private LinkedList<String> patternComponents = new LinkedList<String>();
/**
* Constructor.
*
* @param pattern The access log pattern
*/
public AccessLog() {
dayFormatter = new SimpleDateFormat("dd");
dayFormatter.setTimeZone(tz);
monthFormatter = new SimpleDateFormat("MM");
monthFormatter.setTimeZone(tz);
yearFormatter = new SimpleDateFormat("yyyy");
yearFormatter.setTimeZone(tz);
timeFormatter = new SimpleDateFormat("HH:mm:ss");
timeFormatter.setTimeZone(tz);
}
public static AccessLog getInstance() {
return instance;
}
@Configuration(key="Format", node = "/SipService/AccessLog")
public void setSipAccessLogPattern(String format) {
pattern = format;
if (pattern != null)
this.patternComponents = parsePattern(pattern);
}
@Configuration(key="RotationEnabled", node = "/SipService/AccessLog")
public void setSipAccessLogRotationEnabled(String enabled) {
logRotationEnabled = Boolean.parseBoolean(enabled);
}
@Configuration(key="RotationIntervalInMinutes", node = "/SipService/AccessLog")
public void setSipAccessLogRotationTime(int time) {
logRotationTime = time;
}
@Configuration(key="RotationSuffix", node = "/SipService/AccessLog")
public void setSipAccessLogRotationSuffix(String suffix) {
logRotationSuffix = suffix;
}
@Configuration(key="accessLoggingEnabled", node = "/SipService")
public void setSipAccessLogEnabled(String enabled) {
if (enabled != null && enabled.equals("true")) {
accessLogEnabled = true;
if (fileChannel == null)
openAccessLog();
} else {
if (fileChannel != null)
closeAccessLog();
}
}
@Configuration(key="accesslog", node = "/SipService")
public void setSipAccessLog(String dir) {
accessLogDir = dir;
}
@Configuration(key="rotationLogSize", node = "/SipService")
public void setSipAccessLogRotationFileSize(int size) {
if (size != 0)
logRotationFileSize = size;
}
public boolean getSipAccessLogEnabled() {
return accessLogEnabled;
}
public String getSipAccessLogDir() {
return accessLogDir;
}
public String getSipAccessLogPattern() {
return pattern;
}
public void openAccessLog() {
try {
if (accessLogDir == null)
accessLogDir = System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY)
+ File.separator + "logs" + File.separator + "sipaccess";
File dir = new File(accessLogDir);
dir.mkdirs(); // create the directory if not created
File logFile = new File(accessLogDir + File.separator + SIP_ACCESS_LOG_NAME); // Open the file and then get a channel from the stream
logStartTime = (new Date()).getTime();
fos = new FileOutputStream(logFile, true);
fileChannel = fos.getChannel();
} catch (IOException e) {
try{
if ( fileChannel != null )
fileChannel.close();
} catch (IOException ex){
}
}
}
public void log(String s) {
try{
if (logRotationEnabled)
rotateLog();
if (fileChannel.isOpen()) {
ByteBuffer byteBuffer =
ByteBuffer.wrap(s.getBytes());
while (byteBuffer.hasRemaining()){
fileChannel.write(byteBuffer);
}
}
} catch (IOException ex){
}
}
private synchronized void rotateLog() throws IOException {
if (logRotationTime != 0) {
long currentTime = (new Date()).getTime();
long timeStartedInMins = ((currentTime - logStartTime)/1000)/60;
if (timeStartedInMins > logRotationTime)
createNewAccessLog();
}
else if ((logRotationTime == 0) && (fileChannel.size() > logRotationFileSize)) {
createNewAccessLog();
}
}
private void createNewAccessLog() {
closeAccessLog();
String oldAccessLogName = accessLogDir + File.separator + SIP_ACCESS_LOG_NAME;
DateFormat dateFormat = new SimpleDateFormat(logRotationSuffix);
Date date = new Date();
String newAccessLogName = oldAccessLogName + "." + dateFormat.format(date);
File oldAccessLogFile = new File(oldAccessLogName);
File newAccessLogFile = new File(newAccessLogName);
oldAccessLogFile.renameTo(newAccessLogFile);
openAccessLog();
}
/**
* Close the currently open log file (if any)
*/
public void closeAccessLog() {
try{
if (fileChannel != null)
fileChannel.close();
if (fos != null)
fos.close();
} catch (IOException ex){
}
}
/**
* Appends an access log entry line, with info obtained from the given
* request and response objects, to the given CharBuffer.
*
* @param request The request object from which to obtain access log info
* @param response The response object from which to obtain access log info
* @param charBuffer The CharBuffer to which to append access log info
*/
public void appendLogEntry(Request request, Response response, CharBuffer charBuffer) {
}
/**
* Appends an access log entry line, with info obtained from the given request
*
* @param request The request object from which to obtain access log info
*/
public void logRequestEntry(String header, SipServletRequest sreq) {
String logString = null;
SipServletRequestImpl request = (SipServletRequestImpl) sreq;
CharBuffer charBuffer = CharBuffer.allocate(MIN_BUFFER_SIZE);
for (int i=0; i<patternComponents.size(); i++) {
String pc = patternComponents.get(i);
if (CLIENT_NAME.equals(pc)) {
appendClientName(charBuffer, request.getRemoteUser());
} else if (AUTH_USER_NAME.equals(pc)) {
appendAuthUserName(charBuffer, request.getRemoteHost());
} else if (DATE_TIME.equals(pc)) {
appendCurrentDate(charBuffer);
} else if (REQUEST.equals(pc)) {
appendRequestInfo(charBuffer, request);
} else if (RESPONSE_LENGTH.equals(pc)) {
appendResponseLength(charBuffer, request.getContentLength());
} else if (VIA.equals(pc)) {
Header via = request.getRawHeader(Header.VIA);
appendVia(charBuffer, via);
} else if (CALL_ID.equals(pc)) {
Header callId = request.getRawHeader(Header.CALL_ID);
appendString(charBuffer, callId);
} else if (TO.equals(pc)) {
Header to = request.getRawHeader(Header.TO);
appendString(charBuffer, to);
} else if (FROM.equals(pc)) {
Header from = request.getRawHeader(Header.FROM);
appendString(charBuffer, from);
} else if (CSEQ.equals(pc)) {
Header cseq = request.getRawHeader(Header.CSEQ);
appendString(charBuffer, cseq);
} else if (MAX_FORWARDS.equals(pc)) {
Header maxForwards = request.getRawHeader(Header.MAX_FORWARDS);
appendString(charBuffer, maxForwards);
} else if (CONTACT.equals(pc)) {
Header contact = request.getRawHeader(Header.CONTACT);
appendString(charBuffer, contact);
} else if (CONTENT_TYPE.equals(pc)) {
Header contentType = request.getRawHeader(Header.CONTENT_TYPE);
appendString(charBuffer, contentType);
}
charBuffer.put(SPACE);
}
charBuffer.put("\n");
charBuffer.flip();
logString = charBuffer.toString();
if (logString != null && !logString.trim().equals(""))
log(header + logString);
}
/**
* Appends an access log entry line, with info obtained from the given response
*
* @param request The response object from which to obtain access log info
*/
public void logResponseEntry(String header, SipServletResponse sresponse) {
String logString = null;
SipServletResponseImpl response = (SipServletResponseImpl) sresponse;
CharBuffer charBuffer = CharBuffer.allocate(MIN_BUFFER_SIZE);
for (int i=0; i<patternComponents.size(); i++) {
String pc = patternComponents.get(i);
if (CLIENT_NAME.equals(pc)) {
appendClientName(charBuffer, response.getRemoteUser());
} else if (AUTH_USER_NAME.equals(pc)) {
appendAuthUserName(charBuffer, response.getRemoteAddr());
} else if (DATE_TIME.equals(pc)) {
appendCurrentDate(charBuffer);
} else if (STATUS.equals(pc)) {
appendResponseStatus(charBuffer, response);
} else if (RESPONSE_LENGTH.equals(pc)) {
appendResponseLength(charBuffer, response.getContentLength());
} else if (VIA.equals(pc)) {
Header via = response.getRawHeader(Header.VIA);
appendVia(charBuffer, via);
} else if (CALL_ID.equals(pc)) {
Header callId = response.getRawHeader(Header.CALL_ID);
appendString(charBuffer, callId);
} else if (TO.equals(pc)) {
Header to = response.getRawHeader(Header.TO);
appendString(charBuffer, to);
} else if (FROM.equals(pc)) {
Header from = response.getRawHeader(Header.FROM);
appendString(charBuffer, from);
} else if (CSEQ.equals(pc)) {
Header cseq = response.getRawHeader(Header.CSEQ);
appendString(charBuffer, cseq);
} else if (MAX_FORWARDS.equals(pc)) {
Header maxForwards = response.getRawHeader(Header.MAX_FORWARDS);
appendString(charBuffer, maxForwards);
} else if (CONTACT.equals(pc)) {
Header contact = response.getRawHeader(Header.CONTACT);
appendString(charBuffer, contact);
} else if (CONTENT_TYPE.equals(pc)) {
Header contentType = response.getRawHeader(Header.CONTENT_TYPE);
appendString(charBuffer, contentType);
}
charBuffer.put(SPACE);
}
charBuffer.put("\n");
charBuffer.flip();
logString = charBuffer.toString();
if (logString != null && !logString.trim().equals(""))
log(header + logString);
}
/*
* Parses the access log pattern (that was specified via setPattern) into
* its individual components, and returns them as a list.
*
* @param pattern The pattern to parse
*
* @return List containing the access log pattern components
*/
private LinkedList<String> parsePattern(String pattern) {
LinkedList list = new LinkedList();
int from = 0;
int end = -1;
int index = -1;
if (pattern == null || pattern.indexOf('%') < 0)
_logger.log(Level.SEVERE, "accesslog.invalidAccessLogPattern", pattern);
else {
while ((index = pattern.indexOf('%', from)) >= 0) {
end = pattern.indexOf('%', index+1);
if (end < 0)
_logger.log(Level.SEVERE, "accesslog.missingAccessLogPatternEndDelimiter", pattern);
String component = pattern.substring(index+1, end);
if (!AUTH_USER_NAME.equals(component)
&& !CLIENT_NAME.equals(component)
&& !DATE_TIME.equals(component)
&& !REQUEST.equals(component)
&& !STATUS.equals(component)
&& !RESPONSE_LENGTH.equals(component)) {
_logger.log(Level.SEVERE, "accesslog.invalidAccessLogPatternComponent",
new Object[] { component, pattern });
}
list.add(component);
from = end + 1;
}
}
return list;
}
/*
* Appends the client host name of the given request to the given char
* buffer.
*/
private void appendClientName(CharBuffer cb, String value) {
cb.put(QUOTE);
if (value == null) {
value = "NULL-CLIENT-NAME";
}
cb.put(value);
cb.put(QUOTE);
}
/*
* Appends the authenticated user (if any) to the given char buffer.
*/
private void appendAuthUserName(CharBuffer cb, String user) {
cb.put(QUOTE);
if (user == null) {
user = "NULL-AUTH-USER";
}
cb.put(user);
cb.put(QUOTE);
}
/*
* Appends the current date to the given char buffer.
*/
private void appendCurrentDate(CharBuffer cb) {
cb.put(QUOTE);
Date date = getDate();
cb.put(dayFormatter.format(date)); // Day
cb.put('/');
cb.put(lookup(monthFormatter.format(date))); // Month
cb.put('/');
cb.put(yearFormatter.format(date)); // Year
cb.put(':');
cb.put(timeFormatter.format(date)); // Time
cb.put(SPACE);
cb.put(timeZone); // Time Zone
cb.put(QUOTE);
}
/*
* Appends info about the given request to the given char buffer.
*/
private void appendRequestInfo(CharBuffer cb, SipServletRequest sreq) {
cb.put(QUOTE);
cb.put(sreq.getMethod());
cb.put(SPACE);
cb.put(sreq.getRequestURI().toString());
cb.put(QUOTE);
}
/*
* Appends the response status to the given char buffer.
*/
private void appendResponseStatus(CharBuffer cb, SipServletResponse sresp) {
cb.put(String.valueOf(sresp.getStatus()));
}
/*
* Appends the content length of the given response to the given char
* buffer.
*/
private void appendResponseLength(CharBuffer cb, int length) {
cb.put("" + length);
}
private void appendVia(CharBuffer cb, Header via) {
if (via != null) {
cb.put(QUOTE);
for (ListIterator<String> li = via.getValues() ; li.hasNext();)
cb.put(li.next());
cb.put(QUOTE);
}
}
private void appendString(CharBuffer cb, Header header) {
if (header != null && header.getValue() != null) {
cb.put(QUOTE);
cb.put(header.getValue());
cb.put(QUOTE);
}
}
}