2024-11-11 14:32:15 +00:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/fs"
|
|
|
|
"isle/daemon/daecommon"
|
|
|
|
"isle/jsonutil"
|
|
|
|
"isle/toolkit"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
2024-12-14 14:57:07 +00:00
|
|
|
func configPath(networkStateDir toolkit.Dir) string {
|
|
|
|
return filepath.Join(networkStateDir.Path, "config.json")
|
|
|
|
}
|
|
|
|
|
|
|
|
// loadConfig loads the stored NetworkConfig and returns it, or returns the
|
|
|
|
// default NetworkConfig if none is stored.
|
|
|
|
func loadConfig(networkStateDir toolkit.Dir) (daecommon.NetworkConfig, error) {
|
|
|
|
path := configPath(networkStateDir)
|
|
|
|
|
|
|
|
var config daecommon.NetworkConfig
|
|
|
|
if err := jsonutil.LoadFile(&config, path); errors.Is(err, fs.ErrNotExist) {
|
|
|
|
return daecommon.NewNetworkConfig(nil), nil
|
|
|
|
} else if err != nil {
|
|
|
|
return daecommon.NetworkConfig{}, fmt.Errorf(
|
|
|
|
"loading %q: %w", path, err,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return config, nil
|
|
|
|
}
|
|
|
|
|
2024-11-11 14:32:15 +00:00
|
|
|
// loadStoreConfig writes the given NetworkConfig to the networkStateDir if the
|
|
|
|
// config is non-nil. If the config is nil then a config is read from
|
|
|
|
// networkStateDir, returning the zero value if no config was previously
|
|
|
|
// stored.
|
|
|
|
func loadStoreConfig(
|
|
|
|
networkStateDir toolkit.Dir, config *daecommon.NetworkConfig,
|
|
|
|
) (
|
|
|
|
daecommon.NetworkConfig, error,
|
|
|
|
) {
|
|
|
|
if config == nil {
|
2024-12-14 14:57:07 +00:00
|
|
|
return loadConfig(networkStateDir)
|
2024-11-11 14:32:15 +00:00
|
|
|
}
|
|
|
|
|
2024-12-14 14:57:07 +00:00
|
|
|
path := configPath(networkStateDir)
|
2024-11-11 14:32:15 +00:00
|
|
|
if err := jsonutil.WriteFile(*config, path, 0600); err != nil {
|
|
|
|
return daecommon.NetworkConfig{}, fmt.Errorf(
|
|
|
|
"writing to %q: %w", path, err,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return *config, nil
|
|
|
|
}
|