Returns metrics since given hour.

@param \CachetHQ\Cachet\Models\Metric $metric
@param int                            $hour

@return \Illuminate\Support\Collection
421785
public function getPointsSinceHour(Metric $metric, $hour)
    {
        $queryType = $this->getQueryType($metric);
        $points = DB::select("SELECT DATE_FORMAT({$this->getMetricPointsTable()}.`created_at`, '%Y-%m-%d %H:00') AS `key`, {$queryType} ".
            "FROM {$this->getMetricsTable()} INNER JOIN {$this->getMetricPointsTable()} ON {$this->getMetricsTable()}.id = {$this->getMetricPointsTable()}.metric_id ".
            "WHERE {$this->getMetricsTable()}.id = :metricId ".
            "AND {$this->getMetricPointsTable()}.`created_at` >= DATE_SUB(NOW(), INTERVAL :hour HOUR) ".
            "AND {$this->getMetricPointsTable()}.`created_at` <= NOW() ".
            "GROUP BY HOUR({$this->getMetricPointsTable()}.`created_at`) ".
            "ORDER BY {$this->getMetricPointsTable()}.`created_at`", [
            'metricId' => $metric->id,
            'hour'     => $hour,
        ]);

        return $this->mapResults($metric, $points);
    }
359355
public function start($metric, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        try {
            $this->timers[$metric] = $this->metricFactory->timer($metric, null, $tags, $sampleRate);
            $this->timers[$metric]->start();
        } catch (\Exception $exception) {
            $this->logException($exception);
        }

        return $this;
    }
963188
private Map<MetricName, MetricValue> get_metrics_(DateTime now, Context ctx) {
        final Consumer<Alert> alert_manager = ctx.getAlertManager();
        final long failed_collections = registry_.getFailedCollections();
        final boolean has_config = registry_.hasConfig();
        final Optional<Duration> scrape_duration = registry_.getScrapeDuration();
        final Optional<Duration> rule_eval_duration = registry_.getRuleEvalDuration();
        final Optional<Duration> processor_duration = registry_.getProcessorDuration();
        first_scrape_ts_.compareAndSet(null, now);  // First time, register the timestamp.
        final Duration uptime = new Duration(first_scrape_ts_.get(), now);

        final Optional<DateTime> last_scrape = last_scrape_;
        last_scrape_ = Optional.of(now);

        final long metric_count = ctx.getTSData().getCurrentCollection().getTSValues().stream()
                .map(TimeSeriesValue::getMetrics)
                .collect(Collectors.summingLong(Map::size));

        alert_manager.accept(new Alert(now, MONITOR_FAIL_ALERT, () -> "builtin rule", Optional.of(failed_collections != 0), MON_ALERT_DURATION, "builtin rule: some collectors failed", EMPTY_MAP));
        alert_manager.accept(new Alert(now, HAS_CONFIG_ALERT, () -> "builtin rule", Optional.of(!has_config), Duration.ZERO, "builtin rule: monitor has no configuration file", EMPTY_MAP));

        Map<MetricName, MetricValue> result = new HashMap<>();
        result.put(FAILED_COLLECTIONS_METRIC, MetricValue.fromIntValue(failed_collections));
        result.put(GROUP_COUNT_METRIC, MetricValue.fromIntValue(ctx.getTSData().getCurrentCollection().getGroups(x -> true).size()));
        result.put(METRIC_COUNT_METRIC, MetricValue.fromIntValue(metric_count));
        result.put(CONFIG_PRESENT_METRIC, MetricValue.fromBoolean(has_config));
        result.put(SCRAPE_DURATION, opt_duration_to_metricvalue_(scrape_duration));
        result.put(RULE_EVAL_DURATION, opt_duration_to_metricvalue_(rule_eval_duration));
        result.put(PROCESSOR_DURATION, opt_duration_to_metricvalue_(processor_duration));
        result.put(UPTIME_DURATION, duration_to_metricvalue_(uptime));
        result.put(SCRAPE_COUNT, MetricValue.fromIntValue(++scrape_count_));
        result.put(SCRAPE_INTERVAL, opt_duration_to_metricvalue_(last_scrape.map(prev -> new Duration(prev, now))));
        result.put(SCRAPE_TS, MetricValue.fromIntValue(now.getMillis()));
        return result;
    }
101402
public function time($metric, $func, array $tags = array())
    {
        $timer_start = microtime(true);
        $func();
        $timer_end = microtime(true);
        $time = round(($timer_end - $timer_start) * 1000, 4);
        return $this->timing($metric, $time, $tags);
    }
