-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhealth_checker.go
77 lines (68 loc) · 2.65 KB
/
health_checker.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
74
75
76
77
package pubsub
import (
"cloud.google.com/go/pubsub"
"context"
"fmt"
"time"
)
type PermissionType int
const (
PermissionPublish PermissionType = 0
PermissionSubscribe PermissionType = 1
)
type HealthChecker struct {
name string
client *pubsub.Client
timeout time.Duration
permissionType PermissionType
resourceId string
}
func NewHealthChecker(name string, client *pubsub.Client, resourceId string, permissionType PermissionType, timeout ...time.Duration) *HealthChecker {
if len(timeout) >= 1 {
return &HealthChecker{name: name, client: client, permissionType: permissionType, resourceId: resourceId, timeout: timeout[0]}
}
return &HealthChecker{name: name, client: client, permissionType: permissionType, resourceId: resourceId, timeout: 4 * time.Second}
}
func NewPubHealthChecker(name string, client *pubsub.Client, resourceId string, timeout ...time.Duration) *HealthChecker {
if len(timeout) >= 1 {
return &HealthChecker{name: name, client: client, permissionType: PermissionPublish, resourceId: resourceId, timeout: timeout[0]}
}
return &HealthChecker{name: name, client: client, permissionType: PermissionPublish, resourceId: resourceId, timeout: 4 * time.Second}
}
func NewSubHealthChecker(name string, client *pubsub.Client, resourceId string, timeout ...time.Duration) *HealthChecker {
if len(timeout) >= 1 {
return &HealthChecker{name: name, client: client, permissionType: PermissionSubscribe, resourceId: resourceId, timeout: timeout[0]}
}
return &HealthChecker{name: name, client: client, permissionType: PermissionSubscribe, resourceId: resourceId, timeout: 4 * time.Second}
}
func (h *HealthChecker) Name() string {
return h.name
}
func (h *HealthChecker) Check(ctx context.Context) (map[string]interface{}, error) {
res := make(map[string]interface{})
var permissions []string
var err error
timeoutCtx, _ := context.WithTimeout(ctx, h.timeout)
if h.permissionType == PermissionPublish {
permissions, err = h.client.Topic(h.resourceId).IAM().TestPermissions(timeoutCtx, []string{"pubsub.topics.publish"})
} else if h.permissionType == PermissionSubscribe {
permissions, err = h.client.Subscription(h.resourceId).IAM().TestPermissions(timeoutCtx, []string{"pubsub.subscriptions.consume"})
}
if err != nil {
return res, err
} else if len(permissions) != 1 {
return res, fmt.Errorf("invalid permissions: %v", permissions)
} else {
return res, nil
}
}
func (h *HealthChecker) Build(ctx context.Context, data map[string]interface{}, err error) map[string]interface{} {
if err == nil {
return data
}
if data == nil {
data = make(map[string]interface{}, 0)
}
data["error"] = err.Error()
return data
}