add remote virsh support for bootstrap
[joid.git] / ci / 03-maasdeploy.sh
1 #!/bin/bash
2 #placeholder for deployment script.
3 set -ex
4
5 virtinstall=0
6 labname=$1
7
8 if [ ! -e $HOME/.ssh/id_rsa ]; then
9     ssh-keygen -N '' -f $HOME/.ssh/id_rsa
10 fi
11
12 #install the packages needed
13 sudo apt-add-repository ppa:juju/stable -y
14 sudo apt-add-repository ppa:maas/stable -y
15 sudo apt-add-repository cloud-archive:ocata -y
16 sudo apt-get update -y
17 #sudo apt-get dist-upgrade -y
18 sudo apt-get install bridge-utils openssh-server bzr git virtinst qemu-kvm libvirt-bin juju \
19              maas maas-region-controller python-pip python-psutil python-openstackclient \
20              python-congressclient gsutil charm-tools pastebinit python-jinja2 sshpass \
21              openssh-server vlan ipmitool jq expect -y
22
23 sudo pip install --upgrade pip
24
25 #first parameter should be custom and second should be either
26 # absolute location of file (including file name) or url of the
27 # file to download.
28
29
30 #
31 # Config preparation
32 #
33
34 # Get labconfig and generate deployconfig.yaml
35 case "$labname" in
36     intelpod[569]|orangepod[12]|cengnpod[12] )
37         array=(${labname//pod/ })
38         cp ../labconfig/${array[0]}/pod${array[1]}/labconfig.yaml .
39         python genDeploymentConfig.py -l labconfig.yaml > deployconfig.yaml
40         ;;
41     'attvirpod1' )
42         cp ../labconfig/att/virpod1/labconfig.yaml .
43         python genDeploymentConfig.py -l labconfig.yaml > deployconfig.yaml
44         ;;
45     'custom')
46         labfile=$2
47         if [ -e $labfile ]; then
48             cp $labfile ./labconfig.yaml || true
49         else
50             wget $labconfigfile -t 3 -T 10 -O ./labconfig.yaml || true
51             count=`wc -l labconfig.yaml  | cut -d " " -f 1`
52             if [ $count -lt 10 ]; then
53                 rm -rf labconfig.yaml
54             fi
55         fi
56         if [ ! -e ./labconfig.yaml ]; then
57             virtinstall=1
58             labname="default"
59             cp ../labconfig/default/labconfig.yaml ./
60             cp ../labconfig/default/deployconfig.yaml ./
61         else
62             python genDeploymentConfig.py -l labconfig.yaml > deployconfig.yaml
63             labname=`grep "maas_name" deployconfig.yaml | cut -d ':' -f 2 | sed -e 's/ //'`
64         fi
65         ;;
66     * )
67         virtinstall=1
68         labname="default"
69         cp ../labconfig/default/labconfig.yaml ./
70         python genDeploymentConfig.py -l labconfig.yaml > deployconfig.yaml
71         ;;
72 esac
73
74 python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < labconfig.yaml > labconfig.json
75 python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < deployconfig.yaml > deployconfig.json
76
77 MAAS_IP=$(grep " ip_address" deployconfig.yaml | cut -d ':' -f 2 | sed -e 's/ //')
78 MAAS_NAME=`grep "maas_name" deployconfig.yaml | cut -d ':' -f 2 | sed -e 's/ //'`
79 API_SERVER="http://$MAAS_IP/MAAS/api/2.0"
80 API_SERVERMAAS="http://$MAAS_IP/MAAS/"
81 PROFILE=ubuntu
82 MY_UPSTREAM_DNS=`grep "upstream_dns" deployconfig.yaml | cut -d ':' -f 2 | sed -e 's/ //'`
83 SSH_KEY=`cat ~/.ssh/id_rsa.pub`
84 MAIN_ARCHIVE=`grep "main_archive" deployconfig.yaml | cut -d ':' -f 2-3 | sed -e 's/ //'`
85 URL=https://images.maas.io/ephemeral-v2/daily/
86 KEYRING_FILE=/usr/share/keyrings/ubuntu-cloudimage-keyring.gpg
87 SOURCE_ID=1
88 FABRIC_ID=1
89 PRIMARY_RACK_CONTROLLER="$MAAS_IP"
90 SUBNET_CIDR=`cat labconfig.json | jq '.opnfv.spaces[] | select(.type=="admin")'.cidr | cut -d \" -f 2 `
91 SUBNETDATA_CIDR=`cat labconfig.json | jq '.opnfv.spaces[] | select(.type=="data")'.cidr | cut -d \" -f 2 `
92 SUBNETPUB_CIDR=`cat labconfig.json | jq '.opnfv.spaces[] | select(.type=="public")'.cidr | cut -d \" -f 2 `
93 SUBNETSTOR_CIDR=`cat labconfig.json | jq '.opnfv.spaces[] | select(.type=="storage")'.cidr | cut -d \" -f 2 `
94 SUBNETFLOAT_CIDR=`cat labconfig.json | jq '.opnfv.spaces[] | select(.type=="floating")'.cidr | cut -d \" -f 2 `
95 VLAN_UNTTAGED="untagged"
96
97 # In the case of a virtual deployment get deployconfig.yaml
98 if [ "$virtinstall" -eq 1 ]; then
99     ./cleanvm.sh || true
100 fi
101
102 #create backup directory
103 mkdir ~/joid_config/ || true
104
105 # Backup deployconfig.yaml in joid_config folder
106
107 if [ -e ./deployconfig.yaml ]; then
108     cp ./deployconfig.yaml ~/joid_config/
109     cp ./labconfig.yaml ~/joid_config/
110 fi
111
112 #
113 # Prepare local environment to avoid password asking
114 #
115
116 # make sure no password asked during the deployment.
117 sudoer_file=/etc/sudoers.d/90-joid-init
118 sudoer_entry="$USER ALL=(ALL) NOPASSWD:ALL"
119 if [ -e $sudoer_file ]; then
120     if ! sudo grep -q "$sudoer_entry" $sudoer_file; then
121         sudo sed -i -e "1i$sudoer_entry" $sudoer_file
122     fi
123 else
124     echo "$sudoer_entry" > 90-joid-init
125     sudo chown root:root 90-joid-init
126     sudo mv 90-joid-init /etc/sudoers.d/
127 fi
128
129 echo "... Deployment of maas Started ...."
130
131 #
132 # Virsh preparation
133 #
134
135 # define the pool and try to start even though its already exist.
136 # For fresh install this may or may not there.
137 sudo adduser $USER libvirtd
138 sudo virsh pool-define-as default --type dir --target /var/lib/libvirt/images/ || true
139 sudo virsh pool-start default || true
140 sudo virsh pool-autostart default || true
141
142 # In case of virtual install set network
143 if [ "$virtinstall" -eq 1 ]; then
144     sudo virsh net-dumpxml default > default-net-org.xml
145     sudo sed -i '/dhcp/d' default-net-org.xml
146     sudo sed -i '/range/d' default-net-org.xml
147     sudo virsh net-define default-net-org.xml
148     sudo virsh net-destroy default
149     sudo virsh net-start default
150     rm -f default-net-org.xml
151 fi
152
153 #
154 # Cleanup, juju init and config backup
155 #
156
157 # To avoid problem between apiclient/maas_client and apiclient from google
158 # we remove the package google-api-python-client from yardstick installer
159 if [ $(pip list |grep google-api-python-client |wc -l) == 1 ]; then
160     sudo pip uninstall google-api-python-client
161 fi
162
163
164 if [ ! -e ~maas/.ssh/id_rsa.pub ]; then
165     if [ ! -e $HOME/id_rsa_maas.pub ]; then
166         [ -e $HOME/id_rsa_maas ] && rm -f $HOME/id_rsa_maas
167         sudo su - $USER -c "echo |ssh-keygen -t rsa -f $HOME/id_rsa_maas"
168     fi
169     sudo -u maas mkdir ~maas/.ssh/ || true
170     sudo cp $HOME/id_rsa_maas ~maas/.ssh/id_rsa
171     sudo cp $HOME/id_rsa_maas.pub ~maas/.ssh/id_rsa.pub
172     sudo chown maas:maas ~maas/.ssh/id_rsa
173     sudo chown maas:maas ~maas/.ssh/id_rsa.pub
174 fi
175
176 # Ensure virsh can connect without ssh auth
177 sudo cat ~maas/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
178 sudo cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
179
180 #
181 # MAAS deploy
182 #
183
184 installmaas(){
185     sudo apt-get install maas maas-region-controller -y
186 }
187
188 #
189 # MAAS config
190 # https://insights.ubuntu.com/2016/01/23/maas-setup-deploying-openstack-on-maas-1-9-with-juju/
191 # http://blog.naydenov.net/2016/01/nodes-networking-deploying-openstack-on-maas-1-9-with-juju/
192 #
193 configuremaas(){
194     #reconfigure maas with correct MAAS address.
195     #Below code is needed as MAAS have issue in commisoning without restart.
196     sudo ./maas-reconfigure-region.sh $MAAS_IP
197     sleep 30
198     sudo maas-rack config --region-url http://$MAAS_IP:5240/MAAS
199
200     sudo maas createadmin --username=ubuntu --email=ubuntu@ubuntu.com --password=ubuntu || true
201     API_KEY=`sudo maas-region apikey --username=ubuntu`
202     maas login $PROFILE $API_SERVERMAAS $API_KEY
203     maas $PROFILE maas set-config name='main_archive' value=$MAIN_ARCHIVE || true
204     maas $PROFILE maas set-config name=upstream_dns value=$MY_UPSTREAM_DNS || true
205     maas $PROFILE maas set-config name='maas_name' value=$MAAS_NAME || true
206     maas $PROFILE maas set-config name='ntp_server' value='ntp.ubuntu.com' || true
207     maas $PROFILE sshkeys create "key=$SSH_KEY" || true
208
209     for tag in bootstrap compute control storage
210     do
211         maas $PROFILE tags create name=$tag || true
212     done
213
214     #create the required spaces.
215     maas $PROFILE space update 0 name=default || true
216     for space in unused admin-api internal-api public-api compute-data \
217                  compute-external storage-data storage-cluster
218     do
219         echo "Creating the space $space"
220         maas $PROFILE spaces create name=$space || true
221     done
222
223     #maas $PROFILE boot-source update $SOURCE_ID \
224     #     url=$URL keyring_filename=$KEYRING_FILE || true
225     maas $PROFILE boot-resources import || true
226     sleep 10
227
228     while [ "$(maas $PROFILE boot-resources is-importing)" == "true" ];
229     do
230         sleep 60
231     done
232 }
233
234 setopnfvspaces(){
235     # Create spaces
236     for sp in admin tenant-data public-api tenant-api tenant-public; do
237         maas $PROFILE spaces create name=$sp || true
238     done
239 }
240
241 getfabrichostingnet(){
242     SUBN_CIDR=$1
243     NET_FABRIC_NAME=$(maas $PROFILE subnets read | jq -r ".[] |  select(.cidr==\"$SUBN_CIDR\")".vlan.fabric)
244     NET_FABRIC_ID=$(maas $PROFILE fabric read $NET_FABRIC_NAME | jq -r ".id")
245 }
246
247 deleteexistingnetw(){
248     CIDR_LIST=$(cat labconfig.json | jq --raw-output ".opnfv.spaces[]".cidr | grep -v null)
249     for CIDR in $CIDR_LIST; do
250         NETID=$(maas $PROFILE subnets read | jq ".[] | select(.cidr==\"$CIDR\")".id)
251         maas $PROFILE subnet delete $NETID
252     done
253 }
254
255 deleteunusednetw(){
256     USED_CIDR_LIST=$(cat labconfig.json | jq --raw-output ".opnfv.spaces[]".cidr | grep -v null)
257     CIDR_LIST=$(maas $PROFILE networks read | jq -r ".[].description")
258     for CIDR in $CIDR_LIST; do
259         if [[ $USED_CIDR_LIST != *$CIDR* ]]; then
260             NETID=$(maas $PROFILE subnets read | jq ".[] | select(.cidr==\"$CIDR\")".id)
261             maas $PROFILE subnet delete $NETID
262         fi
263     done
264 }
265
266 setopnfvfabrics(){
267
268     # Based on first node we get the fabric mapping
269     NODE_0_MAC_LIST=$(cat labconfig.json | jq --raw-output ".lab.racks[0].nodes[0].nics[] ".mac[] | sort -u)
270     FAB_ID=1
271     for MAC in $NODE_0_MAC_LIST; do
272         # Get the spaces attached to a mac
273         IF_SPACES=$(cat labconfig.json | jq --raw-output ".lab.racks[0].nodes[$NODE_ID].nics[] | select(.mac[] | contains(\"$MAC\")) ".spaces[])
274         if [[ $IF_SPACES == *admin* ]]; then
275             # Reuse fabric 0 to be sure the interface i hosted by the jumphost (assuming it is the first one)
276             FABRIC_ID=$ADMIN_FABRIC_ID
277             maas $PROFILE fabric update $FABRIC_ID name=opnfv$FAB_ID
278         else
279             # Create a new fabric
280             FABRIC_ID=$(maas $PROFILE fabrics create name=opnfv$FAB_ID| jq --raw-output ".id")
281         fi
282         # Create the network attached to a space
283         for SPACE in $IF_SPACES; do
284             # First check if this space have a vlan
285             SP_VLAN=$(cat labconfig.json | jq --raw-output ".opnfv.spaces[] | select(.type==\"$SPACE\")".vlan)
286             # Create it if needed
287             if ([ $SP_VLAN ] && [ "$SP_VLAN" != "null" ]); then
288                 maas $PROFILE vlans create $FABRIC_ID vid=$SP_VLAN
289                 VID=$SP_VLAN
290                 VID_REQ="vid=$SP_VLAN"
291             else
292                 SP_VLAN=$VLAN_UNTTAGED
293                 VID=0
294                 VID_REQ=""
295             fi
296             # Create the network
297             case "$SPACE" in
298                 'admin')    SUBNET_CIDR=$SUBNET_CIDR;       JUJU_SPACE="admin";         DHCP='enabled' ;;
299                 'data')     SUBNET_CIDR=$SUBNETDATA_CIDR;   JUJU_SPACE="tenant-data";   DHCP='' ;;
300                 'public')   SUBNET_CIDR=$SUBNETPUB_CIDR;    JUJU_SPACE="public-api";    DHCP='' ;;
301                 'storage')  SUBNET_CIDR=$SUBNETSTOR_CIDR;   JUJU_SPACE="tenant-api";    DHCP='' ;;
302                 'floating') SUBNET_CIDR=$SUBNETFLOAT_CIDR;  JUJU_SPACE="tenant-public"; DHCP='' ;;
303                 *) JUJU_SPACE='null'; DHCP='OFF'; echo "      >>> Unknown SPACE" ;;
304             esac
305             # If we have a network, we create it
306             if ([ $SUBNET_CIDR ] && [ "$SUBNET_CIDR" != "null" ]); then
307                 JUJU_SPACE_ID=$(maas $PROFILE spaces read | jq -r ".[] |  select(.name==\"$JUJU_SPACE\")".id)
308                 # If subnet exist move it, else create it (to avoid issues with network discovery by maas)
309                 if maas $PROFILE subnet read $SUBNET_CIDR; then
310                     TARGET_VLAN=$(maas $PROFILE vlans read $FABRIC_ID | jq -r ".[] | select(".vid"==$VID)".id)
311                     maas $PROFILE subnet update $SUBNET_CIDR vlan=$TARGET_VLAN
312                 else
313                     maas $PROFILE subnets create fabric=$FABRIC_ID cidr=$SUBNET_CIDR $VID_REQ space=$JUJU_SPACE_ID
314                 fi
315
316                 # Add the Gateway
317                 GW=$(cat labconfig.json | jq ".opnfv.spaces[] | select(.type==\"$SPACE\")".gateway | cut -d \" -f 2)
318                 if ([ $GW ] && [ "$GW" != "null" ]); then
319                     maas $PROFILE subnet update $SUBNET_CIDR gateway_ip=$GW || true
320                 fi
321                 # Set ranges
322                 SUBNET_PREFIX=${SUBNET_CIDR::-5}
323                 IP_RES_RANGE_LOW="$SUBNET_PREFIX.1"
324                 IP_RES_RANGE_HIGH="$SUBNET_PREFIX.39"
325                 IP_DYNAMIC_RANGE_LOW="$SUBNET_PREFIX.40"
326                 IP_DYNAMIC_RANGE_HIGH="$SUBNET_PREFIX.150"
327                 maas $PROFILE ipranges create type=reserved \
328                      start_ip=$IP_RES_RANGE_LOW end_ip=$IP_RES_RANGE_HIGH \
329                      comment='This is a reserved range' || true
330                 maas $PROFILE ipranges create type=dynamic \
331                     start_ip=$IP_DYNAMIC_RANGE_LOW end_ip=$IP_DYNAMIC_RANGE_HIGH \
332                     comment='This is a reserved dynamic range' || true
333                 # Set DHCP
334                 if [ $DHCP ]; then
335                     PRIMARY_RACK_CONTROLLER=$(maas $PROFILE rack-controllers read | jq -r '.[0].system_id')
336                     maas $PROFILE vlan update $FABRIC_ID $SP_VLAN dhcp_on=True primary_rack=$PRIMARY_RACK_CONTROLLER || true
337                 fi
338             fi
339         done
340         # Increment the fabric ID
341         FAB_ID=$((FAB_ID+1))
342     done
343
344 }
345
346 addnodes(){
347     API_KEY=`sudo maas-region apikey --username=ubuntu`
348     maas login $PROFILE $API_SERVERMAAS $API_KEY
349
350     # make sure there is no machine entry in maas
351     for m in $(maas $PROFILE machines read | jq -r '.[].system_id')
352     do
353         maas ubuntu machine delete $m
354     done
355
356     # if we have a virshurl configuration we use it, else we use local
357     VIRSHURL=$(cat labconfig.json | jq -r '.opnfv.virshurl')
358     if ([ $VIRSHURL == "" ] || [ "$VIRSHURL" == "null" ]); then
359         VIRSHURL="qemu:///system "
360         VIRSHHOST=""
361     else
362         VIRSHHOST=$(echo $VIRSHURL| cut -d\/ -f 3 | cut -d@ -f2)
363     fi
364
365     if [ "$virtinstall" -eq 1 ]; then
366         netw=" --network bridge=virbr0,model=virtio"
367     elif [ $VIRSHHOST != "" ]; then
368         # Get the bridge hosting the remote virsh
369         brid=$(ssh $VIRSHHOST "ip a l | grep $VIRSHHOST | perl -pe 's/.* (.*)\$/\$1/g'")
370         netw=" --network bridge=$brid,model=virtio"
371         # prepare a file containing virsh remote url to connect without adding it n command line
372         echo "export VIRSH_DEFAULT_CONNECT_URI=$VIRSHURL" > virsh_uri.sh
373     else
374         brid=`brctl show | grep 8000 | cut -d "8" -f 1 |  tr "\n" " " | tr "    " " " | tr -s " "`
375
376         netw=""
377         for feature in $brid; do
378             if [ "$feature" == "" ]; then
379                 netw=$netw
380             elif [ "$feature" == "virbr0" ]; then
381                 netw=$netw
382             else
383                 netw=$netw" --network bridge="$feature",model=virtio"
384             fi
385         done
386     fi
387
388     virt-install --connect $VIRSHURL --name bootstrap --ram 4098 --cpu host --vcpus 2 --video \
389                  cirrus --arch x86_64 --disk size=20,format=qcow2,bus=virtio,cache=directsync,io=native,pool=default \
390                  $netw --boot network,hd,menu=off --noautoconsole \
391                  --vnc --print-xml | tee bootstrap
392
393     if [ "$virtinstall" -eq 1 ]; then
394         bootstrapmac=`grep  "mac address" bootstrap | head -1 | cut -d '"' -f 2`
395     else
396         bootstrapmac=""
397         bootstrapmacs=`grep  "mac address" bootstrap| cut -d '"' -f 2`
398         for mac in $bootstrapmacs; do
399             bootstrapmac=$bootstrapmac" mac_addresses="$mac
400         done
401     fi
402     virsh -c $VIRSHURL define --file bootstrap
403     rm -f bootstrap
404
405     sleep 60
406
407     maas $PROFILE machines create autodetect_nodegroup='yes' name='bootstrap' \
408         tags='bootstrap' hostname='bootstrap' power_type='virsh' mac_addresses=$bootstrapmac \
409         power_parameters_power_address=$VIRSHURL \
410         architecture='amd64/generic' power_parameters_power_id='bootstrap'
411
412     bootstrapid=$(maas $PROFILE machines read | jq -r '.[] | select(.hostname == "bootstrap").system_id')
413
414     maas $PROFILE tag update-nodes bootstrap add=$bootstrapid
415
416     if [ "$virtinstall" -eq 1 ]; then
417         units=`cat deployconfig.json | jq .opnfv.units`
418
419         until [ $(($units)) -lt 1 ]; do
420            units=$(($units - 1));
421            NODE_NAME=`cat labconfig.json | jq ".lab.racks[].nodes[$units].name" | cut -d \" -f 2 `
422
423             sudo virt-install --connect qemu:///system --name $NODE_NAME --ram 8192 --cpu host --vcpus 4 \
424                      --disk size=120,format=qcow2,bus=virtio,cache=directsync,io=native,pool=default \
425                      $netw $netw --boot network,hd,menu=off --noautoconsole --vnc --print-xml | tee $NODE_NAME
426
427             nodemac=`grep  "mac address" $NODE_NAME | head -1 | cut -d '"' -f 2`
428             sudo virsh -c qemu:///system define --file $NODE_NAME
429             rm -f $NODE_NAME
430             maas $PROFILE machines create autodetect_nodegroup='yes' name=$NODE_NAME \
431                 tags='control compute' hostname=$NODE_NAME power_type='virsh' mac_addresses=$nodemac \
432                 power_parameters_power_address='qemu+ssh://'$USER'@'$MAAS_IP'/system' \
433                 architecture='amd64/generic' power_parameters_power_id=$NODE_NAME
434             nodeid=$(maas $PROFILE machines read | jq -r '.[] | select(.hostname == '\"$NODE_NAME\"').system_id')
435             maas $PROFILE tag update-nodes control add=$nodeid || true
436             maas $PROFILE tag update-nodes compute add=$nodeid || true
437         done
438     else
439        units=`cat deployconfig.json | jq .opnfv.units`
440
441        until [ $(($units)) -lt 1 ]; do
442            units=$(($units - 1));
443            NODE_NAME=`cat labconfig.json | jq ".lab.racks[].nodes[$units].name" | cut -d \" -f 2 `
444            MAC_ADDRESS=`cat labconfig.json | jq ".lab.racks[].nodes[$units].nics[] | select(.spaces[]==\"admin\").mac"[0] | cut -d \" -f 2 `
445            POWER_TYPE=`cat labconfig.json | jq ".lab.racks[].nodes[$units].power.type" | cut -d \" -f 2 `
446            POWER_IP=`cat labconfig.json |  jq ".lab.racks[].nodes[$units].power.address" | cut -d \" -f 2 `
447            POWER_USER=`cat labconfig.json |  jq ".lab.racks[].nodes[$units].power.user" | cut -d \" -f 2 `
448            POWER_PASS=`cat labconfig.json |  jq ".lab.racks[].nodes[$units].power.pass" | cut -d \" -f 2 `
449
450            maas $PROFILE machines create autodetect_nodegroup='yes' name=$NODE_NAME \
451                hostname=$NODE_NAME power_type=$POWER_TYPE power_parameters_power_address=$POWER_IP \
452                power_parameters_power_user=$POWER_USER power_parameters_power_pass=$POWER_PASS mac_addresses=$MAC_ADDRESS \
453                architecture='amd64/generic'
454        done
455     fi
456
457     # make sure nodes are added into MAAS and none of them is in commisoning state
458     while [ "$(maas $PROFILE nodes read | grep  Commissioning )" ];
459     do
460         sleep 60
461     done
462
463 }
464
465 # configure MAAS with the different options.
466 configuremaas
467 sleep 30
468
469 # functioncall with subnetid to add and second parameter is dhcp enable
470 # third parameter will define the space. It is required to have admin
471
472 setopnfvspaces
473 getfabrichostingnet $SUBNET_CIDR
474 ADMIN_FABRIC_ID=$NET_FABRIC_ID
475 ADMIN_FABRIC_NAME=$NET_FABRIC_NAME
476 deleteexistingnetw
477 sleep 30
478 setopnfvfabrics
479 deleteunusednetw
480
481 #just make sure rack controller has been synced and import only
482 # just whether images have been imported or not.
483 sleep 120
484
485 #lets add the nodes now. Currently works only for virtual deploymnet.
486 addnodes
487
488 echo "... Deployment of maas finish ...."
489
490 #Added the Qtip public to run the Qtip test after install on bare metal nodes.
491 #maas $PROFILE sshkeys new key="`cat ./maas/sshkeys/QtipKey.pub`"
492 #maas $PROFILE sshkeys new key="`cat ./maas/sshkeys/DominoKey.pub`"
493
494 #
495 # Functions for MAAS network customization
496 #
497
498 #Below function will mark the interfaces in Auto mode to enbled by MAAS
499 # using hostname of the node added into MAAS
500 enableautomodebyname() {
501     API_KEY=`sudo maas-region apikey --username=ubuntu`
502     maas login $PROFILE $API_SERVERMAAS $API_KEY
503
504     if [ ! -z "$4" ]; then
505         for i in `seq 1 7`;
506         do
507             nodes=$(maas $PROFILE nodes read | jq -r '.[].system_id')
508             if [ ! -z "$nodes" ]; then
509                 maas $PROFILE interface link-subnet $nodes $1  mode=$2 subnet=$3 || true
510             fi
511        done
512     fi
513 }
514
515 #Below function will create vlan and update interface with the new vlan
516 # will return the vlan id created
517 crvlanupdsubnet() {
518     API_KEY=`sudo maas-region apikey --username=ubuntu`
519     maas login $PROFILE $API_SERVERMAAS $API_KEY
520
521     # TODO: fix subnet creation and use 'jq'
522     newvlanid=`maas $PROFILE vlans create $2 name=$3 vid=$4 | grep resource | cut -d '/' -f 6 `
523     maas $PROFILE subnet update $5 vlan=$newvlanid
524     eval "$1"="'$newvlanid'"
525 }
526
527 #Below function will create interface with new vlan and bind to physical interface
528 crnodevlanint() {
529     API_KEY=`sudo maas-region apikey --username=ubuntu`
530     maas login $PROFILE $API_SERVERMAAS $API_KEY
531
532     for node in $(maas $PROFILE nodes read | jq -r '.[].system_id')
533     do
534         vlanid=$(maas $PROFILE subnets read | jq '.[].vlan | select(.vid=='$1')'.id)
535         fabricid=`maas $PROFILE subnets read | jq '.[].vlan | select(.vid=='$1')'.fabric_id`
536         interface=`maas $PROFILE interfaces read $node | jq '.[] | select(.vlan.fabric_id=='$fabricid')'.id`
537         maas $PROFILE interfaces create-vlan $node vlan=$vlanid parent=$interface || true
538      done
539  }
540
541 #function for JUJU envronment
542
543 addcredential() {
544     API_KEY=`sudo maas-region apikey --username=ubuntu`
545     controllername=`awk 'NR==1{print substr($1, 1, length($1)-1)}' deployconfig.yaml`
546     cloudname=`awk 'NR==1{print substr($1, 1, length($1)-1)}' deployconfig.yaml`
547
548     echo  "credentials:" > credential.yaml
549     echo  "  $controllername:" >> credential.yaml
550     echo  "    opnfv-credentials:" >> credential.yaml
551     echo  "      auth-type: oauth1" >> credential.yaml
552     echo  "      maas-oauth: $API_KEY" >> credential.yaml
553
554     juju add-credential $controllername -f credential.yaml --replace
555 }
556
557 addcloud() {
558     controllername=`awk 'NR==1{print substr($1, 1, length($1)-1)}' deployconfig.yaml`
559     cloudname=`awk 'NR==1{print substr($1, 1, length($1)-1)}' deployconfig.yaml`
560
561     echo "clouds:" > maas-cloud.yaml
562     echo "   $cloudname:" >> maas-cloud.yaml
563     echo "      type: maas" >> maas-cloud.yaml
564     echo "      auth-types: [oauth1]" >> maas-cloud.yaml
565     echo "      endpoint: $API_SERVERMAAS" >> maas-cloud.yaml
566
567     juju add-cloud $cloudname maas-cloud.yaml --replace
568 }
569
570 #
571 # VLAN customization
572 #
573
574 case "$labname" in
575     'intelpod9' )
576         maas refresh
577         crvlanupdsubnet vlan904 fabric-1 "MgmtNetwork" 904 2 || true
578         crvlanupdsubnet vlan905 fabric-2 "PublicNetwork" 905 3 || true
579         crnodevlanint $vlan905 eth1 || true
580         crnodevlanint $vlan905 eth3 || true
581         enableautomodebyname eth1.905 AUTO "10.9.15.0/24" || true
582         enableautomodebyname eth3.905 AUTO "10.9.15.0/24" || true
583         enableautomodebyname eth0 AUTO "10.9.12.0/24" || true
584         enableautomodebyname eth2 AUTO "10.9.12.0/24" || true
585         ;;
586 esac
587
588 #
589 # Enable MAAS nodes interfaces
590 #
591 API_KEY=`sudo maas-region apikey --username=ubuntu`
592 maas login $PROFILE $API_SERVERMAAS $API_KEY
593
594 if [ -e ./labconfig.json ]; then
595     # We will configure all node, so we need the qty, and loop on it
596     NODE_QTY=$(cat labconfig.json | jq --raw-output '.lab.racks[0].nodes[]'.name | wc -l)
597     NODE_QTY=$((NODE_QTY-1))
598     for NODE_ID in $(seq 0 $NODE_QTY); do
599         # Get the NAME/SYS_ID of this node
600         NODE_NAME=$(cat labconfig.json | jq --raw-output ".lab.racks[0].nodes[$NODE_ID].name")
601         NODE_SYS_ID=$(maas $PROFILE nodes read | jq -r ".[] |  select(.hostname==\"$NODE_NAME\")".system_id)
602         echo ">>> Configuring node $NODE_NAME [$NODE_ID][$NODE_SYS_ID]"
603         # Recover the network interfaces list and configure each one
604         #   with sorting the list, we have hardware interface first, than the vlan interfaces
605         IF_LIST=$(cat labconfig.json | jq --raw-output ".lab.racks[0].nodes[$NODE_ID].nics[] ".ifname | sort -u )
606         for IF_NAME in $IF_LIST; do
607             # get the space of the interface
608             IF_SPACE=$(cat labconfig.json | jq --raw-output ".lab.racks[0].nodes[$NODE_ID].nics[] | select(.ifname==\"$IF_NAME\") ".spaces[])
609             case "$IF_SPACE" in
610                 'data') SUBNET_CIDR=$SUBNETDATA_CIDR; IF_MODE='AUTO' ;;
611                 'public') SUBNET_CIDR=$SUBNETPUB_CIDR; IF_MODE='AUTO' ;;
612                 'storage') SUBNET_CIDR=$SUBNETSTOR_CIDR; IF_MODE='AUTO' ;;
613                 'floating') SUBNET_CIDR=$SUBNETFLOAT_CIDR; IF_MODE='link_up' ;;
614                 *) SUBNET_CIDR='null'; IF_MODE='null'; echo "      >>> Unknown SPACE" ;;
615             esac
616             echo "   >>> Configuring interface $IF_NAME [$IF_SPACE][$SUBNET_CIDR]"
617
618             # if we have a vlan parameter in the space config
619             IF_VLAN=$(cat labconfig.json | jq --raw-output ".opnfv.spaces[] | select(.type==\"$IF_SPACE\")".vlan)
620             if ([ -z $IF_VLAN ] && [ $IF_NAME =~ \. ]); then
621                 # We have no vlan specified on spaces, but we have a vlan subinterface
622                 IF_VLAN = ${IF_NAME##*.}; fi
623
624             # in case of interface renaming
625             IF_NEWNAME=$IF_NAME
626
627             # In case of a VLAN interface
628             if ([ $IF_VLAN ] && [ "$IF_VLAN" != "null" ]); then
629                 echo "      >>> Configuring VLAN $IF_VLAN"
630                 VLANID=$(maas $PROFILE subnets read | jq ".[].vlan | select(.vid==$IF_VLAN)".id)
631                 FABRICID=$(maas $PROFILE subnets read | jq ".[].vlan | select(.vid==$IF_VLAN)".fabric_id)
632                 INTERFACE=$(maas $PROFILE interfaces read $NODE_SYS_ID | jq ".[] | select(.vlan.fabric_id==$FABRICID)".id)
633                 if [[ -z $INTERFACE ]]; then
634                     # parent interface is not set because it does not have a SUBNET_CIDR
635                     PARENT_VLANID=$(maas $PROFILE fabrics read | jq ".[].vlans[] | select(.fabric_id==$FABRICID and .name==\"untagged\")".id)
636                     # If we need to rename the interface, use new interface name
637                     if ([ $IF_NEWNAME ] && [ "$IF_NEWNAME" != "null" ]); then
638                         PARENT_IF_NAME=${IF_NEWNAME%%.*}
639                         IF_NAME=$IF_NEWNAME
640                     else
641                         PARENT_IF_NAME=${IF_NAME%%.*}
642                     fi
643                     # We set the physical interface to the targeted fabric
644                     maas $PROFILE interface update $NODE_SYS_ID $PARENT_IF_NAME vlan=$PARENT_VLANID
645                     sleep 2
646                     INTERFACE=$(maas $PROFILE interfaces read $NODE_SYS_ID | jq ".[] | select(.vlan.fabric_id==$FABRICID)".id)
647                 fi
648                 maas $PROFILE interfaces create-vlan $NODE_SYS_ID vlan=$VLANID parent=$INTERFACE || true
649             else
650                 # rename interface if needed
651                 IF_MACLOWER=$( cat labconfig.json | jq ".lab.racks[0].nodes[$NODE_ID].nics[] | select(.ifname==\"$IF_NEWNAME\")".mac[0])
652                 IF_MAC=(${IF_MACLOWER,,})
653                 IF_ID=$( maas ubuntu interfaces read $NODE_SYS_ID | jq ".[] | select(.mac_address==$IF_MAC)".id)
654                 maas $PROFILE interface update $NODE_SYS_ID $IF_ID name=$IF_NEWNAME
655             fi
656             # Configure the interface
657             if ([ $SUBNET_CIDR ] && [ "$SUBNET_CIDR" != "null" ]); then
658                 VLANID=$(maas $PROFILE subnet read $SUBNET_CIDR | jq -r '.vlan.id')
659                 if !([ $IF_VLAN ] && [ "$IF_VLAN" != "null" ]); then
660                     # If this interface is not a VLAN (done withe create-vlan)
661                     maas $PROFILE interface update $NODE_SYS_ID $IF_NAME vlan=$VLANID
662                 fi
663                 maas $PROFILE interface link-subnet $NODE_SYS_ID $IF_NAME  mode=$IF_MODE subnet=$SUBNET_CIDR || true
664                 sleep 2
665             else
666                 echo "      >>> Not configuring, we have an empty Subnet CIDR"
667             fi
668
669         done
670     done
671 fi
672
673 # Add the cloud and controller credentials for MAAS for that lab.
674 jujuver=`juju --version`
675
676 if [[ "$jujuver" > "2" ]]; then
677     addcloud
678     addcredential
679 fi
680
681 #
682 # End of scripts
683 #
684 echo " .... MAAS deployment finished successfully ...."