github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/stage1/init/common/dns_config.go (about) 1 // Copyright 2016 The rkt 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 common 16 17 import ( 18 "bufio" 19 "fmt" 20 "os" 21 "path/filepath" 22 "strings" 23 24 _common "github.com/rkt/rkt/common" 25 "github.com/rkt/rkt/pkg/fs" 26 ) 27 28 /* 29 Bind-mount the hosts /etc/resolv.conf in to the stage1's /etc/rkt-resolv.conf. 30 That file will then be bind-mounted in to the stage2 by perpare-app.c 31 */ 32 func UseHostResolv(mnt fs.MountUnmounter, podRoot string) error { 33 return BindMount( 34 mnt, 35 "/etc/resolv.conf", 36 filepath.Join(_common.Stage1RootfsPath(podRoot), "etc/rkt-resolv.conf"), 37 true) 38 } 39 40 /* 41 Bind-mount the hosts /etc/hosts in to the stage1's /etc/rkt-hosts 42 That file will then be bind-mounted in to the stage2 by perpare-app.c 43 */ 44 func UseHostHosts(mnt fs.MountUnmounter, podRoot string) error { 45 return BindMount( 46 mnt, 47 "/etc/hosts", 48 filepath.Join(_common.Stage1RootfsPath(podRoot), "etc/rkt-hosts"), 49 true) 50 } 51 52 // AddHostsEntry adds an entry to an *existing* hosts file, appending 53 // to the existing IP if needed 54 func AddHostsEntry(filename string, ip string, hostname string) error { 55 fp, err := os.OpenFile(filename, os.O_RDWR, 0644) 56 if err != nil { 57 return err 58 } 59 defer fp.Close() 60 61 out := "" 62 found := false 63 64 scanner := bufio.NewScanner(fp) 65 for scanner.Scan() { 66 line := scanner.Text() 67 words := strings.Fields(line) 68 if !found && len(words) > 0 && words[0] == ip { 69 found = true 70 out += fmt.Sprintf("%s %s\n", line, hostname) 71 } else { 72 out += line 73 out += "\n" 74 } 75 } 76 if err := scanner.Err(); err != nil { 77 return err 78 } 79 80 // If that IP was not found, add a new line 81 if !found { 82 out += fmt.Sprintf("%s\t%s\n", ip, hostname) 83 } 84 85 // Seek to the beginning, truncate, and write again 86 if _, err := fp.Seek(0, 0); err != nil { 87 return err 88 } 89 if err := fp.Truncate(0); err != nil { 90 return err 91 } 92 if _, err := fp.Write([]byte(out)); err != nil { 93 return err 94 } 95 96 return nil 97 }