/
ExecutionService.groovy
3969 lines (3667 loc) · 160 KB
/
ExecutionService.groovy
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rundeck.services
import com.dtolabs.rundeck.app.api.ApiVersions
import com.dtolabs.rundeck.app.internal.logging.LogFlusher
import com.dtolabs.rundeck.app.internal.workflow.MultiWorkflowExecutionListener
import com.dtolabs.rundeck.app.support.*
import com.dtolabs.rundeck.core.authorization.AuthContext
import com.dtolabs.rundeck.core.authorization.UserAndRolesAuthContext
import com.dtolabs.rundeck.core.common.*
import com.dtolabs.rundeck.core.data.SharedDataContextUtils
import com.dtolabs.rundeck.core.dispatcher.ContextView
import com.dtolabs.rundeck.core.dispatcher.DataContextUtils
import com.dtolabs.rundeck.core.execution.ExecutionContextImpl
import com.dtolabs.rundeck.core.execution.ExecutionListener
import com.dtolabs.rundeck.core.execution.StepExecutionItem
import com.dtolabs.rundeck.core.execution.WorkflowExecutionServiceThread
import com.dtolabs.rundeck.core.execution.service.NodeExecutorResultImpl
import com.dtolabs.rundeck.core.execution.workflow.*
import com.dtolabs.rundeck.core.execution.workflow.steps.*
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutionItem
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutor
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResult
import com.dtolabs.rundeck.core.logging.*
import com.dtolabs.rundeck.core.utils.NodeSet
import com.dtolabs.rundeck.core.utils.OptsUtil
import com.dtolabs.rundeck.core.utils.ThreadBoundOutputStream
import com.dtolabs.rundeck.execution.JobExecutionItem
import com.dtolabs.rundeck.execution.JobRefCommand
import com.dtolabs.rundeck.execution.JobReferenceFailureReason
import com.dtolabs.rundeck.plugins.ServiceNameConstants
import com.dtolabs.rundeck.plugins.logging.LogFilterPlugin
import com.dtolabs.rundeck.plugins.scm.JobChangeEvent
import com.dtolabs.rundeck.server.authorization.AuthConstants
import grails.events.EventPublisher
import grails.events.annotation.Subscriber
import grails.gorm.transactions.Transactional
import grails.web.mapping.LinkGenerator
import groovy.transform.ToString
import org.apache.commons.io.FileUtils
import org.apache.log4j.Logger
import org.apache.log4j.MDC
import org.hibernate.StaleObjectStateException
import org.rundeck.storage.api.StorageException
import org.rundeck.util.Sizes
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.MessageSource
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.TransactionDefinition
import org.springframework.dao.DuplicateKeyException
import org.springframework.validation.ObjectError
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.servlet.support.RequestContextUtils as RCU
import rundeck.*
import rundeck.services.events.ExecutionCompleteEvent
import rundeck.services.events.ExecutionPrepareEvent
import rundeck.services.logging.ExecutionLogWriter
import rundeck.services.logging.LoggingThreshold
import javax.annotation.PreDestroy
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession
import java.nio.charset.Charset
import java.text.DateFormat
import java.text.MessageFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.regex.Pattern
/**
* Coordinates Command executions via Ant Project objects
*/
@Transactional
class ExecutionService implements ApplicationContextAware, StepExecutor, NodeStepExecutor, EventPublisher {
static Logger executionStatusLogger = Logger.getLogger("org.rundeck.execution.status")
def FrameworkService frameworkService
def notificationService
def ScheduledExecutionService scheduledExecutionService
def ReportService reportService
def LoggingService loggingService
def WorkflowService workflowService
def StorageService storageService
def ThreadBoundOutputStream sysThreadBoundOut
def ThreadBoundOutputStream sysThreadBoundErr
def String defaultLogLevel
def ApplicationContext applicationContext
def metricService
def apiService
def grailsLinkGenerator
def logFileStorageService
MessageSource messageSource
def jobStateService
def rundeckNodeService
def grailsApplication
def configurationService
def executionUtilService
def fileUploadService
def pluginService
def executorService
static final ThreadLocal<DateFormat> ISO_8601_DATE_FORMAT_WITH_MS_XXX =
new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
}
}
static final ThreadLocal<DateFormat> ISO_8601_DATE_FORMAT_XXX =
new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
}
}
static final ThreadLocal<DateFormat> ISO_8601_DATE_FORMAT_WITH_MS =
new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
}
}
static final ThreadLocal<DateFormat> ISO_8601_DATE_FORMAT =
new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
}
}
boolean getExecutionsAreActive(){
configurationService.executionModeActive
}
void setExecutionsAreActive(boolean active){
configurationService.executionModeActive=active
if(!active){
log.info("Rundeck changed to PASSIVE mode: No executions can be run.")
}else{
log.info("Rundeck changed to ACTIVE: executions can be run.")
}
if(active){
scheduledExecutionService.rescheduleJobs(frameworkService.isClusterModeEnabled()?frameworkService.getServerUUID():null)
}else{
scheduledExecutionService.unscheduleJobs(frameworkService.isClusterModeEnabled()?frameworkService.getServerUUID():null)
}
}
private boolean applicationIsShutdown
public boolean isApplicationShutdown() {
return applicationIsShutdown
}
@PreDestroy
void cleanUp() {
applicationIsShutdown = true;
}
void initialize(){
//TODO: use plugin registry instead
//ExecutionService handles Job reference steps
final cis = frameworkService.rundeckFramework.stepExecutionService
cis.providerRegistryService.registerInstance(JobExecutionItem.STEP_EXECUTION_TYPE, this)
//ExecutionService handles Job reference node steps
final nis = frameworkService.rundeckFramework.nodeStepExecutorService
nis.providerRegistryService.registerInstance(JobExecutionItem.STEP_EXECUTION_TYPE, this)
}
/**
* Render execution document for api response
*/
public def respondExecutionsXml(HttpServletRequest request,HttpServletResponse response, List<Execution> executions, paging = [:]) {
def apiv14=request.api_version>=ApiVersions.V14
return apiService.respondExecutionsXml(request,response,executions.collect { Execution e ->
def data=[
execution: e,
href: apiv14?apiService.apiHrefForExecution(e):apiService.guiHrefForExecution(e),
status: getExecutionState(e),
summary: summarizeJob(e.scheduledExecution, e)
]
if(apiv14){
data.permalink=apiService.guiHrefForExecution(e)
}
if(e.customStatusString){
data.customStatus=e.customStatusString
}
if(e.retryExecution) {
data.retryExecution = [
id : e.retryExecution.id,
href : apiv14 ? apiService.apiHrefForExecution(e.retryExecution) :
apiService.guiHrefForExecution(e.retryExecution),
status: getExecutionState(e.retryExecution),
]
if (apiv14) {
data.retryExecution.permalink = apiService.guiHrefForExecution(e.retryExecution)
}
}
data
}, paging)
}
public def respondExecutionsJson(HttpServletRequest request,HttpServletResponse response, List<Execution> executions, paging = [:]) {
return apiService.respondExecutionsJson(request,response,executions.collect { Execution e ->
def data=[
execution: e,
permalink: apiService.guiHrefForExecution(e),
href: apiService.apiHrefForExecution(e),
status: getExecutionState(e),
summary: summarizeJob(e.scheduledExecution, e)
]
if(e.customStatusString){
data.customStatus=e.customStatusString
}
if(e.retryExecution){
data.retryExecution=[
id:e.retryExecution.id,
permalink: apiService.guiHrefForExecution(e.retryExecution),
href: apiService.apiHrefForExecution(e.retryExecution),
status: getExecutionState(e.retryExecution),
]
}
data
}, paging)
}
/**
* Render xml or json response data for the result of a call to {@link #deleteBulkExecutionIds(java.util.Collection, com.dtolabs.rundeck.core.authorization.AuthContext, java.lang.String)}
*
* @param request
* @param response
* @param result
* @return
*/
def renderBulkExecutionDeleteResult(request, response, result) {
def respFormat = apiService.extractResponseFormat(request, response, ['xml', 'json'])
def total = result.successTotal + result.failures.size()
switch (respFormat) {
case 'json':
return apiService.renderSuccessJson(response) {
requestCount = total
allsuccessful = result.successTotal == total
successCount = result.successTotal
failedCount = result.failures ? result.failures.size() : 0
if (result.failures) {
failures = result.failures.collect { [message: it.message, id: it.id] }
}
}
break
case 'xml':
default:
return apiService.renderSuccessXml(request, response) {
deleteExecutions(requestCount: total, allsuccessful: result.successTotal == total) {
successful(count: result.successTotal)
if (!result.success) {
failed(count: result.failures.size()) {
result.failures.each { failure ->
delegate.'execution'(id: failure.id, message: failure.message)
}
}
}
}
}
break;
}
}
def listLastExecutionsPerProject(AuthContext authContext, int max=5){
def projects = frameworkService.projectNames(authContext)
def c = Execution.createCriteria()
def lastexecs=[:]
projects.each { proj ->
def results = c.list {
eq("project",proj)
maxResults(max)
order("dateCompleted","desc")
}
lastexecs[proj]=results
}
return lastexecs
}
/**
* Return the last execution id in the project
* @param query
* @return
*/
def lastExecutionId(String project) {
def execs = Execution.createCriteria().get {
eq('project', project)
order('dateCompleted', 'desc')
maxResults(1)
projections {
property('id')
}
}
return execs ?: null
}
/**
* query queue, returns map [:]:
*
* query: query object
* _filters: map of used filter names-> properties
* jobs: map of ID to ScheduledExecution for matching jobs
* nowrunning: list of Executions
* total: total executions
*/
def queryQueue(QueueQuery query){
def eqfilters = [
proj: 'project',
]
def txtfilters = [
obj:'name',
type:'type',
cmd:'command',
user:'user',
]
def schedTxtFilters= [
job:'jobName',
]
def schedPathFilters=[
groupPath: 'groupPath'
]
def schedExactFilters= [
groupPathExact:'groupPath',
jobId:'uuid'
]
def schedFilterKeys= (schedExactFilters.keySet() + schedTxtFilters.keySet() + schedPathFilters.keySet())
def filters = [ :]
filters.putAll(txtfilters)
filters.putAll(eqfilters)
def Date endAfterDate = new Date(System.currentTimeMillis()-1000*60*60)
if(query && query.doendafterFilter){
endAfterDate = query.endafterFilter
}
def Date nowDate = new Date()
def allProjectsQuery=query.projFilter=='*';
def crit = Execution.createCriteria()
def runlist = crit.list{
if(query?.max){
maxResults(query.max.toInteger())
}else{
maxResults(grailsApplication.config.rundeck?.pagination?.default?.max ?
grailsApplication.config.rundeck.pagination.default.max.toInteger() :
20 )
}
if(query?.offset){
firstResult(query.offset.toInteger())
}
if(query ){
txtfilters.each{ key,val ->
if(query["${key}Filter"]){
ilike(val,'%'+query["${key}Filter"]+'%')
}
}
if(!allProjectsQuery){
eqfilters.each{ key,val ->
if(query["${key}Filter"]){
eq(val,query["${key}Filter"])
}
}
}
//running status filter.
if (query.runningFilter) {
if (EXECUTION_SCHEDULED == query.runningFilter) {
eq('status', EXECUTION_SCHEDULED)
} else if ('running' == query.runningFilter) {
isNull('dateCompleted')
} else {
and {
eq('status', 'completed' == query.runningFilter ? 'true' : 'false')
eq('cancelled', 'killed' == query.runningFilter ? 'true' : 'false')
isNotNull('dateCompleted')
}
}
}
def schedfilts=[:]
schedFilterKeys.each {
if( query["${it}Filter"]){
schedfilts[it]= query["${it}Filter"]
}
}
if(schedfilts.groupPath=='*'){
schedfilts.remove('groupPath')
}
if(schedfilts){
if(schedfilts['jobId'] == 'null'){
isNull('scheduledExecution')
}else{
scheduledExecution {
schedExactFilters.each{key,v->
if (query["${key}Filter"] == 'null') {
isNull(v)
} else if (query["${key}Filter"] == '!null') {
isNotNull(v)
} else if (query["${key}Filter"]) {
eq(v, query["${key}Filter"] )
}
}
schedTxtFilters.each{key,v->
if (query["${key}Filter"]) {
ilike(v, '%'+query["${key}Filter"] + '%')
}
}
schedPathFilters.each{key,v->
if (query["${key}Filter"]) {
ilike(v, query["${key}Filter"] + '%')
}
}
}
}
}
// if(query.dostartafterFilter && query.dostartbeforeFilter && query.startbeforeFilter && query.startafterFilter){
// between('dateStarted',query.startafterFilter,query.startbeforeFilter)
// }
// else if(query.dostartbeforeFilter && query.startbeforeFilter ){
// le('dateStarted',query.startbeforeFilter)
// }else if (query.dostartafterFilter && query.startafterFilter ){
// ge('dateStarted',query.startafterFilter)
// }
// if(query.doendafterFilter && query.doendbeforeFilter && query.endafterFilter && query.endbeforeFilter){
// between('dateCompleted',query.endafterFilter,query.endbeforeFilter)
// }
// else if(query.doendbeforeFilter && query.endbeforeFilter ){
// le('dateCompleted',query.endbeforeFilter)
// }
// if(query.doendafterFilter && query.endafterFilter ){
// or{
// between("dateCompleted", endAfterDate,nowDate)
isNull("dateCompleted")
// }
// }
}else{
// and {
// or{
// between("dateCompleted", endAfterDate,nowDate)
isNull("dateCompleted")
// }
// }
}
if(query && query.sortBy && filters[query.sortBy]){
order(filters[query.sortBy],query.sortOrder=='ascending'?'asc':'desc')
}else{
order("dateStarted","desc")
}
};
def currunning=[]
runlist.each{
currunning<<it
}
def jobs =[:]
currunning.each{
if(it.scheduledExecution && !jobs[it.scheduledExecution.id.toString()]){
jobs[it.scheduledExecution.id.toString()] = ScheduledExecution.get(it.scheduledExecution.id)
}
}
def total = Execution.createCriteria().count{
if(query ){
txtfilters.each{ key,val ->
if(query["${key}Filter"]){
ilike(val,'%'+query["${key}Filter"]+'%')
}
}
if(!allProjectsQuery){
eqfilters.each{ key,val ->
if(query["${key}Filter"]){
eq(val,query["${key}Filter"])
}
}
}
//running status filter.
if(query.runningFilter){
if('running'==query.runningFilter){
isNull("dateCompleted")
}else {
and{
eq('status',"completed"==query.runningFilter?'true':'false')
eq('cancelled',"killed"==query.runningFilter?'true':'false')
isNotNull('dateCompleted')
}
}
}
def schedfilts = [:]
schedFilterKeys.each {
if (query["${it}Filter"]) {
schedfilts[it] = query["${it}Filter"]
}
}
if (schedfilts.groupPath == '*') {
schedfilts.remove('groupPath')
}
if (schedfilts) {
if (schedfilts['jobId'] == 'null') {
isNull('scheduledExecution')
} else {
scheduledExecution {
schedExactFilters.each { key, v ->
if (query["${key}Filter"] == 'null') {
isNull(v)
} else if (query["${key}Filter"] == '!null') {
isNotNull(v)
} else if (query["${key}Filter"]) {
eq(v, query["${key}Filter"])
}
}
schedTxtFilters.each { key, v ->
if (query["${key}Filter"]) {
ilike(v, '%' + query["${key}Filter"] + '%')
}
}
schedPathFilters.each { key, v ->
if (query["${key}Filter"]) {
ilike(v, query["${key}Filter"] + '%')
}
}
}
}
}
isNull("dateCompleted")
}else{
isNull("dateCompleted")
}
};
return [query:query, _filters:filters,
jobs: jobs, nowrunning:currunning,
total: total]
}
def public finishQueueQuery(query,params,model){
if(!params.max){
params.max=20
}
if(!params.offset){
params.offset=0
}
def paginateParams=[:]
if(query){
model._filters.each{ key,val ->
if(params["${key}Filter"]){
paginateParams["${key}Filter"]=params["${key}Filter"]
}
}
}
def displayParams = [:]
displayParams.putAll(paginateParams)
params.each{key,val ->
if(key ==~ /^(start|end)(do|set|before|after)Filter.*/){
paginateParams[key]=val
}
}
if(query){
if(query.recentFilter && query.recentFilter!='-'){
displayParams.put("recentFilter",query.recentFilter)
paginateParams.put("recentFilter",query.recentFilter)
query.dostartafterFilter=false
query.dostartbeforeFilter=false
query.doendafterFilter=false
query.doendbeforeFilter=false
}else{
if(query.dostartafterFilter && query.startafterFilter){
displayParams.put("startafterFilter",query.startafterFilter)
paginateParams.put("dostartafterFilter","true")
}
if(query.dostartbeforeFilter && query.startbeforeFilter){
displayParams.put("startbeforeFilter",query.startbeforeFilter)
paginateParams.put("dostartbeforeFilter","true")
}
if(query.doendafterFilter && query.endafterFilter){
displayParams.put("endafterFilter",query.endafterFilter)
paginateParams.put("doendafterFilter","true")
}
if(query.doendbeforeFilter && query.endbeforeFilter){
displayParams.put("endbeforeFilter",query.endbeforeFilter)
paginateParams.put("doendbeforeFilter","true")
}
}
}
def remkeys=[]
if(!query || !query.dostartafterFilter){
paginateParams.each{key,val ->
if(key ==~ /^startafterFilter.*/){
remkeys.add(key)
}
}
}
if(!query || !query.dostartbeforeFilter){
paginateParams.each{key,val ->
if(key ==~ /^startbeforeFilter.*/){
remkeys.add(key)
}
}
}
if(!query || !query.doendafterFilter){
paginateParams.each{key,val ->
if(key ==~ /^endafterFilter.*/){
remkeys.add(key)
}
}
}
if(!query || !query.doendbeforeFilter){
paginateParams.each{key,val ->
if(key ==~ /^endbeforeFilter.*/){
remkeys.add(key)
}
}
}
remkeys.each{
paginateParams.remove(it)
}
def tmod=[max: query?.max?query.max:20,
offset:query?.offset?query.offset:0,
paginateParams:paginateParams,
displayParams:displayParams]
model.putAll(tmod)
return model
}
/**
* Return a dataset: [nowrunning: (list of Execution), jobs: [map of id->ScheduledExecution for scheduled jobs],
* total: total number of running executions, max: input max]
*/
def listNowRunning(Framework framework, int max=10){
//find currently running executions
def Date lastHour = new Date(System.currentTimeMillis()-1000*60*60)
def Date nowDate = new Date()
def crit = Execution.createCriteria()
def runlist = crit.list{
maxResults(max)
isNull("dateCompleted")
order("dateStarted","desc")
};
def currunning=[]
runlist.each{
currunning<<it
}
def jobs =[:]
currunning.each{
if(it.scheduledExecution && !jobs[it.scheduledExecution.id.toString()]){
jobs[it.scheduledExecution.id.toString()] = ScheduledExecution.get(it.scheduledExecution.id)
}
}
def total = Execution.createCriteria().count{
isNull("dateCompleted")
};
return [jobs: jobs, nowrunning:currunning, total: total, max: max]
}
/**
* Set the result status to FAIL for any Executions that are not complete,
* excludes executions which are still scheduled and haven't started.
*
* @param serverUUID if not null, only match executions assigned to the given serverUUID
*/
def cleanupRunningJobsAsync(String serverUUID = null, String status = null, Date before = new Date()) {
def executionIds = Execution.withCriteria {
isNotNull('dateStarted')
isNull('dateCompleted')
if (serverUUID == null) {
isNull('serverNodeUUID')
} else {
eq('serverNodeUUID', serverUUID)
}
lt('dateStarted', before)
or{
isNull('status')
ne('status', EXECUTION_SCHEDULED)
}
projections {
property('id')
}
}
executorService.submit {
def found = executionIds.collect { Execution.get(it) }
cleanupRunningJobs(found, status)
}
}
/**
* Find currently running executions. Excludes executions which are scheduled
* to run but have not started yet.
*
* @param serverUUID if not null, only match executions assigned to the given server UUID
*/
private List<Execution> findRunningExecutions(String serverUUID = null, Date before=new Date()) {
return Execution.withCriteria{
isNotNull('dateStarted')
isNull('dateCompleted')
if (serverUUID == null) {
isNull('serverNodeUUID')
} else {
eq('serverNodeUUID', serverUUID)
}
lt('dateStarted', before)
or{
isNull('status')
ne('status', EXECUTION_SCHEDULED)
}
}
}
/**
* Set the result status to FAIL for any Executions that are not complete
* @param serverUUID if not null, only match executions assigned to the given serverUUID
*/
def cleanupRunningJobs(String serverUUID = null, String status = null, Date before = new Date()) {
cleanupRunningJobs(findRunningExecutions(serverUUID, before), status)
}
/**
* Set the result status to FAIL for any Executions that are not complete
* @param serverUUID if not null, only match executions assigned to the given serverUUID
*/
def cleanupRunningJobs(List<Execution> found, String status = null) {
found.each { Execution e ->
cleanupExecution(e, status)
log.error("Stale Execution cleaned up: [${e.id}] in ${e.project}")
metricService.markMeter(this.class.name, 'executionCleanupMeter')
}
}
private void cleanupExecution(Execution e, String status = null) {
saveExecutionState(
e.scheduledExecution?.id,
e.id,
[
status : status ?: String.valueOf(false),
dateCompleted: new Date(),
cancelled : !status
],
null,
null
)
}
/**
* Log details about execution start and finish to a log4j listener named org.rundeck.execution.status
* @param e
* @param event @return @param user
*/
def logExecutionLog4j(Execution e, String event, String user) {
def (Map mdcprops, String message) = createExecutionLogMDCdata(e)
mdcprops.event= event
mdcprops.eventUser= user
logExecutionLog4jState(mdcprops, event+" ("+ user+"): "+ message)
}
protected void logExecutionLog4jState(Map mdcprops, String message) {
mdcprops.each MDC.&put
executionStatusLogger.info(message)
mdcprops.keySet().each(MDC.&remove)
}
protected List createExecutionLogMDCdata(Execution e) {
def state = getExecutionState(e)
def execprops = ['user', 'id', 'abortedby', 'dateStarted', 'dateCompleted', 'project', 'argString']
def jobProps = ['uuid', 'jobName', 'groupPath']
Map mdcprops=[:]
execprops.each { k ->
def v = e[k]
if (v instanceof Date) {
//TODO: reformat date
mdcprops.put(k, v.toString())
mdcprops.put("${k}Time", v.time.toString())
} else if (v instanceof String) {
mdcprops.put(k, v ? v : "-")
} else {
mdcprops.put(k, v ? v.toString() : "-")
}
}
mdcprops.put('state', state)
final jobstring = ''
if (e.scheduledExecution) {
jobProps.each { k ->
final var = e.scheduledExecution[k]
mdcprops.put(k, var ? var : '-')
}
jobstring = " job: " + e.scheduledExecution.extid + " " + (e.scheduledExecution.groupPath ?: '') + "/" +
e.scheduledExecution.jobName
} else {
def adhocCommand = e.workflow.commands.size()==1 && (e.workflow.commands[0] instanceof CommandExec) && e.workflow.commands[0].adhocRemoteString
if (adhocCommand) {
mdcprops.put("command", adhocCommand)
jobstring += " command: " + adhocCommand
}
jobProps.each{k->
mdcprops[k]='-'
}
}
[mdcprops, "id: " + e.id +" state: " + state + " project: " + e.project + " user: " + e.user + jobstring]
}
public logExecution(uri,project,user,issuccess,statusString,execId,Date startDate=null, jobExecId=null, jobName=null,
jobSummary=null,iscancelled=false,istimedout=false,willretry=false, nodesummary=null,
abortedby=null, succeededNodeList=null, failedNodeList=null, filter=null){
def reportMap=[:]
def internalLog = org.apache.log4j.Logger.getLogger("ExecutionService")
if(null==project || null==user ){
//invalid
internalLog.error("could not send execution report: some required values were null: (project:${project},user:${user})")
return
}
if(execId){
reportMap.jcExecId=execId
}
if(startDate){
reportMap.dateStarted=startDate
}
if(jobExecId){
reportMap.jcJobId=jobExecId
}
if(jobName){
reportMap.reportId=jobName
reportMap.adhocExecution = false
}else{
reportMap.reportId='adhoc'
reportMap.adhocExecution = true
}
if(succeededNodeList){
reportMap.succeededNodeList = succeededNodeList
}
if(failedNodeList){
reportMap.failedNodeList = failedNodeList
}
if(filter){
reportMap.filterApplied = filter
}
reportMap.ctxProject=project
if(iscancelled && abortedby){
reportMap.abortedByUser=abortedby
}else if(iscancelled){
reportMap.abortedByUser=user
}
reportMap.author=user
reportMap.title= jobSummary?jobSummary:"Rundeck Job Execution"
def statusMap =[
true:'succeed',
(EXECUTION_SUCCEEDED):'succeed',
(EXECUTION_ABORTED):'cancel',
(EXECUTION_FAILED_WITH_RETRY):'retry',
(EXECUTION_TIMEDOUT):'timeout',
(EXECUTION_FAILED):'fail',
false:'fail',
]
reportMap.status= statusMap[statusString]?:'other'
reportMap.node= null!=nodesummary?nodesummary: frameworkService.getFrameworkNodeName()
reportMap.message=(statusString? "Job status ${statusString}" : issuccess?'Job completed successfully':iscancelled?('Job killed by: '+(abortedby?:user)):
willretry?'Job Failed (will retry)':istimedout?'Job timed out':'Job failed')
reportMap.dateCompleted=new Date()
def result=reportService.reportExecutionResult(reportMap)
if(result.error){
log.error("Failed to create report: "+result.report.errors.allErrors.collect{it.toString()}).join("; ")
}
}
def static HashMap<String, String> exportContextForExecution(Execution execution, LinkGenerator grailsLinkGenerator) {
def jobcontext = new HashMap<String, String>()
if (execution.scheduledExecution) {
jobcontext.name = execution.scheduledExecution.jobName
jobcontext.group = execution.scheduledExecution.groupPath
jobcontext.id = execution.scheduledExecution.extid
jobcontext.successOnEmptyNodeFilter=execution.scheduledExecution.successOnEmptyNodeFilter?"true":"false"
}
if (execution.filter) {
jobcontext.filter = execution.filter
}
jobcontext.execid = execution.id.toString()
jobcontext.executionType = execution.executionType
jobcontext.serverUrl = generateServerURL(grailsLinkGenerator)
jobcontext.url = generateExecutionURL(execution,grailsLinkGenerator)
jobcontext.serverUUID = execution.serverNodeUUID
jobcontext.username = execution.user
jobcontext['user.name'] = execution.user
jobcontext.project = execution.project
jobcontext.loglevel = textLogLevels[execution.loglevel] ?: execution.loglevel
jobcontext.retryAttempt=Integer.toString(execution.retryAttempt?:0)
if(execution.retryAttempt>0 && execution.retryOriginalId!=null){
jobcontext.retryInitialExecId=Long.toString(execution.retryOriginalId)
}else{
jobcontext.retryInitialExecId="0"
}
jobcontext.wasRetry=Boolean.toString(execution.retryAttempt?true:false)
jobcontext.threadcount=Integer.toString(execution.nodeThreadcount?:1)
jobcontext
}
static String generateExecutionURL(Execution execution,LinkGenerator grailsLinkGenerator) {
grailsLinkGenerator.link(controller: 'execution', action: 'follow', id: execution.id, absolute: true,
params: [project: execution.project])
}
static String generateServerURL(LinkGenerator grailsLinkGenerator) {
grailsLinkGenerator.link(controller: 'menu', action: 'index', absolute: true)
}
/**
* starts an execution in a separate thread, returning a map of [thread:Thread, loghandler:LogHandler, threshold:Threshold]
*/
def Map executeAsyncBegin(Framework framework, AuthContext authContext, Execution execution,
ScheduledExecution scheduledExecution=null, Map extraParams = null,
Map extraParamsExposed = null, int retryAttempt=0){
//TODO: method can be transactional readonly
metricService.markMeter(this.class.name,'executionStartMeter')
execution.refresh()
//set up log output threshold
def thresholdMap = ScheduledExecution.parseLogOutputThreshold(scheduledExecution?.logOutputThreshold)
def threshold = LoggingThreshold.fromMap(thresholdMap,scheduledExecution?.logOutputThresholdAction)
def ExecutionLogWriter loghandler= loggingService.openLogWriter(
execution,
logLevelForString(execution.loglevel),
[user:execution.user, node: framework.getFrameworkNodeName()],
threshold
)
execution.outputfilepath = loghandler.filepath?.getAbsolutePath()
execution.save(flush:true)
if(execution.scheduledExecution){
metricService.markMeter(this.class.name,'executionJobStartMeter')
}else{
metricService.markMeter(this.class.name,'executionAdhocStartMeter')
}
try{
def jobcontext=exportContextForExecution(execution,grailsLinkGenerator)
loghandler.openStream()
//manages workflow step+node context data
ContextManager contextmanager = new ContextManager()
ContextLogWriter directLogWriter = new ContextLogWriter(loghandler)
LoggerWithContext directLogger = new LoggerWithContext(directLogWriter, contextmanager)
//can create contexts for using log filter plugins
def logFilterPluginLoader = pluginService.createSimplePluginLoader(
execution.project,
framework,
pluginService.getRundeckPluginRegistry().createPluggableService(LogFilterPlugin)
)