public static void main(String[] args) throws Exception {

    long timeBeforeInMillis = System.currentTimeMillis();

    JmxInvokerArguments arguments = new JmxInvokerArguments();
    CmdLineParser parser = new CmdLineParser(arguments);
    try {
      parser.parseArgument(args);
      arguments.cmdLineParser = parser;
      if (Strings2.isEmpty(arguments.pid) && arguments.pidFile == null) {
        throw new CmdLineException(parser, "Options --pid and --pid-file can NOT be both null");
      } else if (!Strings2.isEmpty(arguments.pid) && arguments.pidFile != null) {
        throw new CmdLineException(parser, "Options --pid and --pid-file can NOT be both defined");
      } else if ((arguments.attribute == null || arguments.attribute.length == 0)
          && (arguments.operation == null || arguments.operation.length == 0)
          && arguments.listMbeans == false
          && arguments.describeMbeans == false) {
        throw new CmdLineException(
            parser,
            "Option --attribute or --operation or --list-mbeans or --describe-mbeans must be defined");
      } else if ((arguments.attribute != null && arguments.attribute.length > 0)
          && (arguments.operation != null && arguments.operation.length > 0)) {
        throw new CmdLineException(
            parser, "Options --attribute and --operation can NOT be both defined");
      }

      String logLevel;
      if (arguments.superVerbose) {
        logLevel = "TRACE";
      } else if (arguments.verbose) {
        logLevel = "DEBUG";
      } else {
        logLevel = "WARN";
      }
      System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, logLevel);

      Map<ObjectName, Result> results = new JmxInvoker().process(arguments);
      for (Map.Entry<ObjectName, Result> entry : results.entrySet()) {
        System.out.println(entry.getValue().description);
      }
    } catch (CmdLineException e) {
      System.err.println("INVALID INVOCATION: " + e.getMessage());
      System.err.println("Arguments: " + Strings2.join(args, " "));
      System.err.println("Usage:");
      parser.printUsage(System.err);
      throw e;
    } catch (Exception e) {
      System.err.println("INVALID INVOCATION: " + e.getMessage());
      System.err.println("Arguments: " + Strings2.join(args, " "));
      e.printStackTrace();
      throw e;
    } finally {
      if (arguments.verbose || arguments.superVerbose) {
        System.out.println("Duration: " + (System.currentTimeMillis() - timeBeforeInMillis) + "ms");
      }
    }
  }
  public void tableChanged(String Message) {
    String inst = Message;
    Notification n =
        new AttributeChangeNotification(
            this,
            sequenceNumber++,
            System.currentTimeMillis(),
            "Table value changed",
            "Table",
            "String",
            Message,
            LocalServer.table
                .getValueAt(
                    Integer.parseInt(
                        inst.substring(
                            inst.indexOf("Row :") + "Row :".length(), inst.indexOf(","))),
                    Integer.parseInt(inst.substring(inst.indexOf("Column:") + "Column:".length())))
                .toString());

    /* Now send the notification using the sendNotification method
    inherited from the parent class NotificationBroadcasterSupport. */
    sendNotification(n);
    // TODO Auto-generated method stub

  }
