github.com/maxgio92/test-infra@v0.1.0/kubetest/boskos/storage/storage.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 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 storage 18 19 import ( 20 "sync" 21 22 "fmt" 23 24 "github.com/maxgio92/test-infra/kubetest/boskos/common" 25 ) 26 27 // PersistenceLayer defines a simple interface to persists Boskos Information 28 type PersistenceLayer interface { 29 Add(r common.Resource) error 30 Delete(name string) error 31 Update(r common.Resource) (common.Resource, error) 32 Get(name string) (common.Resource, error) 33 List() ([]common.Resource, error) 34 } 35 36 type inMemoryStore struct { 37 resources map[string]common.Resource 38 lock sync.RWMutex 39 } 40 41 // NewMemoryStorage creates an in memory persistence layer 42 func NewMemoryStorage() PersistenceLayer { 43 return &inMemoryStore{ 44 resources: map[string]common.Resource{}, 45 } 46 } 47 48 func (im *inMemoryStore) Add(r common.Resource) error { 49 im.lock.Lock() 50 defer im.lock.Unlock() 51 _, ok := im.resources[r.Name] 52 if ok { 53 return fmt.Errorf("resource %s already exists", r.Name) 54 } 55 im.resources[r.Name] = r 56 return nil 57 } 58 59 func (im *inMemoryStore) Delete(name string) error { 60 im.lock.Lock() 61 defer im.lock.Unlock() 62 _, ok := im.resources[name] 63 if !ok { 64 return fmt.Errorf("cannot find item %s", name) 65 } 66 delete(im.resources, name) 67 return nil 68 } 69 70 func (im *inMemoryStore) Update(r common.Resource) (common.Resource, error) { 71 im.lock.Lock() 72 defer im.lock.Unlock() 73 _, ok := im.resources[r.Name] 74 if !ok { 75 return common.Resource{}, fmt.Errorf("cannot find item %s", r.Name) 76 } 77 im.resources[r.Name] = r 78 return r, nil 79 } 80 81 func (im *inMemoryStore) Get(name string) (common.Resource, error) { 82 im.lock.RLock() 83 defer im.lock.RUnlock() 84 r, ok := im.resources[name] 85 if !ok { 86 return common.Resource{}, fmt.Errorf("cannot find item %s", name) 87 } 88 return r, nil 89 } 90 91 func (im *inMemoryStore) List() ([]common.Resource, error) { 92 im.lock.RLock() 93 defer im.lock.RUnlock() 94 var resources []common.Resource 95 for _, r := range im.resources { 96 resources = append(resources, r) 97 } 98 return resources, nil 99 }