This repository has been archived by the owner on Aug 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reviewapp_controller.go
195 lines (172 loc) · 6.44 KB
/
reviewapp_controller.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
/*
Copyright 2021.
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 controllers
import (
"context"
"fmt"
"os"
"reflect"
"github.com/go-logr/logr"
"golang.org/x/sync/singleflight"
"k8s.io/apimachinery/pkg/runtime"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/tools/record"
"k8s.io/utils/exec"
ctrl "sigs.k8s.io/controller-runtime"
dreamkastv1alpha1 "github.com/cloudnativedaysjp/reviewapp-operator/api/v1alpha1"
"github.com/cloudnativedaysjp/reviewapp-operator/domain/models"
"github.com/cloudnativedaysjp/reviewapp-operator/domain/repositories"
"github.com/cloudnativedaysjp/reviewapp-operator/domain/services"
myerrors "github.com/cloudnativedaysjp/reviewapp-operator/errors"
"github.com/cloudnativedaysjp/reviewapp-operator/utils"
"github.com/cloudnativedaysjp/reviewapp-operator/utils/metrics"
"github.com/cloudnativedaysjp/reviewapp-operator/wire"
)
const (
finalizer = "reviewapp.finalizers.cloudnativedays.jp"
)
var (
singleflightGroupForReviewApp singleflight.Group
datetimeFactoryForRA = utils.NewDatetimeFactory()
)
// ReviewAppReconciler reconciles a ReviewApp object
type ReviewAppReconciler struct {
Log logr.Logger
Scheme *runtime.Scheme
Recorder record.EventRecorder
K8sRepository repositories.KubernetesRepository
GitApiRepository repositories.GitAPI
GitCommandRepository repositories.GitCommand
PullRequestService services.PullRequestServiceIface
}
//+kubebuilder:rbac:groups=dreamkast.cloudnativedays.jp,resources=reviewapps,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=dreamkast.cloudnativedays.jp,resources=reviewapps/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=dreamkast.cloudnativedays.jp,resources=reviewapps/finalizers,verbs=update
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=argoproj.io,resources=applications,verbs=get;list;watch
func (r *ReviewAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
result, err, _ := singleflightGroupForReviewApp.Do(fmt.Sprintf("%s/%s", req.Namespace, req.Name), func() (interface{}, error) {
r.Log.Info(fmt.Sprintf("fetching ReviewApp resource: %s/%s", req.Namespace, req.Name))
ra, err := r.K8sRepository.GetReviewApp(ctx, req.Namespace, req.Name)
if err != nil && !myerrors.IsNotFound(err) {
return ctrl.Result{}, err
}
dto, result, err := r.prepare(ctx, ra)
if err != nil {
if myerrors.IsNotFound(err) {
r.Log.Info(err.Error())
return result, nil
}
return result, err
}
// Add Finalizers
if err := r.K8sRepository.AddFinalizersToReviewApp(ctx, ra, finalizer); err != nil {
return ctrl.Result{}, err
}
// Handle deletion reconciliation loop.
if !ra.ObjectMeta.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, *dto)
}
return r.reconcile(ctx, *dto)
})
return result.(ctrl.Result), err
}
func (r *ReviewAppReconciler) reconcile(ctx context.Context, dto ReviewAppPhaseDTO) (result ctrl.Result, err error) {
ra := dto.ReviewApp
raStatus := ra.GetStatus()
// set metrics
metrics.UpVec.WithLabelValues(
ra.Name,
ra.Namespace,
ra.Spec.AppTarget.Organization,
ra.Spec.AppTarget.Repository,
ra.Spec.InfraTarget.Organization,
ra.Spec.InfraTarget.Organization,
).Set(1)
// run/skip processes by ReviewApp state
errs := []error{}
phase := func(cond bool, phase func(ctx context.Context, dto ReviewAppPhaseDTO) (models.ReviewAppStatus, ctrl.Result, error)) {
if cond {
raStatus, result, err = phase(ctx, dto)
if err != nil {
errs = append(errs, err)
}
ra.Status = dreamkastv1alpha1.ReviewAppStatus(raStatus)
dto.ReviewApp = ra
}
}
// if s.sync.status is empty, set SyncStatusCodeInitialize
phase(reflect.DeepEqual(ra.Status, dreamkastv1alpha1.ReviewAppStatus{}),
func(ctx context.Context, dto ReviewAppPhaseDTO) (models.ReviewAppStatus, ctrl.Result, error) {
s := dto.ReviewApp.GetStatus()
s.Sync.Status = dreamkastv1alpha1.SyncStatusCodeInitialize
return s, ctrl.Result{}, nil
},
)
// each phase
phase(raStatus.Sync.Status == dreamkastv1alpha1.SyncStatusCodeInitialize ||
raStatus.Sync.Status == dreamkastv1alpha1.SyncStatusCodeWatchingAppRepoAndTemplates,
r.confirmUpdated)
phase(raStatus.Sync.Status == dreamkastv1alpha1.SyncStatusCodeNeedToUpdateInfraRepo,
r.deployReviewAppManifestsToInfraRepo)
phase(raStatus.Sync.Status == dreamkastv1alpha1.SyncStatusCodeUpdatedInfraRepo,
r.commentToAppRepoPullRequest)
// update status
if err := r.K8sRepository.PatchReviewAppStatus(ctx, ra); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, kerrors.NewAggregate(errs)
}
func (r *ReviewAppReconciler) removeMetrics(ra models.ReviewApp) {
metrics.UpVec.DeleteLabelValues(
ra.Name,
ra.Namespace,
ra.Spec.AppTarget.Organization,
ra.Spec.AppTarget.Repository,
ra.Spec.InfraTarget.Organization,
ra.Spec.InfraTarget.Organization,
)
metrics.RequestToGitHubApiCounterVec.DeleteLabelValues(
ra.Name,
ra.Namespace,
"ReviewApp",
)
}
// SetupWithManager sets up the controller with the Manager.
func (r *ReviewAppReconciler) SetupWithManager(mgr ctrl.Manager) error {
setupLog := ctrl.Log.WithName("setup")
var err error
r.K8sRepository, err = wire.NewKubernetesRepository(r.Log, mgr.GetClient())
if err != nil {
setupLog.Error(err, "unable to initialize", "wire.NewKubernetesRepository")
os.Exit(1)
}
r.GitApiRepository, err = wire.NewGitHubAPIRepository(r.Log)
if err != nil {
setupLog.Error(err, "unable to initialize", "wire.NewGitHubAPIRepository")
os.Exit(1)
}
r.GitCommandRepository, err = wire.NewGitCommandRepository(r.Log, exec.New())
if err != nil {
setupLog.Error(err, "unable to initialize", "wire.NewGitCommandRepository")
os.Exit(1)
}
r.PullRequestService, err = wire.NewPullRequestService(r.Log)
if err != nil {
setupLog.Error(err, "unable to initialize", "wire.NewPullRequestService")
os.Exit(1)
}
return ctrl.NewControllerManagedBy(mgr).
For(&dreamkastv1alpha1.ReviewApp{}).
Complete(r)
}