Search in sources :

Example 1 with SimpleCounter

use of org.apache.flink.metrics.SimpleCounter in project flink by apache.

the class Slf4jReporterTest method testAddCounter.

@Test
void testAddCounter() throws Exception {
    String counterName = "simpleCounter";
    SimpleCounter counter = new SimpleCounter();
    reporter.notifyOfAddedMetric(counter, counterName, metricGroup);
    assertThat(reporter.getCounters()).containsKey(counter);
    String expectedCounterReport = reporter.filterCharacters(SCOPE) + delimiter + reporter.filterCharacters(counterName) + ": 0";
    reporter.report();
    assertThat(testLoggerResource.getMessages()).anyMatch(logOutput -> logOutput.contains(expectedCounterReport));
}
Also used : SimpleCounter(org.apache.flink.metrics.SimpleCounter) Test(org.junit.jupiter.api.Test)

Example 2 with SimpleCounter

use of org.apache.flink.metrics.SimpleCounter in project flink by apache.

the class DataSinkTask method invoke.

@Override
public void invoke() throws Exception {
    // --------------------------------------------------------------------
    // Initialize
    // --------------------------------------------------------------------
    LOG.debug(getLogString("Start registering input and output"));
    // initialize OutputFormat
    initOutputFormat();
    // initialize input readers
    try {
        initInputReaders();
    } catch (Exception e) {
        throw new RuntimeException("Initializing the input streams failed" + (e.getMessage() == null ? "." : ": " + e.getMessage()), e);
    }
    LOG.debug(getLogString("Finished registering input and output"));
    // --------------------------------------------------------------------
    // Invoke
    // --------------------------------------------------------------------
    LOG.debug(getLogString("Starting data sink operator"));
    RuntimeContext ctx = createRuntimeContext();
    final Counter numRecordsIn;
    {
        Counter tmpNumRecordsIn;
        try {
            InternalOperatorIOMetricGroup ioMetricGroup = ((InternalOperatorMetricGroup) ctx.getMetricGroup()).getIOMetricGroup();
            ioMetricGroup.reuseInputMetricsForTask();
            ioMetricGroup.reuseOutputMetricsForTask();
            tmpNumRecordsIn = ioMetricGroup.getNumRecordsInCounter();
        } catch (Exception e) {
            LOG.warn("An exception occurred during the metrics setup.", e);
            tmpNumRecordsIn = new SimpleCounter();
        }
        numRecordsIn = tmpNumRecordsIn;
    }
    if (RichOutputFormat.class.isAssignableFrom(this.format.getClass())) {
        ((RichOutputFormat) this.format).setRuntimeContext(ctx);
        LOG.debug(getLogString("Rich Sink detected. Initializing runtime context."));
    }
    ExecutionConfig executionConfig = getExecutionConfig();
    boolean objectReuseEnabled = executionConfig.isObjectReuseEnabled();
    try {
        // initialize local strategies
        MutableObjectIterator<IT> input1;
        switch(this.config.getInputLocalStrategy(0)) {
            case NONE:
                // nothing to do
                localStrategy = null;
                input1 = reader;
                break;
            case SORT:
                // initialize sort local strategy
                try {
                    // get type comparator
                    TypeComparatorFactory<IT> compFact = this.config.getInputComparator(0, getUserCodeClassLoader());
                    if (compFact == null) {
                        throw new Exception("Missing comparator factory for local strategy on input " + 0);
                    }
                    // initialize sorter
                    Sorter<IT> sorter = ExternalSorter.newBuilder(getEnvironment().getMemoryManager(), this, this.inputTypeSerializerFactory.getSerializer(), compFact.createComparator()).maxNumFileHandles(this.config.getFilehandlesInput(0)).enableSpilling(getEnvironment().getIOManager(), this.config.getSpillingThresholdInput(0)).memoryFraction(this.config.getRelativeMemoryInput(0)).objectReuse(this.getExecutionConfig().isObjectReuseEnabled()).largeRecords(this.config.getUseLargeRecordHandler()).build(this.reader);
                    this.localStrategy = sorter;
                    input1 = sorter.getIterator();
                } catch (Exception e) {
                    throw new RuntimeException("Initializing the input processing failed" + (e.getMessage() == null ? "." : ": " + e.getMessage()), e);
                }
                break;
            default:
                throw new RuntimeException("Invalid local strategy for DataSinkTask");
        }
        // read the reader and write it to the output
        final TypeSerializer<IT> serializer = this.inputTypeSerializerFactory.getSerializer();
        final MutableObjectIterator<IT> input = input1;
        final OutputFormat<IT> format = this.format;
        // check if task has been canceled
        if (this.taskCanceled) {
            return;
        }
        LOG.debug(getLogString("Starting to produce output"));
        // open
        format.open(this.getEnvironment().getTaskInfo().getIndexOfThisSubtask(), this.getEnvironment().getTaskInfo().getNumberOfParallelSubtasks());
        if (objectReuseEnabled) {
            IT record = serializer.createInstance();
            // work!
            while (!this.taskCanceled && ((record = input.next(record)) != null)) {
                numRecordsIn.inc();
                format.writeRecord(record);
            }
        } else {
            IT record;
            // work!
            while (!this.taskCanceled && ((record = input.next()) != null)) {
                numRecordsIn.inc();
                format.writeRecord(record);
            }
        }
        // failed.
        if (!this.taskCanceled) {
            this.format.close();
            this.format = null;
        }
    } catch (Exception ex) {
        // make a best effort to clean up
        try {
            if (!cleanupCalled && format instanceof CleanupWhenUnsuccessful) {
                cleanupCalled = true;
                ((CleanupWhenUnsuccessful) format).tryCleanupOnError();
            }
        } catch (Throwable t) {
            LOG.error("Cleanup on error failed.", t);
        }
        ex = ExceptionInChainedStubException.exceptionUnwrap(ex);
        if (ex instanceof CancelTaskException) {
            // forward canceling exception
            throw ex;
        } else // drop, if the task was canceled
        if (!this.taskCanceled) {
            if (LOG.isErrorEnabled()) {
                LOG.error(getLogString("Error in user code: " + ex.getMessage()), ex);
            }
            throw ex;
        }
    } finally {
        if (this.format != null) {
            // This should only be the case if we had a previous error, or were canceled.
            try {
                this.format.close();
            } catch (Throwable t) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn(getLogString("Error closing the output format"), t);
                }
            }
        }
        // close local strategy if necessary
        if (localStrategy != null) {
            try {
                this.localStrategy.close();
            } catch (Throwable t) {
                LOG.error("Error closing local strategy", t);
            }
        }
        BatchTask.clearReaders(new MutableReader<?>[] { inputReader });
    }
    if (!this.taskCanceled) {
        LOG.debug(getLogString("Finished data sink operator"));
    } else {
        LOG.debug(getLogString("Data sink operator cancelled"));
    }
}
Also used : ExecutionConfig(org.apache.flink.api.common.ExecutionConfig) ExceptionInChainedStubException(org.apache.flink.runtime.operators.chaining.ExceptionInChainedStubException) CancelTaskException(org.apache.flink.runtime.execution.CancelTaskException) InternalOperatorIOMetricGroup(org.apache.flink.runtime.metrics.groups.InternalOperatorIOMetricGroup) SimpleCounter(org.apache.flink.metrics.SimpleCounter) Counter(org.apache.flink.metrics.Counter) SimpleCounter(org.apache.flink.metrics.SimpleCounter) CancelTaskException(org.apache.flink.runtime.execution.CancelTaskException) RuntimeContext(org.apache.flink.api.common.functions.RuntimeContext) RichOutputFormat(org.apache.flink.api.common.io.RichOutputFormat) CleanupWhenUnsuccessful(org.apache.flink.api.common.io.CleanupWhenUnsuccessful)

