Example #1
0
  public static void main(String args[]) {

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

    long init = heapMemoryUsage.getInit();
    long used = heapMemoryUsage.getUsed();
    long max = heapMemoryUsage.getMax();
    long committed = heapMemoryUsage.getCommitted();
    long free = max - used;
    int usedPercent = (int) (used / max);
    int freePercent = (int) (usedPercent / max);

    MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

    List<GarbageCollectorMXBean> garbageCollectorMXBeans =
        ManagementFactory.getGarbageCollectorMXBeans();

    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();

    com.sun.management.OperatingSystemMXBean operatingSystemMXBean =
        (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long commitVirtual = operatingSystemMXBean.getCommittedVirtualMemorySize();

    println(init, used, max, committed);
    println(commitVirtual);
  }
 public void init(final ServletContext context, final Map<String, String> paras) {
   _startTime = new Date();
   _context = context;
   _sipFactory = (SipFactory) context.getAttribute(ServletContextConstants.SIP_FACTORY);
   _mrcpFactory = (MrcpFactory) context.getAttribute(ServletContextConstants.MRCP_FACTORY);
   _appJarUrl =
       _context.getRealPath("/")
           + "WEB-INF"
           + File.separator
           + "lib"
           + File.separator
           + "tropo.jar";
   _cache = Collections.synchronizedMap(new WeakHashMap<Object, Application>());
   _tmx = ManagementFactory.getThreadMXBean();
   _mmx = ManagementFactory.getMemoryMXBean();
   try {
     _tropoBuildDate = Utils.getManifestAttribute(_appJarUrl, "Build-Date");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildDate = "Unknown";
   }
   try {
     _tropoVersionNo = Utils.getManifestAttribute(_appJarUrl, "Version-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoVersionNo = "Unknown";
   }
   try {
     _tropoBuildNo = Utils.getManifestAttribute(_appJarUrl, "Build-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildNo = "Unknown";
   }
   LOG.info(toString() + " / " + getVersionNo() + " / " + getBuildNo());
 }
Example #3
0
  @Override
  public int run(String[] args) throws Exception {
    Job job = new Job(conf);
    job.setJarByClass(StatisticsGenerator.class);
    job.setInputFormatClass(SequenceFileInputFormat.class);
    job.setOutputFormatClass(SequenceFileOutputFormat.class);
    SequenceFileInputFormat.addInputPath(job, new Path(args[0]));
    SequenceFileOutputFormat.setOutputPath(job, new Path(args[1]));
    job.setMapperClass(StatisticsMap.class);
    job.setReducerClass(StatisticsReduce.class);
    job.setMapOutputKeyClass(SortedMapWritableComparable.class);
    job.setMapOutputValueClass(BytesWritable.class);
    job.setNumReduceTasks(16);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(BytesWritable.class);

    long startTime =
        ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId());
    boolean success = job.waitForCompletion(true);
    long endTime =
        ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId());
    double duration = (endTime - startTime) / Math.pow(10, 9);
    logger.info(
        "=== Job Finished in " + duration + " seconds " + (success ? "(success)" : "(failure)"));
    return success ? 0 : 1;
  }
Example #4
0
  public void log() {
    new Thread(new LogRunnable()).start();

    List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
    MemoryPoolMXBean pool = null;
    for (MemoryPoolMXBean bean : beans) {
      if ("Tenured Gen".equals(bean.getName())) {
        pool = bean;
        break;
      }
    }

    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) mbean;
    MemoryListener listener = new MemoryListener();
    emitter.addNotificationListener(listener, null, null);
    pool.setUsageThreshold(8 * 1024 * 1024);

    consumeMemory();
    System.gc();
    checkMemory(pool);
    consumeMemory();
    checkMemory(pool);
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
 public MemoryMonitor() {
   LOG.info("initializing");
   this.springContextId = "Unknown";
   ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
   ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
   lowMemoryListener =
       new NotificationListener() {
         public void handleNotification(Notification n, Object hb) {
           if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
             Map<String, String> memoryUsageStatistics = new HashMap<String, String>();
             memoryUsageStatistics.put(
                 "MemoryMXBean: " + MemoryType.HEAP,
                 ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().toString());
             memoryUsageStatistics.put(
                 "MemoryMXBean:" + MemoryType.NON_HEAP,
                 ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().toString());
             for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
               memoryUsageStatistics.put(
                   "MemoryPoolMXBean: " + pool.getType(), pool.getUsage().toString());
             }
             for (Listener listener : listeners) {
               listener.memoryUsageLow(
                   springContextId,
                   memoryUsageStatistics,
                   Arrays.toString(
                       ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads()));
             }
           }
         }
       };
   ((NotificationEmitter) ManagementFactory.getMemoryMXBean())
       .addNotificationListener(lowMemoryListener, null, null);
 }
  public static void main(String[] args) {
    // We create an instance of a File to represent a partition
    // of our file system. For instance here we used a drive D:
    // as in Windows operating system.
    File file = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro/state/traps");
    File file2 = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro/state/");
    File file3 = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro");

    // Using the getTotalSpace() we can get an information of
    // the actual size of the partition, and we convert it to
    // mega bytes.
    long totalSpace = file.getTotalSpace() / (1024 * 1024);
    /*System.err.println("file.length :: "+getFolderSize(file));
    System.err.println("file2.length :: "+getFolderSize(file2));
    System.err.println("file3.length :: "+getFolderSize(file3));*/
    System.err.println(
        "file.sizeOfDirectory :: " + org.apache.commons.io.FileUtils.sizeOfDirectory(file3));

    // Next we get the free disk space as the name of the
    // method shown us, and also get the size in mega bytes.
    long freeSpace = file.getFreeSpace() / (1024 * 1024);

    // Just print out the values.
    System.out.println("Total Space1 = " + totalSpace + " Mega Bytes");
    System.out.println("Free Space1 = " + freeSpace + " Mega Bytes");

    System.out.println("Free Space3 = " + Runtime.getRuntime().totalMemory() + " Mega Bytes");
    System.out.println("Free Space4 = " + Runtime.getRuntime().freeMemory() + " Mega Bytes");
    System.out.println("Free Space5 = " + Runtime.getRuntime().maxMemory() + "Bytes");
    System.out.println(
        "Free Space6 = " + ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage() + "Bytes");
    System.out.println(
        "Free Space7 = " + ManagementFactory.getMemoryMXBean().getHeapMemoryUsage() + "Bytes");
    System.out.println("Free Space8 = " + file.getUsableSpace() / 1024 / 1024 + " Mega Bytes");
  }
    private void checkCompatibility() {
      OperatingSystemMXBean osmx = ManagementFactory.getOperatingSystemMXBean();
      if (osmx == null) {
        throw new UnsupportedOperationException("Failed to get OperatingSystemMXBean");
      }
      Class[] interfaces = osmx.getClass().getInterfaces();
      boolean hasInterface = false;
      if (interfaces != null) {
        for (Class i : interfaces) {
          if ("com.sun.management.OperatingSystemMXBean".equals(i.getName())
              || "com.sun.management.UnixOperatingSystemMXBean".equals(i.getName())) {
            hasInterface = true;
            break;
          }
        }
      }

      if (!hasInterface) {
        throw new UnsupportedOperationException(
            "Incompatible OperatingSystemMXBean class: " + osmx.getClass().getName());
      }

      RuntimeMXBean rtmx = ManagementFactory.getRuntimeMXBean();
      if (rtmx == null) {
        throw new UnsupportedOperationException("Failed to get RuntimeMXBean");
      }
    }
 @Override
 public void run() {
   while (goOn) {
     try {
       long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
       checkCount.incrementAndGet();
       ids = ids == null ? new long[0] : ids;
       if (ids.length > 0) {
         deadlocked.addAll(asList(ids));
       }
       if (ids.length == 1) {
         throw new RuntimeException("Found 1 deadlocked thread: " + ids[0]);
       } else if (ids.length > 0) {
         ThreadInfo[] infos =
             ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
         System.err.println("Found " + ids.length + " deadlocked threads: ");
         for (ThreadInfo inf : infos) {
           System.err.println(inf.toString());
         }
         throw new RuntimeException("Found " + ids.length + " deadlocked threads");
       }
       Thread.sleep(100);
     } catch (InterruptedException | RuntimeException x) {
       fail(x);
     }
   }
 }
  private void createRuntimeProps(MemberStateImpl memberState) {
    Runtime runtime = Runtime.getRuntime();
    ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    ClassLoadingMXBean clMxBean = ManagementFactory.getClassLoadingMXBean();
    MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemory = memoryMxBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMemory = memoryMxBean.getNonHeapMemoryUsage();

    Map<String, Long> map = new HashMap<String, Long>();
    map.put(
        "runtime.availableProcessors", Integer.valueOf(runtime.availableProcessors()).longValue());
    map.put("date.startTime", runtimeMxBean.getStartTime());
    map.put("seconds.upTime", runtimeMxBean.getUptime());

    map.put("memory.maxMemory", runtime.maxMemory());
    map.put("memory.freeMemory", runtime.freeMemory());
    map.put("memory.totalMemory", runtime.totalMemory());
    map.put("memory.heapMemoryMax", heapMemory.getMax());
    map.put("memory.heapMemoryUsed", heapMemory.getUsed());
    map.put("memory.nonHeapMemoryMax", nonHeapMemory.getMax());
    map.put("memory.nonHeapMemoryUsed", nonHeapMemory.getUsed());
    map.put("runtime.totalLoadedClassCount", clMxBean.getTotalLoadedClassCount());
    map.put(
        "runtime.loadedClassCount", Integer.valueOf(clMxBean.getLoadedClassCount()).longValue());
    map.put("runtime.unloadedClassCount", clMxBean.getUnloadedClassCount());
    map.put("runtime.totalStartedThreadCount", threadMxBean.getTotalStartedThreadCount());
    map.put("runtime.threadCount", Integer.valueOf(threadMxBean.getThreadCount()).longValue());
    map.put(
        "runtime.peakThreadCount", Integer.valueOf(threadMxBean.getPeakThreadCount()).longValue());
    map.put(
        "runtime.daemonThreadCount",
        Integer.valueOf(threadMxBean.getDaemonThreadCount()).longValue());
    memberState.setRuntimeProps(map);
  }
  protected void assertLengthCount(
      String test, int passLength, int numPasswords, List<String> passwords) {

    int count = 0;
    for (Iterator<String> iter = passwords.iterator(); iter.hasNext(); ) {
      ++count;
      String password = (String) iter.next();
      if (password.length() != passLength) {
        System.out.printf(
            "#####========>%s %s %s %d Wrong number of characters: %d vs. %d for %s\n",
            ManagementFactory.getRuntimeMXBean().getName(),
            Thread.currentThread().getName(),
            test,
            count,
            password.length(),
            passLength,
            password);
        Assert.assertEquals(password.length(), passLength);
      }
      System.out.printf(
          "%s %s %s, %3d  Password: %s -> %d\n",
          ManagementFactory.getRuntimeMXBean().getName(),
          Thread.currentThread().getName(),
          test,
          count,
          password,
          password.length());
    }
  }
  protected void process(String test, String[] ar, int numPasswords, int passLength) {

    System.out.println(
        ManagementFactory.getRuntimeMXBean().getName()
            + " --> "
            + Thread.currentThread().getName()
            + " FLAGS: "
            + test
            + " --> "
            + Arrays.deepToString(ar)
            + " -> "
            + passLength);

    List<String> passwords = PwGenerator.process(ar);

    Assert.assertEquals(passwords.size(), numPasswords);

    assertLengthCount(test, passLength, numPasswords, passwords);

    System.out.println(
        ManagementFactory.getRuntimeMXBean().getName()
            + " --> "
            + Thread.currentThread().getName()
            + " #############################");
  }
