67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
|
|
log "git.wntrmute.dev/kyle/goutils/log"
|
|
"git.wntrmute.dev/kyle/kdhcp/iptools"
|
|
"git.wntrmute.dev/kyle/kdhcp/leases"
|
|
)
|
|
|
|
type LeaseState struct {
|
|
Pools map[string]*iptools.Pool `json:"pools"`
|
|
Static map[string]*leases.Info `json:"static"`
|
|
}
|
|
|
|
func (srv *Server) SaveLeases() error {
|
|
state := &LeaseState{
|
|
Pools: srv.Pools,
|
|
Static: srv.Static,
|
|
}
|
|
|
|
out, err := json.MarshalIndent(state, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = os.WriteFile(srv.Config.LeaseFile, out, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
log.Infof("wrote lease state to file %s", srv.Config.LeaseFile)
|
|
return nil
|
|
}
|
|
|
|
func (srv *Server) LoadLeases() error {
|
|
state := &LeaseState{}
|
|
|
|
stateBytes, err := os.ReadFile(srv.Config.LeaseFile)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
log.Infof("not restoring leases from %s: file doesn't exist", srv.Config.LeaseFile)
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
log.Infoln("restored lease states")
|
|
|
|
srv.Pools = state.Pools
|
|
srv.Static = state.Static
|
|
return nil
|
|
}
|