kdhcp/server/lease_state.go

63 lines
1.4 KiB
Go
Raw Normal View History

2023-05-06 05:21:27 +00:00
package server
import (
"fmt"
"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"
"gopkg.in/yaml.v2"
)
type LeaseState struct {
Pools map[string]*iptools.Pool `yaml:"pools"`
Static map[string]*iptools.LeaseInfo `yaml:"static"`
}
func (srv *Server) SaveLeases() error {
leaseFile, err := os.Create(srv.Config.LeaseFile)
if err != nil {
return fmt.Errorf("server: while saving leases: %w", err)
}
defer leaseFile.Close()
encoder := yaml.NewEncoder(leaseFile)
state := &LeaseState{
Pools: srv.Pools,
Static: srv.Static,
}
if err = encoder.Encode(state); err != nil {
return fmt.Errorf("server: while saving leases: %w", err)
}
if err = encoder.Close(); err != nil {
return fmt.Errorf("server: while saving leases: %w", err)
}
return nil
}
func (srv *Server) LoadLeases() error {
leaseState := &LeaseState{}
leaseFile, err := os.Open(srv.Config.LeaseFile)
if err != nil {
if os.IsNotExist(err) {
log.Warningf("server: not loading leases from %s: lease file not found", srv.Config.LeaseFile)
return nil
}
return fmt.Errorf("server: while reading leases: %w", err)
}
defer leaseFile.Close()
decoder := yaml.NewDecoder(leaseFile)
if err = decoder.Decode(leaseState); err != nil {
return fmt.Errorf("server: while reading leases: %w", err)
}
srv.Pools = leaseState.Pools
srv.Static = leaseState.Static
return nil
}