/
transition.go
327 lines (288 loc) · 11.3 KB
/
transition.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package cluster
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/filanov/stateswitch"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/jinzhu/gorm"
"github.com/openshift/assisted-service/internal/common"
"github.com/openshift/assisted-service/internal/events"
"github.com/openshift/assisted-service/internal/host"
"github.com/openshift/assisted-service/internal/metrics"
"github.com/openshift/assisted-service/models"
logutil "github.com/openshift/assisted-service/pkg/log"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
)
type transitionHandler struct {
log logrus.FieldLogger
db *gorm.DB
prepareConfig PrepareConfig
}
////////////////////////////////////////////////////////////////////////////
// CancelInstallation
////////////////////////////////////////////////////////////////////////////
type TransitionArgsCancelInstallation struct {
ctx context.Context
reason string
db *gorm.DB
}
func (th *transitionHandler) PostCancelInstallation(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) error {
sCluster, ok := sw.(*stateCluster)
if !ok {
return errors.New("PostCancelInstallation incompatible type of StateSwitch")
}
params, ok := args.(*TransitionArgsCancelInstallation)
if !ok {
return errors.New("PostCancelInstallation invalid argument")
}
if sCluster.srcState == clusterStatusError {
return nil
}
return th.updateTransitionCluster(logutil.FromContext(params.ctx, th.log), params.db, sCluster,
params.reason)
}
////////////////////////////////////////////////////////////////////////////
// ResetCluster
////////////////////////////////////////////////////////////////////////////
type TransitionArgsResetCluster struct {
ctx context.Context
reason string
db *gorm.DB
}
func (th *transitionHandler) PostResetCluster(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) error {
sCluster, ok := sw.(*stateCluster)
if !ok {
return errors.New("PostResetCluster incompatible type of StateSwitch")
}
params, ok := args.(*TransitionArgsResetCluster)
if !ok {
return errors.New("PostResetCluster invalid argument")
}
return th.updateTransitionCluster(logutil.FromContext(params.ctx, th.log), params.db, sCluster,
params.reason)
}
////////////////////////////////////////////////////////////////////////////
// Prepare for installation
////////////////////////////////////////////////////////////////////////////
type TransitionArgsPrepareForInstallation struct {
ctx context.Context
db *gorm.DB
}
func (th *transitionHandler) PostPrepareForInstallation(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) error {
sCluster, ok := sw.(*stateCluster)
if !ok {
return errors.New("PostResetCluster incompatible type of StateSwitch")
}
params, ok := args.(*TransitionArgsPrepareForInstallation)
if !ok {
return errors.New("PostResetCluster invalid argument")
}
return th.updateTransitionCluster(logutil.FromContext(params.ctx, th.log), th.db, sCluster,
statusInfoPreparingForInstallation, "install_started_at", strfmt.DateTime(time.Now()))
}
////////////////////////////////////////////////////////////////////////////
// Complete installation
////////////////////////////////////////////////////////////////////////////
type TransitionArgsCompleteInstallation struct {
ctx context.Context
isSuccess bool
reason string
}
func (th *transitionHandler) PostCompleteInstallation(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) error {
sCluster, ok := sw.(*stateCluster)
if !ok {
return errors.New("PostCompleteInstallation incompatible type of StateSwitch")
}
params, ok := args.(*TransitionArgsCompleteInstallation)
if !ok {
return errors.New("PostCompleteInstallation invalid argument")
}
return th.updateTransitionCluster(logutil.FromContext(params.ctx, th.log), th.db, sCluster,
params.reason, "install_completed_at", strfmt.DateTime(time.Now()))
}
func (th *transitionHandler) isSuccess(stateSwitch stateswitch.StateSwitch, args stateswitch.TransitionArgs) (b bool, err error) {
params, _ := args.(*TransitionArgsCompleteInstallation)
return params.isSuccess, nil
}
func (th *transitionHandler) notSuccess(stateSwitch stateswitch.StateSwitch, args stateswitch.TransitionArgs) (b bool, err error) {
params, _ := args.(*TransitionArgsCompleteInstallation)
return !params.isSuccess, nil
}
////////////////////////////////////////////////////////////////////////////
// Handle pre-installation error
////////////////////////////////////////////////////////////////////////////
type TransitionArgsHandlePreInstallationError struct {
ctx context.Context
installErr error
}
func (th *transitionHandler) PostHandlePreInstallationError(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) error {
sCluster, _ := sw.(*stateCluster)
params, _ := args.(*TransitionArgsHandlePreInstallationError)
return th.updateTransitionCluster(logutil.FromContext(params.ctx, th.log), th.db, sCluster,
params.installErr.Error())
}
func (th *transitionHandler) updateTransitionCluster(log logrus.FieldLogger, db *gorm.DB, state *stateCluster,
statusInfo string, extra ...interface{}) error {
if cluster, err := updateClusterStatus(log, db, *state.cluster.ID, state.srcState,
swag.StringValue(state.cluster.Status), statusInfo, extra...); err != nil {
return err
} else {
state.cluster = cluster
return nil
}
}
////////////////////////////////////////////////////////////////////////////
// Refresh Cluster
////////////////////////////////////////////////////////////////////////////
type TransitionArgsRefreshCluster struct {
ctx context.Context
eventHandler events.Handler
metricApi metrics.API
hostApi host.API
conditions map[string]bool
validationResults map[string][]validationResult
db *gorm.DB
}
func If(id stringer) stateswitch.Condition {
ret := func(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) (bool, error) {
params, ok := args.(*TransitionArgsRefreshCluster)
if !ok {
return false, errors.Errorf("If(%s) invalid argument", id.String())
}
b, ok := params.conditions[id.String()]
if !ok {
return false, errors.Errorf("If(%s) no such condition", id.String())
}
return b, nil
}
return ret
}
//check if we should move to finalizing state
func (th *transitionHandler) IsFinalizing(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) (bool, error) {
sCluster, ok := sw.(*stateCluster)
mappedMastersByRole := MapMasterHostsByStatus(sCluster.cluster)
// Cluster is in finalizing
mastersInInstalled := mappedMastersByRole[models.HostStatusInstalled]
if ok && len(mastersInInstalled) >= MinHostsNeededForInstallation {
th.log.Infof("Cluster %s has at least %d installed hosts, cluster is finalizing.", sCluster.cluster.ID, len(mastersInInstalled))
return true, nil
}
return false, nil
}
//check if we should stay in installing state
func (th *transitionHandler) IsInstalling(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) (bool, error) {
sCluster, _ := sw.(*stateCluster)
mappedMastersByRole := MapMasterHostsByStatus(sCluster.cluster)
mastersInSomeInstallingStatus := len(mappedMastersByRole[models.HostStatusInstalling]) +
len(mappedMastersByRole[models.HostStatusInstallingInProgress]) +
len(mappedMastersByRole[models.HostStatusInstalled]) +
len(mappedMastersByRole[models.HostStatusInstallingPendingUserAction])
if mastersInSomeInstallingStatus >= MinHostsNeededForInstallation {
return true, nil
}
return false, nil
}
//check if prepare for installation reach to timeout
func (th *transitionHandler) IsPreparingTimedOut(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) (bool, error) {
sCluster, ok := sw.(*stateCluster)
if !ok {
return false, errors.New("IsPreparingTimedOut incompatible type of StateSwitch")
}
// can happen if the service was rebooted or somehow the async part crashed.
if time.Since(time.Time(sCluster.cluster.StatusUpdatedAt)) > th.prepareConfig.InstallationTimeout {
return true, nil
}
return false, nil
}
// Return a post transition function with a constant reason
func (th *transitionHandler) PostRefreshCluster(reason string) stateswitch.PostTransition {
ret := func(sw stateswitch.StateSwitch, args stateswitch.TransitionArgs) error {
sCluster, ok := sw.(*stateCluster)
if !ok {
return errors.New("PostRefreshCluster incompatible type of StateSwitch")
}
params, ok := args.(*TransitionArgsRefreshCluster)
if !ok {
return errors.New("PostRefreshCluster invalid argument")
}
var (
b []byte
err error
updatedCluster *common.Cluster
)
b, err = json.Marshal(¶ms.validationResults)
if err != nil {
return err
}
updatedCluster, err = updateClusterStatus(logutil.FromContext(params.ctx, th.log), params.db, *sCluster.cluster.ID, sCluster.srcState, *sCluster.cluster.Status,
reason, "validations_info", string(b))
//update hosts status to models.HostStatusResettingPendingUserAction if needed
cluster := sCluster.cluster
if updatedCluster != nil {
cluster = updatedCluster
}
setPendingUserResetIfNeeded(params.ctx, logutil.FromContext(params.ctx, th.log), params.db, params.hostApi, cluster)
//if status was changed - we need to send event and metrics
if err == nil && updatedCluster != nil && sCluster.srcState != swag.StringValue(updatedCluster.Status) {
msg := fmt.Sprintf("Updated status of cluster %s to %s", updatedCluster.Name, *updatedCluster.Status)
params.eventHandler.AddEvent(params.ctx, *updatedCluster.ID, nil, models.EventSeverityInfo, msg, time.Now())
//report installation finished metric if needed
reportInstallationCompleteStatuses := []string{models.ClusterStatusInstalled, models.ClusterStatusError}
if sCluster.srcState == models.ClusterStatusInstalling &&
funk.ContainsString(reportInstallationCompleteStatuses, swag.StringValue(updatedCluster.Status)) {
params.metricApi.ClusterInstallationFinished(logutil.FromContext(params.ctx, th.log), swag.StringValue(updatedCluster.Status),
updatedCluster.OpenshiftVersion, updatedCluster.InstallStartedAt)
}
return nil
}
return err
}
return ret
}
func setPendingUserResetIfNeeded(ctx context.Context, log logrus.FieldLogger, db *gorm.DB, hostApi host.API, c *common.Cluster) {
if swag.StringValue(c.Status) == models.ClusterStatusInsufficient {
if isPendingUserResetRequired(hostApi, c) {
log.Infof("Setting cluster: %s hosts to status: %s",
c.ID, models.HostStatusInstallingPendingUserAction)
if err := setPendingUserReset(ctx, c, db, hostApi); err != nil {
log.Errorf("failed setting cluster: %s hosts to status: %s",
c.ID, models.HostStatusInstallingPendingUserAction)
}
}
}
}
func isPendingUserResetRequired(hostAPI host.API, c *common.Cluster) bool {
for _, h := range c.Hosts {
if hostAPI.IsRequireUserActionReset(h) {
return true
}
}
return false
}
func setPendingUserReset(ctx context.Context, c *common.Cluster, db *gorm.DB, hostAPI host.API) error {
txSuccess := false
tx := db.Begin()
defer func() {
if !txSuccess {
tx.Rollback()
}
if r := recover(); r != nil {
tx.Rollback()
}
}()
for _, h := range c.Hosts {
if err := hostAPI.ResetPendingUserAction(ctx, h, tx); err != nil {
return err
}
}
if err := tx.Commit().Error; err != nil {
return err
}
txSuccess = true
return nil
}