123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- package ProcessMonitor
- import (
- "AudioPlayer/Common"
- "encoding/json"
- "fmt"
- "github.com/shirou/gopsutil/v3/process"
- "go-micro.dev/v5/registry"
- "io"
- "os"
- "path/filepath"
- "strings"
- "time"
- )
- // 辅助函数:检查特定 PID 的进程是否存在
- func processExistsByPid(pid int32) bool {
- _, err := process.NewProcess(pid)
- if err != nil {
- if err == process.ErrorProcessNotRunning {
- return false
- }
- return false
- }
- return true
- }
- type PidInfo struct {
- Pid int32
- IdName string
- }
- func (p *PidInfo) Exists() bool {
- return processExistsByPid(p.Pid)
- }
- var StitchingServerPid map[int32]PidInfo
- func task() {
- procs, err := process.Processes()
- if err != nil {
- return
- }
- for _, p := range procs {
- var keysToDelete []int32
- for _, info := range StitchingServerPid {
- if info.Exists() {
- continue
- }
- // 读取文件并解析json
- err = Common.Micro.Deregister(®istry.Service{
- Name: "omat_stitching_server",
- Version: "latest",
- Nodes: []*registry.Node{
- {
- Id: info.IdName,
- },
- },
- })
- keysToDelete = append(keysToDelete, info.Pid)
- }
- for _, key := range keysToDelete {
- delete(StitchingServerPid, key)
- }
- if _, ok := StitchingServerPid[p.Pid]; ok {
- continue
- }
- name, err := p.Name()
- if err != nil {
- continue
- }
- cwd, err := p.Cwd()
- if err != nil {
- continue
- }
- if strings.Contains(name, "StitchingServer") {
- file, err := os.OpenFile(filepath.Join(cwd, "configure", "Server.json"), os.O_RDONLY, 0644)
- defer file.Close()
- all, err := io.ReadAll(file)
- if err != nil {
- continue
- }
- var jsondata StitchingServerServerJson
- err = json.Unmarshal(all, &jsondata)
- if err != nil {
- continue
- }
- err = Common.Micro.Register(®istry.Service{
- Name: "omat_stitching_server",
- Version: "latest",
- Nodes: []*registry.Node{
- {
- Id: Common.Machine + "-" + strings.Replace(fmt.Sprintf("%s-%d", jsondata.Server.Host, jsondata.Server.Port), ".", "-", -1),
- Address: fmt.Sprintf("%s:%d", "0.0.0.0", jsondata.Server.Port),
- Metadata: map[string]string{
- "protocol": "http",
- "ip": strings.Join(Common.Address, ","),
- },
- },
- },
- })
- if err != nil {
- continue
- }
- StitchingServerPid[p.Pid] = PidInfo{
- Pid: p.Pid,
- IdName: Common.Machine + "-" + strings.Replace(fmt.Sprintf("%s-%d", jsondata.Server.Host, jsondata.Server.Port), ".", "-", -1),
- }
- }
- }
- return
- }
- type StitchingServerServerJson struct {
- Server struct {
- Host string `json:"Host"`
- Port int `json:"Port"`
- } `json:"Server"`
- }
- func Start() {
- StitchingServerPid = make(map[int32]PidInfo)
- for {
- task()
- time.Sleep(time.Second * 5)
- }
- }
|