# 监控改造之路2

接上篇

因为团队做的平台会有动态添加主机的需求，为了支持主机监控，以前在prometheus.yml中是这么写的:

```yaml
scrape_configs:
  - job_name: node-exporters
    scrape_interval: 5s
    file_sd_configs:
    - files: 
      - conf.d/*.json
```

嗯，很明显，主机信息是存放在conf.d目录下的.json文件中的，当然，json文件也是通过configmap(后文简称为cm)挂载到prometheus(后面简称为prom)中的。逻辑是清晰的，但是，在动态添加主机的时候，需要先读取cm，然后将新添加的主机信息加入到cm，然后更新这个cm。然而当时开发这个功能的同学在更新完cm后，发现新增加主机并没有在prom的target中，疑惑之下，只得写了一个定时任务：每2分钟调用一次prom的热加载接口("/-/reload")。

初看到这么干，其实我还是挺惊讶的，毕竟prom的官网中对于file\_sd\_configs是这么说的：

"Changes to all defined files are detected via disk watches and applied immediately"

我不信邪，专门去测了一下，发现通过以上方式添加的主机的确不是立马生效的，有15s左右的延迟，但毕竟这里的prom是部署在K8s中，跟裸机部署还是有差别的，此时我想到json文件是通过cm挂载到prom的，会不会跟这一点有关？查询了一些资料之后发现果然如此，想想也是，K8s的资源是存储在etcd，cm更新后，pod并不知啊，于是我想到了一个工具：\[Reloader\]([https://github.com/stakater/Reloader](https://github.com/stakater/Reloader))

> 这个项目叫做 [Reloader](https://github.com/stakater/Reloader)，它可以监控 Configmap/Secret 的变化，根据 Annotation 选择 Deployment，对相关 Deployment 进行滚动更新

似乎问题解决了，cm更新后，关联的prom能及时进行滚动升级，太棒了，然而，又引发另外一个问题：

```plaintext
Opening storage failed open DB in /etc/prometheus/data: Locked by other process
```

好家伙， 滚动升级失败了。这个问题呢，跟我们使用NFS存储prom的时序数据有关，其实prom的官方文档中是有提到这一点的

> **CAUTION:** Non-POSIX compliant filesystems are not supported for Prometheus' local storage as unrecoverable corruptions may happen. NFS filesystems (including AWS's EFS) are not supported. NFS could be POSIX-compliant, but most implementations are not. It is strongly recommended to use a local filesystem for reliability.

简而言之就是，不建议使用NFS存储prom时序数据……在我们的业务场景下，只能通过增加启动参数"--no-lock-file"来解决，真应了那句话：为了解决一个问题，又引发另一个问题。

参考：

* [https://prometheus.io/docs/prometheus/latest/configuration/configuration/#file\_sd\_config](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#file_sd_config)
    
* [https://jimmysong.io/kubernetes-handbook/concepts/configmap-hot-update.html](https://jimmysong.io/kubernetes-handbook/concepts/configmap-hot-update.html)
    
* [https://blog.fleeto.us/post/kube-cm-sec-reloader/](https://blog.fleeto.us/post/kube-cm-sec-reloader/)
    
* [https://liqiang.io/post/lockfile-in-prometheus-c48af447](https://liqiang.io/post/lockfile-in-prometheus-c48af447)
