63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
|
package server
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"os"
|
||
|
|
||
|
log "git.wntrmute.dev/kyle/goutils/syslog"
|
||
|
"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
|
||
|
}
|