Example #12
0
 @RequiresNonNull("startupLogger")
 private static void start(
     File baseDir,
     Map<String, String> properties,
     @Nullable Instrumentation instrumentation,
     @Nullable File glowrootJarFile)
     throws Exception {
   ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
   ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
   String version = Version.getVersion(MainEntryPoint.class);
   String collectorHost = properties.get("glowroot.collector.host");
   if (Strings.isNullOrEmpty(collectorHost)) {
     collectorHost = System.getProperty("glowroot.collector.host");
   }
   Collector customCollector = loadCustomCollector(baseDir);
   if (Strings.isNullOrEmpty(collectorHost) && customCollector == null) {
     glowrootAgentInit = new GlowrootFatAgentInit();
   } else {
     if (customCollector != null) {
       startupLogger.info("Using collector: {}", customCollector.getClass().getName());
     }
     glowrootAgentInit = new GlowrootThinAgentInit();
   }
   glowrootAgentInit.init(
       baseDir,
       collectorHost,
       customCollector,
       properties,
       instrumentation,
       glowrootJarFile,
       version,
       false);
   startupLogger.info("Glowroot started (version {})", version);
 }
Example #13
0
  /**
   * Returns object of class ‘"proc_time"’ which is a numeric vector of length 5, containing the
   * user, system, and total elapsed times for the currently running R process, and the cumulative
   * sum of user and system times of any child processes spawned by it on which it has waited.
   *
   * <p>_The ‘user time’ is the CPU time charged for the execution of user instructions of the
   * calling process. The ‘system time’ is the CPU time charged for execution by the system on
   * behalf of the calling process._
   */
  @Builtin("proc.time")
  public static DoubleVector procTime() {

    DoubleArrayVector.Builder result = new DoubleArrayVector.Builder();
    StringVector.Builder names = new StringVector.Builder();

    long totalCPUTime;
    long userCPUTime;
    long elapsedTime;

    // There doesn't seem to be any platform-independent way of accessing
    // CPU use for the whole JVM process, so we'll have to make do
    // with the timings for the thread we're running on.
    //
    // Additionally, the MX Beans may not be available in all environments,
    // so we need to fallback to app
    try {
      ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
      totalCPUTime = threadMXBean.getCurrentThreadCpuTime();
      userCPUTime = threadMXBean.getCurrentThreadUserTime();

      RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
      elapsedTime = runtimeMXBean.getUptime();
    } catch (Error e) {
      // ThreadMXBean is not available in all environments
      // Specifically, AppEngine will throw variously SecurityErrors or
      // ClassNotFoundErrors if we try to access these classes
      userCPUTime = totalCPUTime = java.lang.System.nanoTime();
      elapsedTime = new Date().getTime();
    }

    // user.self
    names.add("user.self");
    result.add(userCPUTime / NANOSECONDS_PER_SECOND);

    // sys.self
    names.add("sys.self");
    result.add((totalCPUTime - userCPUTime) / NANOSECONDS_PER_SECOND);

    // elapsed
    // (wall clock time)
    names.add("elapsed");
    result.add(elapsedTime);

    // AFAIK, we don't have any platform independent way of accessing
    // this info.

    // user.child
    names.add("user.child");
    result.add(0);

    // sys.child
    names.add("sys.child");
    result.add(0);

    result.setAttribute(Symbols.NAMES, names.build());
    result.setAttribute(Symbols.CLASS, StringVector.valueOf("proc_time"));
    return result.build();
  }
