summaryrefslogtreecommitdiffstats
path: root/scripts/cleanup.sh
blob: 090e57349eb3c9e82165db7c32246c8e315bb865 (plain)
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
#!/bin/bash

export LC_ALL=C

master_url="$1"
current_worker="$2"
current_builder="$3"
current_mode="$4"

worker_id="$(wget -qO- "${master_url%/}/api/v2/workers/$current_worker" | sed -rne 's#^ +"workerid": ([0-9]+),?$#\1#p')"
active_builder_ids="$(wget -qO- "${master_url%/}/api/v2/workers/$worker_id/builds" | sed -rne '/"builderid"/ { s/^.+: ([0-9]+),$/\1/; h }; /"state_string"/ { s/^.+: "([^"]*)".*$/\1/; H; x; s/\n/ /; p }' | sed -ne 's/ building$//p')"

find /tmp/ -maxdepth 1 -mtime +1 '(' -name 'npm-*' -or -name 'jsmake-*' ')' -print0 | xargs -0 -r rm -vr

is_running() {
	local id="$(wget -qO- "${master_url%/}/api/v2/builders/${1//\//_}" | sed -rne 's#^ +"builderid": ([0-9]+),$#\1#p')"
	local running_builder_id
	for running_builder_id in $active_builder_ids; do
		if [ "$running_builder_id" = "$id" ]; then
			return 0
		fi
	done
	return 1
}

do_cleanup() {
	printf "Cleaning up '$current_builder' work directory"

	if [ -d .git ]; then
		echo " using git"
		git reset --hard HEAD
		git clean -f -d -x
	else
		find . -mindepth 1 -maxdepth 1 | while read entry; do
			rm -vrf "$entry" | while read entry2; do
				case "$entry2" in *directory[:\ ]*)
					printf "."
				esac
			done
		done
	fi

	echo ""
}

#
# Sanity check, current builder should be in running builders list
#

if ! is_running "$current_builder"; then
	echo "Current builder '$current_builder' not found in current builders list, aborting cleanup."
	exit 1
fi


#
# Clean up leftovers
#

if [ "$current_mode" = full ]; then
(
	if ! flock -x -w 2700 200; then
		echo "Unable to obtain exclusive lock, aborting cleanup."
		exit 1
	fi

	for build_dir in ../*; do

		current_builder="${build_dir##*/}"
		build_dir="$(readlink -f "$build_dir")"

		if [ -z "$build_dir" ] || [ -L "$build_dir" ] || [ ! -d "$build_dir/build" ]; then
			continue
		fi

		if is_running "$current_builder"; then
			echo "Skipping currently active '$current_builder' work directory."
			continue
		fi

		(
			cd "$build_dir/build"
			do_cleanup
		)
	done

) 200>../cleanup.lock

#
# Clean up current build
#

else
	if [ -d build ]; then (
		cd build
		do_cleanup
	); fi
fi

exit 0