github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/drivers/shared/resolvconf/mount.go (about) 1 package resolvconf 2 3 import ( 4 "io" 5 "os" 6 "path/filepath" 7 8 dresolvconf "github.com/docker/libnetwork/resolvconf" 9 "github.com/docker/libnetwork/types" 10 "github.com/hashicorp/nomad/plugins/drivers" 11 ) 12 13 func GenerateDNSMount(taskDir string, conf *drivers.DNSConfig) (*drivers.MountConfig, error) { 14 var nSearches, nServers, nOptions int 15 path := filepath.Join(taskDir, "resolv.conf") 16 mount := &drivers.MountConfig{ 17 TaskPath: "/etc/resolv.conf", 18 HostPath: path, 19 Readonly: true, 20 PropagationMode: "private", 21 } 22 if conf != nil { 23 nServers = len(conf.Servers) 24 nSearches = len(conf.Searches) 25 nOptions = len(conf.Options) 26 } 27 28 // Use system dns if no configuration is given 29 if nServers == 0 && nSearches == 0 && nOptions == 0 { 30 if err := copySystemDNS(path); err != nil { 31 return nil, err 32 } 33 34 return mount, nil 35 } 36 37 currRC, err := dresolvconf.Get() 38 if err != nil { 39 return nil, err 40 } 41 42 var ( 43 dnsList = dresolvconf.GetNameservers(currRC.Content, types.IP) 44 dnsSearchList = dresolvconf.GetSearchDomains(currRC.Content) 45 dnsOptionsList = dresolvconf.GetOptions(currRC.Content) 46 ) 47 if nServers > 0 { 48 dnsList = conf.Servers 49 } 50 if nSearches > 0 { 51 dnsSearchList = conf.Searches 52 } 53 if nOptions > 0 { 54 dnsOptionsList = conf.Options 55 } 56 57 _, err = dresolvconf.Build(path, dnsList, dnsSearchList, dnsOptionsList) 58 if err != nil { 59 return nil, err 60 } 61 62 return mount, nil 63 } 64 65 func copySystemDNS(dest string) error { 66 in, err := os.Open(dresolvconf.Path()) 67 if err != nil { 68 return err 69 } 70 defer in.Close() 71 72 content, err := io.ReadAll(in) 73 if err != nil { 74 return err 75 } 76 77 return os.WriteFile(dest, content, 0644) 78 }