kdhcp/server/lease_state.go

67 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-05-06 05:21:27 +00:00
package server
import (
2023-05-15 13:09:12 +00:00
"encoding/json"
2023-05-06 05:21:27 +00:00
"os"
2023-05-09 07:28:54 +00:00
log "git.wntrmute.dev/kyle/goutils/log"
2023-05-06 05:21:27 +00:00
"git.wntrmute.dev/kyle/kdhcp/iptools"
2023-05-15 13:09:12 +00:00
"git.wntrmute.dev/kyle/kdhcp/leases"
2023-05-06 05:21:27 +00:00
)
type LeaseState struct {
2023-05-15 13:09:12 +00:00
Pools map[string]*iptools.Pool `json:"pools"`
Static map[string]*leases.Info `json:"static"`
2023-05-06 05:21:27 +00:00
}
func (srv *Server) SaveLeases() error {
state := &LeaseState{
Pools: srv.Pools,
Static: srv.Static,
}
2023-05-15 13:09:12 +00:00
out, err := json.MarshalIndent(state, "", " ")
if err != nil {
return err
2023-05-06 05:21:27 +00:00
}
2023-05-15 13:09:12 +00:00
err = os.WriteFile(srv.Config.LeaseFile, out, 0644)
if err != nil {
return err
2023-05-06 05:21:27 +00:00
}
2023-05-15 13:09:12 +00:00
log.Infof("wrote lease state to file %s", srv.Config.LeaseFile)
2023-05-06 05:21:27 +00:00
return nil
}
func (srv *Server) LoadLeases() error {
2023-05-15 13:09:12 +00:00
state := &LeaseState{}
stateBytes, err := os.ReadFile(srv.Config.LeaseFile)
2023-05-06 05:21:27 +00:00
if err != nil {
if os.IsNotExist(err) {
2023-05-15 13:09:12 +00:00
log.Infof("not restoring leases from %s: file doesn't exist", srv.Config.LeaseFile)
2023-05-06 05:21:27 +00:00
return nil
}
2023-05-15 13:09:12 +00:00
return err
2023-05-06 05:21:27 +00:00
}
2023-05-15 13:09:12 +00:00
err = json.Unmarshal(stateBytes, state)
if err != nil {
switch err := err.(type) {
case *json.UnmarshalTypeError:
log.Infof("type error: %q: [ \"bad type: got %s; want %s\" ]", err.Field, err.Value, err.Type.String())
return err
case *json.InvalidUnmarshalError:
log.Infof("invalid unmarshal error: %s", err)
}
return err
2023-05-06 05:21:27 +00:00
}
2023-05-15 13:09:12 +00:00
log.Infoln("restored lease states")
srv.Pools = state.Pools
srv.Static = state.Static
2023-05-06 05:21:27 +00:00
return nil
}