aboutsummaryrefslogtreecommitdiffstats
path: root/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
blob: 98787eaeeeb8bfd4a8ffaf42169856540084e47c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;

import com.google.inject.Inject;
import com.yahoo.component.AbstractComponent;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Clock;
import java.time.Duration;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Uses a timer to emit metrics
 *
 * @author bjorncs
 * @author vegardh
 *
 */
public class MetricUpdater extends AbstractComponent {

    private static final String FREE_MEMORY_BYTES = "mem.heap.free";
    private static final String USED_MEMORY_BYTES = "mem.heap.used";
    private static final String TOTAL_MEMORY_BYTES = "mem.heap.total";
    private static final String MEMORY_MAPPINGS_COUNT = "jdisc.memory_mappings";
    private static final String OPEN_FILE_DESCRIPTORS = "jdisc.open_file_descriptors";

    private final Scheduler scheduler;

    @Inject
    public MetricUpdater(Metric metric, ContainerWatchdogMetrics containerWatchdogMetrics) {
        this(new TimerScheduler(), metric, containerWatchdogMetrics);
    }

    MetricUpdater(Scheduler scheduler, Metric metric, ContainerWatchdogMetrics containerWatchdogMetrics) {
        this.scheduler = scheduler;
        scheduler.schedule(new UpdaterTask(metric, containerWatchdogMetrics), Duration.ofSeconds(10));
    }

    @Override
    public void deconstruct() {
        scheduler.cancel();
    }

    // Note: Linux-specific
    private static long count_mappings() {
        long count = 0;
        try {
            Path p = Paths.get("/proc/self/maps");
            if (!p.toFile().exists()) return 0; // E.g. MacOS
            byte[] data = Files.readAllBytes(p);
            for (byte b : data) {
                if (b == '\n') {
                    ++count;
                }
            }
        } catch (Exception e) {
            System.err.println("Could not read /proc/self/maps: " + e);
        }
        return count;
    }
    // Note: Linux-specific

    private static long count_open_files() {
        long count = 0;
        try {
            Path p = Paths.get("/proc/self/fd");
            if (!p.toFile().exists()) return 0; // E.g. MacOS
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {
                for (Path entry : stream) {
                    ++count;
                }
            }
        } catch (Exception e) {
            System.err.println("Could not read /proc/self/fd: " + e);
        }
        return count;
    }

    private static class UpdaterTask implements Runnable {

        private final Runtime runtime = Runtime.getRuntime();
        private final Metric metric;
        private final ContainerWatchdogMetrics containerWatchdogMetrics;
        private final GarbageCollectionMetrics garbageCollectionMetrics;

        public UpdaterTask(Metric metric, ContainerWatchdogMetrics containerWatchdogMetrics) {
            this.metric = metric;
            this.containerWatchdogMetrics = containerWatchdogMetrics;
            this.garbageCollectionMetrics = new GarbageCollectionMetrics(Clock.systemUTC());
        }

        @SuppressWarnings("deprecation")
        @Override
        public void run() {
            long freeMemory = runtime.freeMemory();
            long totalMemory = runtime.totalMemory();
            long usedMemory = totalMemory - freeMemory;
            metric.set(FREE_MEMORY_BYTES, freeMemory, null);
            metric.set(USED_MEMORY_BYTES, usedMemory, null);
            metric.set(TOTAL_MEMORY_BYTES, totalMemory, null);
            metric.set(MEMORY_MAPPINGS_COUNT, count_mappings(), null);
            metric.set(OPEN_FILE_DESCRIPTORS, count_open_files(), null);

            containerWatchdogMetrics.emitMetrics(metric);
            garbageCollectionMetrics.emitMetrics(metric);
        }
    }

    private static class TimerScheduler implements Scheduler {

        private final Timer timer = new Timer();

        @Override
        public void schedule(Runnable runnable, Duration frequency) {
            long frequencyMillis = frequency.toMillis();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runnable.run();
                }
            }, frequencyMillis, frequencyMillis) ;
        }

        @Override
        public void cancel() {
            timer.cancel();
        }
    }

    interface Scheduler {
        void schedule(Runnable runnable, Duration frequency);
        void cancel();
    }
}