Skip to content

Commit c4ca3c5

Browse files
authored
chore(cni-plugin): make script stylistically more consistent (#528)
This pr makes no functional changes but makes the cni-plugin/deployment/scripts/install-cni.sh script stylistically more consistent. Signed-off-by: Simon Dickhoven <sdickhoven@everquote.com>
1 parent 90a0446 commit c4ca3c5

File tree

1 file changed

+76
-73
lines changed

1 file changed

+76
-73
lines changed

cni-plugin/deployment/scripts/install-cni.sh

Lines changed: 76 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@
2020
# 2) https://github.com/istio/cni/blob/c63a509539b5ed165a6617548c31b686f13c2133/deployments/kubernetes/install/scripts/install-cni.sh
2121

2222
# Script to install Linkerd CNI on a Kubernetes host.
23-
# - Expects the host CNI binary path to be mounted at /host/opt/cni/bin.
24-
# - Expects the host CNI network config path to be mounted at /host/etc/cni/net.d.
25-
# - Expects the desired CNI config in the CNI_NETWORK_CONFIG env variable.
23+
# - Expects the host CNI binary path to be mounted at /host/opt/cni/bin
24+
# - Expects the host CNI network config path to be mounted at /host/etc/cni/net.d
25+
# - Expects the desired CNI config in the CNI_NETWORK_CONFIG env variable
2626

27-
# Ensure all variables are defined, and that the script fails when an error is hit.
28-
set -u -e -o pipefail
27+
# Ensure all variables are defined, and that the script fails when an error is
28+
# hit.
29+
set -u -e -o pipefail +o noclobber
2930

3031
# Helper function for raising errors
3132
# Usage:
@@ -66,36 +67,37 @@ SERVICEACCOUNT_PATH=/var/run/secrets/kubernetes.io/serviceaccount
6667
# *conflist files, then linkerd-cni configuration parameters will be removed
6768
# from them.
6869
cleanup() {
69-
# First, kill both 'inotifywait' processes so we don't process any DELETE/CREATE events
70+
# First, kill both 'inotifywait' processes so we don't process any
71+
# DELETE/CREATE events.
7072
pids=$(pgrep inotifywait)
71-
if [ -n "$pids" ]; then
73+
if [ -n "${pids}" ]; then
7274
while read -r pid; do
73-
log "Sending SIGKILL to inotifywait (PID: $pid)"
74-
kill -s KILL "$pid"
75-
done <<< "$pids"
75+
log "Sending SIGKILL to inotifywait (PID: ${pid})"
76+
kill -s KILL "${pid}"
77+
done <<< "${pids}"
7678
fi
7779

7880
log 'Removing linkerd-cni artifacts.'
7981

8082
# Find all conflist files and print them out using a NULL separator instead of
8183
# writing each file in a new line. We will subsequently read each string and
8284
# attempt to rm linkerd config from it using jq helper.
83-
local cni_data=''
85+
local cni_data
8486
find "${HOST_CNI_NET}" -maxdepth 1 -type f \( -iname '*conflist' \) -print0 |
8587
while read -r -d $'\0' file; do
86-
log "Removing linkerd-cni config from $file"
87-
cni_data=$(jq 'del( .plugins[]? | select( .type == "linkerd-cni" ))' "$file")
88+
log "Removing linkerd-cni config from ${file}"
89+
cni_data=$(jq 'del( .plugins[]? | select( .type == "linkerd-cni" ))' "${file}")
8890
# TODO (matei): we should write this out to a temp file and then do a `mv`
8991
# to be atomic.
90-
echo "$cni_data" > "$file"
92+
echo "${cni_data}" > "${file}"
9193
done
9294

9395
# Remove binary and kubeconfig file
9496
if [ -e "${HOST_CNI_NET}/${KUBECONFIG_FILE_NAME}" ]; then
9597
log "Removing linkerd-cni kubeconfig: ${HOST_CNI_NET}/${KUBECONFIG_FILE_NAME}"
9698
rm -f "${HOST_CNI_NET}/${KUBECONFIG_FILE_NAME}"
9799
fi
98-
if [ -e "${CONTAINER_MOUNT_PREFIX}${DEST_CNI_BIN_DIR}"/linkerd-cni ]; then
100+
if [ -e "${CONTAINER_MOUNT_PREFIX}${DEST_CNI_BIN_DIR}/linkerd-cni" ]; then
99101
log "Removing linkerd-cni binary: ${CONTAINER_MOUNT_PREFIX}${DEST_CNI_BIN_DIR}/linkerd-cni"
100102
rm -f "${CONTAINER_MOUNT_PREFIX}${DEST_CNI_BIN_DIR}/linkerd-cni"
101103
fi
@@ -117,7 +119,7 @@ install_cni_bin() {
117119
exit_with_error "${dir} is non-writeable, failure"
118120
fi
119121
for path in "${CONTAINER_CNI_BIN_DIR}"/*; do
120-
cp "${path}" "${dir}"/ || exit_with_error "Failed to copy ${path} to ${dir}."
122+
cp "${path}" "${dir}/" || exit_with_error "Failed to copy ${path} to ${dir}."
121123
done
122124

123125
log "Wrote linkerd CNI binaries to ${dir}"
@@ -126,7 +128,7 @@ install_cni_bin() {
126128
create_kubeconfig() {
127129
KUBE_CA_FILE=${KUBE_CA_FILE:-${SERVICEACCOUNT_PATH}/ca.crt}
128130
SKIP_TLS_VERIFY=${SKIP_TLS_VERIFY:-false}
129-
SERVICEACCOUNT_TOKEN=$(cat ${SERVICEACCOUNT_PATH}/token)
131+
SERVICEACCOUNT_TOKEN=$(cat "${SERVICEACCOUNT_PATH}/token")
130132

131133
# Check if we're not running as a k8s pod.
132134
if [[ ! -f "${SERVICEACCOUNT_PATH}/token" ]]; then
@@ -184,40 +186,43 @@ create_cni_conf() {
184186
cp "${CNI_NETWORK_CONFIG_FILE}" "${TMP_CONF}"
185187
elif [ "${CNI_NETWORK_CONFIG}" ]; then
186188
log 'Using CNI config template from CNI_NETWORK_CONFIG environment variable.'
187-
cat >"${TMP_CONF}" <<EOF
189+
cat <<EOF > "${TMP_CONF}"
188190
${CNI_NETWORK_CONFIG}
189191
EOF
190192
fi
191193

192194
# Use alternative command character "~", since these include a "/".
193-
sed -i s~__KUBECONFIG_FILEPATH__~"${DEST_CNI_NET_DIR}/${KUBECONFIG_FILE_NAME}"~g ${TMP_CONF}
195+
sed -i s~__KUBECONFIG_FILEPATH__~"${DEST_CNI_NET_DIR}/${KUBECONFIG_FILE_NAME}"~g "${TMP_CONF}"
194196

195-
log "CNI config: $(cat ${TMP_CONF})"
197+
log "CNI config: $(cat "${TMP_CONF}")"
196198
}
197199

198200
install_cni_conf() {
199-
local cni_conf_path=$1
201+
local cni_conf_path=${1}
200202

201203
# Add the linkerd-cni plugin to the existing list.
202204
local tmp_data
203205
local conf_data
204-
tmp_data=$(cat "$TMP_CONF")
205-
conf_data=$(jq --argjson CNI_TMP_CONF_DATA "$tmp_data" -f /linkerd/filter.jq "$cni_conf_path" || true)
206+
tmp_data=$(cat "${TMP_CONF}")
207+
conf_data=$(jq --argjson CNI_TMP_CONF_DATA "${tmp_data}" -f /linkerd/filter.jq "${cni_conf_path}" || true)
206208

207209
# Ensure that CNI config file did not disappear during processing.
208-
[ -n "$conf_data" ] || return 0
210+
[ -n "${conf_data}" ] || return 0
209211

210-
echo "$conf_data" > "$TMP_CONF"
212+
echo "${conf_data}" > "${TMP_CONF}"
211213

212-
# If the old config filename ends with .conf, rename it to .conflist, because it has changed to be a list
214+
# If the old config filename ends with .conf, rename it to .conflist because
215+
# it has changed to be a list.
216+
local filename
217+
local extension
213218
filename=${cni_conf_path##*/}
214219
extension=${filename##*.}
215220
# When this variable has a file, we must delete it later.
216221
old_file_path=
217222
if [ "${filename}" != '01-linkerd-cni.conf' ] && [ "${extension}" = 'conf' ]; then
218-
old_file_path=${cni_conf_path}
219-
log "Renaming ${cni_conf_path} extension to .conflist"
220-
cni_conf_path="${cni_conf_path}list"
223+
old_file_path=${cni_conf_path}
224+
log "Renaming ${cni_conf_path} extension to .conflist"
225+
cni_conf_path=${cni_conf_path}list
221226
fi
222227

223228
# Store SHA of each patched file in global `CNI_CONF_SHA` variable.
@@ -234,35 +239,36 @@ install_cni_conf() {
234239
# "/etc/cni/net.d/10-bar.conflist": "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"
235240
# }
236241
local new_sha
237-
new_sha=$( (sha256sum "$TMP_CONF" || true) | awk '{print $1}' )
238-
CNI_CONF_SHA=$(jq -c --arg f "$cni_conf_path" --arg sha "$new_sha" '. * {$f: $sha}' <<< "$CNI_CONF_SHA")
242+
new_sha=$( (sha256sum "${TMP_CONF}" || true) | awk '{print $1}' )
243+
CNI_CONF_SHA=$(jq -c --arg f "${cni_conf_path}" --arg sha "${new_sha}" '. * {$f: $sha}' <<< "${CNI_CONF_SHA}")
239244

240245
# Move the temporary CNI config into place.
241246
mv "${TMP_CONF}" "${cni_conf_path}" || exit_with_error 'Failed to mv files.'
242-
[ -n "$old_file_path" ] && rm -f "${old_file_path}" && log "Removing unwanted .conf file"
247+
[ -n "${old_file_path}" ] && rm -f "${old_file_path}" && log "Removing unwanted .conf file"
243248

244249
log "Created CNI config ${cni_conf_path}"
245250
}
246251

247-
# Sync() is responsible for reacting to file system changes. It is used in
248-
# conjunction with inotify events; sync() is called with the event type (which
249-
# can be either 'CREATE', 'MOVED_TO' or 'MODIFY'), and the name of the file that
252+
# `sync()` is responsible for reacting to file system changes. It is used in
253+
# conjunction with inotify events; `sync()` is called with the event type (which
254+
# can be either 'CREATE', 'MOVED_TO', or 'MODIFY') and the name of the file that
250255
# has changed.
251256
#
252-
# Based on the changed file, sync() might re-install the CNI configuration file.
257+
# Based on the changed file, `sync()` might re-install the CNI configuration
258+
# file.
253259
sync() {
254-
local ev=$1
260+
local ev=${1}
255261
local file=${2//\/\//\/} # replace "//" with "/"
256262

257-
[[ "$file" =~ .*.(conflist|conf)$ ]] || return 0
263+
[[ "${file}" =~ .*.(conflist|conf)$ ]] || return 0
258264

259-
log "Detected event: $ev $file"
265+
log "Detected event: ${ev} ${file}"
260266

261267
# Retrieve previous SHA of detected file (if any) and compute current SHA.
262268
local previous_sha
263269
local current_sha
264-
previous_sha=$(jq -r --arg f "$file" '.[$f] | select(.)' <<< "$CNI_CONF_SHA")
265-
current_sha=$( (sha256sum "$file" || true) | awk '{print $1}' )
270+
previous_sha=$(jq -r --arg f "${file}" '.[$f] | select(.)' <<< "${CNI_CONF_SHA}")
271+
current_sha=$( (sha256sum "${file}" || true) | awk '{print $1}' )
266272

267273
# If the SHA hasn't changed or the detected file has disappeared, ignore it.
268274
# When the SHA is the same, we can get into infinite loops whereby a file
@@ -274,21 +280,21 @@ sync() {
274280
# creates a config file and then _immediately_ removes it again _while_ we are
275281
# in the process of patching it. If this happens, we may create a patched CNI
276282
# config file that should *not* exist.
277-
if [ -n "$current_sha" ] && [ "$current_sha" != "$previous_sha" ]; then
278-
log "New/changed file [$file] detected; re-installing"
283+
if [ -n "${current_sha}" ] && [ "${current_sha}" != "${previous_sha}" ]; then
284+
log "New/changed file [${file}] detected; re-installing"
279285
create_kubeconfig
280286
create_cni_conf
281-
install_cni_conf "$file"
287+
install_cni_conf "${file}"
282288
else
283-
log "Ignoring event: $ev $file; no real changes detected or file disappeared"
289+
log "Ignoring event: ${ev} ${file}; no real changes detected or file disappeared"
284290
fi
285291
}
286292

287293
# monitor_cni_config starts a watch on the host's CNI config directory
288294
monitor_cni_config() {
289295
inotifywait -m "${HOST_CNI_NET}" -e create,moved_to,modify |
290296
while read -r directory action filename; do
291-
sync "$action" "$directory/$filename"
297+
sync "${action}" "${directory}/${filename}"
292298
done
293299
}
294300

@@ -302,22 +308,23 @@ monitor_cni_config() {
302308
# Indeed, as per atomic writer's Write function docs, in the final steps the
303309
# ..data_tmp symlink points to a new timestamped directory containing the new
304310
# files, which is then atomically renamed to ..data:
305-
# > 8. A symlink to the new timestamped directory ..data_tmp is created that will
306-
# > become the new data directory.
307-
# > 9. The new data directory symlink is renamed to the data directory; rename is atomic.
311+
# > 8. A symlink to the new timestamped directory ..data_tmp is created that
312+
# > will become the new data directory.
313+
# > 9. The new data directory symlink is renamed to the data directory; rename
314+
# > is atomic.
308315
# See https://github.com/kubernetes/kubernetes/blob/release-1.32/pkg/volume/util/atomic_writer.go
309316
monitor_service_account_token() {
310-
inotifywait -m "${SERVICEACCOUNT_PATH}" -e moved_to |
311-
while read -r _ _ filename; do
312-
if [[ "$filename" == "..data" ]]; then
317+
inotifywait -m "${SERVICEACCOUNT_PATH}" -e moved_to |
318+
while read -r _ _ filename; do
319+
if [[ "${filename}" == "..data" ]]; then
313320
log "Detected change in service account files; recreating kubeconfig file"
314321
create_kubeconfig
315-
fi
316-
done
322+
fi
323+
done
317324
}
318325

319326
log() {
320-
printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1"
327+
printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${1}"
321328
}
322329

323330
################################
@@ -339,24 +346,19 @@ CNI_CONF_SHA='{}'
339346
monitor_cni_config &
340347

341348
# Append our config to any existing config file (*.conflist or *.conf)
342-
config_files=$(find "${HOST_CNI_NET}" -maxdepth 1 -type f \( -iname '*conflist' -o -iname '*conf' \))
343-
if [ -z "$config_files" ]; then
344-
log "No active CNI configuration files found"
349+
config_files=$(find "${HOST_CNI_NET}" -maxdepth 1 -type f ! -name '*linkerd*' \( -iname '*conflist' -o -iname '*conf' \))
350+
if [ -z "${config_files}" ]; then
351+
log "No active CNI configuration files found"
345352
else
346-
config_file_count=$(echo "$config_files" | grep -v linkerd | sort | wc -l)
347-
if [ "$config_file_count" -eq 0 ]; then
348-
log "No active CNI configuration files found"
349-
else
350-
find "${HOST_CNI_NET}" -maxdepth 1 -type f \( -iname '*conflist' -o -iname '*conf' \) -print0 |
351-
while read -r -d $'\0' file; do
352-
log "Trigger CNI config detection for $file"
353-
tmp_file="$(mktemp -u /tmp/linkerd-cni.patch-candidate.XXXXXX)"
354-
cp -fp "$file" "$tmp_file"
355-
# The following will trigger the `sync()` function via filesystem event.
356-
# This requires `monitor_cni_config()` to be up and running!
357-
mv "$tmp_file" "$file" || exit_with_error 'Failed to mv files.'
358-
done
359-
fi
353+
find "${HOST_CNI_NET}" -maxdepth 1 -type f \( -iname '*conflist' -o -iname '*conf' \) -print0 |
354+
while read -r -d $'\0' file; do
355+
log "Trigger CNI config detection for ${file}"
356+
tmp_file="$(mktemp -u /tmp/linkerd-cni.patch-candidate.XXXXXX)"
357+
cp -fp "${file}" "${tmp_file}"
358+
# The following will trigger the `sync()` function via filesystem event.
359+
# This requires `monitor_cni_config()` to be up and running!
360+
mv "${tmp_file}" "${file}" || exit_with_error 'Failed to mv files.'
361+
done
360362
fi
361363

362364
# Watch in bg so we can receive interrupt signals through 'trap'. From 'man
@@ -368,5 +370,6 @@ fi
368370
# the wait builtin to return immediately with an exit status greater than 128,
369371
# immediately after which the trap is executed."
370372
monitor_service_account_token &
371-
# uses -n so that we exit when the first background job exits (when there's an error)
373+
# uses -n so that we exit when the first background job exits (when there's an
374+
# error)
372375
wait -n

0 commit comments

Comments
 (0)