generated from keptn-sandbox/keptn-service-template-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
192 lines (165 loc) · 6.73 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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
cloudevents "github.com/cloudevents/sdk-go/v2" // make sure to use v2 cloudevents here
"github.com/kelseyhightower/envconfig"
keptn "github.com/keptn/go-utils/pkg/lib/keptn"
keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0"
)
var keptnOptions = keptn.KeptnOpts{}
type envConfig struct {
// Port on which to listen for cloudevents
Port int `envconfig:"RCV_PORT" default:"8080"`
// Path to which cloudevents are sent
Path string `envconfig:"RCV_PATH" default:"/"`
// Whether we are running locally (e.g., for testing) or on production
Env string `envconfig:"ENV" default:"local"`
// URL of the Keptn configuration service (this is where we can fetch files from the config repo)
ConfigurationServiceUrl string `envconfig:"CONFIGURATION_SERVICE" default:""`
}
// ServiceName specifies the current services name (e.g., used as source when sending CloudEvents)
const ServiceName = "artillery-service"
/**
* Parses a Keptn Cloud Event payload (data attribute)
*/
func parseKeptnCloudEventPayload(event cloudevents.Event, data interface{}) error {
err := event.DataAs(data)
if err != nil {
log.Fatalf("Got Data Error: %s", err.Error())
return err
}
return nil
}
/**
* This method gets called when a new event is received from the Keptn Event Distributor
* Depending on the Event Type will call the specific event handler functions, e.g: handleDeploymentFinishedEvent
* See https://github.com/keptn/spec/blob/0.2.0-alpha/cloudevents.md for details on the payload
*/
func processKeptnCloudEvent(ctx context.Context, event cloudevents.Event) error {
// create keptn handler
log.Printf("Initializing Keptn Handler")
myKeptn, err := keptnv2.NewKeptn(&event, keptnOptions)
if err != nil {
return errors.New("Could not create Keptn Handler: " + err.Error())
}
log.Printf("gotEvent(%s): %s - %s", event.Type(), myKeptn.KeptnContext, event.Context.GetID())
if err != nil {
log.Printf("failed to parse incoming cloudevent: %v", err)
return err
}
/**
* CloudEvents types in Keptn 0.8.0 follow the following pattern:
* - sh.keptn.event.${EVENTNAME}.triggered
* - sh.keptn.event.${EVENTNAME}.started
* - sh.keptn.event.${EVENTNAME}.status.changed
* - sh.keptn.event.${EVENTNAME}.finished
*
* For convenience, types can be generated using the following methods:
* - triggered: keptnv2.GetTriggeredEventType(${EVENTNAME}) (e.g,. keptnv2.GetTriggeredEventType(keptnv2.DeploymentTaskName))
* - started: keptnv2.GetStartedEventType(${EVENTNAME}) (e.g,. keptnv2.GetStartedEventType(keptnv2.DeploymentTaskName))
* - status.changed: keptnv2.GetStatusChangedEventType(${EVENTNAME}) (e.g,. keptnv2.GetStatusChangedEventType(keptnv2.DeploymentTaskName))
* - finished: keptnv2.GetFinishedEventType(${EVENTNAME}) (e.g,. keptnv2.GetFinishedEventType(keptnv2.DeploymentTaskName))
*
* The following Cloud Events are reserved and specified in the Keptn spec:
* - approval
* - deployment
* - test
* - evaluation
* - release
* - remediation
* - action
* - get-sli (for quality-gate SLI providers)
* - problem / problem.open (both deprecated, use action or remediation instead)
* There are more "internal" Cloud Events that might not have all four status, e.g.:
* - project
* - project.create
* - service
* - service.create
* - configure-monitoring
*
* For those Cloud Events the keptn/go-utils library conveniently provides several data structures
* and strings in github.com/keptn/go-utils/pkg/lib/v0_2_0, e.g.:
* - deployment: DeploymentTaskName, DeploymentTriggeredEventData, DeploymentStartedEventData, DeploymentFinishedEventData
* - test: TestTaskName, TestTriggeredEventData, TestStartedEventData, TestFinishedEventData
* - ... (they all follow the same pattern)
*
*
* In most cases you will be interested in processing .triggered events (e.g., sh.keptn.event.deployment.triggered),
* which you an achieve as follows:
* if event.type() == keptnv2.GetTriggeredEventType(keptnv2.DeploymentTaskName) { ... }
*
* Processing the event payload can be achieved as follows:
*
* eventData := &keptnv2.DeploymentTriggeredEventData{}
* parseKeptnCloudEventPayload(event, eventData)
*
* See https://github.com/keptn/spec/blob/0.2.0-alpha/cloudevents.md for more details of Keptn Cloud Events and their payload
* Also, see https://github.com/keptn-sandbox/echo-service/blob/a90207bc119c0aca18368985c7bb80dea47309e9/pkg/events.go as an example how to create your own CloudEvents
**/
/**
* The following code presents a very generic implementation of processing almost all possible
* Cloud Events that are retrieved by this service.
* Please follow the documentation provided above for more guidance on the different types.
* Feel free to delete parts that you don't need.
**/
switch event.Type() {
// -------------------------------------------------------
// sh.keptn.event.test
case keptnv2.GetTriggeredEventType(keptnv2.TestTaskName): // sh.keptn.event.test.triggered
log.Printf("Processing Test.Triggered Event")
eventData := &keptnv2.TestTriggeredEventData{}
parseKeptnCloudEventPayload(event, eventData)
return HandleTestTriggeredEvent(myKeptn, event, eventData)
}
// Unknown Event -> Throw Error!
var errorMsg string
errorMsg = fmt.Sprintf("Unhandled Keptn Cloud Event: %s", event.Type())
log.Print(errorMsg)
return errors.New(errorMsg)
}
/**
* Usage: ./main
* no args: starts listening for cloudnative events on localhost:port/path
*
* Environment Variables
* env=runlocal -> will fetch resources from local drive instead of configuration service
*/
func main() {
var env envConfig
if err := envconfig.Process("", &env); err != nil {
log.Fatalf("Failed to process env var: %s", err)
}
os.Exit(_main(os.Args[1:], env))
}
/**
* Opens up a listener on localhost:port/path and passes incoming requets to gotEvent
*/
func _main(args []string, env envConfig) int {
// configure keptn options
if env.Env == "local" {
log.Println("env=local: Running with local filesystem to fetch resources")
keptnOptions.UseLocalFileSystem = true
}
keptnOptions.ConfigurationServiceURL = env.ConfigurationServiceUrl
log.Printf("Starting %s...\n", ServiceName)
log.Printf(" on Port = %d; Path=%s", env.Port, env.Path)
ctx := context.Background()
ctx = cloudevents.WithEncodingStructured(ctx)
log.Printf("Creating new http handler")
// configure http server to receive cloudevents
p, err := cloudevents.NewHTTP(cloudevents.WithPath(env.Path), cloudevents.WithPort(env.Port))
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.Printf("Starting receiver")
log.Fatal(c.StartReceiver(ctx, processKeptnCloudEvent))
return 0
}