Skip to content

Commit

Permalink
Feature/add node format (canonical#2623)
Browse files Browse the repository at this point in the history
* Add format option for microk8s add-node (canonical#2395)

* Add output for error calling utils from add_token

Co-authored-by: John P Lettman <john.lettman@canonical.com>
  • Loading branch information
joedborg and johnlettman authored Oct 5, 2021
1 parent 3d9aabe commit 67a8fb0
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 24 deletions.
41 changes: 40 additions & 1 deletion microk8s-resources/actions/common/utils.sh
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,7 @@ mark_boot_time() {
try_copy_users_to_snap_microk8s() {
# try copy users from microk8s to snap_microk8s group
if getent group microk8s >/dev/null 2>&1 &&
getent group snap_microk8s >/dev/null 2>&1
getent group snap_microk8s >/dev/null 2>&1
then
for m in $($SNAP/usr/bin/members microk8s)
do
Expand All @@ -722,3 +722,42 @@ try_copy_users_to_snap_microk8s() {
echo "One of the microk8s or snap_microk8s groups is missing"
fi
}

cluster_agent_port() {
port="25000"
if grep -e port "${SNAP_DATA}"/args/cluster-agent &> /dev/null
then
port=$(cat "${SNAP_DATA}"/args/cluster-agent | "$SNAP"/usr/bin/gawk '{print $2}')
fi

echo "$port"
}

server_cert_check() {
openssl x509 -in "$SNAP_DATA"/certs/server.crt -outform der | sha256sum | cut -d' ' -f1 | cut -c1-12
}

# check if this file is run with arguments
if [[ "$0" == "${BASH_SOURCE}" ]] &&
[[ ! -z "$1" ]]
then
# call help
if echo "$*" | grep -q -- 'help'; then
echo "usage: $0 [function]"
echo ""
echo "Run a utility function and return the output."
echo ""
echo "available functions:"
declare -F | gawk '{print "- "$3}'
exit 0
fi

if declare -F "$1" > /dev/null
then
$1 ${@:2}
exit $?
else
echo "Function does not exist: $1" >&2
exit 1
fi
fi
23 changes: 1 addition & 22 deletions microk8s-resources/wrappers/microk8s-add-node.wrapper
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,4 @@ then
fi

# Use python's built-in (3.6+) secrets generator to produce the token.
token="$(LD_LIBRARY_PATH=$IN_SNAP_LD_LIBRARY_PATH ${SNAP}/usr/bin/python3 ${SNAP}/scripts/cluster/add_token.py $@)"

port="25000"
if grep -e port "${SNAP_DATA}"/args/cluster-agent &> /dev/null
then
port=$(cat "${SNAP_DATA}"/args/cluster-agent | "$SNAP"/usr/bin/gawk '{print $2}')
fi

default_ip="$(get_default_ip)"
all_ips="$(get_ips)"

check=$(openssl x509 -in "$SNAP_DATA"/certs/server.crt -outform der | sha256sum | cut -d' ' -f1 | cut -c1-12)

echo "From the node you wish to join to this cluster, run the following:"
echo "microk8s join ${default_ip}:$port/${token}/${check}"
echo ""
echo "If the node you are adding is not reachable through the default interface you can use one of the following:"
for addr in $(echo "${all_ips}"); do
if ! [[ $addr == *":"* ]]; then
echo " microk8s join ${addr}:$port/${token}/${check}"
fi
done
LD_LIBRARY_PATH=$IN_SNAP_LD_LIBRARY_PATH ${SNAP}/usr/bin/python3 ${SNAP}/scripts/cluster/add_token.py $@
78 changes: 77 additions & 1 deletion scripts/cluster/add_token.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import sys
import time
import argparse
import subprocess

try:
from secrets import token_hex
Expand All @@ -12,6 +14,7 @@ def token_hex(nbytes=None):


cluster_tokens_file = os.path.expandvars("${SNAP_DATA}/credentials/cluster-tokens.txt")
utils_sh_file = os.path.expandvars("${SNAP}/actions/common/utils.sh")
token_with_expiry = "{}|{}\n"
token_without_expiry = "{}\n"

Expand All @@ -36,6 +39,64 @@ def add_token_with_expiry(token, file, ttl):
fp.write(token_without_expiry.format(token))


def run_util(*args, debug=False):
env = os.environ.copy()
prog = ["bash", utils_sh_file]
prog.extend(args)

if debug:
print("\033[;1;32m+ %s\033[;0;0m" % " ".join(prog))

result = subprocess.run(
prog,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
)

try:
result.check_returncode()
except subprocess.CalledProcessError:
print("Failed to call utility function.")
sys.exit(1)

return result.stdout.decode("utf-8").strip()


def get_network_info():
"""
Obtain machine IP address(es) and cluster agent port.
:return: tuple of default IP, all IPs, and cluster agent port
"""
default_ip = run_util("get_default_ip")
all_ips = run_util("get_ips").split(" ")
port = run_util("cluster_agent_port")

return (default_ip, all_ips, port)


def print_pretty(token, check):
default_ip, all_ips, port = get_network_info()

print("From the node you wish to join to this cluster, run the following:")
print(f"microk8s join {default_ip}:{port}/{token}/{check}\n")

print(
"If the node you are adding is not reachable through the default interface you can use one of the following:"
)
for ip in all_ips:
print(f"microk8s join {ip}:{port}/{token}/{check}")


def print_short(token, check):
default_ip, all_ips, port = get_network_info()

print(f"microk8s join {default_ip}:{port}/{token}/{check}")
for ip in all_ips:
print(f"microk8s join {ip}:{port}/{token}/{check}")


if __name__ == "__main__":

# initiate the parser with a description
Expand All @@ -58,6 +119,12 @@ def add_token_with_expiry(token, file, ttl):
help="Specify the bootstrap token to add, must be 32 characters long. "
"Auto generates when empty.",
)
parser.add_argument(
"--format",
help="Format the output of the token in pretty, short, token, or token-check",
default="pretty",
choices={"pretty", "short", "token", "token-check"},
)

# read arguments from the command line
args = parser.parse_args()
Expand All @@ -74,4 +141,13 @@ def add_token_with_expiry(token, file, ttl):
exit(1)

add_token_with_expiry(token, cluster_tokens_file, ttl)
print(token)
check = run_util("server_cert_check")

if args.format == "pretty":
print_pretty(token, check)
elif args.format == "short":
print_short(token, check)
elif args.format == "token-check":
print(f"{token}/{check}")
else:
print(token)

0 comments on commit 67a8fb0

Please sign in to comment.