github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/stream/utils.go (about) 1 /* 2 Copyright 2017 Mirantis 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package stream 18 19 import ( 20 "fmt" 21 "io" 22 "io/ioutil" 23 "path/filepath" 24 "strings" 25 ) 26 27 // DetachError is special error which returned in case of container detach. 28 type DetachError struct{} 29 30 func (DetachError) Error() string { 31 return "detached from container" 32 } 33 34 func getProcessEnvironment(pid int32) (map[string]string, error) { 35 envFile := filepath.Join("/proc", fmt.Sprint(pid), "environ") 36 all, err := ioutil.ReadFile(envFile) 37 if err != nil { 38 return nil, err 39 } 40 env := map[string]string{} 41 42 for _, v := range strings.Split(string(all), "\000") { 43 s := strings.SplitN(v, "=", 2) 44 key := s[0] 45 value := "" 46 if len(s) == 2 { 47 value = s[1] 48 } 49 env[key] = value 50 } 51 return env, nil 52 } 53 54 // CopyDetachable is similar to io.Copy but support a detach key sequence to break out. 55 // based on https://github.com/kubernetes-incubator/cri-o/blob/master/utils/utils.go#L90 56 func CopyDetachable(dst io.Writer, src io.Reader, keys []byte) (written int64, err error) { 57 if len(keys) == 0 { 58 // Default key : ^] 59 keys = []byte{29} 60 } 61 62 buf := make([]byte, 32*1024) 63 for { 64 nr, er := src.Read(buf) 65 if nr > 0 { 66 preservBuf := []byte{} 67 for i, key := range keys { 68 preservBuf = append(preservBuf, buf[0:nr]...) 69 if nr != 1 || buf[0] != key { 70 break 71 } 72 if i == len(keys)-1 { 73 return 0, nil 74 } 75 nr, er = src.Read(buf) 76 } 77 var nw int 78 var ew error 79 if len(preservBuf) > 0 { 80 nw, ew = dst.Write(preservBuf) 81 nr = len(preservBuf) 82 } else { 83 nw, ew = dst.Write(buf[0:nr]) 84 } 85 if nw > 0 { 86 written += int64(nw) 87 } 88 if ew != nil { 89 err = ew 90 break 91 } 92 if nr != nw { 93 err = io.ErrShortWrite 94 break 95 } 96 } 97 if er != nil { 98 if er != io.EOF { 99 err = er 100 } 101 break 102 } 103 } 104 return written, err 105 }