Skip to content

Commit

Permalink
Merge pull request #15 from keptn-sandbox/migratetokeptn08
Browse files Browse the repository at this point in the history
Migratetokeptn08
  • Loading branch information
grabnerandi authored Mar 19, 2021
2 parents 5cc6203 + ecaa7b7 commit 290c96a
Show file tree
Hide file tree
Showing 6 changed files with 324 additions and 571 deletions.
29 changes: 17 additions & 12 deletions deploy/service.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ metadata:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: keptn-monaco-service
name: keptn-monaco-service-secrets
namespace: keptn
labels:
"app": "keptn"
Expand All @@ -21,18 +21,20 @@ rules:
- secrets
verbs:
- get
- list
- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: keptn-monaco-service
name: keptn-monaco-service-secrets
namespace: keptn
labels:
"app": "keptn"
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: keptn-monaco-service
name: keptn-monaco-service-secrets
subjects:
- kind: ServiceAccount
name: keptn-monaco-service
Expand All @@ -55,22 +57,25 @@ spec:
spec:
containers:
- name: monaco-service
image: keptnsandbox/monaco-service:0.2.1
image: grabnerandi/monaco-service:0.8.0
ports:
- containerPort: 8080
env:
- name: EVENTBROKER
value: 'http://event-broker/keptn'
- name: CONFIGURATION_SERVICE
value: 'http://configuration-service:8080'
- name: MONACO_VERBOSE_MODE
value: "true"
- name: MONACO_DRYRUN
value: "true"
- name: MONACO_KEEP_TEMP_DIR
value: "false"
resources:
requests:
memory: "32Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "500m"
- name: distributor
image: keptn/distributor:0.7.3
image: keptn/distributor:0.8.0
livenessProbe:
httpGet:
path: /health
Expand All @@ -82,11 +87,11 @@ spec:
- containerPort: 8080
resources:
requests:
memory: "16Mi"
cpu: "25m"
limits:
memory: "32Mi"
cpu: "50m"
limits:
memory: "128Mi"
cpu: "500m"
env:
- name: PUBSUB_URL
value: 'nats://keptn-nats-cluster'
Expand Down
188 changes: 72 additions & 116 deletions eventhandlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,91 +8,108 @@ import (
"strconv"
"strings"

"github.com/cloudevents/sdk-go/pkg/cloudevents"
keptn "github.com/keptn/go-utils/pkg/lib"
keptnlog "github.com/keptn/go-utils/pkg/lib/keptn"
cloudevents "github.com/cloudevents/sdk-go/v2" // make sure to use v2 cloudevents here
keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0"

"github.com/kristofre/monaco-service/pkg/common"
"github.com/keptn-sandbox/monaco-service/pkg/common"
)

/**
* Here are all the handler functions for the individual event
See https://github.com/keptn/spec/blob/0.1.3/cloudevents.md for details on the payload
-> "sh.keptn.event.configuration.change"
-> "sh.keptn.events.deployment-finished"
-> "sh.keptn.events.tests-finished"
-> "sh.keptn.event.start-evaluation"
-> "sh.keptn.events.evaluation-done"
-> "sh.keptn.event.problem.open"
-> "sh.keptn.events.problem"
-> "sh.keptn.event.action.triggered"
*/

