86 lines
2.7 KiB
Java
86 lines
2.7 KiB
Java
package org.gcube.smartgears.utils;
|
|
|
|
import java.io.IOException;
|
|
|
|
import javax.servlet.ServletException;
|
|
|
|
import org.apache.catalina.connector.Request;
|
|
import org.apache.catalina.connector.Response;
|
|
import org.apache.catalina.valves.ValveBase;
|
|
import org.gcube.accounting.datamodel.UsageRecord.OperationResult;
|
|
import org.gcube.accounting.datamodel.usagerecords.ServiceUsageRecord;
|
|
import org.gcube.accounting.persistence.AccountingPersistence;
|
|
import org.gcube.accounting.persistence.AccountingPersistenceFactory;
|
|
import org.gcube.common.scope.api.ScopeProvider;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
public class GcubeAccountingValve extends ValveBase {
|
|
|
|
private static Logger log = LoggerFactory.getLogger(GcubeAccountingValve.class);
|
|
|
|
private String infra;
|
|
private String serviceClass;
|
|
private String serviceName;
|
|
private String hostAndPort;
|
|
|
|
public void setInfra(String infra) {
|
|
this.infra = infra;
|
|
}
|
|
|
|
public void setServiceClass(String serviceClass) {
|
|
this.serviceClass = serviceClass;
|
|
}
|
|
|
|
public void setServiceName(String serviceName) {
|
|
this.serviceName = serviceName;
|
|
}
|
|
|
|
public void setHostAndPort(String hostAndPort) {
|
|
this.hostAndPort = hostAndPort;
|
|
}
|
|
|
|
@Override
|
|
public void invoke(Request request, Response response) throws IOException, ServletException {
|
|
try {
|
|
String callerIp = request.getHeader("x-forwarded-for");
|
|
if (callerIp == null) {
|
|
callerIp = request.getRemoteAddr();
|
|
}
|
|
|
|
boolean success = response.getStatus()<400;
|
|
ScopeProvider.instance.set(infra);
|
|
AccountingPersistenceFactory.setFallbackLocation("/tmp");
|
|
AccountingPersistence persistence = AccountingPersistenceFactory.getPersistence();
|
|
ServiceUsageRecord serviceUsageRecord = new ServiceUsageRecord();
|
|
try{
|
|
|
|
serviceUsageRecord.setConsumerId("UNKNOWN");
|
|
serviceUsageRecord.setCallerQualifier("UNKNOWN");
|
|
serviceUsageRecord.setScope(infra);
|
|
serviceUsageRecord.setServiceClass(serviceClass);
|
|
serviceUsageRecord.setServiceName(serviceName);
|
|
serviceUsageRecord.setDuration(200l);
|
|
serviceUsageRecord.setHost(hostAndPort);
|
|
serviceUsageRecord.setCalledMethod(request.getRequestURI());
|
|
serviceUsageRecord.setCallerHost(callerIp);
|
|
serviceUsageRecord.setOperationResult(success?OperationResult.SUCCESS:OperationResult.FAILED);
|
|
persistence.account(serviceUsageRecord);
|
|
log.info("Request: {} {} {} {} ", infra, request.getContextPath(), request.getRequestURI(), success);
|
|
}catch(Exception ex){
|
|
log.warn("invalid record passed to accounting ",ex);
|
|
}finally {
|
|
ScopeProvider.instance.reset();
|
|
}
|
|
|
|
}catch (Exception e) {
|
|
log.error("error executing valve", e);
|
|
}
|
|
getNext().invoke(request, response);
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|