Switch to Python Virtual Environment
[kuberef.git] / functions.sh
1 #!/bin/bash
2 # SPDX-license-identifier: Apache-2.0
3 ##############################################################################
4 # Copyright (c) Ericsson AB and others
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11 info() {
12     _print_msg "INFO" "$1"
13 }
14
15 error() {
16     _print_msg "ERROR" "$1"
17     exit 1
18 }
19
20 _print_msg() {
21     echo "$(date +%H:%M:%S) - $1: $2"
22 }
23
24 assert_non_empty() {
25     if [ -z "$1" ]; then
26         error "$2"
27     fi
28 }
29 if [ "${DEBUG:-false}" == "true" ]; then
30     set -o xtrace
31 fi
32
33 check_prerequisites() {
34     info "Check prerequisites"
35
36     #-------------------------------------------------------------------------------
37     # Check for DEPLOYMENT type
38     #-------------------------------------------------------------------------------
39     DEPLOYMENT=${DEPLOYMENT:-full}
40     if ! [[ "$DEPLOYMENT" =~ ^(full|k8s)$ ]]; then
41         error "Unsupported value for DEPLOYMENT ($DEPLOYMENT)"
42     fi
43
44     #-------------------------------------------------------------------------------
45     # We shouldn't be running as root
46     #-------------------------------------------------------------------------------
47     if [[ "$(whoami)" == "root" ]] && [[ "$DEPLOYMENT" != "k8s" ]]; then
48         error "This script must not be run as root! Please switch to a regular user before running the script."
49     fi
50
51     #-------------------------------------------------------------------------------
52     # Check for passwordless sudo
53     #-------------------------------------------------------------------------------
54     if ! sudo -n "true"; then
55         error "passwordless sudo is needed for '$(id -nu)' user."
56     fi
57
58     #-------------------------------------------------------------------------------
59     # Check if SSH key exists
60     #-------------------------------------------------------------------------------
61     if [[ ! -f "$HOME/.ssh/id_rsa" ]]; then
62         error "You must have SSH keypair in order to run this script!"
63     fi
64
65     #-------------------------------------------------------------------------------
66     # We are using sudo so we need to make sure that env_reset is not present
67     #-------------------------------------------------------------------------------
68     sudo sed -i "s/^Defaults.*env_reset/#&/" /etc/sudoers
69
70     #-------------------------------------------------------------------------------
71     # Check if Python Virtual Environment is installed
72     #-------------------------------------------------------------------------------
73     if ! command -v virtualenv &> /dev/null; then
74         error "VirtualEnv not found. Please install."
75     fi
76
77     #-------------------------------------------------------------------------------
78     # Check if PIP Installs Packages is installed
79     #-------------------------------------------------------------------------------
80     if ! command -v pip &> /dev/null; then
81         error "PIP not found. Please install."
82     fi
83
84     #-------------------------------------------------------------------------------
85     # Check is libvirt is installed
86     #-------------------------------------------------------------------------------
87     for tool in ansible yq virsh jq; do
88         if ! command -v "$tool" &> /dev/null; then
89             error "$tool not found. Please install."
90         fi
91     done
92
93     #-------------------------------------------------------------------------------
94     # Check if user belongs to libvirt's group
95     #-------------------------------------------------------------------------------
96     libvirt_group="libvirt"
97     # shellcheck disable=SC1091
98     source /etc/os-release || source /usr/lib/os-release
99     if [ "${ID,,}" == "ubuntu" ] && [ "$VERSION_ID" == "16.04" ]; then
100         libvirt_group+="d"
101     fi
102     if ! groups | grep "$libvirt_group"; then
103         error "$(id -nu) user doesn't belong to $libvirt_group group."
104     fi
105 }
106
107 # Get jumphost VM PXE IP
108 get_host_pxe_ip() {
109     local PXE_NETWORK
110     local PXE_IF_INDEX
111     local PXE_IF_IP
112
113     host=$1
114     assert_non_empty "$host" "get_ip - host parameter not provided"
115
116     PXE_NETWORK=$(yq r "$CURRENTPATH"/hw_config/"$VENDOR"/idf.yaml engine.pxe_network)
117     assert_non_empty "$PXE_NETWORK" "PXE network for jump VM not defined in IDF."
118
119     PXE_IF_INDEX=$(yq r "$CURRENTPATH"/hw_config/"${VENDOR}"/idf.yaml idf.net_config."$PXE_NETWORK".interface)
120     assert_non_empty "$PXE_IF_INDEX" "Index of PXE interface not found in IDF."
121
122     PXE_IF_IP=$(yq r "$CURRENTPATH"/hw_config/"${VENDOR}"/pdf.yaml "$host".interfaces["$PXE_IF_INDEX"].address)
123     assert_non_empty "$PXE_IF_IP" "IP of PXE interface not found in PDF."
124
125     echo "$PXE_IF_IP"
126 }
127
128 # Get public MAC for VM
129 get_host_pub_mac() {
130     local PUB_NETWORK
131     local PUB_IF_INDEX
132     local PUB_IF_MAC
133
134     host=$1
135     assert_non_empty "$host" "get_mac - host parameter not provided"
136
137     PUB_NETWORK=$(yq r "$CURRENTPATH"/hw_config/"$VENDOR"/idf.yaml  engine.public_network)
138     assert_non_empty "$PUB_NETWORK" "Public network for jump VM not defined in IDF."
139
140     PUB_IF_INDEX=$(yq r "$CURRENTPATH"/hw_config/"${VENDOR}"/idf.yaml idf.net_config."$PUB_NETWORK".interface)
141     assert_non_empty "$PUB_IF_INDEX" "Index of public interface not found in IDF."
142
143     PUB_IF_MAC=$(yq r "$CURRENTPATH"/hw_config/"${VENDOR}"/pdf.yaml "$host".interfaces["$PUB_IF_INDEX"].mac_address)
144     assert_non_empty "$PUB_IF_MAC" "MAC of public interface not found in PDF."
145     echo "$PUB_IF_MAC"
146 }
147
148 # Get jumphost VM IP
149 get_vm_ip() {
150     if [[ "$DEPLOYMENT" == "full" ]]; then
151         ip=$(get_host_pxe_ip "jumphost")
152     else
153         mac=$(get_host_pub_mac "jumphost")
154         JUMPHOST_NAME=$(yq r "$CURRENTPATH"/hw_config/"$VENDOR"/pdf.yaml jumphost.name)
155         ipblock=$(virsh domifaddr "$JUMPHOST_NAME" --full | grep "$mac" | awk '{print $4}' | tail -n 1)
156         assert_non_empty "$ipblock" "IP subnet for VM not available."
157         ip="${ipblock%/*}"
158     fi
159     echo "$ip"
160 }
161
162 # Copy files needed by Infra engine & BMRA in the jumphost VM
163 copy_files_jump() {
164     vm_ip="$(get_vm_ip)"
165     scp -r -o StrictHostKeyChecking=no \
166     "$CURRENTPATH"/{hw_config/"$VENDOR"/,sw_config/"$INSTALLER"/} \
167     "$USERNAME@${vm_ip}:$PROJECT_ROOT"
168     if [[ "$DEPLOYMENT" != "full" ]]; then
169         scp -r -o StrictHostKeyChecking=no \
170         ~/.ssh/id_rsa \
171         "$USERNAME@${vm_ip}:.ssh/id_rsa"
172     fi
173 }
174
175 # Host Provisioning
176 provision_hosts() {
177     # shellcheck disable=SC2087
178     ssh -o StrictHostKeyChecking=no -tT "$USERNAME"@"$(get_vm_ip)" << EOF
179 # Install and run cloud-infra
180 if [ ! -d "${PROJECT_ROOT}/engine" ]; then
181     ssh-keygen -t rsa -N "" -f ${PROJECT_ROOT}/.ssh/id_rsa
182     git clone https://gerrit.nordix.org/infra/engine.git
183     cp $PROJECT_ROOT/$VENDOR/{pdf.yaml,idf.yaml} \
184     ${PROJECT_ROOT}/engine/engine
185 fi
186 cd ${PROJECT_ROOT}/engine/engine
187 ./deploy.sh -s ironic -d centos7 \
188 -p file:///${PROJECT_ROOT}/engine/engine/pdf.yaml \
189 -i file:///${PROJECT_ROOT}/engine/engine/idf.yaml
190 EOF
191 }
192
193 # Setup networking on provisioned hosts (Adapt setup_network.sh according to your network setup)
194 setup_network() {
195     # Set Upper limit of number nodes in RI2 cluster (starting from 0)
196     NODE_MAX_ID=$(($(yq r "$CURRENTPATH"/hw_config/"$VENDOR"/idf.yaml --length idf.kubespray.hostnames)-1))
197
198     for idx in $(seq 0 "$NODE_MAX_ID"); do
199         NODE_IP=$(get_host_pxe_ip "nodes[${idx}]")
200         # SSH to jumphost
201         # shellcheck disable=SC2087
202         ssh -o StrictHostKeyChecking=no -tT "$USERNAME"@"$(get_vm_ip)" << EOF
203 ssh -o StrictHostKeyChecking=no root@${NODE_IP} \
204     'bash -s' <  ${PROJECT_ROOT}/${VENDOR}/setup_network.sh
205 EOF
206     done
207 }
208
209 # k8s Provisioning (currently BMRA)
210 provision_k8s() {
211     ansible_cmd="/bin/bash -c '"
212     if [[ "$DEPLOYMENT" == "k8s" ]]; then
213         ansible-playbook -i "$CURRENTPATH"/sw_config/bmra/inventory.ini "$CURRENTPATH"/playbooks/pre-install.yaml
214         ansible_cmd+="yum -y remove python-netaddr; pip install --upgrade pip; pip install ansible==2.9.6; ansible-playbook -i /bmra/inventory.ini /bmra/playbooks/k8s/patch_kubespray.yml;"
215     fi
216     ansible_cmd+="ansible-playbook -i /bmra/inventory.ini /bmra/playbooks/${BMRA_PROFILE}.yml'"
217
218     # shellcheck disable=SC2087
219     ssh -o StrictHostKeyChecking=no -tT "$USERNAME"@"$(get_vm_ip)" << EOF
220 # Install BMRA
221 if ! command -v docker; then
222     curl -fsSL https://get.docker.com/ | sh
223     printf "Waiting for docker service..."
224     until sudo docker info; do
225         printf "."
226         sleep 2
227     done
228 fi
229 if [ ! -d "${PROJECT_ROOT}/container-experience-kits" ]; then
230     git clone --recurse-submodules --depth 1 https://github.com/intel/container-experience-kits.git -b v2.1.0 ${PROJECT_ROOT}/container-experience-kits/
231     cp -r ${PROJECT_ROOT}/container-experience-kits/examples/${BMRA_PROFILE}/group_vars ${PROJECT_ROOT}/container-experience-kits/
232 # NOTE The following condition/workaround will be removed once the reported issue https://github.com/intel/container-experience-kits/issues/68
233 # is fixed upstream
234     if [[ "$DEPLOYMENT" == "full" ]]; then
235        echo "- name: install Python packages
236   pip:
237     name:
238       - pip==9.0.3" >> ${PROJECT_ROOT}/container-experience-kits/roles/bootstrap/install_packages/tasks/rhel.yml
239     fi
240 fi
241 cp ${PROJECT_ROOT}/${INSTALLER}/inventory.ini \
242     ${PROJECT_ROOT}/container-experience-kits/
243 cp ${PROJECT_ROOT}/${INSTALLER}/{all.yml,kube-node.yml} \
244     ${PROJECT_ROOT}/container-experience-kits/group_vars/
245 cp ${PROJECT_ROOT}/${INSTALLER}/patched_cmk_build.yml \
246     ${PROJECT_ROOT}/container-experience-kits/roles/cmk_install/tasks/main.yml
247 sudo docker run --rm \
248 -e ANSIBLE_CONFIG=/bmra/ansible.cfg \
249 -e PROFILE=${BMRA_PROFILE} \
250 -v ${PROJECT_ROOT}/container-experience-kits:/bmra \
251 -v ~/.ssh/:/root/.ssh/ rihabbanday/bmra2.0-install:centos \
252 ${ansible_cmd}
253 EOF
254 }
255
256 # Copy kubeconfig to the appropriate location needed by functest containers
257 copy_k8s_config() {
258 # TODO Use Kubespray variables in BMRA to simplify this
259     MASTER_IP=$(get_host_pxe_ip "nodes[0]")
260     # shellcheck disable=SC2087
261     ssh -o StrictHostKeyChecking=no -tT "$USERNAME"@"$(get_vm_ip)" << EOF
262 scp -o StrictHostKeyChecking=no -q root@$MASTER_IP:/root/.kube/config ${PROJECT_ROOT}/kubeconfig
263 EOF
264
265 # Copy kubeconfig from Jump VM to appropriate location in Jump Host
266 # Direct scp to the specified location doesn't work due to permission/ssh-keys
267     scp  -o StrictHostKeyChecking=no "$USERNAME"@"$(get_vm_ip)":"${PROJECT_ROOT}"/kubeconfig kubeconfig
268     if [ -d "/home/opnfv/functest-kubernetes" ]; then
269         sudo cp kubeconfig /home/opnfv/functest-kubernetes/config
270     fi
271 }
272
273 # Creates a python virtual environment
274 creates_virtualenv() {
275     if [  ! -d "$CURRENTPATH/.venv" ]; then
276         virtualenv .venv
277     fi
278     # shellcheck disable=SC1090
279     source "$CURRENTPATH/.venv/bin/activate"
280     pip install -r "$CURRENTPATH/requirements.txt"
281 }
282
283 # Executes a specific Ansible playbook
284 run_playbook() {
285     ansible_cmd="$(command -v ansible-playbook) -i $CURRENTPATH/inventory/localhost.ini -e ansible_python_interpreter=$(command -v python)"
286     if [ "${DEBUG:-false}" == "true" ]; then
287         ansible_cmd+=" -vvv"
288     fi
289     eval "$ansible_cmd $CURRENTPATH/playbooks/${1}.yaml"
290 }