// Handles ConfigureMonitoringEventType = "sh.keptn.event.monitoring.configure"
func HandleConfigureMonitoringEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.ConfigureMonitoringEventData) error {
log.Printf("Handling Configure Monitoring Event: %s", incomingEvent.Context.GetID())
* See https://github.com/keptn/spec/blob/0.8.0-alpha/cloudevents.md for details on the payload
**/

// GenericLogKeptnCloudEventHandler is a generic handler for Keptn Cloud Events that logs the CloudEvent
func GenericLogKeptnCloudEventHandler(myKeptn *keptnv2.Keptn, incomingEvent cloudevents.Event, data interface{}) error {
log.Printf("Handling %s Event: %s", incomingEvent.Type(), incomingEvent.Context.GetID())
log.Printf("CloudEvent %T: %v", data, data)

return nil
}

// HandleConfigureMonitoringTriggeredEvent handles configure-monitoring.triggered events
// TODO: add in your handler code
func HandleConfigureMonitoringTriggeredEvent(myKeptn *keptnv2.Keptn, incomingEvent cloudevents.Event, data *keptnv2.ConfigureMonitoringTriggeredEventData) error {
log.Printf("Handling configure-monitoring.triggered Event: %s", incomingEvent.Context.GetID())

return nil
}

//
// Handles ConfigurationChangeEventType = "sh.keptn.event.configuration.change"
// HandleConfigureMonitoringTriggeredEvent handles configure-monitoring.triggered events
// TODO: add in your handler code
//
func HandleConfigurationChangeEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.ConfigurationChangeEventData) error {
func HandleMonacoTriggeredEvent(myKeptn *keptnv2.Keptn, incomingEvent cloudevents.Event, data *MonacoStartedEventData) error {
fmt.Println("Handling monaco.triggered Event: %s", incomingEvent.Context.GetID())

data.EventData.Message = "Starting to query for Monaco Projects"
_, err := myKeptn.SendTaskStartedEvent(data, ServiceName)

if err != nil {
return err
}

var shkeptncontext string
incomingEvent.Context.ExtensionAs("shkeptncontext", &shkeptncontext)

stdLogger := keptnlog.NewLogger(shkeptncontext, incomingEvent.Context.GetID(), "monaco-service")
stdLogger.Info(fmt.Sprintf("Handling Configuration Changed Event: %s", incomingEvent.Context.GetID()))
stdLogger.Info(fmt.Sprintf("Processing sh.keptn.event.configuration.change for %s.%s.%s", data.Project, data.Stage, data.Service))
fmt.Sprintf("Handling Configuration Changed Event: %s", incomingEvent.Context.GetID())
fmt.Sprintf("Processing sh.keptn.event.configuration.change for %s.%s.%s", data.EventData.GetProject(), data.EventData.GetStage(), data.EventData.GetService())

keptnEvent := &common.BaseKeptnEvent{}
keptnEvent.Project = data.Project
keptnEvent.Stage = data.Stage
keptnEvent.Service = data.Service
keptnEvent.Labels = data.Labels
keptnEvent.Project = data.EventData.GetProject()
keptnEvent.Stage = data.EventData.GetStage()
keptnEvent.Service = data.EventData.GetService()
keptnEvent.Labels = data.EventData.GetLabels()
keptnEvent.Context = shkeptncontext

monacoConfigFile, _ := common.GetMonacoConfig(keptnEvent, stdLogger)
monacoConfigFile, _ := common.GetMonacoConfig(keptnEvent)
dtCreds := ""
if monacoConfigFile != nil {
// implementing https://github.com/keptn-contrib/dynatrace-sli-service/issues/90
dtCreds = common.ReplaceKeptnPlaceholders(monacoConfigFile.DtCreds, keptnEvent)
stdLogger.Debug("Found monaco.conf.yaml with DTCreds: " + dtCreds)
fmt.Println("Found monaco.conf.yaml with DTCreds: " + dtCreds)
} else {
stdLogger.Debug("Using default DTCreds: dynatrace as no custom monaco.conf.yaml was found!")
fmt.Println("Using default DTCreds: dynatrace as no custom monaco.conf.yaml was found!")
monacoConfigFile = &common.MonacoConfigFile{}
monacoConfigFile.DtCreds = "dynatrace"
}

//
// Adding DtCreds as a label so users know which DtCreds was used
if data.Labels == nil {
data.Labels = make(map[string]string)
if data.EventData.Labels == nil {
data.EventData.Labels = make(map[string]string)
}
data.Labels["DtCreds"] = monacoConfigFile.DtCreds
data.EventData.Labels["DtCreds"] = monacoConfigFile.DtCreds

dtCredentials, err := getDynatraceCredentials(dtCreds, data.Project, stdLogger)
dtCredentials, err := getDynatraceCredentials(dtCreds, data.Project)

if err != nil {
stdLogger.Error("Failed to fetch Dynatrace credentials: " + err.Error())
// fmt.Println("Failed to fetch Dynatrace credentials: " + err.Error())
finishedData := &keptnv2.EventData{
Status: keptnv2.StatusErrored,
Result: keptnv2.ResultFailed,
Message: fmt.Sprintf("Failed to fetch Dynatrace credentials: %v", err.Error()),
}
_, err = myKeptn.SendTaskFinishedEvent(finishedData, ServiceName)
return err
}

// Prepare the folder structure for monaco (create base + shkeptncontext temp folder, copy files, get monaco.zip, extract and copy to temp)
err = common.PrepareFiles(keptnEvent, stdLogger)
err = common.PrepareFiles(keptnEvent)
if err != nil {
stdLogger.Error(fmt.Sprintf("Error preparing monaco files: %s", err.Error()))
// fmt.Println(fmt.Sprintf("Error preparing monaco files: %s", err.Error()))
finishedData := &keptnv2.EventData{
Status: keptnv2.StatusErrored,
Result: keptnv2.ResultFailed,
Message: fmt.Sprintf("Error preparing monaco files: %s", err.Error()),
}
_, err = myKeptn.SendTaskFinishedEvent(finishedData, ServiceName)
return err
}

// generate projects string for monaco
monacoProjects := common.GenerateMonacoProjectStringFromMonacoConfig(monacoConfigFile, keptnEvent)

// test and apply monaco configuration
err = callMonaco(dtCredentials, keptnEvent, monacoProjects, stdLogger)
err = callMonaco(dtCredentials, keptnEvent, monacoProjects)

keeptempString := os.Getenv("MONACO_KEEP_TEMP_DIR")
if keeptempString == "" {
Expand All @@ -101,85 +118,24 @@ func HandleConfigurationChangeEvent(myKeptn *keptn.Keptn, incomingEvent cloudeve
keeptemp, _ := strconv.ParseBool(keeptempString)

if keeptemp {
stdLogger.Info(fmt.Sprintf("Not deleting temp folder (MONACO_KEEP_TEMP_DIR=true) for %s", keptnEvent.Context))
fmt.Sprintf("Not deleting temp folder (MONACO_KEEP_TEMP_DIR=true) for %s", keptnEvent.Context)
} else {
// Clean up: remove temp folder for Context
err = common.DeleteTempFolderForKeptnContext(keptnEvent)
stdLogger.Info(fmt.Sprintf("Delete temp folder for %s", keptnEvent.Context))
fmt.Sprintf("Delete temp folder for %s", keptnEvent.Context)
}

return nil
}

//
// Handles DeploymentFinishedEventType = "sh.keptn.events.deployment-finished"
// TODO: add in your handler code
//
func HandleDeploymentFinishedEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.DeploymentFinishedEventData) error {
//log.Printf("Handling Deployment Finished Event: %s", incomingEvent.Context.GetID())
return nil
}

//
// Handles TestsFinishedEventType = "sh.keptn.events.tests-finished"
// TODO: add in your handler code
//
func HandleTestsFinishedEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.TestsFinishedEventData) error {
//log.Printf("Handling Tests Finished Event: %s", incomingEvent.Context.GetID())

return nil
}

//
// Handles EvaluationDoneEventType = "sh.keptn.events.evaluation-done"
// TODO: add in your handler code
//
func HandleStartEvaluationEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.StartEvaluationEventData) error {
//log.Printf("Handling Start Evaluation Event: %s", incomingEvent.Context.GetID())

return nil
}

//
// Handles DeploymentFinishedEventType = "sh.keptn.events.deployment-finished"
// TODO: add in your handler code
//
func HandleEvaluationDoneEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.EvaluationDoneEventData) error {
//log.Printf("Handling Evaluation Done Event: %s", incomingEvent.Context.GetID())

return nil
}

