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