2022-01-02 02:56:46 +04:00
|
|
|
package prog
|
2021-12-24 23:28:50 +04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/xml"
|
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ProcessList is a map of processes' statuses.
|
|
|
|
type ProcessList map[string]bool
|
|
|
|
|
|
|
|
// NewProcessList returns a ProcessList with initialised map.
|
|
|
|
func NewProcessList() *ProcessList {
|
|
|
|
pl := make(ProcessList)
|
|
|
|
return &pl
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddProcess appends a process to a ProcessList
|
|
|
|
func (pl *ProcessList) AddProcess(name string, isup bool) {
|
|
|
|
(*pl)[name] = isup
|
|
|
|
}
|
|
|
|
|
|
|
|
// ProcessXMLEntry is a XML representation of a process stored in ProcessList.
|
|
|
|
type ProcessXMLEntry struct {
|
|
|
|
XMLName xml.Name
|
|
|
|
Name string `xml:"name,attr"`
|
|
|
|
IsUp bool `xml:",chardata"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalXML implements Marshaler interface for a ProcessList.
|
|
|
|
func (l ProcessList) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
|
|
|
if len(l) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := e.EncodeToken(start); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for key, val := range l {
|
|
|
|
e.Encode(ProcessXMLEntry{
|
|
|
|
XMLName: xml.Name{Local: "Process"},
|
|
|
|
Name: key,
|
|
|
|
IsUp: val})
|
|
|
|
}
|
|
|
|
|
|
|
|
return e.EncodeToken(start.End())
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsProcessUp returns true if process is up, and a list of PIDs for
|
|
|
|
// that process name. Uses pgrep to get PID of a process and if
|
|
|
|
// a process is not working, then pgrep returns nothing.
|
|
|
|
func IsProcessUp(name string) (bool, []int, error) {
|
|
|
|
out, err := exec.Command("pgrep", "-f", name).Output()
|
|
|
|
if err != nil || len(out) < 2 {
|
|
|
|
return false, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
spids := strings.Split(string(out[:len(out)-1]), "\n")
|
|
|
|
pids := make([]int, len(spids))
|
|
|
|
for i, v := range spids {
|
|
|
|
pids[i], err = strconv.Atoi(v)
|
|
|
|
if err != nil {
|
|
|
|
return false, nil, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, pids, nil
|
|
|
|
}
|