Exemple #3
0
 public Q2(String[] args) {
   super();
   this.args = args;
   startTime = System.currentTimeMillis();
   instanceId = UUID.randomUUID();
   parseCmdLine(args);
   libDir = new File(deployDir, "lib");
   dirMap = new TreeMap();
   deployDir.mkdirs();
   mainClassLoader = Thread.currentThread().getContextClassLoader();
 }
  /**
   * Handle a single JMXRequest. The response status is set to 200 if the request was successful
   *
   * @param pJmxReq request to perform
   * @return the already converted answer.
   * @throws InstanceNotFoundException
   * @throws AttributeNotFoundException
   * @throws ReflectionException
   * @throws MBeanException
   */
  public JSONObject handleRequest(JmxRequest pJmxReq)
      throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException,
          MBeanException, IOException {
    lazyInitIfNeeded();

    boolean debug = isDebug();

    long time = 0;
    if (debug) {
      time = System.currentTimeMillis();
    }
    JSONObject json = callRequestDispatcher(pJmxReq);

    // Update global history store
    historyStore.updateAndAdd(pJmxReq, json);
    json.put("status", 200 /* success */);

    if (debug) {
      debug("Execution time: " + (System.currentTimeMillis() - time) + " ms");
      debug("Response: " + json);
    }

    return json;
  }
  public CompositeData getNextEntry(Object[] indexObjects) {

    // User code starts here
    if (!agentName.initAlert()) return null;

    String previousKeys[] = {indexObjects[0].toString(), indexObjects[1].toString()};
    String keys[] = getNextAlert(previousKeys);

    if (keys == null) return null;

    String source = keys[0];

    // String ownerName = keys[1];

    String entity = keys[1];

    Alert alert1 = new Alert();

    alert1.setSource(source);

    //	alert1.setOwnerName(ownerName);

    alert1.setEntity(entity);

    Alert alert2 = new Alert();

    alert2.setModTime(System.currentTimeMillis());

    Vector alerts = null;

    try {
      alerts = agentName.alertAPI.getAlerts(alert1, alert2);

      if (alerts != null) return makeComData((Alert) alerts.elementAt(0));
    } catch (Exception e) {
      return null;
    }

    // User code ends here
    return null;
  }
  /* Setter for the CacheSize attribute. To avoid problems with
  stale values in multithreaded situations, it is a good idea
  for setters to be synchronized. */
  public synchronized void setCacheSize(int size) {
    int oldSize = this.cacheSize;
    this.cacheSize = size;

    /* In a real application, changing the attribute would
    typically have effects beyond just modifying the cacheSize
    field.  For example, resizing the cache might mean
    discarding entries or allocating new ones. The logic for
    these effects would be here. */
    System.out.println("Cache size now " + this.cacheSize);

    /* Construct a notification that describes the change. The
    "source" of a notification is the ObjectName of the MBean
    that emitted it. But an MBean can put a reference to
    itself ("this") in the source, and the MBean server will
    replace this with the ObjectName before sending the
    notification on to its clients.

    For good measure, we maintain a sequence number for each
    notification emitted by this MBean.

    The oldValue and newValue parameters to the constructor are
    of type Object, so we are relying on Tiger's autoboxing
    here.  */
    Notification n =
        new AttributeChangeNotification(
            this,
            sequenceNumber++,
            System.currentTimeMillis(),
            "CacheSize changed",
            "CacheSize",
            "int",
            oldSize,
            this.cacheSize);

    /* Now send the notification using the sendNotification method
    inherited from the parent class NotificationBroadcasterSupport. */
    sendNotification(n);
  }
  public void start() {

    if ((this.state == this.STARTING_STATE)
        || (this.state == this.RUNNING_STATE)
        || (this.state == this.STOPPING_STATE)) {
      throw new RuntimeException(
          new Exception("cannot start because the current state is " + this.state));
    }

    try {
      this.state = this.STARTING_STATE;
      this.stateChanged("j2ee.state.starting");
      module.start(this);
      this.state = this.RUNNING_STATE;
      this.startTime = System.currentTimeMillis();
      this.stateChanged("j2ee.state.running");
    } catch (Exception ex) {
      this.state = this.FAILED_STATE;
      this.stateChanged("j2ee.state.failed");
      if (ex instanceof RuntimeException) throw (RuntimeException) ex;
      throw new RuntimeException(ex);
    }
  }
 /**
  * The notifications dispatch thread. The dispatch thread sends all pending notifications in the
  * buffer to the client. The dispatch thread exits, whenever an IOException occurs during actual
  * dispatch or whenever this connection is being closed (after a call to close())
  */
 public void run() {
   /* XXX: Even when we are exiting should we send the remaining notifications?
    *      OR just drop the remaining notifications ?
    *
    *     Currently we drop all the remaining notifications!!
    */
   while (!isExiting() && !hasIOExceptionOccurred()) {
     synchronized (que) {
       while (que.isEmpty() && !isExiting() && !hasIOExceptionOccurred()) {
         try {
           que.wait();
         } catch (InterruptedException intre) {
         }
       }
     }
     if (isExiting() || hasIOExceptionOccurred()) break;
     dispatching = true;
     while (!que.isEmpty() && !isExiting() && !hasIOExceptionOccurred()) {
       NotificationWrapper wrapr = (NotificationWrapper) que.remove();
       try {
         sendNotificationMsg(wrapr);
       } catch (IOException ioe) {
         if (isExiting()) break;
         // XXX: Log it; drop the notification
         if (!isDisconnected(ioe)) break;
         isIOException = true;
         synchronized (this) {
           this.notify();
         }
         break;
       }
     }
     lastNotifTime = System.currentTimeMillis();
     dispatching = false;
   }
 }
Exemple #9
0
 public long getUptime() {
   return System.currentTimeMillis() - startTime;
 }
