lib/Rex/Rancher/Uninstall.pm

filter: Statementstmt 100% 113 / 113 Branchbran 100% 14 / 14 Conditioncond 62.5% 5 / 8 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 100% 31 / 31 Podpod 100% 9 / 9 totaltotal 96.6% 173 / 179 CC 13 SCAR 6.1
CC
13
Cov
98%
uninstall_failure
4.0
__ANON__
3.1
uninstall_node
3.0
CRAP 1.8
« lib/Rex/Rancher/Checksum.pm ↑ Summary lib/Rex/Rancher/Distribution/K3s.pm »
1 # ABSTRACT: Take RKE2/K3s and Cilium's datapath off a host, and refuse to install over what Cilium left
2  
3 package Rex::Rancher::Uninstall;
4 57 our $VERSION = '0.004';
5 57 ▶use v5.14.4;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 57 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 57 ▶use Rex::Commands::Run ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 57 ▶use Rex::Logger ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 57 ▶use Rex::Rancher::Distribution;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 57 require Rex::Exporter;
13 57 ▶use base qw(Rex::Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 57 ▶use vars qw(@EXPORT);
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 57 @EXPORT = qw(
18 uninstall_node
19 );
20  
21 # Cilium's datapath outlives the vendor uninstallers (kubernetes-ocp k190,
22 # measured on ocpt-cp). rke2-uninstall.sh stops the agent but not what the
23 # agent attached to the kernel: the socket-LB programs on the root cgroup
24 # (through /run/cilium/cgroupv2), the tc/tcx programs on the host's devices,
25 # the maps and links pinned in bpffs, the cilium_* devices, the CILIUM_*
26 # iptables chains and Cilium's policy-routing ip rules. Until a reboot the
27 # socket LB keeps translating the old cluster's service addresses to pods that
28 # are gone, so connect() to one of them -- a registry mirror on localhost:30500
29 # that every containerd is pointed at -- hangs instead of being refused, every
30 # image pull waits minutes for it, and a fresh RKE2 on the host never gets
31 # etcd up within its start bound.
32 #
33 # One module for both sides of that: the check install_server and
34 # install_agent run before they touch the host, and the uninstall that clears
35 # it. Both test the same signals, cilium_residue.
36  
37  
38 247 ▶sub distribution_class { 'Rex::Rancher::Distribution' }
Subroutine distribution_class: called CC=1 SCAR=0.0
Pod documented
39  
40  
41 417 ▶sub cilium_residue {
Subroutine cilium_residue: called CC=1 SCAR=0.0
Pod documented
42 417 my ( $self ) = @_;
43 417 my $cgroup = $self->_cilium_cgroup_root;
44 return (
45 417 [ '[ -e /sys/fs/bpf/cilium ]', '/sys/fs/bpf/cilium' ],
46 [ 'grep -qs " '.$cgroup.' " /proc/mounts', $cgroup ],
47 [ 'ip link show dev cilium_host >/dev/null 2>&1', 'cilium_host' ]
48 );
49 }
50  
51  
52 192 ▶sub cilium_residue_probe_cmd {
Subroutine cilium_residue_probe_cmd: called CC=1 SCAR=0.0
Pod documented
53 192 my ( $self ) = @_;
54 return 'if '.$self->_distribution_present_cmd.'; then :; else '
55 192 .join('', map { $_->[0].' && echo '.$_->[1].'; ' } $self->cilium_residue)
56 .'fi; true';
57 }
58  
59  
60 199 ▶sub cilium_residue_in {
Subroutine cilium_residue_in: called CC=2 SCAR=6.9
Pod documented
61 199 my ( $self, $out ) = @_;
62 199 my %name = map { $_->[1] => 1 } $self->cilium_residue;
63 199 ▶ return grep { $name{$_} } map { s/\A\s+|\s+\z//gr } split /\n/, $out // '';
Condition100%2/2
$out // ""
l!l
1981
MC/DC100%1/1
$out // ""
$out
Truth table100%2/2
A
A= $out
Aresult
11
00
64 }
65  
66  
67 191 ▶sub check_cilium_residue {
Subroutine check_cilium_residue: called CC=3 SCAR=11.0
Pod documented
68 191 my ( $self ) = @_;
69 # auto_die => 0: the probe ends in `true`, so a non-zero exit means it did
70 # not run; that is warned about below, not mistaken for a clean host.
71 191 my $out = Rex::Commands::Run::run($self->cilium_residue_probe_cmd, auto_die => 0);
72 191 my $exit = $? >> 8;
73 191 my @found = $self->cilium_residue_in($out);
74 191 ▶ if (!@found) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@found) 183 8 191
75 183 ▶ Rex::Logger::info("Could not check this host for Cilium datapath state left by an "
Branch: 1 branch
BranchTrueFalseTotal
if $exit 4 179 183
76 . "earlier cluster (the probe exited $exit): going on without that check", 'warn')
77 if $exit;
78 183 return 1;
79 }
80 8 my $labels = $self->_distribution_labels;
81 8 die "This host still carries Cilium datapath state from an earlier cluster ("
82 . join(', ', @found) . "), and no $labels is installed on it. Until the host is "
83 . "rebooted, Cilium's socket load balancer keeps translating the old cluster's "
84 . "service addresses to pods that are gone: connections to them hang instead of "
85 . "being refused, a registry mirror among them, so every image pull of the new "
86 . "install stalls and it does not come up in time. Nothing was written or "
87 . "installed. Reboot the host, then run the install again.\n";
88 }
89  
90  
91 25 ▶sub uninstall_cmd {
Subroutine uninstall_cmd: called CC=1 SCAR=0.0
Pod documented
92 25 my ( $self ) = @_;
93 25 my @dists = $self->_distributions;
94 25 my $labels = $self->_distribution_labels;
95 return join ' ; ',
96 50 'for u in ' . join(' ', map { $_->uninstall_scripts } @dists) . '; do'
97 . ' if command -v $u >/dev/null 2>&1; then $u 2>/dev/null || true; fi;'
98 . ' done',
99 50 ( map { $self->_env_files_cmd($_) } @dists ),
100 # --one-file-system: /run/k3s holds containerd's task mounts, a pod's
101 # hostPath bind among them; one the uninstaller left mounted is skipped,
102 # never recursed into.
103 'rm -rf --one-file-system ' . join(' ', $self->_leftover_paths) . ' 2>/dev/null || true',
104 $self->_cilium_cleanup_cmd,
105 'for t in ' . join(' ', $self->_cilium_ip_tables)
106 . '; do while ip rule del lookup $t 2>/dev/null; do :; done; done',
107 # Back at priority 0 first, then the relocated one goes -- never the
108 # other way round, or the host has no local-table lookup in between.
109 'ip rule list 2>/dev/null | grep -qE "^0:[[:space:]].*lookup local"'
110 . ' || ip rule add from all lookup local priority 0 2>/dev/null || true',
111 'ip rule list 2>/dev/null | grep -qE "^0:[[:space:]].*lookup local"'
112 . ' && ip rule del from all lookup local priority 100 2>/dev/null || true',
113 # The same for IPv6, after the IPv4 lines. Same tolerance: a host without
114 # IPv6 (no kernel support, ipv6.disable=1) fails every `ip -6` quietly.
115 'for t in ' . join(' ', $self->_cilium_ip_tables)
116 . '; do while ip -6 rule del lookup $t 2>/dev/null; do :; done; done',
117 'ip -6 rule list 2>/dev/null | grep -qE "^0:[[:space:]].*lookup local"'
118 . ' || ip -6 rule add from all lookup local priority 0 2>/dev/null || true',
119 'ip -6 rule list 2>/dev/null | grep -qE "^0:[[:space:]].*lookup local"'
120 . ' && ip -6 rule del from all lookup local priority 100 2>/dev/null || true',
121 # Every step above is guarded, so without this the line exited 0
122 # whatever happened -- a missing or failing uninstaller left rke2 in
123 # place and read as a clean uninstall (kubernetes-ocp k175).
124 'still=""',
125 50 'for b in ' . join(' ', map { $_->binary } @dists) . ';'
126 . ' do p=$(command -v $b 2>/dev/null) && still="$still $p"; done',
127 'if [ -n "$still" ]; then echo "' . $labels . ' is still installed after the uninstall:$still'
128 . ' -- its uninstall script is missing or failed" >&2; exit 1; fi',
129 # And the datapath: a host whose Cilium state survived hangs the next
130 # install on it. Only a reboot clears what is left.
131 'left=""',
132 25 ( map { $_->[0] . ' && left="$left ' . $_->[1] . '"' } $self->cilium_residue ),
133 'if [ -n "$left" ]; then echo "Cilium datapath state is still on the host after the uninstall:$left'
134 . ' -- reboot the host before ' . $labels . ' is installed on it again" >&2; exit 1; fi';
135 }
136  
137  
138 19 ▶sub uninstall_warnings {
Subroutine uninstall_warnings: called CC=2 SCAR=6.9
Pod documented
139 19 my ( $self, @output ) = @_;
140 19 my $marker = $self->_warning_marker;
141 49 ▶ return map { /\A\Q$marker\E:\s*(\S.*)\z/ ? $1 : () }
Branch: 1 branch
BranchTrueFalseTotal
/\A\Q$marker\E:\s*(\S.*)\z/u ? : 13 36 49
142 19 map { s/\A\s+|\s+\z//gr } map { split /\n/ } grep { defined } @output;
143 }
144  
145  
146 18 ▶sub uninstall_failure {
Subroutine uninstall_failure: called CC=4 SCAR=13.9
Pod documented
147 18 my ( $self, $exit, $stderr ) = @_;
148 18 ▶ return unless $exit;
Branch: 1 branch
BranchTrueFalseTotal
unless $exit 7 11 18
149 11 my $marker = $self->_warning_marker;
150 11 ▶ my $why = join "\n", grep { !/\A\s*\Q$marker\E:/ } split /\n/, $stderr // '';
Condition50%1/2
$stderr // ""
l!l
110
MC/DC0%0/1
$stderr // ""
$stderr
Truth table50%1/2
A
A= $stderr
Aresult
11
00
151 11 $why =~ s/\s+\z//;
152 11 ▶ return "Uninstall of " . $self->_distribution_labels . " failed (exit $exit)"
Branch: 1 branch
BranchTrueFalseTotal
length $why ? : 8 3 11
153 . ( length $why ? ": $why" : '' ) . "\n";
154 }
155  
156  
157 9 ▶sub uninstall_node {
Subroutine uninstall_node: called CC=3 SCAR=11.0
Pod documented
158 9 my $self = __PACKAGE__;
159 9 Rex::Logger::info("Uninstalling " . $self->_distribution_labels
160 . " and clearing Cilium's datapath from this host");
161 9 my ( $stdout, $stderr ) = ( '', '' );
162 # auto_die => 0: the exit status and stderr make the message below.
163 Rex::Commands::Run::run($self->uninstall_cmd,
164 9 ▶ sub { my ( $out, $err ) = @_; $stdout = $out // ''; $stderr = $err // ''; return $out },
Subroutine __ANON__: called CC=3 SCAR=11.4
Condition50%2/4
$out // ""
l!l
90
$err // ""
l!l
90
MC/DC0%0/1
$out // ""
$out
MC/DC0%0/1
$err // ""
$err
Truth table50%1/2
A
A= $out
Aresult
11
00
Truth table50%1/2
A
A= $err
Aresult
11
00
165 9 auto_die => 0);
166 9 my $exit = $? >> 8;
167 9 Rex::Logger::info($_, 'warn') for $self->uninstall_warnings($stdout, $stderr);
168 9 my $failure = $self->uninstall_failure($exit, $stderr);
169 9 ▶ die $failure if defined $failure;
Branch: 1 branch
BranchTrueFalseTotal
if defined $failure 4 5 9
170 5 Rex::Logger::info($self->_distribution_labels . " uninstalled, no Cilium datapath state left");
171 5 return 1;
172 }
173  
174 #
175 # What the lines above are made of
176 #
177  
178 # Every distribution, the default first, as unknown_distribution lists them.
179 275 ▶sub _distributions {
Subroutine _distributions: called CC=1 SCAR=0.0
180 275 my ( $self ) = @_;
181 275 my $class = $self->distribution_class;
182 275 my $default = $class->default_distribution;
183 550 return map { $class->new_for($_) }
184 275 $default, sort grep { $_ ne $default } keys %{ $class->distribution_classes };
185 }
186  
187 58 ▶sub _distribution_labels {
Subroutine _distribution_labels: called CC=1 SCAR=0.0
188 58 my ( $self ) = @_;
189 58 return join '/', map { $_->label } $self->_distributions;
190 }
191  
192 # A distribution is there: its binary on PATH, or one of its units active
193 # (systemctl is-active is true when any of the units named is).
194 192 ▶sub _distribution_present_cmd {
Subroutine _distribution_present_cmd: called CC=1 SCAR=0.0
195 192 my ( $self ) = @_;
196 192 my @dists = $self->_distributions;
197 return join ' || ',
198 384 ( map { 'command -v ' . $_->binary . ' >/dev/null 2>&1' } @dists ),
199 'systemctl is-active --quiet '
200 192 . join(' ', map { ( $_->server_service, $_->agent_service ) } @dists)
201 . ' 2>/dev/null';
202 }
203  
204 # The PATH file ensure_nvidia_runtime_path writes for the NVIDIA runtime
205 # lookup, which no vendor uninstaller removes (kubernetes-ocp, a GPU host
206 # after destroy). The line also runs on hosts Rex::Rancher did not set up, so
207 # a file goes only when it is exactly what is written on a host without one:
208 # runtime_path_line and nothing else ($(...) drops trailing newlines). A file
209 # with anything more is the admin's and stays whole, our PATH line in it too:
210 # whatever PATH that line replaced is gone, so editing it out restores
211 # nothing. Recognised by content, not a marker: the file is in restart_watch,
212 # and adding one to it would restart rke2 on every node's next run. And only
213 # once the distribution's binary is gone, since its units read the file (the
214 # outcome check reports a binary that stayed). K3s has no env files: no step.
215 50 ▶sub _env_files_cmd {
Subroutine _env_files_cmd: called CC=2 SCAR=6.9
216 50 my ( $self, $dist ) = @_;
217 50 ▶ my @files = $dist->env_files or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@files) = $dist->env_files or return 25 25 50
218 25 return 'command -v ' . $dist->binary . ' >/dev/null 2>&1 || for f in ' . join(' ', @files) . ';'
219 . ' do if [ -f $f ] && [ "$(cat $f 2>/dev/null)" = "' . $dist->runtime_path_line . '" ];'
220 . ' then rm -f $f 2>/dev/null || true; fi; done';
221 }
222  
223 # What the vendor uninstallers stop short of: the Cilium CLI
224 # (Rex::Rancher::Cilium installs it), the CNI directory (Cilium's cni.binPath,
225 # /opt/cni/bin, on both distributions) and the runtime dir RKE2 and K3s share.
226 # A stale cilium binary is not cosmetic: install_cilium keeps a CLI whose
227 # version happens to match instead of installing the one asked for.
228 #
229 # And the NVIDIA GPU Operator's: its toolkit directory /usr/local/nvidia and
230 # the two CDI specs it writes under /var/run/cdi. A re-join otherwise has
231 # rke2 pick the operator's runtime from the leftover toolkit config at start
232 # (kubernetes-ocp #228: every GPU sandbox failed on an old crun). Exactly
233 # these files, not /var/run/cdi (other specs live there), not /etc/cdi
234 # (Rex::GPU writes its own specs there with gpu.toolkit false), no host
235 # driver, no /usr/bin/nvidia-*. Distribution-independent.
236 25 ▶sub _leftover_paths {
Subroutine _leftover_paths: called CC=1 SCAR=0.0
237 25 qw(
238 /usr/local/bin/cilium /opt/cni /run/k3s
239 /usr/local/nvidia
240 /var/run/cdi/k8s.device-plugin.nvidia.com-gpu.json
241 /var/run/cdi/management.nvidia.com-gpu.yaml
242 )
243 }
244  
245 # A warning is one line on stderr, starting with the marker, so that
246 # uninstall_warnings finds it among whatever else the channel carries. The
247 # text goes between double quotes: no ", $, ` or backslash in it -- and no
248 # single quote, which the line as a whole has none of.
249 80 ▶sub _warning_marker { 'rex-rancher-uninstall-warning' }
Subroutine _warning_marker: called CC=1 SCAR=0.0
250  
251 50 ▶sub _warning_cmd {
Subroutine _warning_cmd: called CC=1 SCAR=0.0
252 50 my ( $self, $text ) = @_;
253 # || true: a warning that cannot be written must not fail the line.
254 50 return 'echo "' . $self->_warning_marker . ': ' . $text . '" >&2 || true';
255 }
256  
257 # Cilium's proxy route tables (2004 to-proxy, 2005 from-proxy); nothing else
258 # uses these table ids.
259 50 ▶sub _cilium_ip_tables { ( 2004, 2005 ) }
Subroutine _cilium_ip_tables: called CC=1 SCAR=0.0
260  
261 25 ▶sub _cilium_pins { qw( /sys/fs/bpf/cilium /sys/fs/bpf/tc/globals/cilium_* ) }
Subroutine _cilium_pins: called CC=1 SCAR=0.0
262 442 ▶sub _cilium_cgroup_root { '/run/cilium/cgroupv2' }
Subroutine _cilium_cgroup_root: called CC=1 SCAR=0.0
263 25 ▶sub _cilium_run_dir { '/run/cilium' }
Subroutine _cilium_run_dir: called CC=1 SCAR=0.0
264 25 ▶sub _cilium_links { qw( cilium_host cilium_net cilium_vxlan cilium_geneve cilium_wg0 ) }
Subroutine _cilium_links: called CC=1 SCAR=0.0
265 25 ▶sub _iptables {
Subroutine _iptables: called CC=1 SCAR=0.0
266 25 qw( iptables ip6tables iptables-legacy ip6tables-legacy iptables-nft ip6tables-nft )
267 }
268  
269 # The way Cilium's own post-uninstall cleanup clears it, without bpftool (not
270 # on the hosts) and without the agent's image:
271 #
272 # - pinned objects: Cilium attaches its cgroup and tcx programs as bpf_links
273 # (kernel 5.7+) and pins the links under /sys/fs/bpf/cilium so they
274 # survive the agent. Unpinning the last reference -- the agent is gone --
275 # releases the link, and the kernel detaches the program: the rm IS the
276 # detach;
277 # - legacy tc attachments (kernel without tcx): the clsact qdisc of every
278 # device that carries a Cilium program goes, and its filters with it;
279 # - Cilium's devices, and its iptables chains in every backend present:
280 # jumps into them deleted, then flushed and removed, in one restore
281 # transaction per table;
282 # - the cgroup2 mount, then Cilium's runtime dir -- with --one-file-system,
283 # so a mount that refused to go is never recursed into.
284 #
285 # A tool the tc or the iptables step needs that is missing skips that step
286 # with a warning, not silently: tc is not in Rocky's/RHEL's base (it comes
287 # with iproute-tc), and a host may have no iptables tools at all while
288 # Cilium's own container wrote the chains.
289 #
290 # Taken over as kubernetes-ocp runs it (OCP::Role::Provider::ExistingHost).
291 25 ▶sub _cilium_cleanup_cmd {
Subroutine _cilium_cleanup_cmd: called CC=1 SCAR=0.0
292 25 my ( $self ) = @_;
293 25 my $cgroup = $self->_cilium_cgroup_root;
294 25 return join ' ; ',
295 'if command -v tc >/dev/null 2>&1; then'
296 . ' for d in /sys/class/net/*; do d=${d##*/};'
297 . ' if tc filter show dev $d ingress 2>/dev/null | grep -qE "cil_|bpf_(netdev|host|overlay|lxc)"'
298 . ' || tc filter show dev $d egress 2>/dev/null | grep -qE "cil_|bpf_(netdev|host|overlay|lxc)";'
299 . ' then tc qdisc del dev $d clsact 2>/dev/null || true; fi; done;'
300 . ' else ' . $self->_warning_cmd('tc is not installed: tc attachments Cilium left on the host'
301 . ' devices were not checked or removed (on Rocky/RHEL, tc comes with the iproute-tc package);'
302 . ' a reboot clears them') . '; fi',
303 'rm -rf ' . join(' ', $self->_cilium_pins) . ' 2>/dev/null || true',
304 'for l in ' . join(' ', $self->_cilium_links) . '; do ip link del dev $l 2>/dev/null || true; done',
305 'ipt_used=""',
306 'for ipt in ' . join(' ', $self->_iptables) . '; do'
307 . ' command -v $ipt-save >/dev/null 2>&1 && command -v $ipt-restore >/dev/null 2>&1 || continue;'
308 . ' ipt_used=1;'
309 . ' for tb in filter nat mangle raw; do'
310 . ' s=$($ipt-save -t $tb 2>/dev/null) || continue;'
311 . ' printf "%s\n" "$s" | grep -qE "^:(OLD_)?CILIUM_" || continue;'
312 . ' { echo "*$tb";'
313 . ' printf "%s\n" "$s" | grep -E "^-A " | grep -vE "^-A (OLD_)?CILIUM_" | grep -E -- "-j (OLD_)?CILIUM_" | sed "s/^-A /-D /";'
314 . ' printf "%s\n" "$s" | sed -nE "s/^:((OLD_)?CILIUM_[^ ]*) .*/-F \1/p";'
315 . ' printf "%s\n" "$s" | sed -nE "s/^:((OLD_)?CILIUM_[^ ]*) .*/-X \1/p";'
316 . ' echo COMMIT; } | $ipt-restore --noflush 2>/dev/null || true;'
317 . ' done; done',
318 '[ -n "$ipt_used" ] || ' . $self->_warning_cmd('no iptables backend with both -save and -restore'
319 . ' is installed: the CILIUM_* iptables chains Cilium left were not checked or removed;'
320 . ' a reboot clears them'),
321 "umount $cgroup 2>/dev/null || umount -l $cgroup 2>/dev/null || true",
322 'rm -rf --one-file-system ' . $self->_cilium_run_dir . ' 2>/dev/null || true';
323 }
324  
325 57 1;
326  
327 __END__
« lib/Rex/Rancher/Checksum.pm ↑ Summary lib/Rex/Rancher/Distribution/K3s.pm »