腾讯mini项目-【指标监控服务重构】2023-07-21

今日已办

当在Docker容器中运行程序时,可能会遇到使用os.Getpid()函数时出现异常的情况。这是因为Docker容器中的进程隔离机制与宿主机器不同,容器内部的进程可能无法访问宿主机器的进程信息。

要解决这个问题,可以尝试:

使用docker run命令启动容器时,添加--pid=host选项,将容器与宿主机器共享进程命名空间。这样,容器内部的进程就可以访问宿主机器的进程信息。

需要注意的是,使用这种方法可能会破坏容器的隔离性,可能导致容器内部的进程与宿主机器的进程产生冲突。此外,该选项需要在启动容器时指定,无法在程序运行时动态设置。

sh 复制代码
docker run --pid=host <image-name>
go 复制代码
// createMemoryPercentObserver
// @Description  createMemoryPercentObserver
// @Author xzx 2023-07-21 16:24:51
// @Param err
// @Param periodicMeter
func createMemoryPercentObserver(err error, periodicMeter metric.Meter) {
   _, err = periodicMeter.Float64ObservableGauge(
      "profile/memory_percent",
      metric.WithFloat64Callback(func(ctx context.Context, observer metric.Float64Observer) error {
         p, err2 := process.NewProcess(int32(os.Getpid()))
         if err2 != nil {
            return err2
         }
         memoryPercent, err2 := p.MemoryPercent()
         if err2 != nil {
            return err2
         }
         memoryPercent *= 100.0
         log.Logger.Info(fmt.Sprintf("profile memory percentage: %f%%", memoryPercent))
         observer.Observe(float64(memoryPercent))
         return nil
      }),
      metric.WithDescription("the memory percentage of profile server"),
   )
}

// createCpuPercentObserver
// @Description  createCpuPercentObserver
// @Author xzx 2023-07-21 16:19:59
// @Param err
// @Param periodicMeter
// @Return error
func createCpuPercentObserver(err error, periodicMeter metric.Meter) error {
   _, err = periodicMeter.Float64ObservableGauge(
      "profile/cpu_percent",
      metric.WithFloat64Callback(func(ctx context.Context, observer metric.Float64Observer) error {
         p, err2 := process.NewProcess(int32(os.Getpid()))
         if err2 != nil {
            return err2
         }
         cpuPercent, err2 := p.CPUPercent()
         if err2 != nil {
            return err2
         }
         cpuPercent *= 100.0
         log.Logger.Info(fmt.Sprintf("profile cpu percentage: %f%%", cpuPercent))
         observer.Observe(cpuPercent)
         return nil
      }),
      metric.WithDescription("the cpu percentage of profile server"),
   )
   return err
}

明日待办

相关推荐
vipxieliang6 小时前
语言对比卡:PHP vs Go vs Java 的优缺点、适用场景与「为什么选 PHP」
java·go·php
我不会起名字3221 天前
Redis 从 0 到 1(二十七):JSON 体积是 Protobuf 的 3.7 倍?3 种序列化的 Go 基准测试
redis·go·序列化·protobuf·messagepack
我不会起名字3221 天前
Redis 从 0 到 1(二十三):一个热 key 打到 10 万 QPS——hotkey 与本地缓存的 Go 实现
redis·缓存·go·qps·hotkey
开目软件1 天前
圆满验收 | 泰胜风能 & 开目MOM,数智重构风电塔筒制造内核
重构·制造
KKKlucifer2 天前
国内数据安全服务的产品智能化转型:大模型赋能下的技术能力重构分析
大数据·数据库·重构
Patrick_Wilson2 天前
Go 为什么需要 defer?从函数怎么收尾说起
后端·go·编程语言
Patrick_Wilson2 天前
从文本输出理解 Go 方法与接口
后端·go·编程语言
nm_zfyjt2 天前
信息流广告投放优化实践:线索成本评估模型与转化链路重构(家装建材案例)
算法·重构·内蒙古朋友圈广告服务商·内蒙古朋友圈获客
WiKiLeaks_successor2 天前
重构Time库的抽象设计
python·重构
Patrick_Wilson2 天前
读懂一个 Go JSON 处理函数:从输入数据追踪结构体、校验与错误返回
go·json·编程语言