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

明日待办

相关推荐
妙码生花21 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十八):后台系统配置管理实现
前端·后端·go
小满zs1 天前
Go语言第七章(Map)
后端·go
智塑未来1 天前
AI广告视频怎么提效?MiniMax H3与PixPix重构商业内容工作流
人工智能·重构
设计总监老谢1 天前
初创公司商标设计注册拿到证要等多久?
go
程序边界1 天前
从烟囱到融合:一次MongoDB迁移引发的架构重构深思
mongodb·重构·架构
用户125758524361 天前
为什么队列长度归零,不代表后台异步任务真的跑完了
redis·后端·go
独隅1 天前
从 Copilot 到 Agent:AI 驱动的开发工作流重构指南
人工智能·重构·copilot
他们叫我秃子2 天前
前端开发转 Go 全栈(五):终于遇到熟人了,Go 的闭包和高阶函数原来这么像 JavaScript
前端·后端·go
妙码生花2 天前
从 PHP 到 AI + Golang,程序员自救转型手记(五十七):AI时代对组件封装的新理解、agInput 统一入口,动态表单预备
前端·后端·go