Example 3 with SimpleCounter

use of org.apache.flink.metrics.SimpleCounter in project flink by apache.

the class PrometheusReporterTest method metricIsRemovedWhenCollectorIsNotUnregisteredYet.

@Test
void metricIsRemovedWhenCollectorIsNotUnregisteredYet() throws UnirestException {
    JobManagerMetricGroup jmMetricGroup = JobManagerMetricGroup.createJobManagerMetricGroup(registry, HOST_NAME);
    String metricName = "metric";
    Counter metric1 = new SimpleCounter();
    FrontMetricGroup<JobManagerJobMetricGroup> metricGroup1 = new FrontMetricGroup<>(createReporterScopedSettings(), jmMetricGroup.addJob(JobID.generate(), "job_1"));
    reporter.notifyOfAddedMetric(metric1, metricName, metricGroup1);
    Counter metric2 = new SimpleCounter();
    FrontMetricGroup<JobManagerJobMetricGroup> metricGroup2 = new FrontMetricGroup<>(createReporterScopedSettings(), jmMetricGroup.addJob(JobID.generate(), "job_2"));
    reporter.notifyOfAddedMetric(metric2, metricName, metricGroup2);
    reporter.notifyOfRemovedMetric(metric1, metricName, metricGroup1);
    String response = pollMetrics(reporter.getPort()).getBody();
    assertThat(response).doesNotContain("job_1");
}
Also used : JobManagerMetricGroup(org.apache.flink.runtime.metrics.groups.JobManagerMetricGroup) SimpleCounter(org.apache.flink.metrics.SimpleCounter) Counter(org.apache.flink.metrics.Counter) FrontMetricGroup(org.apache.flink.runtime.metrics.groups.FrontMetricGroup) SimpleCounter(org.apache.flink.metrics.SimpleCounter) JobManagerJobMetricGroup(org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup) Test(org.junit.jupiter.api.Test)

