Merge "Update jump server to Ubuntu 20.04"
[icn.git] / env / lib / common.sh
1 #!/usr/bin/env bash
2 set -eu -o pipefail
3
4 IRONIC_DATA_DIR=${IRONIC_DATA_DIR:-"/opt/ironic"}
5 NODES_FILE=${NODES_FILE:-"${IRONIC_DATA_DIR}/nodes.json"}
6 #IRONIC_PROVISIONING_INTERFACE is required to be provisioning, don't change it
7 IRONIC_INTERFACE=${IRONIC_INTERFACE:-}
8 IRONIC_PROVISIONING_INTERFACE=${IRONIC_PROVISIONING_INTERFACE:-"provisioning"}
9 IRONIC_PROVISIONING_INTERFACE_IP=${IRONIC_PROVISIONING_INTERFACE_IP:-"172.22.0.1"}
10 BM_IMAGE_URL=${BM_IMAGE_URL:-"https://cloud-images.ubuntu.com/focal/current/focal-server-cloudimg-amd64.img"}
11 BM_IMAGE=${BM_IMAGE:-"focal-server-cloudimg-amd64.img"}
12
13 #Baremetal operator repository URL
14 BMOREPO="${BMOREPO:-https://github.com/metal3-io/baremetal-operator.git}"
15 #Path to clone the baremetal operator repo
16 BMOPATH="/opt/src/github.com/metal3-io/baremetal-operator"
17 #Bare Metal Operator version to use
18 BMO_VERSION="capm3-v0.5.1"
19
20 #KuD repository URL
21 KUDREPO="${KUDREPO:-https://github.com/onap/multicloud-k8s.git}"
22 #Path to clone the KuD repo
23 KUDPATH="/opt/src/github.com/onap/multicloud-k8s"
24 #KuD version to use
25 KUD_VERSION="ed96bca7fe415f1636d82c26af15d7474bdfe876"
26
27 #EMCO repository URL
28 EMCOREPO="${EMCOREPO:-https://github.com/open-ness/EMCO.git}"
29 #Path to clone the EMCO repo
30 EMCOPATH="/opt/src/github.com/open-ness/EMCO"
31 #EMCO version to use
32 EMCO_VERSION="openness-21.03.06"
33
34 #Discard existing repo directory
35 FORCE_REPO_UPDATE="${FORCE_REPO_UPDATE:-true}"
36
37 # The kustomize version to use
38 KUSTOMIZE_VERSION="v4.3.0"
39
40 #Cluster API version to use
41 CAPI_VERSION="v0.4.3"
42
43 #Cluster API version to use
44 CAPM3_VERSION="v0.5.1"
45
46 #The flux version to use
47 FLUX_VERSION="0.20.0"
48
49 #The sops version to use
50 SOPS_VERSION="v3.7.1"
51
52 #refered from onap
53 function call_api {
54     #Runs curl with passed flags and provides
55     #additional error handling and debug information
56
57     #Function outputs server response body
58     #and performs validation of http_code
59
60     local status
61     local curl_response_file="$(mktemp -p /tmp)"
62     local curl_common_flags=(-s -w "%{http_code}" -o "${curl_response_file}")
63     local command=(curl "${curl_common_flags[@]}" "$@")
64
65     echo "[INFO] Running '${command[@]}'" >&2
66     if ! status="$("${command[@]}")"; then
67         echo "[ERROR] Internal curl error! '$status'" >&2
68         cat "${curl_response_file}"
69         rm "${curl_response_file}"
70         return 2
71     else
72         echo "[INFO] Server replied with status: ${status}" >&2
73         cat "${curl_response_file}"
74         rm "${curl_response_file}"
75         if [[ "${status:0:1}" =~ [45] ]]; then
76             return 1
77         else
78             return 0
79         fi
80     fi
81 }
82
83 function list_nodes {
84     if [ ! -f "$NODES_FILE" ]; then
85         exit 1
86     fi
87
88     # The boot MAC address must be specified when a port is included
89     # in the IPMI driver address (i.e when using the VirtualBMC
90     # controller).  Note that the below is a bit of a hack as it only
91     # checks the first entry in NODES_FILE for the port.
92     if cat "$NODES_FILE" |
93             jq -r '.nodes[0].ipmi_driver_info.address' | grep -c ':[0-9]\+$' >/dev/null; then
94         BOOT_LINK=$(cat "$NODES_FILE" |
95                         jq -r '.nodes[0].net.links | map(.id=="provisioning_nic") | index(true)')
96         cat "$NODES_FILE" |
97             jq -r --argjson BOOT_LINK $BOOT_LINK '.nodes[] | [
98                .name,
99                .ipmi_driver_info.username,
100                .ipmi_driver_info.password,
101                .ipmi_driver_info.address,
102                .net.links[$BOOT_LINK].ethernet_mac_address,
103                .os.username,
104                .os.password,
105                .os.image_name
106                ] | @csv' |
107             sed 's/"//g'
108     else
109         cat "$NODES_FILE" |
110             jq -r '.nodes[] | [
111                .name,
112                .ipmi_driver_info.username,
113                .ipmi_driver_info.password,
114                .ipmi_driver_info.address,
115                "",
116                .os.username,
117                .os.password,
118                .os.image_name
119                ] | @csv' |
120             sed 's/"//g'
121     fi
122 }
123
124 function node_userdata {
125     name="$1"
126     username="$2"
127     password="$3"
128     COMPUTE_NODE_FQDN="$name.akraino.icn.org"
129
130     # validate that the user isn't expecting the deprecated
131     # COMPUTE_NODE_PASSWORD to be used
132     if [ "$password" != "${COMPUTE_NODE_PASSWORD:-$password}" ]; then
133         cat <<EOF
134 COMPUTE_NODE_PASSWORD "$COMPUTE_NODE_PASSWORD" not equal to nodes.json $name password "$password".
135 Unset COMPUTE_NODE_PASSWORD and retry.
136 EOF
137         exit 1
138     fi
139
140     printf "userData:\n"
141     if [ -n "$username" ]; then
142         printf "  name: ${username}\n"
143     fi
144     if [ -n "$password" ]; then
145         passwd=$(mkpasswd --method=SHA-512 --rounds 4096 "$password")
146         printf "  hashedPassword: ${passwd}\n"
147     fi
148
149     if [ -n "$COMPUTE_NODE_FQDN" ]; then
150         printf "  fqdn: ${COMPUTE_NODE_FQDN}\n"
151     fi
152
153     if [ ! -f $HOME/.ssh/id_rsa.pub ]; then
154         yes y | ssh-keygen -t rsa -N "" -f $HOME/.ssh/id_rsa
155     fi
156
157     printf "  sshAuthorizedKey: $(cat $HOME/.ssh/id_rsa.pub)\n"
158 }
159
160 # Returns "null" when the field is not present
161 function networkdata_networks_field {
162     name=$1
163     network=$2
164     field=$3
165     cat $NODES_FILE | jq -c -r --arg name "$name" --arg network "$network" --arg field "$field" '.nodes[] | select(.name==$name) | .net.networks[] | select(.id==$network).'${field}
166 }
167
168 # Returns "null" when the field is not present
169 function networkdata_links_field {
170     name=$1
171     link=$2
172     field=$3
173     cat $NODES_FILE | jq -c -r --arg name "$name" --arg link "$link" --arg field "$field" '.nodes[] | select(.name==$name) | .net.links[] | select(.id==$link).'${field}
174 }
175
176 function node_networkdata {
177     name=$1
178
179     if [ ! -f "$NODES_FILE" ]; then
180         exit 1
181     fi
182
183     printf "networks:\n"
184     for network in $(cat $NODES_FILE | jq -r --arg name "$name" '.nodes[] | select(.name==$name) | .net.networks[].id'); do
185         link=$(networkdata_networks_field $name $network "link")
186         type=$(networkdata_networks_field $name $network "type")
187         mac=$(networkdata_links_field $name $link "ethernet_mac_address")
188
189         # Optional values
190         ip_address=$(networkdata_networks_field $name $network "ip_address")
191         gateway=$(networkdata_networks_field $name $network "gateway")
192         dns_nameservers=$(networkdata_networks_field $name $network "dns_nameservers")
193
194         printf "  ${network}:\n"
195         printf "    macAddress: ${mac}\n"
196         printf "    type: ${type}\n"
197         if [[ $ip_address != "null" ]]; then
198             printf "    ipAddress: ${ip_address}\n"
199         fi
200         if [[ $gateway != "null" ]]; then
201             printf "    gateway: ${gateway}\n"
202         fi
203         if [[ $dns_nameservers != "null" ]]; then
204             printf "    nameservers: ${dns_nameservers}\n"
205         fi
206     done
207 }
208
209 function wait_for {
210     local -r interval=${WAIT_FOR_INTERVAL:-30s}
211     local -r max_tries=${WAIT_FOR_TRIES:-20}
212     local try=0
213     until "$@"; do
214         echo "[${try}/${max_tries}] - Waiting ${interval} for $*"
215         sleep ${interval}
216         try=$((try+1))
217         if [[ ${try} -ge ${max_tries} ]]; then
218             return 1
219         fi
220     done
221 }
222
223 # This is intended to be used together with list_nodes in the
224 # following way:
225 #   list_nodes | while IFS=',' read -r name ipmi_username ipmi_password ipmi_address boot_mac os_username os_password os_image_name; do ...
226 function node_machine_values {
227     printf "machineName: ${name}\n"
228     printf "machineLabels:\n"
229     printf "  machine: ${name}\n"
230     printf "bmcUsername: ${ipmi_username}\n"
231     printf "bmcPassword: ${ipmi_password}\n"
232     printf "bmcAddress: ipmi://${ipmi_address}\n"
233     if [[ ! -z ${boot_mac} ]]; then
234         printf "bootMACAddress: ${boot_mac}\n"
235     fi
236     printf "imageName: ${BM_IMAGE}\n"
237     node_userdata ${name} ${os_username} ${os_password}
238     node_networkdata ${name}
239 }
240
241 function clone_repository {
242     local -r path=$1
243     local -r repo=$2
244     local -r version=$3
245     mkdir -p $(dirname ${path})
246     if [[ -d ${path} && "${FORCE_REPO_UPDATE}" == "true" ]]; then
247        rm -rf "${path}"
248     fi
249     if [ ! -d "${path}" ] ; then
250         pushd $(dirname ${path})
251         git clone "${repo}"
252         popd
253     else
254        pushd "${path}"
255        git fetch
256        popd
257     fi
258     pushd "${path}"
259     git reset --hard "${version}"
260     popd
261 }
262
263 function clone_baremetal_operator_repository {
264     clone_repository ${BMOPATH} ${BMOREPO} ${BMO_VERSION}
265 }
266
267 function clone_kud_repository {
268     clone_repository ${KUDPATH} ${KUDREPO} ${KUD_VERSION}
269 }
270
271 function clone_emco_repository {
272     clone_repository ${EMCOPATH} ${EMCOREPO} ${EMCO_VERSION}
273 }
274
275 function install_kustomize {
276     curl -sL "https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2F${KUSTOMIZE_VERSION}/kustomize_${KUSTOMIZE_VERSION}_linux_amd64.tar.gz" -o kustomize_${KUSTOMIZE_VERSION}_linux_amd64.tar.gz
277     tar xzf kustomize_${KUSTOMIZE_VERSION}_linux_amd64.tar.gz --no-same-owner
278     sudo install -o root -g root -m 0755 kustomize /usr/local/bin/kustomize
279     rm kustomize_${KUSTOMIZE_VERSION}_linux_amd64.tar.gz kustomize
280     kustomize version
281 }
282
283 function install_clusterctl {
284     curl -L https://github.com/kubernetes-sigs/cluster-api/releases/download/${CAPI_VERSION}/clusterctl-linux-amd64 -o clusterctl
285     sudo install -o root -g root -m 0755 clusterctl /usr/local/bin/clusterctl
286     rm clusterctl
287     clusterctl version
288 }
289
290 function install_flux_cli {
291     export FLUX_VERSION
292     curl -s https://fluxcd.io/install.sh | sudo -E bash
293     flux --version
294 }
295
296 function install_emcoctl {
297     clone_emco_repository
298     make -C ${EMCOPATH}/src/tools/emcoctl
299     sudo install -o root -g root -m 0755 ${EMCOPATH}/bin/emcoctl/emcoctl /usr/local/bin/emcoctl
300 }
301
302 function install_sops {
303     curl -L https://github.com/mozilla/sops/releases/download/${SOPS_VERSION}/sops-${SOPS_VERSION}.linux -o sops
304     sudo install -o root -g root -m 0755 sops /usr/local/bin/sops
305     rm sops
306     sops --version
307 }
308
309 function fetch_image {
310     if [[ "${BM_IMAGE_URL}" && "${BM_IMAGE}" ]]; then
311        mkdir -p "${IRONIC_DATA_DIR}/html/images"
312        pushd ${IRONIC_DATA_DIR}/html/images
313        local_checksum="0"
314        if [[ -f "${BM_IMAGE}" ]]; then
315            local_checksum=$(md5sum ${BM_IMAGE} | awk '{print $1}')
316        fi
317        remote_checksum=$(curl -sL "$(dirname ${BM_IMAGE_URL})/MD5SUMS" | grep ${BM_IMAGE} | awk '{print $1}')
318        if [[ ${local_checksum} != ${remote_checksum} ]]; then
319             curl -o ${BM_IMAGE} --insecure --compressed -O -L ${BM_IMAGE_URL}
320             md5sum ${BM_IMAGE} | awk '{print $1}' > ${BM_IMAGE}.md5sum
321        fi
322        popd
323     fi
324 }