620588
function (metric) {
      var now = (new Date().getTime()).toFixed(0)
      var line = null
      if (metric.sct === 'OS' && /collectd/.test(metric.name)) {
        line = this.collectdFormatLine(metric)
      } else {
        if (metric.sct === 'OS') {
          // new OS metric format
          if (metric.filters instanceof Array) {
            line = util.format('%d\t%s\t%d\t%s\t%s', now, metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
          } else {
            line = util.format('%d\t%s\t%d\t%s', now, metric.name, metric.ts, formatArray(metric.value))
          }
          logger.log(line)
        } else {
          line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
          logger.log(line)
        }
      }
      return line
    }
1257335
protected function isMetricValid($metric) {
        if (!isset($metric) || !is_array($metric) 
                || !isset($metric["influx"]) || !isset($metric["influx"]["tags"]) 
                || !isset($metric["mysql"]) || !isset($metric["mysql"]["query"])) {
                    return false;
        }
        return true;
    }
569960
public function getTotal($rp, $metric, $tags) {
        try {
            $todayDt = date("Y-m-d") . "T00:00:00Z";
            
            return  $this->mapper->getRpSum('forever', $metric, $tags) +
                    $this->mapper->getRpSum($rp, $metric, $tags, $todayDt) +
                    $this->mapper->getSum($metric, $tags);
        } catch (Exception $e) {
            throw new AnalyticsException("Analytics client get total exception", 0, $e);
        }
    }
1148512
protected function getSparkline($metric)
    {
        // sparkline is always echoed, so we need to buffer the output
        $view = $this->getRowEvolutionGraph($graphType = 'sparkline', $metrics = array($metric => $metric));

        ob_start();
        $view->render();
        $spark = ob_get_contents();
        ob_end_clean();

        // undo header change by sparkline renderer
        Common::sendHeader('Content-type: text/html');

        // base64 encode the image and put it in an img tag
        $spark = base64_encode($spark);
        return '<img width="100" height="25" src="data:image/png;base64,' . $spark . '" />';
    }
576053
public function gauge($metric, $level, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        return new Gauge($this->prefix($metric), $level, array_merge($this->defaultTags, $tags), $sampleRate);
    }
652814
protected function seedMetricPoints()
    {
        MetricPoint::truncate();

        // Generate 11 hours of metric points
        for ($i = 0; $i < 11; $i++) {
            $metricTime = (new DateTime())->sub(new DateInterval('PT'.$i.'H'));

            MetricPoint::create([
                'metric_id'  => 1,
                'value'      => random_int(1, 10),
                'created_at' => $metricTime,
                'updated_at' => $metricTime,
            ]);
        }
    }
1321702
public function showEditMetricAction(Metric $metric)
    {
        return View::make('dashboard.metrics.edit')
            ->withPageTitle(trans('dashboard.metrics.edit.title').' - '.trans('dashboard.dashboard'))
            ->withMetric($metric)
            ->withAcceptableThresholds(Metric::ACCEPTABLE_THRESHOLDS);
    }
521967
public function counter($metric, $count = 1, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        return new Counter($this->prefix($metric), $count, array_merge($this->defaultTags, $tags), $sampleRate);
    }
77693
public boolean deleteMetric(Metric metric) {
        String metricName = metric.getName();
        checkMetricIsEmpty(metricName);
        QueryPart<Metric> queryPart = new Query<Metric>("metrics")
                .path(metricName, true);
        return httpClientManager.updateMetaData(queryPart, delete());
    }
990290
public function histogram($metric, $duration = null, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        return new Histogram($this->prefix($metric), $duration, array_merge($this->defaultTags, $tags), $sampleRate);
    }
996114
public function getMetricValues($resultClass, $metricName)
    {
        $values = [];

        foreach ($this->iterations as $iteration) {
            if ($iteration->hasResult($resultClass)) {
                $values[] = $iteration->getMetric($resultClass, $metricName);
            }
        }

        return $values;
    }
666742
public function gauge($metric, $level, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        try {
            $this->sendMetric($this->metricFactory->gauge($metric, $level, $tags, $sampleRate));
        } catch (\Exception $exception) {
            $this->logException($exception);
        }

        return $this;
    }
744259
public function setMetrics(array $metrics)
    {
        $this->metrics = array();

        foreach ($metrics as $metric) {
            $this->addMetric($metric);
        }
        
        return $this;
    }