Exemple #10
0
  // The Run Method.
  // Started by main() on a single thread, this code publishes Cloud membership
  // to the Cloud once a second (across all members).  If anybody disagrees
  // with the membership Heartbeat, they will start a round of Paxos group
  // discovery.
  public void run() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName os;
    try {
      os = new ObjectName("java.lang:type=OperatingSystem");
    } catch (MalformedObjectNameException e) {
      throw Log.errRTExcept(e);
    }
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    int counter = 0;
    while (true) {
      // Once per second, for the entire cloud a Node will multi-cast publish
      // itself, so other unrelated Clouds discover each other and form up.
      try {
        Thread.sleep(SLEEP);
      } // Only once-sec per entire Cloud
      catch (InterruptedException e) {
      }

      // Update the interesting health self-info for publication also
      H2O cloud = H2O.CLOUD;
      HeartBeat hb = H2O.SELF._heartbeat;
      hb._hb_version = HB_VERSION++;
      hb._jvm_boot_msec = TimeLine.JVM_BOOT_MSEC;
      final Runtime run = Runtime.getRuntime();
      hb.set_free_mem(run.freeMemory());
      hb.set_max_mem(run.maxMemory());
      hb.set_tot_mem(run.totalMemory());
      hb._keys = (H2O.STORE.size());
      hb.set_valsz(myHisto.histo(false)._cached);
      hb._num_cpus = (char) run.availableProcessors();
      if (counter % 300 == 2) {
        // run mini-benchmark every 5 mins
        hb._gflops = Linpack.run();
        hb._membw = MemoryBandwidth.run();
      }
      Object load = null;
      try {
        load = mbs.getAttribute(os, "SystemLoadAverage");
      } catch (Exception e) {
        // Ignore, data probably not available on this VM
      }
      hb._system_load_average = load instanceof Double ? ((Double) load).floatValue() : 0;
      int rpcs = 0;
      for (H2ONode h2o : cloud._memary) rpcs += h2o.taskSize();
      hb._rpcs = (char) rpcs;
      // Scrape F/J pool counts
      hb._fjthrds = new short[H2O.MAX_PRIORITY + 1];
      hb._fjqueue = new short[H2O.MAX_PRIORITY + 1];
      for (int i = 0; i < hb._fjthrds.length; i++) {
        hb._fjthrds[i] = (short) H2O.getWrkThrPoolSize(i);
        hb._fjqueue[i] = (short) H2O.getWrkQueueSize(i);
      }
      hb._tcps_active = (char) H2ONode.TCPS.get();

      // get the usable and total disk storage for the partition where the
      // persistent KV pairs are stored
      hb.set_free_disk(Persist.getIce().getUsableSpace());
      hb.set_max_disk(Persist.getIce().getTotalSpace());

      // get cpu utilization for the system and for this process.  (linux only.)
      LinuxProcFileReader lpfr = new LinuxProcFileReader();
      lpfr.read();
      if (lpfr.valid()) {
        hb._system_idle_ticks = lpfr.getSystemIdleTicks();
        hb._system_total_ticks = lpfr.getSystemTotalTicks();
        hb._process_total_ticks = lpfr.getProcessTotalTicks();
        hb._process_num_open_fds = lpfr.getProcessNumOpenFds();
      } else {
        hb._system_idle_ticks = -1;
        hb._system_total_ticks = -1;
        hb._process_total_ticks = -1;
        hb._process_num_open_fds = -1;
      }
      hb._pid = lpfr.getProcessID();

      // Announce what Cloud we think we are in.
      // Publish our health as well.
      UDPHeartbeat.build_and_multicast(cloud, hb);

      // If we have no internet connection, then the multicast goes
      // nowhere and we never receive a heartbeat from ourselves!
      // Fake it now.
      long now = System.currentTimeMillis();
      H2O.SELF._last_heard_from = now;

      // Look for napping Nodes & propose removing from Cloud
      for (H2ONode h2o : cloud._memary) {
        long delta = now - h2o._last_heard_from;
        if (delta > SUSPECT) { // We suspect this Node has taken a dirt nap
          if (!h2o._announcedLostContact) {
            Paxos.print("hart: announce suspect node", cloud._memary, h2o.toString());
            h2o._announcedLostContact = true;
          }
        } else if (h2o._announcedLostContact) {
          Paxos.print("hart: regained contact with node", cloud._memary, h2o.toString());
          h2o._announcedLostContact = false;
        }
      }
      counter++;
    }
  }
 private boolean isIdle() {
   boolean ret =
       ((System.currentTimeMillis() - lastNotifTime) >= DefaultConfiguration.NOTIF_WAIT_INTERVAL);
   return ret;
 }
public abstract class J2EEDeployedObjectMdl extends J2EEEventProviderMOMdl {

  public static final int STARTING_STATE = 0;
  public static final int RUNNING_STATE = 1;
  public static final int STOPPING_STATE = 2;
  public static final int STOPPED_STATE = 3;
  public static final int FAILED_STATE = 4;

  private J2EEModuleCallBack module;
  private int state = this.RUNNING_STATE;
  private long startTime = System.currentTimeMillis();

  private long sequenceNo = 0;

  // private com.sun.enterprise.tools.deployment.backend.DeploymentContext userData = null;