Example #14
0
  /**
   * Gets maps that are not installed, but may be downloaded.
   *
   * @return set of all maps available for download
   */
  public static Set<AutoRefMap> getRemoteMaps() {
    // check the cache first, we might want to just use the cached value
    long time = ManagementFactory.getRuntimeMXBean().getUptime() - _cachedRemoteMapsTime;
    if (_cachedRemoteMaps != null && time < AutoRefMap.REMOTE_MAP_CACHE_LENGTH)
      return _cachedRemoteMaps;

    Set<AutoRefMap> maps = Sets.newHashSet();
    String repo = AutoRefMatch.getMapRepo();

    try {
      Map<String, String> params = Maps.newHashMap();
      params.put("prefix", "maps/");

      for (; ; ) {
        String url = String.format("%s?%s", repo, QueryUtil.prepareParams(params));
        Element listing = new SAXBuilder().build(new URL(url)).getRootElement();
        assert "ListBucketResult".equals(listing.getName()) : "Unexpected response";
        Namespace ns = listing.getNamespace();

        String lastkey = null;
        for (Element entry : listing.getChildren("Contents", ns)) {
          lastkey = entry.getChildTextTrim("Key", ns);
          if (!lastkey.endsWith(".zip")) continue;

          String[] keyparts = lastkey.split("/");
          String mapfile = keyparts[keyparts.length - 1];

          String mapslug = mapfile.substring(0, mapfile.length() - 4);
          String slugparts[] = mapslug.split("-v");

          if (slugparts.length < 2) {
            AutoReferee.log("Invalid map filename: " + mapfile, Level.WARNING);
            AutoReferee.log("Map files should be of the form \"MapName-vX.X.zip\"", Level.WARNING);
          } else {
            String etag = entry.getChildTextTrim("ETag", ns);
            maps.add(
                new AutoRefMap(
                    slugparts[0], slugparts[1], lastkey, etag.substring(1, etag.length() - 1)));
          }
        }

        // stop looping if the result says that it hasn't been truncated (no more results)
        if (!Boolean.parseBoolean(listing.getChildText("IsTruncated", ns))) break;

        // use the last key as a marker for the next pass
        if (lastkey != null) params.put("marker", lastkey);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }

    _cachedRemoteMapsTime = ManagementFactory.getRuntimeMXBean().getUptime();
    return _cachedRemoteMaps = maps;
  }
Example #15
0
 public SystemManager() {
   memoryBean = ManagementFactory.getMemoryMXBean();
   BufferPoolMXBean localBean = null;
   List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
   for (BufferPoolMXBean b : pools) {
     if (b.getName().equals("direct")) {
       localBean = b;
     }
   }
   directBean = localBean;
 }
Example #16
0
  /** Uses reflection to get ThreadInfo with monitors & synchronizers. */
  private static ThreadInfo[] getThreadInfo(long[] ids) {
    try {
      Method m =
          ThreadMXBean.class.getDeclaredMethod(
              "getThreadInfo", new Class[] {long[].class, boolean.class, boolean.class});
      Object o = m.invoke(ManagementFactory.getThreadMXBean(), new Object[] {ids, true, true});
      return (ThreadInfo[]) o;
    } catch (Throwable t) {
    }

    // fallback to retrieving info w/o monitor & synchronizer info
    return ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
  }
Example #17
0
 public static JSONObject geGCInfo(String app) throws Exception {
   ObjectName obj = new ObjectName("java.lang:type=GarbageCollector,*");
   MBeanServer conn = ManagementFactory.getPlatformMBeanServer();
   Set<ObjectInstance> MBeanset = conn.queryMBeans(obj, null);
   Class<GarbageCollectorMXBean> cls = GarbageCollectorMXBean.class;
   JSONObject data = new JSONObject();
   for (ObjectInstance objx : MBeanset) {
     String name = objx.getObjectName().getCanonicalName();
     String keyName = objx.getObjectName().getKeyProperty("name");
     GarbageCollectorMXBean gc = ManagementFactory.newPlatformMXBeanProxy(conn, name, cls);
     data.put(keyName + "-time", gc.getCollectionTime() / 1000.0);
     data.put(keyName + "-count", gc.getCollectionCount());
   }
   return data;
 }
Example #18
0
  public static Struct getMemoryUsageAsStruct(int type) {
    java.util.List<MemoryPoolMXBean> manager = ManagementFactory.getMemoryPoolMXBeans();
    Iterator<MemoryPoolMXBean> it = manager.iterator();

    MemoryPoolMXBean bean;
    MemoryUsage usage;
    MemoryType _type;
    long used = 0, max = 0, init = 0;
    while (it.hasNext()) {
      bean = it.next();
      usage = bean.getUsage();
      _type = bean.getType();
      if ((type == MEMORY_TYPE_HEAP && _type == MemoryType.HEAP)
          || (type == MEMORY_TYPE_NON_HEAP && _type == MemoryType.NON_HEAP)) {
        used += usage.getUsed();
        max += usage.getMax();
        init += usage.getInit();
      }
    }
    Struct sct = new StructImpl();
    sct.setEL(KeyConstants._used, Caster.toDouble(used));
    sct.setEL(KeyConstants._max, Caster.toDouble(max));
    sct.setEL(KeyConstants._init, Caster.toDouble(init));
    sct.setEL(KeyImpl.init("available"), Caster.toDouble(max - used));
    return sct;
  }
Example #19
0
    HeapUsageMonitor() {
      int c = 0;
      for (MemoryPoolMXBean m : ManagementFactory.getMemoryPoolMXBeans()) {
        if (m.getType() != MemoryType.HEAP) // only interested in HEAP
        continue;
        if (m.isCollectionUsageThresholdSupported() && m.isUsageThresholdSupported()) {
          // should be Old pool, get called when memory is critical
          _oldGenBean = m;
          _gc_callback = MEM_MAX;
          // Really idiotic API: no idea what the usageThreshold is, so I have
          // to guess. Start high, catch IAE & lower by 1/8th and try again.
          while (true) {
            try {
              m.setCollectionUsageThreshold(_gc_callback);
              break;
            } catch (IllegalArgumentException iae) {
              // Do NOT log this exception, it is expected and unavoidable and
              // entirely handled.

              _gc_callback -= (_gc_callback >> 3);
            }
          }
          NotificationEmitter emitter = (NotificationEmitter) _allMemBean;
          emitter.addNotificationListener(this, null, m);
          ++c;
        }
      }
      assert c == 1;
    }
Example #20
0
  /**
   * Attempts to load the agent through the Attach API
   *
   * @return true if agent was loaded (which could have happened thought the -javaagent switch)
   */
  static boolean loadAgent() {
    synchronized (AgentLoader.class.getName().intern()) {
      if (!agentIsAvailable() && VIRTUAL_MACHINE_LOAD_AGENT != null) {
        try {
          warnIfOSX();
          String name = ManagementFactory.getRuntimeMXBean().getName();
          Object vm = VIRTUAL_MACHINE_ATTACH.invoke(null, name.substring(0, name.indexOf('@')));
          try {
            File agent = getAgentFile();
            LOGGER.info("Trying to load agent @ {}", agent);
            if (agent != null) {
              VIRTUAL_MACHINE_LOAD_AGENT.invoke(vm, agent.getAbsolutePath());
            }
          } finally {
            VIRTUAL_MACHINE_DETACH.invoke(vm);
          }
        } catch (Throwable e) {
          LOGGER.info(
              "Failed to attach to VM and load the agent: {}: {}", e.getClass(), e.getMessage());
        }
      }

      return agentIsAvailable();
    }
  }
  static {
    String dummy = System.getenv(EnvVarNames.CCP_TASKSYSTEMID);
    taskid = -1;
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        taskid = Integer.parseInt(dummy);
      } catch (NumberFormatException e) {
        // taskid stays at -1;
      }
    }

    dummy = System.getenv(EnvVarNames.CCP_JOBID);
    jobid = -1;
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        jobid = Integer.parseInt(dummy);
      } catch (NumberFormatException e) {
        // jobid stays at -1;
      }
    }

    dummy = System.getenv(EnvVarNames.LONG_LOADING_TEST);
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        Thread.sleep(30 * 1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    scheduler = System.getenv(EnvVarNames.CCP_SCHEDULER);
    try {
      String logPath = System.getenv(EnvVarNames.GRACEFUL_EXIT);
      if (!Utility.isNullOrEmpty(logPath)) {
        File baseDir = new File(logPath);
        File logDir = new File(baseDir, "CCP_AITest_Trace_" + jobid);
        File logFile = new File(logDir, taskid + ".txt");

        if (!System.getenv("CCP_OnAzure").equals("1")) {
          try {
            logDir.mkdirs();
          } catch (Exception e) {
            e.printStackTrace();
          }
          PrintWriter writer = new PrintWriter(new FileWriter(logFile, true));
          writer.println(Utility.getCurrentTime() + ": Svchost starts.");
          writer.close();
        }
        System.out.println(Utility.getCurrentTime() + ": Svchost starts.");

        ServiceContext.exitingEvents.addMyEventListener(new DefaultOnExitHandler(logFile));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    String pid = ManagementFactory.getRuntimeMXBean().getName();
    int index = pid.indexOf("@");
    processId = Integer.parseInt(pid.substring(0, index));
  }
 /**
  * @return
  * @throws NullPointerException
  * @throws MalformedObjectNameException
  * @throws ReflectionException
  * @throws MBeanException
  * @throws InstanceNotFoundException
  * @throws AttributeNotFoundException
  */
 private String getServerId()
     throws MalformedObjectNameException, NullPointerException, AttributeNotFoundException,
         InstanceNotFoundException, MBeanException, ReflectionException {
   MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
   ObjectName name = new ObjectName("java.lang:type=Runtime");
   return ((String) mbeanServer.getAttribute(name, "Name")).replace('@', '-');
 }
 public JettyServerImpl(JettyServerConfiguration jettyServerConfiguration) {
   server = new Server(jettyServerConfiguration.getPort());
   serverConfiguration = jettyServerConfiguration;
   server.addLifeCycleListener(getSystemPropertiesListener(systemProperties));
   server.addBean(new MBeanContainer(ManagementFactory.getPlatformMBeanServer()));
   server.setHandler(getWebAppHandler(jettyServerConfiguration.getWarLocation(), server));
 }
  static {
    String hostname;
    try {
      hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception e) {
      hostname = "localhost";
    }
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      byte[] machine = md.digest(hostname.getBytes());
      ObjectId.MACHINE[0] = machine[0];
      ObjectId.MACHINE[1] = machine[1];
      ObjectId.MACHINE[2] = machine[2];
    } catch (Exception e) {
      ObjectId.MACHINE[0] = (byte) (Math.random() * 255);
      ObjectId.MACHINE[1] = (byte) (Math.random() * 255);
      ObjectId.MACHINE[2] = (byte) (Math.random() * 255);
    }

    int pid;
    try {
      String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
      int p = nameOfRunningVM.indexOf('@');
      pid = Integer.parseInt(nameOfRunningVM.substring(0, p));
    } catch (Exception e) {
      pid = (int) (Math.random() * 0x00ffffff);
    }

    PID = pid;
  }
Example #25
0
  public static boolean registerDriver(Driver driver) {
    try {
      DriverManager.registerDriver(driver);

      try {
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

        ObjectName objectName = new ObjectName(MBEAN_NAME);
        if (!mbeanServer.isRegistered(objectName)) {
          mbeanServer.registerMBean(instance, objectName);
        }
      } catch (Throwable ex) {
        if (LOG == null) {
          LOG = LogFactory.getLog(DruidDriver.class);
        }
        LOG.warn("register druid-driver mbean error", ex);
      }

      return true;
    } catch (Exception e) {
      if (LOG == null) {
        LOG = LogFactory.getLog(DruidDriver.class);
      }

      LOG.error("registerDriver error", e);
    }

    return false;
  }
Example #26
0
 private void doThreadUpdates() {
   ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
   long threadIds[] = threadMXBean.getAllThreadIds();
   ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0);
   int threadsNew = 0;
   int threadsRunnable = 0;
   int threadsBlocked = 0;
   int threadsWaiting = 0;
   int threadsTimedWaiting = 0;
   int threadsTerminated = 0;
   for (ThreadInfo threadInfo : threadInfos) {
     // threadInfo is null if the thread is not alive or doesn't exist
     if (threadInfo == null) continue;
     Thread.State state = threadInfo.getThreadState();
     if (state == NEW) {
       threadsNew++;
     } else if (state == RUNNABLE) {
       threadsRunnable++;
     } else if (state == BLOCKED) {
       threadsBlocked++;
     } else if (state == WAITING) {
       threadsWaiting++;
     } else if (state == TIMED_WAITING) {
       threadsTimedWaiting++;
     } else if (state == TERMINATED) {
       threadsTerminated++;
     }
   }
   metrics.setMetric("threadsNew", threadsNew);
   metrics.setMetric("threadsRunnable", threadsRunnable);
   metrics.setMetric("threadsBlocked", threadsBlocked);
   metrics.setMetric("threadsWaiting", threadsWaiting);
   metrics.setMetric("threadsTimedWaiting", threadsTimedWaiting);
   metrics.setMetric("threadsTerminated", threadsTerminated);
 }
  @Override
  public void closeOp(boolean abort) throws HiveException {

    // ricardoj checking mapper hashmap usage
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    long usedMemory = memoryMXBean.getHeapMemoryUsage().getUsed();
    LOG.info("ricardoj memory usage after deleting tables: " + usedMemory / (1024 * 1024) + "MB");

    if (mapJoinTables != null) {
      for (HashMapWrapper<?, ?> hashTable : mapJoinTables.values()) {
        hashTable.close();
      }
    }

    mapJoinTables = null;
    // ricardoj
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    System.gc();
    usedMemory = memoryMXBean.getHeapMemoryUsage().getUsed();
    LOG.info("ricardoj memory usage after deleting tables: " + usedMemory / (1024 * 1024) + "MB");

    super.closeOp(abort);
  }
  @Test
  public void testResolveHelloBean() throws Exception {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName =
        new ObjectName("org.apache.camel:context=camel-2,type=context,name=\"camel-2\"");
    String methodSignature[] = {String.class.getName(), Object.class.getName()};
    Object methodParams[] = {"direct:start", null};

    // Get Camel to return the BeanManagers that are in use
    Map<String, BeanManager> beanMangers =
        (Map<String, BeanManager>)
            server.invoke(objectName, "requestBody", methodParams, methodSignature);

    BeanManager subModuleBeanManager = beanMangers.get("subModule");
    BeanManager camelBeanManager = beanMangers.get("camel");

    System.err.println(">>>>>> [Sub Module BeanManager] " + subModuleBeanManager);
    System.err.println(">>>>>> [Camel BeanManager] " + camelBeanManager);

    // Assert that the @Named HelloBean can be resolved
    Assert.assertTrue(
        "Sub module bean manager could not resolve helloBean",
        beanManagerCanResolveBean(subModuleBeanManager, "helloBean"));

    Assert.assertTrue(
        "Camel bean manager could not resolve helloBean",
        beanManagerCanResolveBean(camelBeanManager, "helloBean"));
  }
