Skip to content
48 changes: 2 additions & 46 deletions cmd/dnsname/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,10 @@ package main

import (
"errors"
"os"
"path/filepath"

"github.com/containernetworking/cni/pkg/types"
)

const (
// confFileName is the name of the dns masq conf file
confFileName = "dnsmasq.conf"
// hostsFileName is the name of the addnhosts file
hostsFileName = "addnhosts"
// pidFileName is the file where the dnsmasq file is stored
pidFileName = "pidfile"
)

const dnsMasqTemplate = `## WARNING: THIS IS AN AUTOGENERATED FILE
## AND SHOULD NOT BE EDITED MANUALLY AS IT
## LIKELY TO AUTOMATICALLY BE REPLACED.
strict-order
local=/{{.Domain}}/
domain={{.Domain}}
expand-hosts
pid-file={{.PidFile}}
except-interface=lo
bind-dynamic
no-hosts
interface={{.NetworkInterface}}
addn-hosts={{.AddOnHostsFile}}
resolv-file=/etc/resolv.conf.upstream
`

var (
// ErrBinaryNotFound means that the dnsmasq binary was not found
ErrBinaryNotFound = errors.New("unable to locate dnsmasq in path")
Expand All @@ -44,26 +17,9 @@ var (
type DNSNameConf struct {
types.NetConf
DomainName string `json:"domainName"`
Hosts string `json:"hosts"`
Pidfile string `json:"pidfile"`
RuntimeConfig struct { // The capability arg
Aliases map[string][]string `json:"aliases"`
} `json:"runtimeConfig,omitempty"`
}

// dnsNameFile describes the plugin's attributes
type dnsNameFile struct {
AddOnHostsFile string
Binary string
ConfigFile string
Domain string
NetworkInterface string
PidFile string
}

// dnsNameConfPath tells where we store the conf, pid, and hosts files
func dnsNameConfPath() string {
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
if xdgRuntimeDir != "" {
return filepath.Join(xdgRuntimeDir, "containers/cni/dnsname")
}
return "/run/containers/cni/dnsname"
}
75 changes: 0 additions & 75 deletions cmd/dnsname/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,89 +2,14 @@ package main

import (
"bufio"
"bytes"
"fmt"
"net"
"os"
"strings"
"text/template"

"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk"
"github.com/coreos/go-iptables/iptables"
"github.com/sirupsen/logrus"
)

// dnsNameLock embeds the CNI disk lock so we can hang methods from it
type dnsNameLock struct {
lock *disk.FileLock
}

// release unlocks and closes the disk lock.
func (m *dnsNameLock) release() error {
if err := m.lock.Unlock(); err != nil {
return err
}
return m.lock.Close()
}

// acquire locks the disk lock.
func (m *dnsNameLock) acquire() error {
return m.lock.Lock()
}

// getLock returns a dnsNameLock synchronizing the configuration directory for
// the domain.
func getLock(path string) (*dnsNameLock, error) {
l, err := disk.NewFileLock(path)
if err != nil {
return nil, err
}
return &dnsNameLock{l}, nil
}

// checkFromDNSMasqConfFile ensures that the dnsmasq conf file for
// the network interface exists or it creates it
func checkForDNSMasqConfFile(conf dnsNameFile) error {
if _, err := os.Stat(conf.ConfigFile); err == nil {
// the file already exists, we can proceed
return err
}
newConfig, err := generateDNSMasqConfig(conf)
if err != nil {
return err
}
ip, err := iptables.New()
if err != nil {
return err
}
args := []string{"-i", conf.NetworkInterface, "-p", "udp", "-m", "udp", "--dport", "53", "-j", "ACCEPT"}
exists, err := ip.Exists("filter", "INPUT", args...)
if err != nil {
return err
}
if !exists {
if err := ip.Insert("filter", "INPUT", 1, args...); err != nil {
return err
}
}
// Generate the template and compile it.
return os.WriteFile(conf.ConfigFile, newConfig, 0600)
}

// generateDNSMasqConfig fills out the configuration file template for the dnsmasq service
func generateDNSMasqConfig(config dnsNameFile) ([]byte, error) {
var buf bytes.Buffer
templ, err := template.New("dnsmasq-conf-file").Parse(dnsMasqTemplate)
if err != nil {
return nil, err
}
if err := templ.Execute(&buf, config); err != nil {
return nil, err
}
buf.WriteByte('\n')
return buf.Bytes(), nil
}

// appendToFile appends a new entry to the dnsmasqs hosts file
func appendToFile(path, podname string, aliases []string, ips []*net.IPNet) error {
f, err := openFile(path)
Expand Down
138 changes: 30 additions & 108 deletions cmd/dnsname/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,69 +28,51 @@ package main

import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"fmt"

"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version"
"github.com/gofrs/flock"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)

func cmdAdd(args *skel.CmdArgs) error {
if err := findDNSMasq(); err != nil {
return ErrBinaryNotFound
}
netConf, result, podname, err := parseConfig(args.StdinData, args.Args)
if err != nil {
return errors.Wrap(err, "failed to parse config")
}

if netConf.PrevResult == nil {
return errors.Errorf("must be called as chained plugin")
}

ips, err := getIPs(result)
if err != nil {
return err
}
dnsNameConf, err := newDNSMasqFile(netConf.DomainName, result.Interfaces[0].Name, netConf.Name)
if err != nil {
return err
}
domainBaseDir := filepath.Dir(dnsNameConf.PidFile)
// Check if the configuration file directory exists, else make it
if _, err := os.Stat(domainBaseDir); os.IsNotExist(err) {
if makeDirErr := os.MkdirAll(domainBaseDir, 0700); makeDirErr != nil {
return makeDirErr
}
}
// we use the configuration directory for our locking mechanism but read/write and hup
lock, err := getLock(domainBaseDir)
if err != nil {
return err
}
if err := lock.acquire(); err != nil {

lock := flock.New(netConf.Hosts)
if err := lock.Lock(); err != nil {
return err
}
defer func() {
if err := lock.release(); err != nil {
logrus.Errorf("unable to release lock for %q: %v", dnsNameConf.AddOnHostsFile, err)
if err := lock.Unlock(); err != nil {
logrus.Errorf("unable to release lock for %q: %v", netConf.Hosts, err)
}
}()
if err := checkForDNSMasqConfFile(dnsNameConf); err != nil {
return err
}

aliases := netConf.RuntimeConfig.Aliases[netConf.Name]
if err := appendToFile(dnsNameConf.AddOnHostsFile, podname, aliases, ips); err != nil {
if err := appendToFile(netConf.Hosts, podname, aliases, ips); err != nil {
return err
}
// Now we need to HUP
if err := dnsNameConf.hup(); err != nil {
if err := hup(netConf.Pidfile); err != nil {
return err
}
nameservers, err := getInterfaceAddresses(dnsNameConf)
nameservers, err := getInterfaceAddresses(result.Interfaces[0].Name)
if err != nil {
return err
}
Expand All @@ -106,44 +88,31 @@ func cmdAdd(args *skel.CmdArgs) error {
// Do not return an error, otherwise cni will stop
// and not invoke the following plugins del command.
func cmdDel(args *skel.CmdArgs) error {
if err := findDNSMasq(); err != nil {
logrus.Error(ErrBinaryNotFound)
return nil
}
netConf, result, podname, err := parseConfig(args.StdinData, args.Args)
if err != nil {
logrus.Error(errors.Wrap(err, "failed to parse config"))
return nil
} else if result == nil {
return nil
}
dnsNameConf, err := newDNSMasqFile(netConf.DomainName, result.Interfaces[0].Name, netConf.Name)
if err != nil {
logrus.Error(err)
return nil
}
domainBaseDir := filepath.Dir(dnsNameConf.PidFile)
lock, err := getLock(domainBaseDir)
if err != nil {
logrus.Error(err)
return nil
}
if err := lock.acquire(); err != nil {
logrus.Error(err)
return nil

lock := flock.New(netConf.Hosts)
if err := lock.Lock(); err != nil {
return err
}
defer func() {
// if the lock isn't given up by another process
if err := lock.release(); err != nil {
logrus.Errorf("unable to release lock for %q: %v", domainBaseDir, err)
if err := lock.Unlock(); err != nil {
logrus.Errorf("unable to release lock for %q: %v", netConf.Hosts, err)
}
}()
if err := removeFromFile(filepath.Join(domainBaseDir, hostsFileName), podname); err != nil {

if err := removeFromFile(netConf.Hosts, podname); err != nil {
logrus.Error(err)
return nil
}

// Now we need to HUP
err = dnsNameConf.hup()
err = hup(netConf.Pidfile)
if err != nil {
logrus.Error(err)
}
Expand All @@ -155,9 +124,6 @@ func main() {
}

func cmdCheck(args *skel.CmdArgs) error {
if err := findDNSMasq(); err != nil {
return ErrBinaryNotFound
}
netConf, result, _, err := parseConfig(args.StdinData, args.Args)
if err != nil {
return errors.Wrap(err, "failed to parse config")
Expand All @@ -167,63 +133,24 @@ func cmdCheck(args *skel.CmdArgs) error {
if result == nil {
return errors.Errorf("Required prevResult missing")
}
dnsNameConf, err := newDNSMasqFile(netConf.DomainName, result.Interfaces[0].Name, netConf.Name)
if err != nil {
return err
}
domainBaseDir := filepath.Dir(dnsNameConf.PidFile)
lock, err := getLock(domainBaseDir)
if err != nil {
return err
}
if err := lock.acquire(); err != nil {

lock := flock.New(netConf.Hosts)
if err := lock.Lock(); err != nil {
return err
}
defer func() {
// if the lock isn't given up by another process
if err := lock.release(); err != nil {
logrus.Errorf("unable to release lock for %q: %v", domainBaseDir, err)
if err := lock.Unlock(); err != nil {
logrus.Errorf("unable to release lock for %q: %v", netConf.Hosts, err)
}
}()

pid, err := dnsNameConf.getProcess()
if err != nil {
return err
if _, err := getProcess(netConf.Pidfile); err != nil {
return fmt.Errorf("dnsmasq instance not running: %w", err)
}

// Ensure the dnsmasq instance is running
if !isRunning(pid) {
return errors.Errorf("dnsmasq instance not running")
}
// Above will make sure the pidfile exists
files, err := os.ReadDir(dnsNameConfPath())
if err != nil {
return err
}
conffiles := make([]string, len(files))
for i, f := range files {
conffiles[i] = f.Name()
}
if !stringInSlice("addnhosts", conffiles) {
return errors.Errorf("addnhost file missing from configuration")
}
if !stringInSlice("dnsmasq.conf", conffiles) {
return errors.Errorf("dnsmasq.conf file missing from configuration")
}
return nil
}

// stringInSlice is simple util to check for the presence of a string
// in a string slice
func stringInSlice(s string, slice []string) bool {
for _, sl := range slice {
if s == sl {
return true
}
}
return false
}

type podname struct {
types.CommonArgs
K8S_POD_NAME types.UnmarshallableString `json:"podname,omitempty"` //nolint:revive,stylecheck
Expand Down Expand Up @@ -254,8 +181,3 @@ func parseConfig(stdin []byte, args string) (*DNSNameConf, *current.Result, stri
}
return &conf, result, string(e.K8S_POD_NAME), nil
}

func findDNSMasq() error {
_, err := exec.LookPath("dnsmasq")
return err
}
4 changes: 2 additions & 2 deletions cmd/dnsname/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ func isInterfaceIndexSandox(idx int, r *current.Result) bool {

// getInterfaceAddresses gets all globalunicast IP addresses for a given
// interface
func getInterfaceAddresses(nameConf dnsNameFile) ([]string, error) {
func getInterfaceAddresses(iface string) ([]string, error) {
var nameservers []string
nic, err := net.InterfaceByName(nameConf.NetworkInterface)
nic, err := net.InterfaceByName(iface)
if err != nil {
return nil, err
}
Expand Down
Loading