/
registrar.go
89 lines (73 loc) · 2.04 KB
/
registrar.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
package cluster
import (
context "context"
"time"
"github.com/pkg/errors"
"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/models"
"github.com/sirupsen/logrus"
)
func NewRegistrar(log logrus.FieldLogger, db *gorm.DB) *registrar {
return ®istrar{
log: log,
db: db,
}
}
type registrar struct {
log logrus.FieldLogger
db *gorm.DB
}
func (r *registrar) RegisterCluster(ctx context.Context, cluster *common.Cluster) error {
cluster.Status = swag.String(clusterStatusInsufficient)
cluster.StatusInfo = swag.String(statusInfoInsufficient)
cluster.StatusUpdatedAt = strfmt.DateTime(time.Now())
tx := r.db.Begin()
defer func() {
if rec := recover(); rec != nil {
r.log.Error("update cluster failed")
tx.Rollback()
}
}()
if tx.Error != nil {
r.log.WithError(tx.Error).Error("failed to start transaction")
}
if err := tx.Preload("Hosts").Create(cluster).Error; err != nil {
r.log.Errorf("Error registering cluster %s", cluster.Name)
tx.Rollback()
return err
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
return err
}
return nil
}
func (r *registrar) DeregisterCluster(ctx context.Context, cluster *common.Cluster) error {
var txErr error
tx := r.db.Begin()
defer func() {
if txErr != nil {
tx.Rollback()
}
}()
if swag.StringValue(cluster.Status) == clusterStatusInstalling {
tx.Rollback()
return errors.Errorf("cluster %s can not be removed while being installed", cluster.ID)
}
if txErr = tx.Where("cluster_id = ?", cluster.ID).Delete(&models.Host{}).Error; txErr != nil {
tx.Rollback()
return errors.Errorf("failed to deregister host while unregistering cluster %s", cluster.ID)
}
if txErr = tx.Delete(cluster).Error; txErr != nil {
tx.Rollback()
return errors.Errorf("failed to delete cluster %s", cluster.ID)
}
if tx.Commit().Error != nil {
tx.Rollback()
return errors.Errorf("failed to delete cluster %s, commit tx", cluster.ID)
}
return nil
}