Example #29
0
  @Override
  protected void registerMBeans() {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    try {
      server.registerMBean(this, new ObjectName(MBEAN_BOOTSTRAP_HOST));
    } catch (Exception e) {
      logger.error("Unable to register " + MBEAN_BOOTSTRAP_HOST + " mbean", e);
    }

    try {
      HierarchyDynamicMBean hdm = new HierarchyDynamicMBean();
      server.registerMBean(hdm, new ObjectName(MBEAN_LOG4J_HIERARCHY));

      // Add the root logger to the Hierarchy MBean
      hdm.addLoggerMBean(Logger.getRootLogger().getName());

      LoggerRepository r = LogManager.getLoggerRepository();

      @SuppressWarnings("rawtypes")
      Enumeration loggers = r.getCurrentLoggers();
      while (loggers.hasMoreElements()) {
        hdm.addLoggerMBean(((Logger) loggers.nextElement()).getName());
      }
    } catch (Exception e) {
      logger.error("Unable to register " + MBEAN_LOG4J_HIERARCHY + " mbean", e);
    }

    super.registerMBeans();
  }
Example #30
0
  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.common.test.SpeedTest#startTimer(java.lang.String)
   */
  public void startTimer(final String iName) {
    Runtime.getRuntime().runFinalization();
    Runtime.getRuntime().gc();

    try {
      Thread.sleep(TIME_WAIT);
    } catch (InterruptedException e) {
    }

    final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

    currentTestName = iName;

    currentTestHeapCommittedMemory = heapMemoryUsage.getCommitted();
    currentTestHeapUsedMemory = heapMemoryUsage.getUsed();
    currentTestHeapMaxMemory = heapMemoryUsage.getMax();

    currentTestNonHeapCommittedMemory = nonHeapMemoryUsage.getCommitted();
    currentTestNonHeapUsedMemory = nonHeapMemoryUsage.getUsed();
    currentTestNonHeapMaxMemory = nonHeapMemoryUsage.getMax();

    System.out.println("-> Started the test of '" + currentTestName + "' (" + cycles + " cycles)");

    currentTestTimer = System.currentTimeMillis();
  }