-
Notifications
You must be signed in to change notification settings - Fork 23
/
pipelines.go
245 lines (208 loc) · 7.97 KB
/
pipelines.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
package shuffle
import (
"encoding/json"
"context"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/google/uuid"
)
// Pipeline is a sequence of stages that are executed in order.
// We will deploy the pipeline to run something from Orborus by adding it to the Orborus queue to be handled
func HandleNewPipelineRegister(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
// Removed check here as it may be a public workflow
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[AUDIT] Api authentication failed in getting specific workflow: %s. Continuing because it may be public.", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Role == "org-reader" {
resp.WriteHeader(403)
resp.Write([]byte(`{"success": false, "reason": "You do not have permission to register a new pipeline."}`))
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("[WARNING] Error with body read in new pipeline: %s", err)
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false}`))
return
}
var pipeline PipelineRequest
err = json.Unmarshal(body, &pipeline)
if err != nil {
log.Printf("[WARNING] Failed new pipeline unmarshal: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("[AUDIT] User %s in org %s (%s) is creating a new pipeline with command '%s' in environment '%s'", user.Username, user.ActiveOrg.Name, user.ActiveOrg.Id, pipeline.Type, pipeline.Environment)
if len(pipeline.Name) < 1 {
log.Printf("[WARNING] Name is required for new pipelines")
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Name is required"}`))
return
}
if len(pipeline.Environment) < 1 {
log.Printf("[WARNING] Environment is required for new pipelines")
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Environment is required"}`))
return
}
pipeline.Environment = strings.TrimSpace(pipeline.Environment)
if strings.ToLower(pipeline.Environment) == "cloud" {
log.Printf("[WARNING] Cloud is not a valid environment")
resp.WriteHeader(400)
resp.Write([]byte(`{"success": false, "reason": "Cloud is not a valid environment. Choose one of your Organizations' environments."}`))
return
}
ctx := GetContext(request)
environments, err := GetEnvironments(ctx, user.ActiveOrg.Id)
if err != nil {
log.Printf("[WARNING] Error getting environments: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
envFound := false
for _, env := range environments {
if env.Name == pipeline.Environment {
envFound = true
break
}
}
if !envFound && pipeline.Type != "delete"{
log.Printf("[WARNING] Environment '%s' is not available", pipeline.Environment)
resp.WriteHeader(400)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Environment '%s' is not available. Please make it, or change the environment you want to deploy to."}`, pipeline.Environment)))
return
}
availableCommands := []string{
"create", "delete", "start", "stop",
}
matchingCommand := ""
for _, command := range availableCommands {
if strings.HasPrefix(strings.ToLower(pipeline.Type), command) {
matchingCommand = command
break
}
}
if len(matchingCommand) == 0 {
log.Printf("[WARNING] Command Type '%s' is not available for %s (%s)", pipeline.Type, user.ActiveOrg.Name, user.ActiveOrg.Id)
resp.WriteHeader(400)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Command type '%s' is not available"}`, pipeline.Type)))
return
}
// Look for PIPELINE_ command that exists in the queue already
startCommand := strings.ToUpper(strings.Split(pipeline.Type, " ")[0])
//check if this is the first time creating the pipeline
pipelineInfo, err := GetPipeline(ctx, pipeline.TriggerId)
if err != nil {
if (startCommand == "DELETE" || startCommand == "STOP") && err.Error() == "pipeline doesn't exist" {
log.Printf("[WARNING] Failed getting pipeline %s, reason: %s", pipeline.TriggerId, err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
} else if startCommand == "START" && err.Error() == "pipeline doesn't exist" {
startCommand = "CREATE"
}
} else if startCommand == "CREATE" {
startCommand = "START"
}
//parsedId := fmt.Sprintf("%s_%s", strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(pipeline.Environment, " ", "-"), "_", "-")), user.ActiveOrg.Id)
parsedEnv := fmt.Sprintf("%s_%s", strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(pipeline.Environment, " ", "-"), "_", "-")), user.ActiveOrg.Id)
if project.Environment != "cloud" {
parsedEnv = strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(pipeline.Environment, " ", "-"), "_", "-"))
}
formattedType := fmt.Sprintf("PIPELINE_%s", startCommand)
existingQueue, _ := GetWorkflowQueue(ctx, parsedEnv, 10)
for _, queue := range existingQueue.Data {
if strings.HasPrefix(queue.Type, "PIPELINE") {
//log.Printf("[WARNING] Pipeline type already exists: %s", formattedType)
//resp.WriteHeader(400)
//resp.Write([]byte(`{"success": false, "reason": "Pipeline type already exists. Please wait for existing Pipeline request to be fullfilled by Orborus (could take a few seconds)."}`))
//return
}
}
//log.Printf("[INFO] Pipeline type: %s", formattedType)
// 2. Send to environment queue
execRequest := ExecutionRequest{
Type: formattedType,
ExecutionId: uuid.New().String(),
ExecutionSource: pipeline.Name,
ExecutionArgument: pipeline.Command,
Priority: 11,
}
//log.Printf("EXECREQUEST: Type: %s, Source: %s, Argument: %s", execRequest.Type, execRequest.ExecutionSource, execRequest.ExecutionArgument)
pipelineData := Pipeline{}
if startCommand == "DELETE" {
err := deletePipeline(ctx, *pipelineInfo)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Failed deleting the pipeline."}`))
return
}
} else if startCommand == "STOP" {
pipelineInfo.Status = "stopped"
err = savePipelineData(ctx, *pipelineInfo)
if err != nil {
log.Printf("[ERROR] Failed to stop the pipeline with trigger id: %s, reason: %s", pipelineInfo.TriggerId, err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("[INFO] Stopped the pipeline successfully", pipelineInfo.ID)
} else {
pipelineData.Name = pipeline.Name
pipelineData.Type = startCommand
pipelineData.Command = pipeline.Command
pipelineData.Environment = pipeline.Environment
pipelineData.WorkflowId = pipeline.WorkflowId
pipelineData.OrgId = user.ActiveOrg.Id
pipelineData.Owner = user.Id
pipelineData.Status = "running"
pipelineData.TriggerId = pipeline.TriggerId
pipelineData.StartNode = pipeline.StartNode
pipelineData.Url = pipeline.Url
err = savePipelineData(ctx, pipelineData)
if err != nil {
log.Printf("[ERROR] Failed to create the pipeline with trigger id: %s, reason: %s", pipeline.TriggerId, err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("[INFO] Set up pipeline with trigger ID %s and environment %s", pipeline.TriggerId, pipeline.Environment)
}
err = SetWorkflowQueue(ctx, execRequest, parsedEnv)
if err != nil {
log.Printf("[ERROR] Failed setting workflow queue for env: %s", err)
resp.WriteHeader(500)
resp.Write([]byte(`{"success": false}`))
return
}
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true, "reason": "Pipeline handled successfully."}`))
}
func deletePipeline(ctx context.Context, pipeline Pipeline) error {
pipeline.Status = "stopped"
err := savePipelineData(ctx, pipeline)
if err != nil {
log.Printf("[WARNING] Failed saving pipeline: %s", err)
return err
}
err = DeleteKey(ctx, "pipelines", pipeline.TriggerId)
if err != nil {
log.Printf("[WARNING] Error deleting pipeline %s, reason: %s", pipeline.TriggerId, err)
return err
}
log.Printf("[INFO] Successfully deleted pipeline %s", pipeline.TriggerId)
return nil
}