gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/runsc/cmd/fd_mapping.go (about) 1 // Copyright 2023 The gVisor 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 cmd 16 17 import ( 18 "fmt" 19 "strconv" 20 "strings" 21 22 "gvisor.dev/gvisor/runsc/boot" 23 ) 24 25 // fdMappings can be used with flags that appear multiple times. 26 type fdMappings []boot.FDMapping 27 28 // String implements flag.Value. 29 func (i *fdMappings) String() string { 30 var mappings []string 31 for _, m := range *i { 32 mappings = append(mappings, fmt.Sprintf("%v:%v", m.Host, m.Guest)) 33 } 34 return strings.Join(mappings, ",") 35 } 36 37 // Get implements flag.Value. 38 func (i *fdMappings) Get() any { 39 return i 40 } 41 42 // GetArray returns an array of mappings. 43 func (i *fdMappings) GetArray() []boot.FDMapping { 44 return *i 45 } 46 47 // Set implements flag.Value and appends a mapping from the command line to the 48 // mappings array. Set(String()) should be idempotent. 49 func (i *fdMappings) Set(s string) error { 50 for _, m := range strings.Split(s, ",") { 51 split := strings.Split(m, ":") 52 if len(split) != 2 { 53 // Split returns a slice of length 1 if its first argument does not 54 // contain the separator. An additional length check is not necessary. 55 // In case no separator is used and the argument is a valid integer, we 56 // assume that host FD and guest FD should be identical. 57 fd, err := strconv.Atoi(split[0]) 58 if err != nil { 59 return fmt.Errorf("invalid flag value: must be an integer or a mapping of format M:N") 60 } 61 *i = append(*i, boot.FDMapping{ 62 Host: fd, 63 Guest: fd, 64 }) 65 return nil 66 } 67 68 fdHost, err := strconv.Atoi(split[0]) 69 if err != nil { 70 return fmt.Errorf("invalid flag host value: %v", err) 71 } 72 if fdHost < 0 { 73 return fmt.Errorf("flag host value must be >= 0: %d", fdHost) 74 } 75 76 fdGuest, err := strconv.Atoi(split[1]) 77 if err != nil { 78 return fmt.Errorf("invalid flag guest value: %v", err) 79 } 80 if fdGuest < 0 { 81 return fmt.Errorf("flag guest value must be >= 0: %d", fdGuest) 82 } 83 84 *i = append(*i, boot.FDMapping{ 85 Host: fdHost, 86 Guest: fdGuest, 87 }) 88 } 89 return nil 90 }