//
// Handles InternalGetSLIEventType = "sh.keptn.internal.event.get-sli"
// TODO: add in your handler code
//
func HandleInternalGetSLIEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.InternalGetSLIEventData) error {

return nil
}

//
// Handles ProblemOpenEventType = "sh.keptn.event.problem.open"
// Handles ProblemEventType = "sh.keptn.events.problem"
// TODO: add in your handler code
//
func HandleProblemEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.ProblemEventData) error {
//log.Printf("Handling Problem Event: %s", incomingEvent.Context.GetID())
// Deprecated since Keptn 0.7.0 - use the HandleActionTriggeredEvent instead
return nil
}
finishedData := &keptnv2.EventData{
Status: keptnv2.StatusSucceeded,
Result: keptnv2.ResultPass,
Message: "Successfully ran monaco!",
}
_, err = myKeptn.SendTaskFinishedEvent(finishedData, ServiceName)

//
// Handles ActionTriggeredEventType = "sh.keptn.event.action.triggered"
// TODO: add in your handler code
//
func HandleActionTriggeredEvent(myKeptn *keptn.Keptn, incomingEvent cloudevents.Event, data *keptn.ActionTriggeredEventData) error {
//log.Printf("Handling Action Triggered Event: %s", incomingEvent.Context.GetID())
return nil
}