  private String[] eventTypes =
      new String[] {
        "j2ee.state.starting",
        "j2ee.state.running",
        "j2ee.state.stopping",
        "j2ee.state.stopped",
        "j2ee.state.failed"
      };

  J2EEDeployedObjectMdl(J2EEModuleCallBack m) {
    super(m.getName(), m.getServerName(), false, false);
    module = m;
  }

  /**
   * The deploymentDescriptor string must contain the original XML deployment descriptor that was
   * created for this module during the deployment process.
   */
  public String getdeploymentDescriptor() {
    return module.getDeploymentDescriptor();
  }

  /** returns the OBJECT_NAME of the J2EEServer this module is deployed on. */
  public String getserver() {
    String qs = "name=" + getJ2EEServer() + ",j2eeType=J2EEServer";
    Set s = findNames(qs);
    ObjectName[] sa = (ObjectName[]) s.toArray(new ObjectName[s.size()]);
    if (sa.length > 0) {
      return sa[0].toString();
    }
    return "Failed to find the server ObjectName";
  }

  public String[] geteventTypes() {
    return eventTypes;
  }

  public int getstate() {
    return this.state;
  }

  public void setstate(int st) {
    this.state = st;
    this.stateChanged(eventTypes[st]);
  }

  public long getstartTime() {
    return this.startTime;
  }

  public void start() {

    if ((this.state == this.STARTING_STATE)
        || (this.state == this.RUNNING_STATE)
        || (this.state == this.STOPPING_STATE)) {
      throw new RuntimeException(
          new Exception("cannot start because the current state is " + this.state));
    }

    try {
      this.state = this.STARTING_STATE;
      this.stateChanged("j2ee.state.starting");
      module.start(this);
      this.state = this.RUNNING_STATE;
      this.startTime = System.currentTimeMillis();
      this.stateChanged("j2ee.state.running");
    } catch (Exception ex) {
      this.state = this.FAILED_STATE;
      this.stateChanged("j2ee.state.failed");
      if (ex instanceof RuntimeException) throw (RuntimeException) ex;
      throw new RuntimeException(ex);
    }
  }

  public void stop() throws MBeanException {

    if ((this.state == this.STOPPED_STATE) || (this.state == this.STOPPING_STATE)) {
      throw new RuntimeException(
          new Exception("cannot stop because the current state is " + this.state));
    }

    try {
      this.state = this.STOPPING_STATE;
      this.stateChanged("j2ee.state.stopping");
      module.stop(this);
      this.state = this.STOPPED_STATE;
      this.stateChanged("j2ee.state.stopped");
    } catch (Exception ex) {
      this.state = this.FAILED_STATE;
      this.stateChanged("j2ee.state.failed");
      if (ex instanceof RuntimeException) throw (RuntimeException) ex;
      throw new RuntimeException(ex);
    }
  }

  public void startRecursive() throws MBeanException {
    start();
  }

  private void stateChanged(String state) {
    /*
        Called when this MBean is not yet registered (see below).
        Since nothing should be listening to an MBean that is not yet registered, just
        skip the Notification.  If there were listeners, 'this' could be used as the
        source object; it needn't be an ObjectName.

        com.sun.enterprise.management.util.J2EEManagementObjectManager.setState(J2EEManagementObjectManager.java:1550)
        com.sun.enterprise.management.util.J2EEManagementObjectManager.setApplicationState(J2EEManagementObjectManager.java:1498)
        com.sun.enterprise.server.ApplicationLoader.setState(ApplicationLoader.java:395)
        com.sun.enterprise.server.AbstractManager.load(AbstractManager.java:211)
        com.sun.enterprise.server.ApplicationLifecycle.onStartup(ApplicationLifecycle.java:204)
        com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:326)
        com.sun.enterprise.server.ondemand.OnDemandServer.onStartup(OnDemandServer.java:112)
        com.sun.enterprise.server.PEMain.run(PEMain.java:326)
        com.sun.enterprise.server.PEMain.main(PEMain.java:260)
    */
    // final ObjectName objectName    = getObjectName();
    ObjectName objectName = null;
    try {
      objectName = new ObjectName(this.getobjectName());
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (objectName != null) {
      Notification notification = null;
      synchronized (this) // thread safety, visibility of 'sequenceNo'
      {
        notification = new Notification(state, objectName, sequenceNo);
        ++sequenceNo;
      }
      this.sendNotification(notification);
    }
  }

  /**
   * Getter for property userData.
   *
   * @return Value of property userData.
   */
  // public com.sun.enterprise.tools.deployment.backend.DeploymentContext getUserData() {
  // return userData;
  // }

  /**
   * Setter for property userData.
   *
   * @param userData New value of property userData.
   */
  // public void setUserData(com.sun.enterprise.tools.deployment.backend.DeploymentContext userData)
  // {
  // this.userData = userData;
  // }
}