This repository has been archived by the owner on Jan 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
249 lines (209 loc) · 8.91 KB
/
main.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
package main
import (
"context"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"sync"
"syscall"
"github.com/keptn-contrib/helm-service/controller"
"github.com/keptn-contrib/helm-service/pkg/common"
"github.com/keptn-contrib/helm-service/pkg/configurationchanger"
"github.com/keptn-contrib/helm-service/pkg/helm"
logger "github.com/sirupsen/logrus"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/keptn/go-utils/pkg/common/kubeutils"
"github.com/keptn-contrib/helm-service/pkg/namespacemanager"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/kelseyhightower/envconfig"
configutils "github.com/keptn/go-utils/pkg/api/utils"
keptnapi "github.com/keptn/go-utils/pkg/api/utils"
keptncommon "github.com/keptn/go-utils/pkg/lib/keptn"
keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0"
"github.com/keptn-contrib/helm-service/pkg/mesh"
"github.com/keptn-contrib/helm-service/pkg/serviceutils"
utils "github.com/keptn/go-utils/pkg/api/utils"
authorizationv1 "k8s.io/api/authorization/v1"
)
type envConfig struct {
// Port on which to listen for cloudevents
Port int `envconfig:"RCV_PORT" default:"8080"`
Path string `envconfig:"RCV_PATH" default:"/"`
LogLevel string `envconfig:"LOG_LEVEL" default:"info"`
}
const serviceName = "helm-service"
func main() {
var env envConfig
if err := envconfig.Process("", &env); err != nil {
logger.Fatalf("Failed to process env var: %s", err)
}
logger.SetLevel(logger.InfoLevel)
if os.Getenv(env.LogLevel) != "" {
logLevel, err := logger.ParseLevel(os.Getenv(env.LogLevel))
if err != nil {
logger.WithError(err).Error("could not parse log level provided by 'LOG_LEVEL' env var")
} else {
logger.SetLevel(logLevel)
}
}
os.Exit(_main(os.Args[1:], env))
}
func gotEvent(ctx context.Context, event cloudevents.Event) error {
serviceName := serviceName
if event.Context.GetSource() == serviceName {
return nil
}
keptnHandler, err := keptnv2.NewKeptn(&event, keptncommon.KeptnOpts{
ConfigurationServiceURL: os.Getenv("RESOURCE_SERVICE"),
})
if err != nil {
fmt.Println("Could not initialize keptn handler: " + err.Error())
return err
}
configServiceURL, err := serviceutils.GetConfigServiceURL()
if err != nil {
logger.WithError(err).Error("Error when getting configServiceURL")
return err
}
shipyardControllerURL, err := serviceutils.GetShipyardControllerURL()
if err != nil {
logger.WithError(err).Error("Error when getting shipyardControllerURL")
return err
}
//create dependencies
istioMesh := mesh.NewIstioMesh()
logger.Debug("Got event of type " + event.Type())
// ToDo: Multithreaded is important here, such that the endpoint responds immediately
// else we will have deployment handler take 30 seconds, and after that the response will be sent
if event.Type() == keptnv2.GetTriggeredEventType(keptnv2.DeploymentTaskName) {
deploymentHandler := createDeploymentHandler(configServiceURL, keptnHandler, istioMesh)
go gracefulMiddleware(ctx, event, deploymentHandler)
} else if event.Type() == keptnv2.GetTriggeredEventType(keptnv2.ReleaseTaskName) {
releaseHandler := createReleaseHandler(configServiceURL, istioMesh, keptnHandler)
go gracefulMiddleware(ctx, event, releaseHandler)
} else if event.Type() == keptnv2.GetTriggeredEventType(keptnv2.RollbackTaskName) {
rollbackHandler := createRollbackHandler(configServiceURL, istioMesh, keptnHandler)
go gracefulMiddleware(ctx, event, rollbackHandler)
} else if event.Type() == keptnv2.GetTriggeredEventType(keptnv2.ActionTaskName) {
actionHandler := createActionTriggeredHandler(configServiceURL, keptnHandler)
go gracefulMiddleware(ctx, event, actionHandler)
} else if event.Type() == keptnv2.GetFinishedEventType(keptnv2.ServiceDeleteTaskName) {
deleteHandler := createDeleteHandler(configServiceURL, shipyardControllerURL, keptnHandler)
go gracefulMiddleware(ctx, event, deleteHandler)
} else {
logger.Error("Received unexpected keptn event")
}
return nil
}
func createKeptnBaseHandler(url *url.URL, keptn *keptnv2.Keptn) controller.Handler {
namespaceManager := namespacemanager.NewNamespaceManager(keptn.Logger)
helmExecutor := helm.NewHelmV3Executor(keptn.Logger, namespaceManager)
keptnHandlerBase := controller.NewHandlerBase(keptn, helmExecutor, url.String())
return keptnHandlerBase
}
func createDeleteHandler(configServiceURL *url.URL, shipyardControllerURL *url.URL, keptn *keptnv2.Keptn) *controller.DeleteHandler {
stagesHandler := configutils.NewStageHandler(shipyardControllerURL.String())
keptnBaseHandler := createKeptnBaseHandler(configServiceURL, keptn)
deleteHandler := controller.NewDeleteHandler(keptnBaseHandler, stagesHandler, configServiceURL.String())
return deleteHandler
}
func createActionTriggeredHandler(configServiceURL *url.URL, keptn *keptnv2.Keptn) *controller.ActionTriggeredHandler {
configChanger := configurationchanger.NewConfigurationChanger(configServiceURL.String())
keptnBaseHandler := createKeptnBaseHandler(configServiceURL, keptn)
actionHandler := controller.NewActionTriggeredHandler(keptnBaseHandler, configChanger)
return actionHandler
}
func createReleaseHandler(url *url.URL, mesh *mesh.IstioMesh, keptn *keptnv2.Keptn) *controller.ReleaseHandler {
configChanger := configurationchanger.NewConfigurationChanger(url.String())
chartGenerator := helm.NewGeneratedChartGenerator(mesh)
chartStorer := common.NewChartStorer(utils.NewResourceHandler(url.String()))
chartPackager := common.NewChartPackager()
keptnBaseHandler := createKeptnBaseHandler(url, keptn)
releaseHandler := controller.NewReleaseHandler(keptnBaseHandler, mesh, configChanger, chartGenerator, chartStorer, chartPackager)
return releaseHandler
}
func createRollbackHandler(url *url.URL, mesh *mesh.IstioMesh, keptn *keptnv2.Keptn) *controller.RollbackHandler {
configChanger := configurationchanger.NewConfigurationChanger(url.String())
keptnBaseHandler := createKeptnBaseHandler(url, keptn)
rollbackHandler := controller.NewRollbackHandler(keptnBaseHandler, mesh, configChanger)
return rollbackHandler
}
func createOnboarder(configServiceURL *url.URL, keptn *keptnv2.Keptn, mesh *mesh.IstioMesh) controller.Onboarder {
namespaceManager := namespacemanager.NewNamespaceManager(keptn.Logger)
chartStorer := common.NewChartStorer(utils.NewResourceHandler(configServiceURL.String()))
chartGenerator := helm.NewGeneratedChartGenerator(mesh)
chartPackager := common.NewChartPackager()
keptnBaseHandler := createKeptnBaseHandler(configServiceURL, keptn)
onBoarder := controller.NewOnboarder(keptnBaseHandler, namespaceManager, chartStorer, chartGenerator, chartPackager)
return onBoarder
}
func createDeploymentHandler(url *url.URL, keptn *keptnv2.Keptn, mesh *mesh.IstioMesh) *controller.DeploymentHandler {
chartGenerator := helm.NewGeneratedChartGenerator(mesh)
onBoarder := createOnboarder(url, keptn, mesh)
keptnBaseHandler := createKeptnBaseHandler(url, keptn)
deploymentHandler := controller.NewDeploymentHandler(keptnBaseHandler, mesh, onBoarder, chartGenerator)
return deploymentHandler
}
func _main(args []string, env envConfig) int {
// Check admin rights
adminRights, err := hasAdminRights()
if err != nil {
log.Fatal(fmt.Sprintf("failed to check whether helm-service has admin right: %v", err))
}
if !adminRights {
log.Println("Warning: helm-service is running without admin RBAC rights. See #3511 for details.")
}
ctx := getGracefulContext()
p, err := cloudevents.NewHTTP(cloudevents.WithPath(env.Path), cloudevents.WithPort(env.Port), cloudevents.WithGetHandlerFunc(keptnapi.HealthEndpointHandler))
if err != nil {
log.Fatalf("failed to create client, %v", err)
}
c, err := cloudevents.NewClient(p)
if err != nil {
log.Fatalf("failed to create client, %v", err)
}
log.Fatal(c.StartReceiver(ctx, gotEvent))
return 0
}
// hasAdminRights checks if the current pod is assigned the Admin Role
func hasAdminRights() (bool, error) {
clientset, err := kubeutils.GetClientSet(true)
if err != nil {
return false, err
}
sar := &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{},
},
}
resp, err := clientset.AuthorizationV1().SelfSubjectAccessReviews().Create(context.TODO(), sar, v1.CreateOptions{})
if err != nil {
return false, err
}
return resp.Status.Allowed, nil
}
func getGracefulContext() context.Context {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
wg := &sync.WaitGroup{}
ctx, cancel := context.WithCancel(cloudevents.WithEncodingStructured(context.WithValue(context.Background(), controller.GracefulShutdownKey, wg)))
go func() {
<-ch
log.Println("Container termination triggered, starting graceful shutdown")
wg.Wait()
cancel()
}()
return ctx
}
func gracefulMiddleware(ctx context.Context, ce cloudevents.Event, handler controller.Handler) {
val := ctx.Value(controller.GracefulShutdownKey)
if val != nil {
if wg, ok := val.(*sync.WaitGroup); ok {
wg.Add(1)
handler.HandleEvent(ce)
wg.Done()
}
}
}