github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/context/store/tlsstore.go (about) 1 package store 2 3 import ( 4 "os" 5 "path/filepath" 6 7 "github.com/docker/docker/errdefs" 8 "github.com/docker/docker/pkg/ioutils" 9 "github.com/pkg/errors" 10 ) 11 12 const tlsDir = "tls" 13 14 type tlsStore struct { 15 root string 16 } 17 18 func (s *tlsStore) contextDir(name string) string { 19 return filepath.Join(s.root, string(contextdirOf(name))) 20 } 21 22 func (s *tlsStore) endpointDir(name, endpointName string) string { 23 return filepath.Join(s.contextDir(name), endpointName) 24 } 25 26 func (s *tlsStore) createOrUpdate(name, endpointName, filename string, data []byte) error { 27 parentOfRoot := filepath.Dir(s.root) 28 if err := os.MkdirAll(parentOfRoot, 0o755); err != nil { 29 return err 30 } 31 endpointDir := s.endpointDir(name, endpointName) 32 if err := os.MkdirAll(endpointDir, 0o700); err != nil { 33 return err 34 } 35 return ioutils.AtomicWriteFile(filepath.Join(endpointDir, filename), data, 0o600) 36 } 37 38 func (s *tlsStore) getData(name, endpointName, filename string) ([]byte, error) { 39 data, err := os.ReadFile(filepath.Join(s.endpointDir(name, endpointName), filename)) 40 if err != nil { 41 if os.IsNotExist(err) { 42 return nil, errdefs.NotFound(errors.Errorf("TLS data for %s/%s/%s does not exist", name, endpointName, filename)) 43 } 44 return nil, errors.Wrapf(err, "failed to read TLS data for endpoint %s", endpointName) 45 } 46 return data, nil 47 } 48 49 // remove deletes all TLS data for the given context. 50 func (s *tlsStore) remove(name string) error { 51 if err := os.RemoveAll(s.contextDir(name)); err != nil { 52 return errors.Wrapf(err, "failed to remove TLS data") 53 } 54 return nil 55 } 56 57 func (s *tlsStore) removeEndpoint(name, endpointName string) error { 58 if err := os.RemoveAll(s.endpointDir(name, endpointName)); err != nil { 59 return errors.Wrapf(err, "failed to remove TLS data for endpoint %s", endpointName) 60 } 61 return nil 62 } 63 64 func (s *tlsStore) listContextData(name string) (map[string]EndpointFiles, error) { 65 contextDir := s.contextDir(name) 66 epFSs, err := os.ReadDir(contextDir) 67 if err != nil { 68 if os.IsNotExist(err) { 69 return map[string]EndpointFiles{}, nil 70 } 71 return nil, errors.Wrapf(err, "failed to list TLS files for context %s", name) 72 } 73 r := make(map[string]EndpointFiles) 74 for _, epFS := range epFSs { 75 if epFS.IsDir() { 76 fss, err := os.ReadDir(filepath.Join(contextDir, epFS.Name())) 77 if os.IsNotExist(err) { 78 continue 79 } 80 if err != nil { 81 return nil, errors.Wrapf(err, "failed to list TLS files for endpoint %s", epFS.Name()) 82 } 83 var files EndpointFiles 84 for _, fs := range fss { 85 if !fs.IsDir() { 86 files = append(files, fs.Name()) 87 } 88 } 89 r[epFS.Name()] = files 90 } 91 } 92 return r, nil 93 } 94 95 // EndpointFiles is a slice of strings representing file names 96 type EndpointFiles []string