Skip to content

Commit

Permalink
Switch to structured logging
Browse files Browse the repository at this point in the history
closes #9
  • Loading branch information
corny committed Jun 5, 2024
1 parent 36e160a commit c8b6d39
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 19 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'
go-version: '1.21'

- name: Build
run: go build -v ./...
Expand Down
16 changes: 10 additions & 6 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package dhclient
import (
"errors"
"fmt"
"log"
"log/slog"
"math/rand"
"net"
"sync"
Expand All @@ -27,6 +27,7 @@ type Client struct {
OnBound Callback // On renew or rebound
OnExpire Callback // On expiration of a lease
DHCPOptions []Option // List of options to send on discovery and requests
Logger *slog.Logger

conn *packet.Conn // Raw socket
xid uint32 // Transaction ID
Expand Down Expand Up @@ -92,6 +93,9 @@ func (client *Client) AddParamRequest(dhcpOpt layers.DHCPOpt) {

// Start starts the client
func (client *Client) Start() {
if client.Logger == nil {
client.Logger = slog.New(&discardHandler{})
}

// Add default DHCP options if none added yet.
if client.DHCPOptions == nil {
Expand All @@ -102,7 +106,7 @@ func (client *Client) Start() {
}

if client.notify != nil {
log.Panicf("client for %s already started", client.Iface.Name)
panic(fmt.Sprintf("client for %s already started", client.Iface.Name))
}
client.notify = make(chan struct{})
client.wg.Add(1)
Expand All @@ -111,7 +115,7 @@ func (client *Client) Start() {

// Stop stops the client
func (client *Client) Stop() {
log.Printf("[%s] shutting down dhclient", client.Iface.Name)
slog.Info("shutting down dhclient")
client.shutdown = true
close(client.notify)

Expand Down Expand Up @@ -155,7 +159,7 @@ func (client *Client) runOnce() {
}

if err != nil {
log.Printf("[%s] error: %s", client.Iface.Name, err)
client.Logger.Error("failed to acquire lease", "error", err)
// delay for a second
select {
case <-client.notify:
Expand Down Expand Up @@ -277,7 +281,7 @@ func (client *Client) request(lease *Lease) error {

// sendPacket creates and sends a DHCP packet
func (client *Client) sendPacket(msgType layers.DHCPMsgType, options []Option) error {
log.Printf("[%s] sending %s", client.Iface.Name, msgType)
client.Logger.Debug("sending packet", "type", msgType)
return client.sendMulticast(client.newPacket(msgType, options))
}

Expand Down Expand Up @@ -366,7 +370,7 @@ func (client *Client) waitForResponse(msgTypes ...layers.DHCPMsgType) (layers.DH
// do we have the expected message type?
for _, t := range msgTypes {
if t == msgType {
log.Printf("[%s] received %s", client.Iface.Name, msgType)
client.Logger.Debug("received packet", "type", msgType)
return msgType, &res, nil
}
}
Expand Down
25 changes: 14 additions & 11 deletions cmd/dhclient/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import (
"flag"
"fmt"
"log"
"log/slog"
"net"
"os"
"os/signal"
Expand All @@ -28,7 +28,6 @@ func init() {
}

func main() {
log.SetFlags(log.Ltime | log.Lshortfile)
flag.Parse()

if flag.NArg() != 1 {
Expand All @@ -43,22 +42,26 @@ func main() {
os.Exit(1)
}

logHandler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug})
logger := slog.New(logHandler)

client := dhclient.Client{
Iface: iface,
Iface: iface,
Logger: logger,
OnBound: func(lease *dhclient.Lease) {
log.Printf("Bound: %+v", lease)
logger.Info("bound", "lease", lease)
},
}

// Add requests for default options
for _, param := range dhclient.DefaultParamsRequestList {
log.Printf("Requesting default option %d", param)
logger.Info("Requesting default option", "param", param)
client.AddParamRequest(layers.DHCPOpt(param))
}

// Add requests for custom options
for _, param := range requestParams {
log.Printf("Requesting custom option %d", param)
logger.Info("Requesting custom option", "param", param)
client.AddParamRequest(layers.DHCPOpt(param))
}

Expand All @@ -68,26 +71,26 @@ func main() {

// Add custom options
for _, option := range options {
log.Printf("Adding option %d=0x%x", option.Type, option.Data)
slog.Info("Adding custom option", "type", option.Type, "value", fmt.Sprintf("0x%x", option.Data))
client.AddOption(option.Type, option.Data)
}

client.Start()
defer client.Stop()

c := make(chan os.Signal)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGUSR1)
for {
sig := <-c
log.Println("received", sig)
logger.Info("received signal", "type", sig)
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
return
case syscall.SIGHUP:
log.Println("renew lease")
logger.Info("renew lease")
client.Renew()
case syscall.SIGUSR1:
log.Println("acquire new lease")
logger.Info("acquire new lease")
client.Rebind()
}
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ require (
gopkg.in/yaml.v3 v3.0.1 // indirect
)

go 1.18
go 1.21
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
Expand Down
14 changes: 14 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package dhclient

import (
"context"
"log/slog"
)

type discardHandler struct {
slog.JSONHandler
}

func (d *discardHandler) Enabled(context.Context, slog.Level) bool {
return false
}

0 comments on commit c8b6d39

Please sign in to comment.