Debian Codegraph @

pkg/testutils/dns.go

raw symbols SCIP
1 // Copyright 2019 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package testutils
16
17 import (
18 "fmt"
19 "os"
20 "strings"
21
22 "github.com/containernetworking/cni/pkg/types"
23 )
24
25 // TmpResolvConf will create a temporary file and write the provided DNS settings to
26 // it in the resolv.conf format. It returns the path of the created temporary file or
27 // an error if any occurs while creating/writing the file. It is the caller's
28 // responsibility to remove the file.
29 func TmpResolvConf(dnsConf types.DNS) (string, error) {
30 f, err := os.CreateTemp("", "cni_test_resolv.conf")
31 if err != nil {
32 return "", fmt.Errorf("failed to get temp file for CNI test resolv.conf: %v", err)
33 }
34 defer f.Close()
35
36 path := f.Name()
37 defer func() {
38 if err != nil {
39 os.RemoveAll(path)
40 }
41 }()
42
43 // see "man 5 resolv.conf" for the format of resolv.conf
44 var resolvConfLines []string
45 for _, nameserver := range dnsConf.Nameservers {
46 resolvConfLines = append(resolvConfLines, fmt.Sprintf("nameserver %s", nameserver))
47 }
48 resolvConfLines = append(resolvConfLines, fmt.Sprintf("domain %s", dnsConf.Domain))
49 resolvConfLines = append(resolvConfLines, fmt.Sprintf("search %s", strings.Join(dnsConf.Search, " ")))
50 resolvConfLines = append(resolvConfLines, fmt.Sprintf("options %s", strings.Join(dnsConf.Options, " ")))
51
52 resolvConf := strings.Join(resolvConfLines, "\n")
53 _, err = f.Write([]byte(resolvConf))
54 if err != nil {
55 return "", fmt.Errorf("failed to write temp resolv.conf for CNI test: %v", err)
56 }
57
58 return path, err
59 }