Use this API to count lbmetrictable_metric_binding resources configued on NetScaler.
328467
public static long count(nitro_service service, String metrictable) throws Exception{
		lbmetrictable_metric_binding obj = new lbmetrictable_metric_binding();
		obj.set_metrictable(metrictable);
		options option = new options();
		option.set_count(true);
		lbmetrictable_metric_binding response[] = (lbmetrictable_metric_binding[]) obj.get_resources(service,option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}
965075
protected List<MetricDatum> metricOfRequestOrRetryCount(
            Field metricType, Request<?> req, Object resp) {
        AWSRequestMetrics m = req.getAWSRequestMetrics();
        TimingInfo ti = m.getTimingInfo();
        // Always retrieve the request count even for retry which is equivalent
        // to the number of requests minus one.
        Number counter = ti.getCounter(Field.RequestCount.name());
        if (counter == null) {
            // this is possible if one of the request handlers screwed up
            return Collections.emptyList();
        }
        int requestCount = counter.intValue();
        if (requestCount < 1) {
            LogFactory.getLog(getClass()).debug(
                "request count must be at least one");
            return Collections.emptyList();
        }
        final double count = metricType == Field.RequestCount
                           ? requestCount
                           : requestCount-1 // retryCount = requestCount - 1
                           ;
        if (count < 1) {
            return Collections.emptyList();
        } else {
            return Collections.singletonList(new MetricDatum()
                .withMetricName(req.getServiceName())
                .withDimensions(new Dimension()
                    .withName(Dimensions.MetricType.name())
                    .withValue(metricType.name()))
                .withUnit(StandardUnit.Count)
                .withValue(Double.valueOf(count))
                .withTimestamp(endTimestamp(ti)))
                ;
        }
    }
321344
static void checkMetricAndTags(final String metric,
      final Map<String, String> tags) {
    if (tags.size() <= 0) {
      throw new IllegalArgumentException("Need at least one tag (metric="
          + metric + ", tags=" + tags + ')');
    } else if (tags.size() > Const.MAX_NUM_TAGS()) {
      throw new IllegalArgumentException("Too many tags: " + tags.size()
          + " maximum allowed: " + Const.MAX_NUM_TAGS() + ", tags: " + tags);
    }

    Tags.validateString("metric name", metric);
    for (final Map.Entry<String, String> tag : tags.entrySet()) {
      Tags.validateString("tag name with value [" + tag.getValue() + "]", 
          tag.getKey());
      Tags.validateString("tag value with key [" + tag.getKey() + "]", 
          tag.getValue());
    }
  }
1092951
public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory)
   {
      if (metricsTrackerFactory != null) {
         this.metricsTracker = new MetricsTrackerDelegate(metricsTrackerFactory.create(config.getPoolName(), getPoolStats()));
      }
      else {
         this.metricsTracker = new NopMetricsTrackerDelegate();
      }
   }
1080354
@Override
    protected void collectMetrics(final Metrics metrics) {
        for (final JvmMetricsCollector collector : _collectorsEnabled) {
            collector.collect(metrics, _managementFactory);
        }
    }
814240
public void collectClient(RpcClientLookoutModel rpcClientMetricsModel) {

        try {
            Id methodConsumerId = createMethodConsumerId(rpcClientMetricsModel);
            MixinMetric methodConsumerMetric = Lookout.registry().mixinMetric(methodConsumerId);

            recordCounterAndTimer(methodConsumerMetric, rpcClientMetricsModel);

            recordSize(methodConsumerMetric, rpcClientMetricsModel);

        } catch (Throwable t) {
            LOGGER.error(LogCodes.getLog(LogCodes.ERROR_METRIC_REPORT_ERROR), t);
        }
    }
1162111
public Set<Metric> getMetricsByInstanceTypeAndName(
      MetricsSystem.InstanceType instanceType, String name) {
    if (instanceType == InstanceType.MASTER) {
      return getMasterMetrics(name);
    }

    if (instanceType == InstanceType.WORKER) {
      synchronized (mWorkerMetrics) {
        return mWorkerMetrics.getByField(NAME_INDEX, name);
      }
    } else if (instanceType == InstanceType.CLIENT) {
      synchronized (mClientMetrics) {
        return mClientMetrics.getByField(NAME_INDEX, name);
      }
    } else {
      throw new IllegalArgumentException("Unsupported instance type " + instanceType);
    }
  }
