springboot2增加diskspace指标

本文主要研究下如何在springboot2新增一个diskspace指标

disk health indicator

DiskSpaceHealthIndicatorProperties

spring-boot-actuator-autoconfigure-2.0.1.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorProperties.java

/**
 * External configuration properties for {@link DiskSpaceHealthIndicator}.
 *
 * @author Andy Wilkinson
 * @since 1.2.0
 */
@ConfigurationProperties(prefix = "management.health.diskspace")
public class DiskSpaceHealthIndicatorProperties {

    private static final int MEGABYTES = 1024 * 1024;

    private static final int DEFAULT_THRESHOLD = 10 * MEGABYTES;

    /**
     * Path used to compute the available disk space.
     */
    private File path = new File(".");

    /**
     * Minimum disk space, in bytes, that should be available.
     */
    private long threshold = DEFAULT_THRESHOLD;

    public File getPath() {
        return this.path;
    }

    public void setPath(File path) {
        Assert.isTrue(path.exists(), () -> "Path '" + path + "' does not exist");
        Assert.isTrue(path.canRead(), () -> "Path '" + path + "' cannot be read");
        this.path = path;
    }

    public long getThreshold() {
        return this.threshold;
    }

    public void setThreshold(long threshold) {
        Assert.isTrue(threshold >= 0, "threshold must be greater than 0");
        this.threshold = threshold;
    }

}

DiskSpaceHealthIndicator

spring-boot-actuator-2.0.1.RELEASE-sources.jar!/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java

/**
 * A {@link HealthIndicator} that checks available disk space and reports a status of
 * {@link Status#DOWN} when it drops below a configurable threshold.
 *
 * @author Mattias Severson
 * @author Andy Wilkinson
 * @since 2.0.0
 */
public class DiskSpaceHealthIndicator extends AbstractHealthIndicator {

    private static final Log logger = LogFactory.getLog(DiskSpaceHealthIndicator.class);

    private final File path;

    private final long threshold;

    /**
     * Create a new {@code DiskSpaceHealthIndicator} instance.
     * @param path the Path used to compute the available disk space
     * @param threshold the minimum disk space that should be available (in bytes)
     */
    public DiskSpaceHealthIndicator(File path, long threshold) {
        super("DiskSpace health check failed");
        this.path = path;
        this.threshold = threshold;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        long diskFreeInBytes = this.path.getUsableSpace();
        if (diskFreeInBytes >= this.threshold) {
            builder.up();
        }
        else {
            logger.warn(String.format(
                    "Free disk space below threshold. "
                            + "Available: %d bytes (threshold: %d bytes)",
                    diskFreeInBytes, this.threshold));
            builder.down();
        }
        builder.withDetail("total", this.path.getTotalSpace())
                .withDetail("free", diskFreeInBytes)
                .withDetail("threshold", this.threshold);
    }

}

metrics

这里我们把disk的health indicator转为metrics

@Component
public class DiskMetrics implements MeterBinder {

    private File rootFilePath;

    public DiskMetrics() {
        this.rootFilePath = new File(".");
    }

    @Override
    public void bindTo(MeterRegistry registry) {
        Gauge.builder("diskspace.total", rootFilePath, c -> c.getTotalSpace())
                .register(registry);
        Gauge.builder("diskspace.free", rootFilePath, c -> c.getFreeSpace())
                .register(registry);
        Gauge.builder("diskspace.usage", rootFilePath, c -> {
            long totalDiskSpace = rootFilePath.getTotalSpace();
            if (totalDiskSpace == 0) {
                return 0.0;
            }

            long usedDiskSpace = totalDiskSpace - rootFilePath.getFreeSpace();
            return Double.valueOf(usedDiskSpace) / totalDiskSpace * 100;
        })
                .register(registry);
    }
}

输出

  • /actuator/metrics { "names": [ "jvm.memory.committed", "jvm.buffer.memory.used", "jvm.gc.memory.allocated", "jvm.memory.used", "jvm.gc.max.data.size", "logback.events", "system.cpu.count", "jvm.memory.max", "jvm.buffer.total.capacity", "jvm.buffer.count", "process.files.max", "jvm.threads.daemon", "process.start.time", "diskspace.usage", "jvm.gc.live.data.size", "process.files.open", "process.cpu.usage", "process.uptime", "system.load.average.1m", "statsd.queue.size", "statsd.queue.capacity", "http.server.requests", "system.cpu.usage", "diskspace.free", "jvm.threads.live", "jvm.classes.loaded", "jvm.classes.unloaded", "jvm.threads.peak", "jvm.gc.pause", "jvm.gc.memory.promoted", "diskspace.total" ] }
  • /actuator/metrics/diskspace.usage { "name": "diskspace.usage", "measurements": [ { "statistic": "VALUE", "value": 96.99886102691765 } ], "availableTags": [] }

小结

springboot2默认把diskspace作为一个healthIndicator,其阈值默认为10M。这里通过自定义micrometer的metrics,新增diskspace相关指标,这样就可以统一通过metrcis进行监控报警。

doc

  • SpringBoot四大神器之Actuator
  • micrometer自定义metrics

原文发布于微信公众号 - 码匠的流水账(geek_luandun)

原文发表时间:2018-04-15

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Spark学习技巧

textFile构建RDD的分区及compute计算策略

1,textFile A),第一点,就是输入格式,key,value类型及并行度的意义。 def textFile( path: String, mi...

2557
来自专栏小樱的经验随笔

Codeforces 839E Mother of Dragons【__builtin_popcount()的使用】

E. Mother of Dragons time limit per test:2 seconds memory limit per test:256 meg...

2738
来自专栏文武兼修ing——机器学习与IC设计

Python解决大规模二进制数据错位问题描述解决方法实验代码最终代码

问题描述 有一些二进制数据,每八位按顺序存为一个十进制数保存成CSV文件,每行为一个二进数数据,每个单元格均为一个十进制数。若数据为0000 0001 1000...

35010
来自专栏机器人网

中英文对照,瞬间理解西门子PLC指令

指令( 英文全称意思 ) :指令含义 1、LD ( Load 装载 ) :动合触点 2、LDN ( Load Not 不装载 ) : 动断触点 3、A ( A...

3577
来自专栏Android知识点总结

看得见的数据结构Android版之单链表篇

711
来自专栏北京马哥教育

Python 中被忽略的 else

1444
来自专栏阿尔法go

Pandas速查手册中文版

本文翻译自文章: Pandas Cheat Sheet - Python for Data Science,同时添加了部分注解。 对于数据科学家,无论是数据分析...

8447
来自专栏数据之美

BloomFilter 简介及在 Hadoop reduce side join 中的应用

1、BloomFilter能解决什么问题?      以少量的内存空间判断一个元素是否属于这个集合, 代价是有一定的错误率 2、工作原理 ...

2517
来自专栏数据结构与算法

BZOJ1269: [AHOI2006]文本编辑器editor

Descriptio 这些日子,可可不和卡卡一起玩了,原来可可正废寝忘食的想做一个简单而高效的文本编辑器。你能帮助他吗? 为了明确任务目标,可可对“文本编辑器...

2907
来自专栏张善友的专栏

轻型的ORM类Dapper

Dapper是一个轻型的ORM类。代码就一个SqlMapper.cs文件,主要是IDbConnection的扩展方法,编译后就40K的一个很小的dll。官方站点...

2129

扫码关注云+社区

领取腾讯云代金券