summaryrefslogtreecommitdiff
path: root/plugins/meta/dnsname/main.go
blob: 114b16b6bdeee8a2628ed155564abf9ae20bfd63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright 2019 dnsname authors
// Copyright 2017 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This is a post-setup plugin that establishes port forwarding - using iptables,
// from the host's network interface(s) to a pod's network interface.
//
// It is intended to be used as a chained CNI plugin, and determines the container
// IP from the previous result. If the result includes an IPv6 address, it will
// also be configured. (IPTables will not forward cross-family).
//
// This has one notable limitation: it does not perform any kind of reservation
// of the actual host port. If there is a service on the host, it will have all
// its traffic captured by the container. If another container also claims a given
// port, it will capture the traffic - it is last-write-wins.
package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/containernetworking/cni/pkg/skel"
	"github.com/containernetworking/cni/pkg/types"
	"github.com/containernetworking/cni/pkg/types/current"
	"github.com/containernetworking/cni/pkg/version"
	bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
	"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 {
		return err
	}
	defer func() {
		if err := lock.release(); err != nil {
			logrus.Errorf("unable to release lock for %q: %v", dnsNameConf.AddOnHostsFile, err)
		}
	}()
	if err := checkForDNSMasqConfFile(dnsNameConf); err != nil {
		return err
	}
	if err := appendToFile(dnsNameConf.AddOnHostsFile, podname, ips); err != nil {
		return err
	}
	// Now we need to HUP
	if err := dnsNameConf.hup(); err != nil {
		return err
	}
	nameservers, err := getInterfaceAddresses(dnsNameConf)
	if err != nil {
		return err
	}
	// keep anything that was passed in already
	nameservers = append(nameservers, result.DNS.Nameservers...)
	result.DNS.Nameservers = nameservers
	// Pass through the previous result
	return types.PrintResult(result, netConf.CNIVersion)
}

func cmdDel(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")
	} else if result == nil {
		return nil
	}
	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 {
		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)
		}
	}()
	shouldHUP, err := removeFromFile(filepath.Join(domainBaseDir, hostsFileName), podname)
	if err != nil {
		return err
	}
	if !shouldHUP {
		// if there are no hosts, we should just stop the dnsmasq instance to not take
		// system resources
		return dnsNameConf.stop()
	}
	// Now we need to HUP
	return dnsNameConf.hup()
}

func main() {
	skel.PluginMain(cmdAdd, cmdCheck, cmdDel, version.All, bv.BuildString("dnsname"))
}

func cmdCheck(args *skel.CmdArgs) error {
	var (
		conffiles []string
	)
	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")
	}

	// Ensure we have previous result.
	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 {
		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)
		}
	}()

	pid, err := dnsNameConf.getProcess()
	if err != nil {
		return 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 := ioutil.ReadDir(dnsNameConfPath)
	if err != nil {
		return err
	}
	for _, f := range files {
		conffiles = append(conffiles, 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"`
}

// parseConfig parses the supplied configuration (and prevResult) from stdin.
func parseConfig(stdin []byte, args string) (*DNSNameConf, *current.Result, string, error) {
	conf := DNSNameConf{}
	if err := json.Unmarshal(stdin, &conf); err != nil {
		return nil, nil, "", errors.Wrap(err, "failed to parse network configuration")
	}
	// Parse previous result.
	var result *current.Result
	if conf.RawPrevResult != nil {
		var err error
		if err = version.ParsePrevResult(&conf.NetConf); err != nil {
			return nil, nil, "", errors.Wrap(err, "could not parse prevResult")
		}
		result, err = current.NewResultFromResult(conf.PrevResult)
		if err != nil {
			return nil, nil, "", errors.Wrap(err, "could not convert result to current version")
		}
	}
	e := podname{}
	if err := types.LoadArgs(args, &e); err != nil {
		return nil, nil, "", err
	}
	return &conf, result, string(e.K8S_POD_NAME), nil
}

func findDNSMasq() error {
	_, err := exec.LookPath("dnsmasq")
	return err
}