-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
64 lines (56 loc) · 2.25 KB
/
service.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
package metrics_scope_collector
import (
"context"
"fmt"
"strings"
crmbox "github.com/sinmetalcraft/gcpbox/cloudresourcemanager/v3"
)
type Service struct {
MetricsScopesService *MetricsScopesService
ResourceManagerService *crmbox.ResourceManagerService
}
func NewService(ctx context.Context, metricsScopesService *MetricsScopesService, resourceManagerService *crmbox.ResourceManagerService) (*Service, error) {
return &Service{
MetricsScopesService: metricsScopesService,
ResourceManagerService: resourceManagerService,
}, nil
}
// ImportMonitoredProjects is scopingProjectのMetricsScopeにparentResourceID配下のProjectを追加する
func (s *Service) ImportMonitoredProjects(ctx context.Context, scopingProject string, parentResourceID *crmbox.ResourceID) (int, error) {
scope, err := s.MetricsScopesService.GetMetricsScope(ctx, scopingProject)
if err != nil {
return 0, fmt.Errorf("failed MetricsScopesService.GetMetricsScope. scopingProject=%s,parentResourceID=%v : %w", scopingProject, parentResourceID, err)
}
existsMonitoredProjects := make(map[string]bool, len(scope.GetMonitoredProjects()))
for _, v := range scope.GetMonitoredProjects() {
// locations/global/metricsScopes/{ScopingProjectNumber}/projects/{MonitoredProjectNumber}
l := strings.Split(v.GetName(), "/")
if len(l) != 6 {
return 0, fmt.Errorf("invalid MonitoredProjects format. %s", v.GetName())
}
existsMonitoredProjects[l[5]] = true
}
l, err := s.ResourceManagerService.GetRelatedProject(ctx, parentResourceID)
if err != nil {
return 0, fmt.Errorf("failed ResourceManagerService.GetRelatedProject. scopingProject=%s,parentResourceID=%v : %w", scopingProject, parentResourceID, err)
}
var createdCount int
for _, v := range l {
projectNumber := strings.ReplaceAll(v.Name, "projects/", "")
if projectNumber == scopingProject {
continue
}
_, ok := existsMonitoredProjects[projectNumber]
if ok {
continue
}
ret, err := s.MetricsScopesService.CreateMonitoredProject(ctx, scopingProject, projectNumber)
if err != nil {
fmt.Printf("failed CreateMonitoredProject: %s(%s). %s\n", v.ProjectId, projectNumber, err)
continue
}
fmt.Printf("created MonitoredProject: %s (%s)\n", ret.GetName(), v.ProjectId)
createdCount++
}
return createdCount, nil
}