813752
private void addMetric(
      List<Metric> metrics,
      String name,
      TagList tags,
      Object value) {
    long now = System.currentTimeMillis();
    if (onlyNumericMetrics) {
      value = asNumber(value);
    }
    if (value != null) {

      TagList newTags = counters.matches(MonitorConfig.builder(name).withTags(tags).build())
          ? getTagListWithAdditionalTag(tags, DataSourceType.COUNTER)
          : getTagListWithAdditionalTag(tags, DataSourceType.GAUGE);
      Metric m = new Metric(name, newTags, now, value);
      metrics.add(m);
    }
  }
614972
public static lbmetrictable_binding get(nitro_service service, String metrictable) throws Exception{
		lbmetrictable_binding obj = new lbmetrictable_binding();
		obj.set_metrictable(metrictable);
		lbmetrictable_binding response = (lbmetrictable_binding) obj.get_resource(service);
		return response;
	}
120905
public void registerMetrics() {
        if (metricsAreRegistered) {
            return;
        }
        getMetricRegistry().register("jvm.attribute", new JvmAttributeGaugeSet());
        getMetricRegistry().register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory
                                                                               .getPlatformMBeanServer()));
        getMetricRegistry().register("jvm.classloader", new ClassLoadingGaugeSet());
        getMetricRegistry().register("jvm.filedescriptor", new FileDescriptorRatioGauge());
        getMetricRegistry().register("jvm.gc", new GarbageCollectorMetricSet());
        getMetricRegistry().register("jvm.memory", new MemoryUsageGaugeSet());
        getMetricRegistry().register("jvm.threads", new ThreadStatesGaugeSet());

        JmxReporter.forRegistry(metricRegistry).build().start();
        metricsAreRegistered = true;
    }
56641
def _cache_metrics_metadata(self, instance):
        
        # ## <TEST-INSTRUMENTATION>
        t = Timer()
        # ## </TEST-INSTRUMENTATION>

        i_key = self._instance_key(instance)
        self.metadata_cache.init_instance(i_key)
        self.log.info("Warming metrics metadata cache for instance {}".format(i_key))
        server_instance = self._get_server_instance(instance)
        perfManager = server_instance.content.perfManager
        custom_tags = instance.get('tags', [])

        new_metadata = {}
        metric_ids = []
        # Use old behaviour with metrics to collect defined by our constants
        if self.in_compatibility_mode(instance, log_warning=True):
            for counter in perfManager.perfCounter:
                metric_name = self.format_metric_name(counter, compatibility=True)
                new_metadata[counter.key] = {'name': metric_name, 'unit': counter.unitInfo.key}
                # Build the list of metrics we will want to collect
                if instance.get("all_metrics") or metric_name in BASIC_METRICS:
                    metric_ids.append(vim.PerformanceManager.MetricId(counterId=counter.key, instance="*"))
        else:
            collection_level = instance.get("collection_level", 1)
            for counter in perfManager.QueryPerfCounterByLevel(collection_level):
                new_metadata[counter.key] = {"name": self.format_metric_name(counter), "unit": counter.unitInfo.key}
                # Build the list of metrics we will want to collect
                metric_ids.append(vim.PerformanceManager.MetricId(counterId=counter.key, instance="*"))

        self.log.info("Finished metadata collection for instance {}".format(i_key))
        # Reset metadata
        self.metadata_cache.set_metadata(i_key, new_metadata)
        self.metadata_cache.set_metric_ids(i_key, metric_ids)

        self.cache_config.set_last(CacheConfig.Metadata, i_key, time.time())

        # ## <TEST-INSTRUMENTATION>
        self.histogram('datadog.agent.vsphere.metric_metadata_collection.time', t.total(), tags=custom_tags)
501874
private StandardUnit getMetricUnit(final String metricName) {
        String result = null;

        if (metricName.equals(Constants.CPU_UTILIZATION)) {
            result = Constants.UNIT_PERCENT;
        } else if (metricName.equals(Constants.DISK_READ_BYTES)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.DISK_READ_OPS)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.DISK_WRITE_BYTES)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.DISK_WRITE_OPS)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.NETWORK_IN)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.NETWORK_OUT)) {
            result = Constants.UNIT_BYTES;
        } else if (metricName.equals(Constants.NETWORK_PACKETS_IN)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.NETWORK_PACKETS_OUT)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.STATUS_CHECK_FAILED)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.STATUS_CHECK_FAILED_INSTANCE)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.STATUS_CHECK_FAILED_SYSTEM)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.CPU_CREDIT_USAGE)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.ESTIMATED_CHARGES)) {
            result = Constants.UNIT_COUNT;
        } else if (metricName.equals(Constants.CPU_CREDIT_BALANCE)) {
            result = Constants.UNIT_COUNT;
        }

        return StandardUnit.fromValue(result);
    }
