1
0
httpprocprobed/prog/confguration.go

97 lines
2.5 KiB
Go

/*
httpprocwatchd provides HTTP interface to a list of process' statuses
formatted as JSON.
Copyright (c) 2021 Alexander "Arav" Andreev <me@arav.top>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package prog
import (
"encoding/json"
"io/ioutil"
)
// Configuration holds a list of process names to be tracked and a listen address.
type Configuration struct {
ListenAddress string `json:"listen_address"`
Processes []string `json:"processes"`
}
// LoadConfiguration loads configuration from a JSON file.
func LoadConfiguration(path string) (conf *Configuration, err error) {
conf = &Configuration{}
file, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
if err := json.Unmarshal(file, conf); err != nil {
return nil, err
}
return conf, nil
}
// StoreConfiguration writes Configuration into a JSON file.
func StoreConfiguration(path string, conf *Configuration) (err error) {
config, err := json.Marshal(*conf)
if err != nil {
return err
}
err = ioutil.WriteFile(path, config, 0644)
if err != nil {
return err
}
return nil
}
// AddProcessToList appends a new given process into a configuration file.
func AddProcessToList(process string, conf *Configuration, configPath string) error {
for _, v := range conf.Processes {
if v == process {
return ErrIsOnList
}
}
conf.Processes = append(conf.Processes, process)
if err := StoreConfiguration(configPath, conf); err != nil {
return err
}
return nil
}
// RemoveProcessFromList removes a given process from a configuration file.
func RemoveProcessFromList(process string, conf *Configuration, configPath string) error {
for k, v := range conf.Processes {
if v == process {
newlist := make([]string, len(conf.Processes)-1)
newlist = append(conf.Processes[:k], conf.Processes[k+1:]...)
conf.Processes = newlist
if err := StoreConfiguration(configPath, conf); err != nil {
return err
}
return nil
}
}
return ErrNotFound
}