generated from kyma-project/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 15
/
provider.go
73 lines (65 loc) · 2.03 KB
/
provider.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
63
64
65
66
67
68
69
70
71
72
73
package client
import (
"context"
"google.golang.org/api/cloudresourcemanager/v1"
"google.golang.org/api/option"
"google.golang.org/api/transport"
"net/http"
"sync"
)
type ClientProvider[T any] func(ctx context.Context, httpClient *http.Client) (T, error)
func NewCachedClientProvider[T comparable](p ClientProvider[T]) ClientProvider[T] {
var result T
var nilT T
var m sync.Mutex
return func(ctx context.Context, httpClient *http.Client) (T, error) {
m.Lock()
defer m.Unlock()
var err error
if result == nilT {
result, err = p(ctx, gcpClient)
}
return result, err
}
}
var gcpClient *http.Client
var clientMutex sync.Mutex
func newCachedGcpClient(ctx context.Context, saJsonKeyPath string) (*http.Client, error) {
clientMutex.Lock()
defer clientMutex.Unlock()
if gcpClient == nil {
client, _, err := transport.NewHTTPClient(ctx, option.WithCredentialsFile(saJsonKeyPath), option.WithScopes("https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform"))
if err != nil {
return nil, err
}
gcpClient = client
}
return gcpClient, nil
}
func GetCachedGcpClient(ctx context.Context, saJsonKeyPath string) (*http.Client, error) {
if gcpClient == nil {
return newCachedGcpClient(ctx, saJsonKeyPath)
}
return gcpClient, nil
}
var projectNumbers map[string]int64 = make(map[string]int64)
var projectNumbersMutex sync.Mutex
// GetCachedProjectNumber get project number from cloud resources manager for a given project id
func GetCachedProjectNumber(ctx context.Context, projectId string, httpClient *http.Client) (int64, error) {
projectNumbersMutex.Lock()
defer projectNumbersMutex.Unlock()
projectNumber, ok := projectNumbers[projectId]
if !ok {
crmService, err := cloudresourcemanager.NewService(ctx, option.WithHTTPClient(httpClient))
if err != nil {
return 0, err
}
project, err := crmService.Projects.Get(projectId).Do()
if err != nil {
return 0, err
}
projectNumbers[projectId] = project.ProjectNumber
projectNumber = project.ProjectNumber
}
return projectNumber, nil
}