forked from rebuy-de/aws-nuke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregion.go
62 lines (52 loc) · 1.51 KB
/
region.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cmd
import (
"fmt"
"sync"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/rebuy-de/aws-nuke/pkg/awsutil"
)
// SessionFactory support for custom endpoints
type SessionFactory func(regionName, svcType string) (*session.Session, error)
// ResourceTypeResolver returns the service type from the resourceType
type ResourceTypeResolver func(regionName, resourceType string) string
type Region struct {
Name string
NewSession SessionFactory
ResTypeResolver ResourceTypeResolver
cache map[string]*session.Session
lock *sync.RWMutex
}
func NewRegion(name string, typeResolver ResourceTypeResolver, sessionFactory SessionFactory) *Region {
return &Region{
Name: name,
NewSession: sessionFactory,
ResTypeResolver: typeResolver,
lock: &sync.RWMutex{},
cache: make(map[string]*session.Session),
}
}
func (region *Region) Session(resourceType string) (*session.Session, error) {
svcType := region.ResTypeResolver(region.Name, resourceType)
if svcType == "" {
return nil, awsutil.ErrSkipRequest(fmt.Sprintf(
"No service available in region '%s' to handle '%s'",
region.Name, resourceType))
}
// Need to read
region.lock.RLock()
sess := region.cache[svcType]
region.lock.RUnlock()
if sess != nil {
return sess, nil
}
// Need to write:
region.lock.Lock()
sess, err := region.NewSession(region.Name, svcType)
if err != nil {
region.lock.Unlock()
return nil, err
}
region.cache[svcType] = sess
region.lock.Unlock()
return sess, nil
}