woodpecker/cmd/agent/config.go

81 lines
2 KiB
Go
Raw Normal View History

2023-07-12 16:51:40 +00:00
// Copyright 2022 Woodpecker Authors
// Copyright 2019 Laszlo Fogas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/json"
"os"
"strings"
"github.com/rs/zerolog/log"
)
type AgentConfig struct {
AgentID int64 `json:"agent_id"`
}
const defaultAgentIDValue = int64(-1)
func readAgentConfig(agentConfigPath string) AgentConfig {
conf := AgentConfig{
AgentID: defaultAgentIDValue,
}
if agentConfigPath == "" {
return conf
}
2023-07-12 16:51:40 +00:00
rawAgentConf, err := os.ReadFile(agentConfigPath)
if err != nil {
if os.IsNotExist(err) {
2023-07-12 16:51:40 +00:00
log.Info().Msgf("no agent config found at '%s', start with defaults", agentConfigPath)
} else {
log.Error().Err(err).Msgf("could not open agent config at '%s'", agentConfigPath)
}
return conf
}
if strings.TrimSpace(string(rawAgentConf)) == "" {
return conf
}
if err := json.Unmarshal(rawAgentConf, &conf); err != nil {
log.Error().Err(err).Msg("could not parse agent config")
}
return conf
}
func writeAgentConfig(conf AgentConfig, agentConfigPath string) error {
2023-07-12 16:51:40 +00:00
rawAgentConf, err := json.Marshal(conf)
if err != nil {
log.Error().Err(err).Msg("could not marshal agent config")
return err
2023-07-12 16:51:40 +00:00
}
// get old config
oldRawAgentConf, _ := os.ReadFile(agentConfigPath)
// if config differ write to disk
2023-07-17 12:53:02 +00:00
if !bytes.Equal(rawAgentConf, oldRawAgentConf) {
2023-07-12 16:51:40 +00:00
if err := os.WriteFile(agentConfigPath, rawAgentConf, 0o644); err != nil {
log.Error().Err(err).Msgf("could not persist agent config at '%s'", agentConfigPath)
return err
2023-07-12 16:51:40 +00:00
}
}
return nil
2023-07-12 16:51:40 +00:00
}