PostHogAccessLog.java [src/csip] Revision:   Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2023, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip;

import static csip.ModelDataServiceConstants.CANCELED;
import static csip.ModelDataServiceConstants.FAILED;
import static csip.ModelDataServiceConstants.FINISHED;
import static csip.ModelDataServiceConstants.KEY_CPU_TIME;
import static csip.ModelDataServiceConstants.KEY_REQ_IP;
import static csip.ModelDataServiceConstants.KEY_SERVICE_URL;
import static csip.ModelDataServiceConstants.KEY_STATUS;
import static csip.ModelDataServiceConstants.TIMEDOUT;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 */
class PostHogAccessLog implements AccessLog {

  static final List<String> sub = Arrays.asList(FINISHED, FAILED, CANCELED, TIMEDOUT);
  Logger log;

//  PostHog posthog;

  PostHogAccessLog(Logger l, String url, String apiKey) {
    log = l;
    // posthog = new PostHog.Builder(apiKey).host(host).build();
    log.log(Level.INFO, "Connected to access log: {0}", url);
  }


  @Override
  public synchronized void close() throws Exception {
    // posthog.shutdown();  // send the last events in queue
  }


  @Override
  public void log(JSONObject metainfo) {
    if (metainfo == null)
      return;
    try {
      String status = metainfo.getString(KEY_STATUS);
      // ingnore all other status changes. 
      if (!sub.contains(status))
        return;

      String req_ip = metainfo.getString(KEY_REQ_IP);
      String service_url = metainfo.getString(KEY_SERVICE_URL);
      long cpu_time = metainfo.optLong(KEY_CPU_TIME, -1);

      URL u = new URL(service_url);
      String service = u.getPath().substring(1);

      Map<String, Object> props = new HashMap<>();
      props.put("status", status);
      props.put("port", u.getPort());
      props.put("cpu_time", cpu_time);

      if (log.isLoggable(Level.INFO)) {
        log.log(Level.INFO, "AccessLog: {0} - {1}", new Object[]{req_ip, service});
        log.log(Level.INFO, "AccessLog Properties: {0}", props);
      }

//    posthog.capture(req_ip, service, props);
    } catch (MalformedURLException | JSONException ex) {
      log.log(Level.SEVERE, null, ex);
    }
  }

  /*
   * // // run commands posthog.capture("10.2.3.152",
   * "test_csip-srv/m/run/1.0", new HashMap<String, Object>() { {
   * put("cpu_time", "133"); put("status", "done"); } });
   *
   */
}