-
Notifications
You must be signed in to change notification settings - Fork 148
/
reporter.go
185 lines (158 loc) · 5.57 KB
/
reporter.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Copyright 2022 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kubernetes
import (
"context"
"fmt"
"time"
"go.uber.org/zap"
"google.golang.org/grpc"
"github.com/pipe-cd/pipecd/pkg/app/piped/livestatestore/kubernetes"
"github.com/pipe-cd/pipecd/pkg/app/server/service/pipedservice"
"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/model"
)
const (
maxNumEventsPerRequest = 1000
)
type applicationLister interface {
ListByCloudProvider(name string) []*model.Application
}
type apiClient interface {
ReportApplicationLiveState(ctx context.Context, req *pipedservice.ReportApplicationLiveStateRequest, opts ...grpc.CallOption) (*pipedservice.ReportApplicationLiveStateResponse, error)
ReportApplicationLiveStateEvents(ctx context.Context, req *pipedservice.ReportApplicationLiveStateEventsRequest, opts ...grpc.CallOption) (*pipedservice.ReportApplicationLiveStateEventsResponse, error)
}
type Reporter interface {
Run(ctx context.Context) error
ProviderName() string
}
type reporter struct {
provider config.PipedCloudProvider
appLister applicationLister
stateGetter kubernetes.Getter
eventIterator kubernetes.EventIterator
apiClient apiClient
flushInterval time.Duration
snapshotFlushInterval time.Duration
logger *zap.Logger
snapshotVersions map[string]model.ApplicationLiveStateVersion
}
func NewReporter(cp config.PipedCloudProvider, appLister applicationLister, stateGetter kubernetes.Getter, apiClient apiClient, logger *zap.Logger) Reporter {
logger = logger.Named("kubernetes-reporter").With(
zap.String("cloud-provider", cp.Name),
)
return &reporter{
provider: cp,
appLister: appLister,
stateGetter: stateGetter,
eventIterator: stateGetter.NewEventIterator(),
apiClient: apiClient,
flushInterval: 5 * time.Second,
snapshotFlushInterval: 10 * time.Minute,
logger: logger,
snapshotVersions: make(map[string]model.ApplicationLiveStateVersion),
}
}
func (r *reporter) Run(ctx context.Context) error {
r.logger.Info("start running app live state reporter")
r.logger.Info("waiting for livestatestore to be ready")
if err := r.stateGetter.WaitForReady(ctx, 10*time.Minute); err != nil {
r.logger.Error("livestatestore was unable to be ready in time", zap.Error(err))
return err
}
// Do the first snapshot flushing after the statestore becomes ready.
r.flushSnapshots(ctx)
snapshotTicker := time.NewTicker(r.snapshotFlushInterval)
defer snapshotTicker.Stop()
ticker := time.NewTicker(r.flushInterval)
defer ticker.Stop()
for {
select {
case <-snapshotTicker.C:
r.flushSnapshots(ctx)
case <-ticker.C:
r.flushEvents(ctx)
case <-ctx.Done():
r.logger.Info("app live state reporter has been stopped")
return nil
}
}
}
func (r *reporter) flushSnapshots(ctx context.Context) error {
// TODO: In the future, maybe we should apply worker model for this or
// send multiple application states in one request.
apps := r.appLister.ListByCloudProvider(r.provider.Name)
for _, app := range apps {
state, ok := r.stateGetter.GetKubernetesAppLiveState(app.Id)
if !ok {
r.logger.Info(fmt.Sprintf("no app state of kubernetes application %s to report", app.Id))
continue
}
snapshot := &model.ApplicationLiveStateSnapshot{
ApplicationId: app.Id,
PipedId: app.PipedId,
ProjectId: app.ProjectId,
Kind: app.Kind,
Kubernetes: &model.KubernetesApplicationLiveState{
Resources: state.Resources,
},
Version: &state.Version,
}
snapshot.DetermineAppHealthStatus()
req := &pipedservice.ReportApplicationLiveStateRequest{
Snapshot: snapshot,
}
if _, err := r.apiClient.ReportApplicationLiveState(ctx, req); err != nil {
r.logger.Error("failed to report application live state",
zap.String("application-id", app.Id),
zap.Error(err),
)
continue
}
r.snapshotVersions[app.Id] = state.Version
r.logger.Info(fmt.Sprintf("successfully reported application live state for application: %s", app.Id))
}
return nil
}
func (r *reporter) flushEvents(ctx context.Context) error {
events := r.eventIterator.Next(maxNumEventsPerRequest)
if len(events) == 0 {
return nil
}
filteredEvents := make([]*model.KubernetesResourceStateEvent, 0, len(events))
for i, event := range events {
snapshotVersion, ok := r.snapshotVersions[event.ApplicationId]
if ok && event.SnapshotVersion.IsBefore(snapshotVersion) {
continue
}
filteredEvents = append(filteredEvents, &events[i])
}
if len(filteredEvents) == 0 {
return nil
}
req := &pipedservice.ReportApplicationLiveStateEventsRequest{
KubernetesEvents: filteredEvents,
}
if _, err := r.apiClient.ReportApplicationLiveStateEvents(ctx, req); err != nil {
r.logger.Error("failed to report application live state events",
zap.Error(err),
)
return err
}
r.logger.Info(fmt.Sprintf("successfully reported %d events about application live state", len(filteredEvents)))
return nil
}
func (r *reporter) ProviderName() string {
return r.provider.Name
}