github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/pkg/pod/uuid.go (about) 1 // Copyright 2015 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 pod 16 17 import ( 18 "bytes" 19 "errors" 20 "fmt" 21 "io/ioutil" 22 "strings" 23 24 "github.com/appc/spec/schema/types" 25 "github.com/hashicorp/errwrap" 26 ) 27 28 // matchUUID attempts to match the uuid specified as uuid against all pods present. 29 // An array of matches is returned, which may be empty when nothing matches. 30 func matchUUID(dataDir, uuid string) ([]string, error) { 31 if uuid == "" { 32 return nil, types.ErrNoEmptyUUID 33 } 34 35 ls, err := listPods(dataDir, IncludeMostDirs) 36 if err != nil { 37 return nil, err 38 } 39 40 var matches []string 41 for _, p := range ls { 42 if strings.HasPrefix(p, uuid) { 43 matches = append(matches, p) 44 } 45 } 46 47 return matches, nil 48 } 49 50 // resolveUUID attempts to resolve the uuid specified as uuid against all pods present. 51 // An unambiguously matched uuid or nil is returned. 52 func resolveUUID(dataDir, uuid string) (*types.UUID, error) { 53 uuid = strings.ToLower(uuid) 54 m, err := matchUUID(dataDir, uuid) 55 if err != nil { 56 return nil, err 57 } 58 59 if len(m) == 0 { 60 return nil, fmt.Errorf("no matches found for %q", uuid) 61 } 62 63 if len(m) > 1 { 64 return nil, fmt.Errorf("ambiguous uuid, %d matches", len(m)) 65 } 66 67 u, err := types.NewUUID(m[0]) 68 if err != nil { 69 return nil, errwrap.Wrap(errors.New("invalid UUID"), err) 70 } 71 72 return u, nil 73 } 74 75 // ReadUUIDFromFile reads the uuid string from the given path. 76 func ReadUUIDFromFile(path string) (string, error) { 77 uuid, err := ioutil.ReadFile(path) 78 if err != nil { 79 return "", err 80 } 81 return string(bytes.TrimSpace(uuid)), nil 82 } 83 84 // WriteUUIDToFile writes the uuid string to the given path. 85 func WriteUUIDToFile(uuid *types.UUID, path string) error { 86 return ioutil.WriteFile(path, []byte(uuid.String()), 0644) 87 }