func getDynatraceCredentials(secretName string, project string, logger *keptnlog.Logger) (*common.DTCredentials, error) {
func getDynatraceCredentials(secretName string, project string) (*common.DTCredentials, error) {

secretNames := []string{secretName, fmt.Sprintf("dynatrace-credentials-%s", project), "dynatrace-credentials", "dynatrace"}

Expand All @@ -190,21 +146,21 @@ func getDynatraceCredentials(secretName string, project string, logger *keptnlog

dtCredentials, err := common.GetDTCredentials(secret)

if err != nil {
logger.Error(fmt.Sprintf("Error retrieving secret '%s': %v", secret, err))
}
/* if err != nil {
fmt.Println("Error retrieving secret '%s': %v", secret, err)
}*/

if err == nil && dtCredentials != nil {
// lets validate if the tenant URL is
logger.Info(fmt.Sprintf("Secret '%s' with credentials found, returning (%s) ...", secret, dtCredentials.Tenant))
fmt.Println("Secret '%s' with credentials found, returning (%s) ...", secret, dtCredentials.Tenant)
return dtCredentials, nil
}
}

return nil, errors.New("Could not find any Dynatrace specific secrets with the following names: " + strings.Join(secretNames, ","))
}

func callMonaco(dtCredentials *common.DTCredentials, keptnEvent *common.BaseKeptnEvent, projects string, logger *keptnlog.Logger) error {
func callMonaco(dtCredentials *common.DTCredentials, keptnEvent *common.BaseKeptnEvent, projects string) error {

// Get Env-Variables on whether we should first do a dry run and whether we should do verbose
verboseString := os.Getenv("MONACO_VERBOSE_MODE")
Expand Down
14 changes: 5 additions & 9 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
module github.com/kristofre/monaco-service
module github.com/keptn-sandbox/monaco-service

go 1.13

require (
github.com/cloudevents/sdk-go v1.1.2
github.com/ghodss/yaml v1.0.0
github.com/cloudevents/sdk-go/v2 v2.3.1
github.com/go-openapi/jsonreference v0.19.3 // indirect
github.com/kelseyhightower/envconfig v1.4.0
github.com/keptn-contrib/dynatrace-sli-service v0.0.0-20201109135042-2f782ba7aa70
github.com/keptn/go-utils v0.7.2-alpha
github.com/keptn/go-utils v0.8.0
github.com/onsi/ginkgo v1.12.0 // indirect
github.com/onsi/gomega v1.9.0 // indirect
golang.org/x/mod v0.3.0
gopkg.in/yaml.v2 v2.3.0
k8s.io/api v0.17.2
gopkg.in/yaml.v2 v2.4.0
k8s.io/apimachinery v0.17.2
k8s.io/cli-runtime v0.17.2
k8s.io/client-go v0.17.2
)
Loading

0 comments on commit 290c96a

Please sign in to comment.