1092141
public TopologyMaster.MetricResponse getMetrics(TopologyMaster.MetricRequest request) {
    String componentName = request.getComponentName();
    if (!cache.componentInstanceExists(componentName, null)) {
      return buildResponseNotOk(
          String.format("Unknown component %s found in MetricRequest %s", componentName, request)
      ).build();
    }
    if (request.getInstanceIdCount() > 0) {
      for (String instanceId : request.getInstanceIdList()) {
        if (!cache.componentInstanceExists(componentName, instanceId)) {
          return buildResponseNotOk(
              String.format("Unknown instance %s found in MetricRequest %s", instanceId, request)
          ).build();
        }
      }
    }
    if (!request.hasInterval() && !request.hasExplicitInterval()) {
      return buildResponseNotOk("No purgeIntervalSec or explicit purgeIntervalSec set").build();
    }

    MetricRequest request1 = MetricsCacheQueryUtils.fromProtobuf(request);
    MetricResponse response1 = cache.getMetrics(request1, metricNameType);
    TopologyMaster.MetricResponse response = MetricsCacheQueryUtils.toProtobuf(response1, request1);
    return response;
  }
667758
def _process_limit_metric(self, m_name, metric, cache, scraper_config, pct_m_name=None):
        
        samples = self._sum_values_by_context(metric, self._get_entity_id_if_container_metric)
        for c_id, sample in iteritems(samples):
            limit = sample[self.SAMPLE_VALUE]
            pod_uid = self._get_pod_uid(sample[self.SAMPLE_LABELS])
            if self.pod_list_utils.is_excluded(c_id, pod_uid):
                continue

            tags = tagger.tag(c_id, tagger.HIGH)
            tags += scraper_config['custom_tags']

            if m_name:
                self.gauge(m_name, limit, tags)

            if pct_m_name and limit > 0:
                c_name = self._get_container_label(sample[self.SAMPLE_LABELS], 'name')
                if not c_name:
                    continue
                usage, tags = cache.get(c_name, (None, None))
                if usage:
                    self.gauge(pct_m_name, float(usage / float(limit)), tags)
                else:
                    self.log.debug(
                        "No corresponding usage found for metric %s and "
                        "container %s, skipping usage_pct for now." % (pct_m_name, c_name)
                    )
478819
public static lbmetrictable[] get(nitro_service service, String metrictable[]) throws Exception{
		if (metrictable !=null && metrictable.length>0) {
			lbmetrictable response[] = new lbmetrictable[metrictable.length];
			lbmetrictable obj[] = new lbmetrictable[metrictable.length];
			for (int i=0;i<metrictable.length;i++) {
				obj[i] = new lbmetrictable();
				obj[i].set_metrictable(metrictable[i]);
				response[i] = (lbmetrictable) obj[i].get_resource(service);
			}
			return response;
		}
		return null;
	}
88588
@SuppressWarnings("unchecked")
  private void gatherOneMetric(
      String metricName,
      Metrics.MetricPublisherPublishMessage.Builder builder) {
    Object metricValue = metrics.get(metricName).getValueAndReset();
    // Decide how to handle the metric based on type
    if (metricValue == null) {
      return;
    }
    if (metricValue instanceof Map) {
      for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) metricValue).entrySet()) {
        if (entry.getKey() != null && entry.getValue() != null) {
          addDataToMetricPublisher(
              builder, metricName + "/" + entry.getKey().toString(), entry.getValue());
        }
      }
    } else if (metricValue instanceof Collection) {
      int index = 0;
      for (Object value : (Collection) metricValue) {
        addDataToMetricPublisher(builder, metricName + "/" + (index++), value);
      }
    } else {
      addDataToMetricPublisher(builder, metricName, metricValue);
    }
  }
756676
public MetricRegistry registerMetrics(final MetricRegistry registry) {
      registry.register(MetricRegistry.name(ConnectionPool.class, name), metrics);
      return registry;
   }