/
ScheduledExecutionService.groovy
4420 lines (4050 loc) · 179 KB
/
ScheduledExecutionService.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.support.ScheduledExecutionQuery
import com.dtolabs.rundeck.core.authorization.AuthContext
import com.dtolabs.rundeck.core.authorization.UserAndRoles
import com.dtolabs.rundeck.core.authorization.UserAndRolesAuthContext
import com.dtolabs.rundeck.core.plugins.DescribedPlugin
import com.dtolabs.rundeck.core.plugins.JobLifecyclePluginException
import com.dtolabs.rundeck.core.plugins.ValidatedPlugin
import grails.converters.JSON
import grails.gorm.transactions.NotTransactional
import grails.orm.HibernateCriteriaBuilder
import groovy.transform.CompileStatic
import org.grails.web.json.JSONArray
import org.grails.web.json.JSONElement
import org.hibernate.criterion.DetachedCriteria
import org.hibernate.criterion.Projections
import org.hibernate.criterion.Subqueries
import org.rundeck.app.components.RundeckJobDefinitionManager
import org.rundeck.app.components.jobs.ImportedJob
import org.rundeck.app.components.jobs.JobDefinitionException
import org.hibernate.sql.JoinType
import org.rundeck.app.components.jobs.JobQuery
import org.rundeck.app.components.jobs.JobQueryInput
import org.rundeck.app.components.schedule.TriggerBuilderHelper
import org.rundeck.app.components.schedule.TriggersExtender
import org.rundeck.app.components.jobs.UnsupportedFormatException
import org.rundeck.core.auth.AuthConstants
import com.dtolabs.rundeck.core.common.Framework
import com.dtolabs.rundeck.core.common.INodeSet
import com.dtolabs.rundeck.core.common.IRundeckProject
import com.dtolabs.rundeck.core.common.IRundeckProjectConfig
import com.dtolabs.rundeck.core.common.NodesSelector
import com.dtolabs.rundeck.core.common.SelectorUtils
import com.dtolabs.rundeck.core.execution.workflow.WorkflowStrategy
import com.dtolabs.rundeck.core.jobs.JobOption
import com.dtolabs.rundeck.core.jobs.JobReference
import com.dtolabs.rundeck.core.jobs.JobRevReference
import com.dtolabs.rundeck.core.plugins.PluginConfigSet
import com.dtolabs.rundeck.core.plugins.PluginProviderConfiguration
import com.dtolabs.rundeck.core.plugins.SimplePluginConfiguration
import com.dtolabs.rundeck.core.plugins.configuration.Property
import com.dtolabs.rundeck.core.plugins.configuration.PropertyResolver
import com.dtolabs.rundeck.core.plugins.configuration.PropertyScope
import com.dtolabs.rundeck.core.plugins.configuration.Validator
import com.dtolabs.rundeck.core.schedule.JobScheduleFailure
import com.dtolabs.rundeck.core.schedule.JobScheduleManager
import com.dtolabs.rundeck.core.utils.NodeSet
import com.dtolabs.rundeck.plugins.ServiceNameConstants
import com.dtolabs.rundeck.plugins.jobs.ExecutionLifecyclePlugin
import com.dtolabs.rundeck.plugins.jobs.JobPersistEventImpl
import com.dtolabs.rundeck.plugins.logging.LogFilterPlugin
import com.dtolabs.rundeck.plugins.scm.JobChangeEvent
import com.dtolabs.rundeck.plugins.util.PropertyBuilder
import com.fasterxml.jackson.databind.ObjectMapper
import grails.events.EventPublisher
import grails.gorm.transactions.Transactional
import grails.plugins.quartz.listeners.SessionBinderJobListener
import org.grails.web.json.JSONObject
import org.hibernate.StaleObjectStateException
import org.hibernate.criterion.CriteriaSpecification
import org.hibernate.criterion.Restrictions
import org.quartz.*
import org.rundeck.util.Sizes
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.beans.factory.InitializingBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.MessageSource
import org.springframework.transaction.annotation.Propagation
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.servlet.support.RequestContextUtils
import rundeck.*
import rundeck.controllers.EditOptsController
import rundeck.controllers.ScheduledExecutionController
import rundeck.controllers.WorkflowController
import rundeck.quartzjobs.ExecutionJob
import rundeck.quartzjobs.ExecutionsCleanUp
import rundeck.services.events.ExecutionPrepareEvent
import org.rundeck.core.projects.ProjectConfigurable
import rundeck.utils.OptionsUtil
import javax.servlet.http.HttpSession
import java.text.MessageFormat
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit
/**
* ScheduledExecutionService manages scheduling jobs with the Quartz scheduler
*/
@Transactional
class ScheduledExecutionService implements ApplicationContextAware, InitializingBean, ProjectConfigurable, EventPublisher {
static transactional = true
public static final String CONF_GROUP_EXPAND_LEVEL = 'project.jobs.gui.groupExpandLevel'
public static final String CONF_PROJECT_DISABLE_EXECUTION = 'project.disable.executions'
public static final String CONF_PROJECT_DISABLE_SCHEDULE = 'project.disable.schedule'
def JobScheduleManager rundeckJobScheduleManager
RundeckJobDefinitionManager rundeckJobDefinitionManager
public final String REMOTE_OPTION_DISABLE_JSON_CHECK = 'project.jobs.disableRemoteOptionJsonCheck'
public static final List<Property> ProjectConfigProperties = [
PropertyBuilder.builder().with {
integer 'groupExpandLevel'
title 'Job Group Expansion Level'
description 'In the Jobs page, expand Job groups to this depth by default.\n\n' +
'* `0`: collapse all Groups\n' +
'* `-1`: expand all Groups.'
required(false)
defaultValue '1'
renderingOption('projectConfigCategory', 'gui')
}.build(),
PropertyBuilder.builder().with {
booleanType 'disableExecution'
title 'Disable Execution'
required(false)
defaultValue null
renderingOptions( ['booleanTrueDisplayValueClass': 'text-warning','groupName':'Enable/Disable Execution Now'])
}.build(),
PropertyBuilder.builder().with {
booleanType 'disableSchedule'
title 'Disable Schedule'
required(false)
defaultValue null
renderingOptions( ['booleanTrueDisplayValueClass': 'text-warning','groupName':'Enable/Disable Execution Now'])
}.build(),
]
public static final LinkedHashMap<String, String> ConfigPropertiesMapping = [
groupExpandLevel: CONF_GROUP_EXPAND_LEVEL,
disableExecution: CONF_PROJECT_DISABLE_EXECUTION,
disableSchedule: CONF_PROJECT_DISABLE_SCHEDULE,
]
public static final String CLEANER_EXECUTIONS_JOB_GROUP_NAME = "cleanerExecutionsJob"
FrameworkService frameworkService
def NotificationService notificationService
//private field to set lazy bean dependency
private ExecutionService executionServiceBean
def executorService
def Scheduler quartzScheduler
/**
* defined in quartz plugin
*/
def SessionBinderJobListener sessionBinderListener
ApplicationContext applicationContext
def grailsApplication
def MessageSource messageSource
PluginService pluginService
def executionUtilService
FileUploadService fileUploadService
JobSchedulerService jobSchedulerService
JobLifecyclePluginService jobLifecyclePluginService
ExecutionLifecyclePluginService executionLifecyclePluginService
def jobSchedulesService
private def triggerComponents
@Override
void afterPropertiesSet() throws Exception {
//add listener for every job
quartzScheduler?.getListenerManager()?.addJobListener(sessionBinderListener)
triggerComponents = applicationContext.getBeansOfType(TriggersExtender) ?: [:]
}
@Override
Map<String, String> getCategories() {
[groupExpandLevel: 'gui', disableExecution: 'executionMode', disableSchedule: 'executionMode',]
}
@Override
List<Property> getProjectConfigProperties() { ProjectConfigProperties }
@Override
Map<String, String> getPropertiesMapping() { ConfigPropertiesMapping }
/**
* Return project config for node cache delay
* @param project
* @return
*/
int getJobExpandLevel(final IRundeckProjectConfig projectConfig) {
projectConfig.hasProperty(CONF_GROUP_EXPAND_LEVEL) ?
tryParseInt(projectConfig).orElse(1) :
1
}
private Optional<Integer> tryParseInt(IRundeckProjectConfig projectConfig) {
try {
Optional.of(Integer.parseInt(projectConfig.getProperty(CONF_GROUP_EXPAND_LEVEL)))
} catch (NumberFormatException e) {
Optional.empty()
}
}
/**
* private getter for executionService that is not auto-injected
* @return
*/
private ExecutionService getExecutionService(){
if(null==executionServiceBean){
this.executionServiceBean = applicationContext.getBean("executionService",ExecutionService)
}
return executionServiceBean
}
def getWorkflowStrategyPluginDescriptions(){
pluginService.listPlugins(WorkflowStrategy, frameworkService.rundeckFramework.workflowStrategyService).collect {
it.value.description
}.sort { a, b -> a.name <=> b.name }
}
boolean getPaginationEnabled() {
grailsApplication.config.rundeck.gui.paginatejobs.enabled in ["true",true]
}
def getConfiguredMaxPerPage(int defaultMax) {
if(paginationEnabled) {
return grailsApplication.config.rundeck.gui.paginatejobs.max.per.page.isEmpty() ? defaultMax : grailsApplication.config.rundeck.gui.paginatejobs.max.per.page.toInteger()
}
return defaultMax
}
def Map finishquery ( query,params,model){
if(!params.max){
params.max=getConfiguredMaxPerPage(10)
}
if(!params.offset){
params.offset=0
}
def paginateParams=[:]
if(query){
model._filters.each{ key,val ->
if(null!=query."${key}Filter" && !''.equals(query."${key}Filter")){
paginateParams["${key}Filter"]=query."${key}Filter"
}
}
if(null!=query.'idlist' && !''.equals(query.'idlist')){
paginateParams['idlist']=query.'idlist'
}
}
def displayParams = [:]
displayParams.putAll(paginateParams)
if(query.groupPath && query.groupPath!="*"){
paginateParams['groupPath']=query.groupPath
}else{
params.groupPath=null
}
if(model.customFilters && !model.customFilters.isEmpty()){
def totalCustomFilters = [:]
model.customFilters.each{
totalCustomFilters.putAll(it)
}
if(totalCustomFilters && !totalCustomFilters.isEmpty()){
paginateParams.customFilters = totalCustomFilters
}
}
def tmod=[max: query?.max?query.max:getConfiguredMaxPerPage(10),
offset:query?.offset?query.offset:0,
paginateParams:paginateParams,
displayParams:displayParams]
model.putAll(tmod)
return model
}
/**
* Query for job definitions based on the input
* @param queryInput
* @param params parameter map, used to extend query criteria
* @return
*/
def listWorkflows(JobQueryInput queryInput, Map params=[:]){
JobQueryInput query = queryInput
def jobQueryComponents = applicationContext.getBeansOfType(JobQuery)
def txtfilters = ScheduledExecutionQuery.TEXT_FILTERS
def eqfilters=ScheduledExecutionQuery.EQ_FILTERS
def boolfilters=ScheduledExecutionQuery.BOOL_FILTERS
def filters = ScheduledExecutionQuery.ALL_FILTERS
def xfilters = ScheduledExecutionQuery.X_FILTERS
def totalCustomFilters = []
Integer queryMax=query.max
Integer queryOffset=query.offset
if(paginationEnabled) {
if (!queryMax) {
queryMax = getConfiguredMaxPerPage(10)
}
if (!queryOffset) {
queryOffset = 0
}
}
def idlist=[]
if(query.idlist){
def arr = query.idlist.split(",")
arr.each{
try{
idlist<<Long.valueOf(it)
}catch(NumberFormatException e){
idlist<<it
}
}
}
def crit = ScheduledExecution.createCriteria()
def scheduled = crit.list{
if(queryMax && queryMax>0){
maxResults(queryMax)
}else{
// maxResults(10)
}
if(queryOffset){
firstResult(queryOffset.toInteger())
}
if(idlist){
or{
idlist.each{ theid->
if(theid instanceof Long){
eq("id",theid)
}else{
eq("uuid", theid)
}
}
}
}
txtfilters.each{ key,val ->
if(query["${key}Filter"]){
ilike(val,'%'+query["${key}Filter"]+'%')
}
}
eqfilters.each{ key,val ->
if(query["${key}Filter"]){
eq(val,query["${key}Filter"])
}
}
def restr = Restrictions.conjunction()
boolfilters.each{ key,val ->
if(null!=query["${key}Filter"]){
restr.add(Restrictions.eq(val, query["${key}Filter"]))
}
}
if(query.runJobLaterFilter){
Date now = new Date()
DetachedCriteria subquery = DetachedCriteria.forClass(Execution.class, "e").with{
setProjection Projections.property('e.id')
add(Restrictions.gt('e.dateStarted', now))
add Restrictions.conjunction().
add(Restrictions.eqProperty('e.scheduledExecution.id', 'this.id'))
}
add(Restrictions.disjunction().add(Subqueries.exists(subquery)).add(restr))
} else if(restr.conditions().size() > 0){
add(restr)
}
if('-'==query["groupPath"]||"-"==query["groupPathExact"]){
or {
eq("groupPath", "")
isNull("groupPath")
}
}else if(query["groupPath"] && '*'!=query["groupPath"]){
or{
like("groupPath",query["groupPath"]+"/%")
eq("groupPath",query['groupPath'])
}
}else if(query["groupPathExact"]){
or{
eq("groupPath",query['groupPathExact'])
}
}
def critDelegate=delegate
jobQueryComponents?.each { name, jobQuery ->
def customFilters = jobQuery.extendCriteria(query, params, critDelegate)
if(customFilters && !customFilters.isEmpty()){
totalCustomFilters.add(customFilters)
}
}
if(query && query.sortBy && xfilters[query.sortBy]){
order(xfilters[query.sortBy],query.sortOrder=='ascending'?'asc':'desc')
}else{
if(paginationEnabled) {
order("groupPath","asc")
}
order("jobName","asc")
}
};
def schedlist = [];
scheduled.each{
schedlist << it
}
def total = schedlist.size()
if(queryMax && queryMax>0) {
//count full result set
total = ScheduledExecution.createCriteria().count {
if (idlist) {
or {
idlist.each { theid ->
if (theid instanceof Long) {
eq("id", theid)
} else {
eq("uuid", theid)
}
}
}
}
txtfilters.each { key, val ->
if (query["${key}Filter"]) {
ilike(val, '%' + query["${key}Filter"] + '%')
}
}
eqfilters.each { key, val ->
if (query["${key}Filter"]) {
eq(val, query["${key}Filter"])
}
}
boolfilters.each { key, val ->
if (null != query["${key}Filter"]) {
eq(val, query["${key}Filter"])
}
}
if('-'==query["groupPath"]||"-"==query["groupPathExact"]){
or {
eq("groupPath", "")
isNull("groupPath")
}
}else if(query["groupPath"] && '*'!=query["groupPath"]){
or{
like("groupPath",query["groupPath"]+"/%")
eq("groupPath",query['groupPath'])
}
}else if(query["groupPathExact"]){
or{
eq("groupPath",query['groupPathExact'])
}
}
def critDelegate=delegate
jobQueryComponents?.each { name, jobQuery ->
def customFilters = jobQuery.extendCriteria(query, params, critDelegate)
if(customFilters && !customFilters.isEmpty()){
totalCustomFilters.add(customFilters)
}
}
}
}
return [
query:query,
schedlist:schedlist,
total: total,
_filters:filters,
customFilters: totalCustomFilters
]
}
/**
* return a map of defined group path to count of the number of jobs with that exact path
*/
def Map getGroups(project, AuthContext authContext){
def groupMap=[:]
//collect all jobs and authorize the user for the set of available Job actions
Set res = new HashSet()
def schedlist= ScheduledExecution.findAllByProject(project)
schedlist.each { ScheduledExecution sched ->
res.add(frameworkService.authResourceForJob(sched))
}
// Filter the groups by what the user is authorized to see.
def decisions = frameworkService.authorizeProjectResources(authContext,res,
new HashSet([AuthConstants.ACTION_READ]),project)
decisions.each{
if(it.authorized){
if(null!= groupMap[it.resource['group']]){
groupMap[it.resource['group']]= groupMap[it.resource['group']]+1
}else{
groupMap[it.resource['group']]=1
}
}
}
return groupMap
}
/**
* Claim schedule for a job with the passed in serverUUID
* @param scheduledExecution
* @param serverUUID uuid to assign to the scheduled job
* @return
*/
private Map claimScheduledJob(
ScheduledExecution scheduledExecution,
String serverUUID,
String fromServerUUID = null
)
{
def schedId=scheduledExecution.id
def retry = true
List<Execution> claimedExecs = []
Date claimDate = new Date()
int maxTries = 10
int tryCount = 0
while (retry && tryCount < maxTries) {
try {
// ScheduledExecution.withNewSession { session -> //TODO: withNewSession dont work on integration test
scheduledExecution = ScheduledExecution.get(schedId)
scheduledExecution.refresh()
if (jobSchedulesService.isScheduled(scheduledExecution.uuid)) {
scheduledExecution.serverNodeUUID = serverUUID
if (scheduledExecution.save()) {
log.info("claimScheduledJob: schedule claimed for ${schedId} on node ${serverUUID}")
} else {
log.debug("claimScheduledJob: failed for ${schedId} on node ${serverUUID}")
}
}
//claim scheduled adhoc executions
Execution.findAllByScheduledExecutionAndStatusAndDateStartedGreaterThanAndDateCompletedIsNull(
scheduledExecution,
'scheduled',
claimDate
).each {
it.serverNodeUUID = serverUUID
it.save()
log.info("claimed adhoc execution ${it.id}")
claimedExecs << it
}
retry = false
// }
} catch (org.springframework.dao.ConcurrencyFailureException e) {
log.error("claimScheduledJob: failed for ${schedId} on node ${serverUUID}: locking failure")
retry = true
tryCount++
} catch (StaleObjectStateException e) {
log.error("claimScheduledJob: failed for ${schedId} on node ${serverUUID}: stale data")
retry = true
tryCount++
}
}
return [claimed: !retry, executions: claimedExecs]
}
/**
* Claim scheduling for any jobs assigned to fromServerUUID, or not assigned if it is null
* @param toServerUUID uuid to assign to scheduled jobs
* @param fromServerUUID uuid to claim from, or null to claim from unassigned jobs
*
* @return Map of job ID to boolean, indicating whether the job was claimed
*/
def Map claimScheduledJobs(
String toServerUUID,
String fromServerUUID = null,
boolean selectAll = false,
String projectFilter = null,
List<String> jobids = null
)
{
Map claimed = [:]
def queryFromServerUUID = fromServerUUID
def queryProject = projectFilter
ScheduledExecution.withSession { session ->
def scheduledExecutions = jobSchedulesService.getSchedulesJobToClaim(toServerUUID, queryFromServerUUID, selectAll, queryProject, jobids)
scheduledExecutions.each { ScheduledExecution se ->
def orig = se.serverNodeUUID
if (!claimed[se.extid]) {
def claimResult = claimScheduledJob(se, toServerUUID, queryFromServerUUID)
claimed[se.extid] = [
success : claimResult.claimed,
job : se,
previous : orig,
executions: claimResult.executions
]
}
}
session.flush()
}
claimed
}
/**
* Remove all scheduling for job executions, triggered when passive mode is enabled
* @param serverUUID
*/
def unscheduleJobs(String serverUUID=null){
def schedJobs = serverUUID ? jobSchedulesService.getAllScheduled(serverUUID) : jobSchedulesService.getAllScheduled()
schedJobs.each { ScheduledExecution se ->
def jobname = se.generateJobScheduledName()
def groupname = se.generateJobGroupName()
quartzScheduler.deleteJob(new JobKey(jobname,groupname))
log.info("Unscheduled job: ${se.id}")
}
def results = Execution.isScheduledAdHoc()
if (serverUUID) {
results = results.withServerNodeUUID(serverUUID)
}
results.list().each { Execution e ->
ScheduledExecution se = e.scheduledExecution
def identity = getJobIdent(se, e)
quartzScheduler.deleteJob(new JobKey(identity.jobname, identity.groupname))
log.info("Unscheduled job: ${se.id}")
}
}
/**
* Remove all scheduling for job executions, triggered when passive mode is enabled
* @param serverUUID
*/
def unscheduleJobsForProject(String project,String serverUUID=null){
def schedJobs = serverUUID ? jobSchedulesService.getAllScheduled(serverUUID, project) : jobSchedulesService.getAllScheduled(null, project)
schedJobs.each { ScheduledExecution se ->
def jobname = se.generateJobScheduledName()
def groupname = se.generateJobGroupName()
quartzScheduler.deleteJob(new JobKey(jobname,groupname))
log.info("Unscheduled job: ${se.id}")
}
def results = Execution.isScheduledAdHoc()
if (serverUUID) {
results = results.withServerNodeUUID(serverUUID)
}
results = results.withProject(project)
results.list().each { Execution e ->
ScheduledExecution se = e.scheduledExecution
def identity = getJobIdent(se, e)
quartzScheduler.deleteJob(new JobKey(identity.jobname, identity.groupname))
log.info("Unscheduled job: ${se.id}")
}
}
def rescheduleJob(ScheduledExecution scheduledExecution) {
rescheduleJob(scheduledExecution, false, null, null, false)
}
def rescheduleJob(ScheduledExecution scheduledExecution, wasScheduled, oldJobName, oldJobGroup, boolean forceLocal) {
if (jobSchedulesService.shouldScheduleExecution(scheduledExecution.uuid) && shouldScheduleInThisProject(scheduledExecution.project)) {
def nextdate = null
def nextExecNode = null
try {
(nextdate, nextExecNode) = scheduleJob(scheduledExecution, oldJobName, oldJobGroup, forceLocal);
} catch (SchedulerException e) {
log.error("Unable to schedule job: ${scheduledExecution.extid}: ${e.message}")
}
} else if (wasScheduled && oldJobName && oldJobGroup) {
deleteJob(oldJobName, oldJobGroup)
}
}
/**
* Reschedule all scheduled jobs which match the given serverUUID, or all jobs if it is null.
* @param serverUUID
* @return
*/
def rescheduleJobsAsync(String serverUUID=null) {
executorService.execute{
rescheduleJobs(serverUUID)
}
}
/**
* Reschedule all scheduled jobs which match the given serverUUID, or all jobs if it is null.
* @param serverUUID
* @return
*/
def rescheduleJobs(String serverUUID = null, String project = null) {
Date now = new Date()
def succeededJobs = []
def failedJobs = []
// Reschedule jobs on fixed schedules
def scheduledList = jobSchedulesService.getAllScheduled(serverUUID, project)
scheduledList.each { ScheduledExecution se ->
try {
def nexttime = null
def nextExecNode = null
(nexttime, nextExecNode) = scheduleJob(se, null, null, true)
succeededJobs << [job: se, nextscheduled: nexttime]
log.info("rescheduled job in project ${se.project}: ${se.extid}")
} catch (Exception e) {
failedJobs << [job: se, error: e.message]
log.error("Job not rescheduled in project ${se.project}: ${se.extid}: ${e.message}", e)
//log.error(e)
}
}
// Reschedule any executions which were scheduled ad hoc
def results = Execution.isScheduledAdHoc()
if (serverUUID) {
results = results.withServerNodeUUID(serverUUID)
}
if(project) {
results = results.withProject(project)
}
def executionList = results.list()
def adhocRescheduleResult = rescheduleOnetimeExecutions(executionList)
[jobs: succeededJobs, failedJobs: failedJobs, executions: adhocRescheduleResult.executions, failedExecutions: adhocRescheduleResult.failedExecutions]
}
/**
* Reschedule the provided one-time executions. Invalid executions will be cleaned up.
* @param executionList The list of executions to reschedule.
* @return A map with: <pre>
* [executions: List, // succeeded executions<br>
* failedExecutions: List] // failed executions
* </pre>
*/
def rescheduleOnetimeExecutions(List<Execution> executionList) {
Date now = new Date()
// Reschedule any executions which were scheduled for one time execution.
List<Execution> cleanupExecutions = []
def succeedExecutions = []
executionList.each { Execution e ->
boolean ok = true
ScheduledExecution se = e.scheduledExecution
if (se.options.find { it.secureInput } != null) {
log.error("One-time execution not rescheduled: ${se.jobName} [${e.id}]: " +
"cannot reschedule automatically as it has secure input options")
ok = false
} else if (e.dateStarted == null) {
log.error("One-time execution not rescheduled: ${se.jobName} [${e.id}]: " +
"no start time is set: ${e}")
ok = false
} else if (e.dateStarted.before(now)) {
log.error("One-time execution not rescheduled: ${se.jobName} [${e.id}]: " +
"the schedule time has past")
ok = false
}
if (ok) {
log.info("Rescheduling one-time execution of: " +
"${se.jobName} [${e.id}]: ${e.dateStarted}"
)
try {
AuthContext authContext = frameworkService.getAuthContextForUserAndRolesAndProject(
e.user ?: se.user,
e.userRoles ?: se.userRoles,
e.project
)
Date nexttime = scheduleAdHocJob(
se,
authContext.username,
authContext,
e,
null,
null,
e.dateStarted,
false
)
if (nexttime) {
succeedExecutions << [execution: e, time: nexttime]
}
} catch (Exception ex) {
log.error("One Time job not rescheduled: ${se.jobName}: ${ex.message}", ex)
ok = false
}
}
if (!ok) {
// Mark this execution to be cleaned up (killed)
cleanupExecutions.add(e)
}
}
if (!cleanupExecutions.isEmpty()) {
log.error("${cleanupExecutions.size()} one-time scheduled executions " +
"could not be rescheduled and will be killed")
executionService.cleanupRunningJobs(cleanupExecutions)
}
[executions: succeedExecutions, failedExecutions: cleanupExecutions]
}
/**
* Claim scheduling of jobs from the given fromServerUUID, and return a map identifying successfully claimed jobs
* @param fromServerUUID server UUID to claim scheduling of jobs from
* @return map of job ID to [success:boolean, job:ScheduledExecution] indicating reclaim was successful or not.
*/
def reclaimAndScheduleJobs(String fromServerUUID, boolean all=false, String project=null, List<String> ids=null) {
def toServerUuid = frameworkService.getServerUUID()
if (toServerUuid == fromServerUUID) {
return [:]
}
def claimed = claimScheduledJobs(toServerUuid, fromServerUUID, all, project, ids)
if (claimed.find { it.value.success }) {
rescheduleJobs(toServerUuid)
}
claimed
}
/**
* Return a Map with a tree structure of the available grouppaths, and their job counts
* <pre>
[
'a' :[
count:6,
subs:[
'b': [
count:4,
],
'c': [
count:1,
subs:[
'd': [
count: 1,
]
]
]
]
]
]
* </pre>
*/
def Map getGroupTree(project, AuthContext authContext){
def groupMap = getGroups(project, authContext)
def tree=[:]
groupMap.keySet().each{
tree[it]=[]
}
return tree
}
/**
*
* @param maxDepth
* @param workflow
* @param readAuth if true, includes contents of each step, if false only includes only basic step details
* @return List of maps for each step, descend up to maxDepth following job references
*/
def getWorkflowDescriptionTree(String project,Workflow workflow,readAuth,maxDepth=3){
def jobids=[:]
def cmdData={}
cmdData={x,WorkflowStep step->
def map=readAuth?step.toMap():step.toDescriptionMap()
map.remove('plugins')
if(map.type){
map.remove('configuration')
}
if(step instanceof JobExec) {
ScheduledExecution refjob = step.findJob(project)
if(!step.useName && step.uuid){
if(refjob) {
map.jobref.name = refjob.jobName
map.jobref.group = refjob.groupPath
}
}
if(refjob){
map.jobId=refjob.extid
boolean doload=(null==jobids[map.jobId])
if(doload){
jobids[map.jobId]=[]
}
if(doload && x>0){
map.workflow=jobids[map.jobId]
jobids[map.jobId].addAll(refjob.workflow.commands.collect(cmdData.curry(x-1)))
}
}
}
def eh = step.errorHandler
if(eh instanceof JobExec) {
ScheduledExecution refjob = eh.findJob(project)
if(refjob){
map.ehJobId=refjob.extid
boolean doload=(null==jobids[map.ehJobId])
if(doload){
jobids[map.ehJobId]=[]
}
if(doload && x>0){
map.ehWorkflow=jobids[map.ehJobId]
jobids[map.ehJobId].addAll(refjob.workflow.commands.collect(cmdData.curry(x-1)))
}
}
}
return map
}
workflow.commands.collect(cmdData.curry(maxDepth))
}
/**
* Delete all executions for a job. Return a map with results, as {@link ExecutionService#deleteBulkExecutionIds(java.util.Collection, com.dtolabs.rundeck.core.authorization.AuthContext, java.lang.String)}
* @param scheduledExecution
* @param authContext @param var
*/
def deleteJobExecutions(ScheduledExecution scheduledExecution, AuthContext authContext, def username){
Execution.withTransaction {
//unlink any Execution records
def executions = Execution.findAllByScheduledExecution(scheduledExecution)
def results=executionService.deleteBulkExecutionIds(executions*.id, authContext, username)
return results
}
}
/**
* Immediately delete a ScheduledExecution
* @param username @param scheduledExecution
* @return
*/
def deleteScheduledExecution(ScheduledExecution scheduledExecution, boolean deleteExecutions=false,
AuthContext authContext=null, String username){
scheduledExecution = ScheduledExecution.get(scheduledExecution.id)
def originalRef=jobEventRevRef(scheduledExecution)
def jobname = scheduledExecution.generateJobScheduledName()
def groupname = scheduledExecution.generateJobGroupName()
def errmsg=null
def success = false
Execution.withTransaction {
//find any currently running executions for this job, and if so, throw exception
def found = Execution.createCriteria().get {
delegate.'scheduledExecution' {
eq('id', scheduledExecution.id)
}
isNotNull('dateStarted')
isNull('dateCompleted')
}
if (found) {
errmsg = 'Cannot delete {{Job ' + scheduledExecution.extid + '}} "' + scheduledExecution.jobName +
'" it is currently being executed: {{Execution ' + found.id + '}}'
return [success:false,error:errmsg]
}
def stats= ScheduledExecutionStats.findAllBySe(scheduledExecution)
if(stats){
stats.each { st ->
st.delete()
}
}
def refExec = ReferencedExecution.findAllByScheduledExecution(scheduledExecution)
if(refExec){
refExec.each { re ->
re.delete()
}
}
//unlink any Execution records
def result = Execution.findAllByScheduledExecution(scheduledExecution)
if(deleteExecutions){
executionService.deleteBulkExecutionIds(result*.id,authContext, username)
}else{
result.each { Execution exec ->
exec.scheduledExecution = null
}
}
fileUploadService.deleteRecordsForScheduledExecution(scheduledExecution)
//before delete job
rundeckJobDefinitionManager.beforeDelete(scheduledExecution, authContext)
try {
scheduledExecution.delete(flush: true)
deleteJob(jobname, groupname)
success = true
} catch (org.springframework.dao.ConcurrencyFailureException e) {
scheduledExecution.discard()
errmsg = 'Cannot delete Job "' + scheduledExecution.jobName + '" [' + scheduledExecution.extid + ']: it may have been modified or executed by another user'