腾讯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
}

明日待办

相关推荐
邹小邹2 小时前
Go 1.25 强势来袭:GC 速度飙升、并发测试神器上线,内存检测更精准!
后端·go
用户89535603282206 小时前
Go泛型实战:告别 interface{} 地狱,从零拆解数据流处理库
go
郭京京1 天前
go语言os.Signal接收操作系统发送的信号的通道
go
郭京京1 天前
go语言context包
go
Ashlee_code1 天前
香港券商智能櫃台系統技術解決方案——融合跨境清算與AI風控,助力券商把握滬港雙市爆發機遇**
java·科技·金融·重构·架构·系统架构·php
smallyu1 天前
Go 语言 GMP 调度器的原理是什么
后端·go
ERP老兵_冷溪虎山1 天前
GoLand 卡成幻灯片?Gopher 必藏的 vmoptions 调优表(续集:WebStorm 飞升后,轮到 Go 开发神器起飞)
后端·go
江湖十年1 天前
万字长文:彻底掌握 Go 1.23 中的迭代器——原理篇
后端·面试·go
程序员爱钓鱼1 天前
Go语言实战案例-实现分页查询接口
后端·google·go
狼爷2 天前
生产环境慎用 context.Background ():你的系统可能在 “空转”
go