Skip to content

Commit

Permalink
refactor: provide explicit logger for networkd
Browse files Browse the repository at this point in the history
This changes will make easier running networkd as a goroutine in machined.

Signed-off-by: Andrey Smirnov <smirnov.andrey@gmail.com>
  • Loading branch information
smira authored and talos-bot committed Mar 12, 2021
1 parent 22f3753 commit 4aae924
Show file tree
Hide file tree
Showing 15 changed files with 134 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ func CreateOSReleaseFile(seq runtime.Sequence, data interface{}) (runtime.TaskEx
// SetupDiscoveryNetwork represents the task for setting up the initial network.
func SetupDiscoveryNetwork(seq runtime.Sequence, data interface{}) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
nwd, err := networkd.New(r.Config())
nwd, err := networkd.New(logger, r.Config())
if err != nil {
return err
}
Expand Down Expand Up @@ -585,7 +585,7 @@ func ValidateConfig(seq runtime.Sequence, data interface{}) (runtime.TaskExecuti
// ResetNetwork resets the network.
func ResetNetwork(seq runtime.Sequence, data interface{}) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
nwd, err := networkd.New(r.Config())
nwd, err := networkd.New(logger, r.Config())
if err != nil {
return err
}
Expand Down
36 changes: 19 additions & 17 deletions internal/app/networkd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package main

import (
"context"
"flag"
"log"
"os"
"os/signal"
Expand All @@ -25,21 +24,11 @@ import (
func init() {
// Explicitly disable memory profiling to save around 1.4MiB of memory.
runtime.MemProfileRate = 0

log.SetFlags(log.Lshortfile | log.Ldate | log.Lmicroseconds | log.Ltime)

flag.Parse()
}

func main() {
if err := run(); err != nil {
log.Fatal(err)
}

log.Println("networkd stopped")
}
logger := log.New(os.Stderr, "", log.Lshortfile|log.Ldate|log.Lmicroseconds|log.Ltime)

func run() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

Expand All @@ -55,16 +44,24 @@ func run() error {
}
}()

var eg errgroup.Group
if err := run(ctx, logger); err != nil {
logger.Fatal(err)
}

log.Println("starting initial network configuration")
logger.Println("networkd stopped")
}

func run(ctx context.Context, logger *log.Logger) error {
var eg errgroup.Group

config, err := configloader.NewFromStdin()
if err != nil {
return err
}

nwd, err := networkd.New(config)
logger.Println("starting initial network configuration")

nwd, err := networkd.New(logger, config)
if err != nil {
return err
}
Expand All @@ -73,16 +70,21 @@ func run() error {
return err
}

registrator, err := reg.NewRegistrator(logger, nwd)
if err != nil {
return err
}

if err = nwd.RunControllers(ctx, &eg); err != nil {
return err
}

log.Println("completed initial network configuration")
logger.Println("completed initial network configuration")

nwd.Renew(ctx)

server := factory.NewServer(
reg.NewRegistrator(nwd),
registrator,
factory.WithDefaultLog(),
)

Expand Down
3 changes: 2 additions & 1 deletion internal/app/networkd/pkg/address/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package address

import (
"context"
"log"
"net"
"time"
)
Expand All @@ -15,7 +16,7 @@ import (
// supported.
type Addressing interface {
Address() *net.IPNet
Discover(context.Context, *net.Interface) error
Discover(context.Context, *log.Logger, *net.Interface) error
Family() int
Hostname() string
Link() *net.Interface
Expand Down
10 changes: 5 additions & 5 deletions internal/app/networkd/pkg/address/dhcp4.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ func (d *DHCP4) Link() *net.Interface {
}

// Discover handles the DHCP client exchange stores the DHCP Ack.
func (d *DHCP4) Discover(ctx context.Context, link *net.Interface) error {
func (d *DHCP4) Discover(ctx context.Context, logger *log.Logger, link *net.Interface) error {
d.NetIf = link
err := d.discover(ctx)
err := d.discover(ctx, logger)

return err
}
Expand Down Expand Up @@ -186,7 +186,7 @@ func (d *DHCP4) Hostname() (hostname string) {
}

// discover handles the actual DHCP conversation.
func (d *DHCP4) discover(ctx context.Context) error {
func (d *DHCP4) discover(ctx context.Context, logger *log.Logger) error {
opts := []dhcpv4.OptionCode{
dhcpv4.OptionClasslessStaticRoute,
dhcpv4.OptionDomainNameServer,
Expand Down Expand Up @@ -228,15 +228,15 @@ func (d *DHCP4) discover(ctx context.Context) error {

if err != nil {
// TODO: Make this a well defined error so we can make it not fatal
log.Printf("failed dhcp request for %q: %v", d.NetIf.Name, err)
logger.Printf("failed dhcp request for %q: %v", d.NetIf.Name, err)

// clear offer if request fails to start with discover sequence next time
d.Offer = nil

return err
}

log.Printf("DHCP ACK on %q: %s", d.NetIf.Name, collapseSummary(lease.ACK.Summary()))
logger.Printf("DHCP ACK on %q: %s", d.NetIf.Name, collapseSummary(lease.ACK.Summary()))

d.Ack = lease.ACK
d.Offer = lease.Offer
Expand Down
24 changes: 12 additions & 12 deletions internal/app/networkd/pkg/address/dhcp6.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ func (d *DHCP6) Link() *net.Interface {
}

// Discover handles the DHCP client exchange stores the DHCP Ack.
func (d *DHCP6) Discover(ctx context.Context, link *net.Interface) error {
func (d *DHCP6) Discover(ctx context.Context, logger *log.Logger, link *net.Interface) error {
d.NetIf = link
err := d.discover(ctx)
err := d.discover(ctx, logger)

return err
}
Expand Down Expand Up @@ -119,16 +119,16 @@ func (d *DHCP6) Hostname() (hostname string) {
}

// discover handles the actual DHCP conversation.
func (d *DHCP6) discover(ctx context.Context) error {
if err := waitIPv6LinkReady(d.NetIf); err != nil {
log.Printf("failed waiting for IPv6 readiness: %s", err)
func (d *DHCP6) discover(ctx context.Context, logger *log.Logger) error {
if err := waitIPv6LinkReady(logger, d.NetIf); err != nil {
logger.Printf("failed waiting for IPv6 readiness: %s", err)

return err
}

cli, err := nclient6.New(d.NetIf.Name)
if err != nil {
log.Printf("failed to create dhcp6 client: %s", err)
logger.Printf("failed to create dhcp6 client: %s", err)

return err
}
Expand All @@ -139,19 +139,19 @@ func (d *DHCP6) discover(ctx context.Context) error {
reply, err := cli.RapidSolicit(ctx)
if err != nil {
// TODO: Make this a well defined error so we can make it not fatal
log.Printf("failed dhcp6 request for %q: %v", d.NetIf.Name, err)
logger.Printf("failed dhcp6 request for %q: %v", d.NetIf.Name, err)

return err
}

log.Printf("DHCP6 REPLY on %q: %s", d.NetIf.Name, collapseSummary(reply.Summary()))
logger.Printf("DHCP6 REPLY on %q: %s", d.NetIf.Name, collapseSummary(reply.Summary()))

d.Reply = reply

return nil
}

func waitIPv6LinkReady(iface *net.Interface) error {
func waitIPv6LinkReady(logger *log.Logger, iface *net.Interface) error {
conn, err := rtnetlink.Dial(nil)
if err != nil {
return err
Expand All @@ -160,7 +160,7 @@ func waitIPv6LinkReady(iface *net.Interface) error {
defer conn.Close() //nolint:errcheck

return retry.Constant(30*time.Second, retry.WithUnits(100*time.Millisecond)).Retry(func() error {
ready, err := isIPv6LinkReady(iface, conn)
ready, err := isIPv6LinkReady(logger, iface, conn)
if err != nil {
return retry.UnexpectedError(err)
}
Expand All @@ -175,7 +175,7 @@ func waitIPv6LinkReady(iface *net.Interface) error {

// isIPv6LinkReady returns true if the interface has a link-local address
// which is not tentative.
func isIPv6LinkReady(iface *net.Interface, conn *rtnetlink.Conn) (bool, error) {
func isIPv6LinkReady(logger *log.Logger, iface *net.Interface, conn *rtnetlink.Conn) (bool, error) {
addrs, err := conn.Address.List()
if err != nil {
return false, err
Expand All @@ -192,7 +192,7 @@ func isIPv6LinkReady(iface *net.Interface, conn *rtnetlink.Conn) (bool, error) {

if addr.Attributes.Address.IsLinkLocalUnicast() && (addr.Flags&unix.IFA_F_TENTATIVE == 0) {
if addr.Flags&unix.IFA_F_DADFAILED != 0 {
log.Printf("DADFAILED for %v, continuing anyhow", addr.Attributes.Address)
logger.Printf("DADFAILED for %v, continuing anyhow", addr.Attributes.Address)
}

return true, nil
Expand Down
3 changes: 2 additions & 1 deletion internal/app/networkd/pkg/address/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package address

import (
"context"
"log"
"net"
"time"

Expand All @@ -28,7 +29,7 @@ type Static struct {

// Discover doesnt do anything in the static configuration since all
// the necessary configuration data is supplied via config.
func (s *Static) Discover(ctx context.Context, link *net.Interface) error {
func (s *Static) Discover(ctx context.Context, logger *log.Logger, link *net.Interface) error {
s.NetIf = link

return nil
Expand Down
14 changes: 7 additions & 7 deletions internal/app/networkd/pkg/networkd/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
// we need to.
//
//nolint:gocyclo
func filterInterfaces(interfaces []net.Interface) (filtered []net.Interface, err error) {
func filterInterfaces(logger *log.Logger, interfaces []net.Interface) (filtered []net.Interface, err error) {
var conn *rtnetlink.Conn

for _, iface := range interfaces {
Expand Down Expand Up @@ -52,15 +52,15 @@ func filterInterfaces(interfaces []net.Interface) (filtered []net.Interface, err
for _, iface := range filtered {
link, err := conn.Link.Get(uint32(iface.Index))
if err != nil {
log.Printf("error getting link %q", iface.Name)
logger.Printf("error getting link %q", iface.Name)

continue
}

if link.Flags&unix.IFF_UP == unix.IFF_UP && !(link.Flags&unix.IFF_RUNNING == unix.IFF_RUNNING) {
log.Printf("no carrier for link %q", iface.Name)
logger.Printf("no carrier for link %q", iface.Name)
} else {
log.Printf("link %q has carrier signal", iface.Name)
logger.Printf("link %q has carrier signal", iface.Name)
filtered[n] = iface
n++
}
Expand All @@ -72,7 +72,7 @@ func filterInterfaces(interfaces []net.Interface) (filtered []net.Interface, err
}

// writeResolvConf generates a /etc/resolv.conf with the specified nameservers.
func writeResolvConf(resolvers []string) (err error) {
func writeResolvConf(logger *log.Logger, resolvers []string) (err error) {
var resolvconf strings.Builder

for idx, resolver := range resolvers {
Expand All @@ -82,7 +82,7 @@ func writeResolvConf(resolvers []string) (err error) {
}

if _, err = resolvconf.WriteString(fmt.Sprintf("nameserver %s\n", resolver)); err != nil {
log.Println("failed to add some resolver to resolvconf:", resolver)
logger.Println("failed to add some resolver to resolvconf:", resolver)

return err
}
Expand All @@ -96,7 +96,7 @@ func writeResolvConf(resolvers []string) (err error) {
}
}

log.Println("writing resolvconf")
logger.Println("writing resolvconf")

return ioutil.WriteFile("/etc/resolv.conf", []byte(resolvconf.String()), 0o644)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/app/networkd/pkg/networkd/netconf.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
// buildOptions translates the supplied config to nic.Option used for
// configuring the interface.
//nolint:gocyclo,cyclop
func buildOptions(device config.Device, hostname string) (name string, opts []nic.Option, err error) {
func buildOptions(logger *log.Logger, device config.Device, hostname string) (name string, opts []nic.Option, err error) {
opts = append(opts, nic.WithName(device.Interface()))

if device.Ignore() || procfs.ProcCmdline().Get(constants.KernelParamNetworkInterfaceIgnore).Contains(device.Interface()) {
Expand Down Expand Up @@ -59,7 +59,7 @@ func buildOptions(device config.Device, hostname string) (name string, opts []ni
default:
// Allow master interface without any addressing if VLANs exist
if len(device.Vlans()) > 0 {
log.Printf("no addressing for master device %s", device.Interface())
logger.Printf("no addressing for master device %s", device.Interface())

opts = append(opts, nic.WithNoAddressing())
} else {
Expand Down
4 changes: 3 additions & 1 deletion internal/app/networkd/pkg/networkd/netconf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
package networkd

import (
"log"
"net"
"os"
"testing"

"github.com/stretchr/testify/suite"
Expand All @@ -28,7 +30,7 @@ func TestNetconfSuite(t *testing.T) {

func (suite *NetconfSuite) TestBaseNetconf() {
for _, device := range sampleConfig() {
_, opts, err := buildOptions(device, "")
_, opts, err := buildOptions(log.New(os.Stderr, "", log.LstdFlags), device, "")
suite.Require().NoError(err)

_, err = nic.New(opts...)
Expand Down
Loading

0 comments on commit 4aae924

Please sign in to comment.