Example 4 with SimpleCounter

use of org.apache.flink.metrics.SimpleCounter in project flink by apache.

the class PrometheusReporterTest method counterIsReportedAsPrometheusGauge.

/**
 * {@link io.prometheus.client.Counter} may not decrease, so report {@link Counter} as {@link
 * io.prometheus.client.Gauge}.
 *
 * @throws UnirestException Might be thrown on HTTP problems.
 */
@Test
void counterIsReportedAsPrometheusGauge() throws UnirestException {
    Counter testCounter = new SimpleCounter();
    testCounter.inc(7);
    assertThatGaugeIsExported(testCounter, "testCounter", "7.0");
}
Also used : SimpleCounter(org.apache.flink.metrics.SimpleCounter) Counter(org.apache.flink.metrics.Counter) SimpleCounter(org.apache.flink.metrics.SimpleCounter) Test(org.junit.jupiter.api.Test)

Example 5 with SimpleCounter

use of org.apache.flink.metrics.SimpleCounter in project flink by apache.

the class PrometheusReporterTest method registeringSameMetricTwiceDoesNotThrowException.

@Test
void registeringSameMetricTwiceDoesNotThrowException() {
    Counter counter = new SimpleCounter();
    counter.inc();
    String counterName = "testCounter";
    reporter.notifyOfAddedMetric(counter, counterName, metricGroup);
    reporter.notifyOfAddedMetric(counter, counterName, metricGroup);
}
Also used : SimpleCounter(org.apache.flink.metrics.SimpleCounter) Counter(org.apache.flink.metrics.Counter) SimpleCounter(org.apache.flink.metrics.SimpleCounter) Test(org.junit.jupiter.api.Test)

Aggregations

SimpleCounter (org.apache.flink.metrics.SimpleCounter)31 Counter (org.apache.flink.metrics.Counter)23 Test (org.junit.Test)13 Test (org.junit.jupiter.api.Test)12 Meter (org.apache.flink.metrics.Meter)8 Histogram (org.apache.flink.metrics.Histogram)7 TestHistogram (org.apache.flink.metrics.util.TestHistogram)7 Gauge (org.apache.flink.metrics.Gauge)6 TestMeter (org.apache.flink.metrics.util.TestMeter)5 MonitoringInfo (org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo)4 SimpleMonitoringInfoBuilder (org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder)4 Tuple2 (org.apache.flink.api.java.tuple.Tuple2)4 MetricGroupTest (org.apache.flink.runtime.metrics.groups.MetricGroupTest)4 HashMap (java.util.HashMap)3 MetricGroup (org.apache.flink.metrics.MetricGroup)3 UnregisteredMetricsGroup (org.apache.flink.metrics.groups.UnregisteredMetricsGroup)3 TestMetricGroup (org.apache.flink.metrics.util.TestMetricGroup)3 List (java.util.List)2 Map (java.util.Map)2 ExecutionConfig (org.apache.flink.api.common.ExecutionConfig)2