Debian Codegraph @

rundeck/job.go

raw symbols SCIP
1 package rundeck
2
3 import (
4 "encoding/xml"
5 "fmt"
6 "strings"
7 )
8
9 // JobSummary is an abbreviated description of a job that includes only its basic
10 // descriptive information and identifiers.
11 type JobSummary struct {
12 XMLName xml.Name `xml:"job"`
13 ID string `xml:"id,attr"`
14 Name string `xml:"name"`
15 GroupName string `xml:"group"`
16 ProjectName string `xml:"project"`
17 Description string `xml:"description,omitempty"`
18 }
19
20 type jobSummaryList struct {
21 XMLName xml.Name `xml:"jobs"`
22 Jobs []JobSummary `xml:"job"`
23 }
24
25 // JobDetail is a comprehensive description of a job, including its entire definition.
26 type JobDetail struct {
27 XMLName xml.Name `xml:"job"`
28 ID string `xml:"uuid,omitempty"`
29 Name string `xml:"name"`
30 GroupName string `xml:"group,omitempty"`
31 ProjectName string `xml:"context>project,omitempty"`
32 OptionsConfig *JobOptions `xml:"context>options,omitempty"`
33 Description string `xml:"description"`
34 ExecutionEnabled bool `xml:"executionEnabled"`
35 LogLevel string `xml:"loglevel,omitempty"`
36 AllowConcurrentExecutions bool `xml:"multipleExecutions,omitempty"`
37 Dispatch *JobDispatch `xml:"dispatch,omitempty"`
38 CommandSequence *JobCommandSequence `xml:"sequence,omitempty"`
39 Notification *JobNotification `xml:"notification,omitempty"`
40 Timeout string `xml:"timeout,omitempty"`
41 Retry string `xml:"retry,omitempty"`
42 NodeFilter *JobNodeFilter `xml:"nodefilters,omitempty"`
43
44 /* If Dispatch is enabled, nodesSelectedByDefault is always present with true/false.
45 * by this reason omitempty cannot be present.
46 * This has to be handle by the user.
47 */
48 NodesSelectedByDefault *Boolean `xml:"nodesSelectedByDefault"`
49 Schedule *JobSchedule `xml:"schedule,omitempty"`
50 ScheduleEnabled bool `xml:"scheduleEnabled"`
51 }
52
53 type Boolean struct {
54 Value bool `xml:",chardata"`
55 }
56
57 type JobNotification struct {
58 OnFailure *Notification `xml:"onfailure,omitempty"`
59 OnStart *Notification `xml:"onstart,omitempty"`
60 OnSuccess *Notification `xml:"onsuccess,omitempty"`
61 }
62
63 type Notification struct {
64 Email *EmailNotification `xml:"email,omitempty"`
65 WebHook *WebHookNotification `xml:"webhook,omitempty"`
66 Plugin *JobPlugin `xml:"plugin"`
67 }
68
69 type EmailNotification struct {
70 AttachLog bool `xml:"attachLog,attr,omitempty"`
71 Recipients NotificationEmails `xml:"recipients,attr"`
72 Subject string `xml:"subject,attr"`
73 }
74
75 type NotificationEmails []string
76
77 type WebHookNotification struct {
78 Urls NotificationUrls `xml:"urls,attr"`
79 }
80
81 type NotificationUrls []string
82
83 type JobSchedule struct {
84 XMLName xml.Name `xml:"schedule"`
85 DayOfMonth *JobScheduleDayOfMonth `xml:"dayofmonth,omitempty"`
86 Time JobScheduleTime `xml:"time"`
87 Month JobScheduleMonth `xml:"month"`
88 WeekDay *JobScheduleWeekDay `xml:"weekday,omitempty"`
89 Year JobScheduleYear `xml:"year"`
90 }
91
92 type JobScheduleDayOfMonth struct {
93 XMLName xml.Name `xml:"dayofmonth"`
94 }
95
96 type JobScheduleMonth struct {
97 XMLName xml.Name `xml:"month"`
98 Day string `xml:"day,attr,omitempty"`
99 Month string `xml:"month,attr"`
100 }
101
102 type JobScheduleYear struct {
103 XMLName xml.Name `xml:"year"`
104 Year string `xml:"year,attr"`
105 }
106
107 type JobScheduleWeekDay struct {
108 XMLName xml.Name `xml:"weekday"`
109 Day string `xml:"day,attr"`
110 }
111
112 type JobScheduleTime struct {
113 XMLName xml.Name `xml:"time"`
114 Hour string `xml:"hour,attr"`
115 Minute string `xml:"minute,attr"`
116 Seconds string `xml:"seconds,attr"`
117 }
118
119 type jobDetailList struct {
120 XMLName xml.Name `xml:"joblist"`
121 Jobs []JobDetail `xml:"job"`
122 }
123
124 // JobOptions represents the set of options on a job, if any.
125 type JobOptions struct {
126 PreserveOrder bool `xml:"preserveOrder,attr,omitempty"`
127 Options []JobOption `xml:"option"`
128 }
129
130 // JobOption represents a single option on a job.
131 type JobOption struct {
132 XMLName xml.Name `xml:"option"`
133
134 // If AllowsMultipleChoices is set, the string that will be used to delimit the multiple
135 // chosen options.
136 MultiValueDelimiter string `xml:"delimiter,attr,omitempty"`
137
138 // If set, Rundeck will reject values that are not in the set of predefined choices.
139 RequirePredefinedChoice bool `xml:"enforcedvalues,attr,omitempty"`
140
141 // When either ValueChoices or ValueChoicesURL is set, controls whether more than one
142 // choice may be selected as the value.
143 AllowsMultipleValues bool `xml:"multivalued,attr,omitempty"`
144
145 // The name of the option, which can be used to interpolate its value
146 // into job commands.
147 Name string `xml:"name,attr,omitempty"`
148
149 // Regular expression to be used to validate the option value.
150 ValidationRegex string `xml:"regex,attr,omitempty"`
151
152 // If set, Rundeck requires a value to be set for this option.
153 IsRequired bool `xml:"required,attr,omitempty"`
154
155 // If set, the input for this field will be obscured in the UI. Useful for passwords
156 // and other secrets.
157 ObscureInput bool `xml:"secure,attr,omitempty"`
158
159 // If ObscureInput is set, StoragePath can be used to point out credentials.
160 StoragePath string `xml:"storagePath,attr,omitempty"`
161
162 // The default value of the option.
163 DefaultValue string `xml:"value,attr,omitempty"`
164
165 // If set, the value can be accessed from scripts.
166 ValueIsExposedToScripts bool `xml:"valueExposed,attr,omitempty"`
167
168 // A sequence of predefined choices for this option. Mutually exclusive with ValueChoicesURL.
169 ValueChoices JobValueChoices `xml:"values,attr"`
170
171 // A URL from which the predefined choices for this option will be retrieved.
172 // Mutually exclusive with ValueChoices
173 ValueChoicesURL string `xml:"valuesUrl,attr,omitempty"`
174
175 // Description of the value to be shown in the Rundeck UI.
176 Description string `xml:"description,omitempty"`
177 }
178
179 // JobValueChoices is a specialization of []string representing a sequence of predefined values
180 // for a job option.
181 type JobValueChoices []string
182
183 // JobCommandSequence describes the sequence of operations that a job will perform.
184 type JobCommandSequence struct {
185 XMLName xml.Name `xml:"sequence"`
186
187 // If set, Rundeck will continue with subsequent commands after a command fails.
188 ContinueOnError bool `xml:"keepgoing,attr"`
189
190 // Chooses the strategy by which Rundeck will execute commands. Can either be "node-first" or
191 // "step-first".
192 OrderingStrategy string `xml:"strategy,attr,omitempty"`
193
194 // Sequence of commands to run in the sequence.
195 Commands []JobCommand `xml:"command"`
196
197 // Description
198 Description string `xml:"description,omitempty"`
199 }
200
201 // JobCommand describes a particular command to run within the sequence of commands on a job.
202 // The members of this struct are mutually-exclusive except for the pair of ScriptFile and
203 // ScriptFileArgs.
204 type JobCommand struct {
205 XMLName xml.Name
206
207 // If the Workflow keepgoing is false, this allows the Workflow to continue when the Error Handler is successful.
208 ContinueOnError bool `xml:"keepgoingOnSuccess,attr,omitempty"`
209
210 // Description
211 Description string `xml:"description,omitempty"`
212
213 // On error:
214 ErrorHandler *JobCommand `xml:"errorhandler,omitempty"`
215
216 // A literal shell command to run.
217 ShellCommand string `xml:"exec,omitempty"`
218
219 // Add extension to the temporary filename.
220 FileExtension string `xml:"fileExtension,omitempty"`
221
222 // An inline program to run. This will be written to disk and executed, so if it is
223 // a shell script it should have an appropriate #! line.
224 Script string `xml:"script,omitempty"`
225
226 // A pre-existing file (on the target nodes) that will be executed.
227 ScriptFile string `xml:"scriptfile,omitempty"`
228
229 // When ScriptFile is set, the arguments to provide to the script when executing it.
230 ScriptFileArgs string `xml:"scriptargs,omitempty"`
231
232 // ScriptInterpreter is used to execute (Script)File with.
233 ScriptInterpreter *JobCommandScriptInterpreter `xml:"scriptinterpreter,omitempty"`
234
235 // A reference to another job to run as this command.
236 Job *JobCommandJobRef `xml:"jobref"`
237
238 // Configuration for a step plugin to run as this command.
239 StepPlugin *JobPlugin `xml:"step-plugin"`
240
241 // Configuration for a node step plugin to run as this command.
242 NodeStepPlugin *JobPlugin `xml:"node-step-plugin"`
243 }
244
245 // (Inline) Script interpreter
246 type JobCommandScriptInterpreter struct {
247 XMLName xml.Name `xml:"scriptinterpreter"`
248 InvocationString string `xml:",chardata"`
249 ArgsQuoted bool `xml:"argsquoted,attr,omitempty"`
250 }
251
252 // JobCommandJobRef is a reference to another job that will run as one of the commands of a job.
253 type JobCommandJobRef struct {
254 XMLName xml.Name `xml:"jobref"`
255 Name string `xml:"name,attr"`
256 GroupName string `xml:"group,attr"`
257 RunForEachNode bool `xml:"nodeStep,attr"`
258 Dispatch *JobDispatch `xml:"dispatch,omitempty"`
259 NodeFilter *JobNodeFilter `xml:"nodefilters,omitempty"`
260 Arguments JobCommandJobRefArguments `xml:"arg"`
261 }
262
263 // JobCommandJobRefArguments is a string representing the arguments in a JobCommandJobRef.
264 type JobCommandJobRefArguments string
265
266 // Plugin is a configuration for a plugin to run within a job or notification.
267 type JobPlugin struct {
268 XMLName xml.Name
269 Type string `xml:"type,attr"`
270 Config JobPluginConfig `xml:"configuration"`
271 }
272
273 // JobPluginConfig is a specialization of map[string]string for job plugin configuration.
274 type JobPluginConfig map[string]string
275
276 // JobNodeFilter describes which nodes from the project's resource list will run the configured
277 // commands.
278 type JobNodeFilter struct {
279 Query string `xml:"filter,omitempty"`
280 }
281
282 type jobImportResults struct {
283 Succeeded jobImportResultsCategory `xml:"succeeded"`
284 Failed jobImportResultsCategory `xml:"failed"`
285 Skipped jobImportResultsCategory `xml:"skipped"`
286 }
287
288 type jobImportResultsCategory struct {
289 Count int `xml:"count,attr"`
290 Results []jobImportResult `xml:"job"`
291 }
292
293 type jobImportResult struct {
294 ID string `xml:"id,omitempty"`
295 Name string `xml:"name"`
296 GroupName string `xml:"group,omitempty"`
297 ProjectName string `xml:"context>project,omitempty"`
298 Error string `xml:"error"`
299 }
300
301 type JobDispatch struct {
302 ExcludePrecedence *Boolean `xml:"excludePrecedence"`
303 MaxThreadCount int `xml:"threadcount,omitempty"`
304 ContinueOnError bool `xml:"keepgoing"`
305 RankAttribute string `xml:"rankAttribute,omitempty"`
306 RankOrder string `xml:"rankOrder,omitempty"`
307 }
308
309 // GetJobSummariesForProject returns summaries of the jobs belonging to the named project.
310 func (c *Client) GetJobSummariesForProject(projectName string) ([]JobSummary, error) {
311 jobList := &jobSummaryList{}
312 err := c.get([]string{"project", projectName, "jobs"}, nil, jobList)
313 return jobList.Jobs, err
314 }
315
316 // GetJobsForProject returns the full job details of the jobs belonging to the named project.
317 func (c *Client) GetJobsForProject(projectName string) ([]JobDetail, error) {
318 jobList := &jobDetailList{}
319 err := c.get([]string{"jobs", "export"}, map[string]string{"project": projectName}, jobList)
320 if err != nil {
321 return nil, err
322 }
323 return jobList.Jobs, nil
324 }
325
326 // GetJob returns the full job details of the job with the given id.
327 func (c *Client) GetJob(id string) (*JobDetail, error) {
328 jobList := &jobDetailList{}
329 err := c.get([]string{"job", id}, nil, jobList)
330 if err != nil {
331 return nil, err
332 }
333 return &jobList.Jobs[0], nil
334 }
335
336 // CreateJob creates a new job based on the provided structure.
337 func (c *Client) CreateJob(job *JobDetail) (*JobSummary, error) {
338 return c.importJob(job, "create")
339 }
340
341 // CreateOrUpdateJob takes a job detail structure which has its ID set and either updates
342 // an existing job with the same id or creates a new job with that id.
343 func (c *Client) CreateOrUpdateJob(job *JobDetail) (*JobSummary, error) {
344 return c.importJob(job, "update")
345 }
346
347 func (c *Client) importJob(job *JobDetail, dupeOption string) (*JobSummary, error) {
348 jobList := &jobDetailList{
349 Jobs: []JobDetail{*job},
350 }
351 args := map[string]string{
352 "format": "xml",
353 "dupeOption": dupeOption,
354 "uuidOption": "preserve",
355 }
356 result := &jobImportResults{}
357 err := c.postXMLBatch([]string{"jobs", "import"}, args, jobList, result)
358 if err != nil {
359 return nil, err
360 }
361
362 if result.Failed.Count > 0 {
363 errMsg := result.Failed.Results[0].Error
364 return nil, fmt.Errorf(errMsg)
365 }
366
367 if result.Succeeded.Count != 1 {
368 // Should never happen, since we send nothing in the request
369 // that should cause a job to be skipped.
370 return nil, fmt.Errorf("job was skipped")
371 }
372
373 return result.Succeeded.Results[0].JobSummary(), nil
374 }
375
376 // DeleteJob deletes the job with the given id.
377 func (c *Client) DeleteJob(id string) error {
378 return c.delete([]string{"job", id})
379 }
380
381 func (c NotificationEmails) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
382 if len(c) > 0 {
383 return xml.Attr{name, strings.Join(c, ",")}, nil
384 } else {
385 return xml.Attr{}, nil
386 }
387 }
388
389 func (c *NotificationEmails) UnmarshalXMLAttr(attr xml.Attr) error {
390 values := strings.Split(attr.Value, ",")
391 *c = values
392 return nil
393 }
394
395 func (c NotificationUrls) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
396 if len(c) > 0 {
397 return xml.Attr{name, strings.Join(c, ",")}, nil
398 } else {
399 return xml.Attr{}, nil
400 }
401 }
402
403 func (c *NotificationUrls) UnmarshalXMLAttr(attr xml.Attr) error {
404 values := strings.Split(attr.Value, ",")
405 *c = values
406 return nil
407 }
408
409 func (c JobValueChoices) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
410 if len(c) > 0 {
411 return xml.Attr{name, strings.Join(c, ",")}, nil
412 } else {
413 return xml.Attr{}, nil
414 }
415 }
416
417 func (c *JobValueChoices) UnmarshalXMLAttr(attr xml.Attr) error {
418 values := strings.Split(attr.Value, ",")
419 *c = values
420 return nil
421 }
422
423 func (a JobCommandJobRefArguments) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
424 start.Attr = []xml.Attr{
425 xml.Attr{xml.Name{Local: "line"}, string(a)},
426 }
427 e.EncodeToken(start)
428 e.EncodeToken(xml.EndElement{start.Name})
429 return nil
430 }
431
432 func (a *JobCommandJobRefArguments) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
433 type jobRefArgs struct {
434 Line string `xml:"line,attr"`
435 }
436 args := jobRefArgs{}
437 d.DecodeElement(&args, &start)
438
439 *a = JobCommandJobRefArguments(args.Line)
440
441 return nil
442 }
443
444 func (c JobPluginConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
445 rc := map[string]string(c)
446 return marshalMapToXML(&rc, e, start, "entry", "key", "value")
447 }
448
449 func (c *JobPluginConfig) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
450 rc := (*map[string]string)(c)
451 return unmarshalMapFromXML(rc, d, start, "entry", "key", "value")
452 }
453
454 // JobSummary produces a JobSummary instance with values populated from the import result.
455 // The summary object won't have its Description populated, since import results do not
456 // include descriptions.
457 func (r *jobImportResult) JobSummary() *JobSummary {
458 return &JobSummary{
459 ID: r.ID,
460 Name: r.Name,
461 GroupName: r.GroupName,
462 ProjectName: r.ProjectName,
463 }
464 }