-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.groovy
100 lines (83 loc) · 2.56 KB
/
cleanup.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
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import hudson.node_monitors.*;
import hudson.model.*;
import hudson.util.*;
import jenkins.model.*;
import hudson.FilePath.FileCallable;
import hudson.slaves.OfflineCause;
import hudson.node_monitors.*;
// small function to use for comparison of ws paths
def getTimeAccessed(ws) {
pathStr = ws.getRemote()
Path dir = Paths.get(pathStr)
BasicFileAttributes attrs = Files.readAttributes(dir, BasicFileAttributes)
return attrs.lastAccessTime()
}
def wsList = []
// Master
jInstance = Jenkins.instance
for (item in jInstance.items) {
jobName = item.getFullDisplayName()
if (item.isBuilding()) {
println(".. job " + jobName + " is currently running, skipped")
continue
}
workspacePath = jInstance.getWorkspaceFor(item)
if (workspacePath == null) {
println(".... could not get workspace path")
continue
}
println(".... workspace = " + workspacePath)
pathAsString = workspacePath.getRemote()
if (workspacePath.exists()) {
wsList << workspacePath
println(".... added to list " + pathAsString)
} else {
println(".... nothing to delete at " + pathAsString)
}
}
if (wsList) {
wsList.sort{a,b -> getTimeAccessed(a)<=>getTimeAccessed(b)}
for (ws in wsList[0..-3]) {
println(".. proceeding to delete " + ws.getRemote())
ws.deleteRecursive()
}
}
wsList = []
// Slaves
for (node in jInstance.nodes) {
computer = node.toComputer()
if (computer.getChannel() == null) continue
computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("disk cleanup"))
for (item in jInstance.items) {
jobName = item.getFullDisplayName()
if (item.isBuilding()) {
println(".. job " + jobName + " is currently running, skipped")
continue
}
workspacePath = node.getWorkspaceFor(item)
if (workspacePath == null) {
println(".... could not get workspace path")
continue
}
println(".... workspace = " + workspacePath)
pathAsString = workspacePath.getRemote()
if (workspacePath.exists()) {
wsList << workspacePath
println(".... added " + pathAsString + " to list")
} else {
println(".... nothing to delete at " + pathAsString)
}
}
computer.setTemporarilyOffline(false, null)
}
if (wsList) {
wsList.sort{a,b -> getTimeAccessed(a)<=>getTimeAccessed(b)}
for (ws in wsList[0..-3]) {
println(".. proceeding to delete " + ws.getRemote())
ws.deleteRecursive()
}
}