Exalogic Installation Series -14- accessing Exalogic via Command Line

Having worked with the Exalogic Command Line for a while I decided to wrap some of the common functions in a simplified bash script. This saves me creating the keys, connecting and identifying the appropriate Ids. Instead I can simply specify the Name and the script will do the rest of the work. This initial version has just a few commands in it but as I add more the blog entry will expand, as will the script, and document the new functionality.

Commands

All the Command below will work against the whole vDC unless they are restricted to an Account by using the -a option or a vServer by using the -v option. For all actions the script requires a User and password to be passed.

–list-vservers

This command will work through all the Accounts on a given vDC and display the vServers that are available within that Account. Issuing the command in it’s simplest form, below, will display the following:

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password --list-vservers
JAVA_HOME is not defined using /usr/java/latest
GlobalResources|LB-2
GlobalResources|nis-vserver-s
GlobalResources|JOI28GB
GlobalResources|nis-vserver-m
GlobalResources|dns
GlobalResources|LB-1

Andrew|VS002
Andrew|VS003

UliAccount|test-vm
UliAccount|sc-tvm
UliAccount|uliAdmin
UliAccount|otd-tvm
UliAccount|nis-tvm
UliAccount|wcdb-vm
UliAccount|lvm-tvm
UliAccount|sc-vm1
UliAccount|wc-vm1
UliAccount|sc-vm3
UliAccount|sc-vm2
UliAccount|wc-vm2

FAPoc|FA-DB
FAPoc|FA-01
FAPoc|OTD01
FAPoc|FA-02
FAPoc|FA-IDM
FAPoc|FA-03

Users can also specify that a Verbose format be used (–verbose) which will print the full set of information available for the given vServers as below.

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password --list-vservers --verbose -a Andrew
JAVA_HOME is not defined using /usr/java/latest
Andrew|VS002|VSRV-616bdf32-2a92-44e4-a9ea-862d0b97c0bb|VS002|Created By CreateAsset.sh|RUNNING|VNET-52a60524-d7e6-4e3f-8204-8cf8bb798ddb,VNET-1b2402d7-9010-45db-a887-4b955377584d|10.242.96.72,172.17.0.40|TMPL-a06a1406-cf5a-479d-a3ea-7c8657bb4013|ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCrGYXTkLFoahLbmc4AfCCGqjfwERUubU+TyBk5jyMq46L0eqILhQuRKBRwGp1YbvlEbeFFgQkoR11wJCw7L5wZCNXE99dY1Iya7cst68TgajMlRAunlyD7owGC2ICvTsR3aqzdOtZ6xdXPB6OEYkTI+HLBAKAdZsPdQdb6oI3eKiNzX0FcJHFT68WNuOiaD0aALV1Ct81tkAkDpLNRlag9Pt|2006|true
Andrew|VS003|VSRV-5ab971c4-1bad-4cee-8575-7e80a68ef0b3|VS003|Created By CreateAsset.sh|RUNNING|VNET-1b2402d7-9010-45db-a887-4b955377584d,VNET-52a60524-d7e6-4e3f-8204-8cf8bb798ddb|172.17.0.36,10.242.96.75|TMPL-a06a1406-cf5a-479d-a3ea-7c8657bb4013|ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCrGYXTkLFoahLbmc4AfCCGqjfwERUubU+TyBk5jyMq46L0eqILhQuRKBRwGp1YbvlEbeFFgQkoR11wJCw7L5wZCNXE99dY1Iya7cst68TgajMlRAunlyD7owGC2ICvTsR3aqzdOtZ6xdXPB6OEYkTI+HLBAKAdZsPdQdb6oI3eKiNzX0FcJHFT68WNuOiaD0aALV1Ct81tkAkDpLNRlag9Pt|2006|true

–status-vservers

Issuing the status command will cause the script to loop through the vServers within the vDC Accounts and simply display the current status of the vServer.

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password --status-vservers
JAVA_HOME is not defined using /usr/java/latest
GlobalResources|LB-2|RUNNING
GlobalResources|nis-vserver-s|RUNNING
GlobalResources|JOI28GB|SHUTDOWN
GlobalResources|nis-vserver-m|RUNNING
GlobalResources|dns|RUNNING
GlobalResources|LB-1|RUNNING

Andrew|VS002|RUNNING
Andrew|VS003|RUNNING

UliAccount|test-vm|RUNNING
UliAccount|sc-tvm|SHUTDOWNDETACHED
UliAccount|uliAdmin|RUNNING
UliAccount|otd-tvm|RUNNING
UliAccount|nis-tvm|RUNNING
UliAccount|wcdb-vm|RUNNING
UliAccount|lvm-tvm|RUNNING
UliAccount|sc-vm1|RUNNING
UliAccount|wc-vm1|RUNNING
UliAccount|sc-vm3|RUNNING
UliAccount|sc-vm2|RUNNING
UliAccount|wc-vm2|RUNNING

FAPoc|FA-DB|RUNNING
FAPoc|FA-01|SHUTDOWNDETACHED
FAPoc|OTD01|SHUTDOWNDETACHED
FAPoc|FA-02|SHUTDOWNDETACHED
FAPoc|FA-IDM|RUNNING
FAPoc|FA-03|SHUTDOWNDETACHED

–stop-vservers

The stop-vservers will use the cli to force a shutdown of the vservers. By default this will loop through all vServers in the vDC an stop them on an Account by Account basis.

–start-vservers

The start-vservers will use the cli to force a shutdown of the vservers. By default this will loop through all vServers in the vDC an start them on an Account by Account basis.

–list-distgroups

This command will work through all the Accounts on a given vDC and display the Distribution Groups that are available within that Account. Issuing the command in it’s simplest form, below, will display the following:

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password -url https://localhost --list-distgroups
JAVA_HOME is not defined using /usr/java/latest
GlobalResources|NIS-GROUP|

Andrew|test|

UliAccount|uliCA1|

–list-vnets

This command will work through all the Accounts on a given vDC and display the Networks that are available within that Account. Issuing the command in it’s simplest form, below, will display the following:

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password -url https://localhost --list-vnets
JAVA_HOME is not defined using /usr/java/latest
GlobalResources|EoIB1-client-access|10.242.96.0/21
GlobalResources|IPoIB-default|192.168.48.0/21
GlobalResources|IPoIB-vserver-shared-storage|172.17.0.0/16

Andrew|IPoIB-default|192.168.48.0/21
Andrew|EoIB1-client-access|10.242.96.0/21
Andrew|VN002|192.168.2.0/24
Andrew|VN003|192.168.4.0/24
Andrew|IPoIB-vserver-shared-storage|172.17.0.0/16
Andrew|VN004|192.168.5.0/24
Andrew|EoIB-external-mgmt|10.242.80.0/21
Andrew|VN001|192.168.3.0/24

UliAccount|EoIB1-client-access|10.242.96.0/21
UliAccount|wc-privat|192.168.0.32/28
UliAccount|EoIB-external-mgmt|10.242.80.0/21
UliAccount|IPoIB-vserver-shared-storage|172.17.0.0/16
UliAccount|IPoIB-default|192.168.48.0/21

FAPoc|IPoIB-priv-fa|192.168.0.0/28
FAPoc|IPoIB-vserver-shared-storage|172.17.0.0/16
FAPoc|EoIB1-client-access|10.242.96.0/21

–list-volumes

This command will work through all the Accounts on a given vDC and display the Volumes that are available within that Account. Issuing the command in it’s simplest form, below, will display the following:

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password -url https://localhost --list-volumes
JAVA_HOME is not defined using /usr/java/latest

Andrew|VOL666|6.0

UliAccount|resizedVolume|4.0
UliAccount|SPMSVol1|16.0
UliAccount|db-u01|20.0
UliAccount|lvmVol1|16.0
UliAccount|adminVolume|32.0

–list-templates

This command will work through all the Accounts on a given vDC and display the Templates that are available within that Account. Issuing the command in it’s simplest form, below, will display the following:

[root@ec1-vm ~]# ./SimplifiedCli.sh -u root -p password -url https://localhost --list-templates
JAVA_HOME is not defined using /usr/java/latest
GlobalResources|NavstarDefaultTemplate
GlobalResources|NavstarDefaultTemplate

Andrew|NavstarDefaultTemplate
Andrew|Navstar40GBTemplate

UliAccount|NavstarDefaultTemplate
UliAccount|LVM-CBT-v1_1
UliAccount|NavstarSingleImageLVMTemplate
UliAccount|scTestTemplate2
UliAccount|WebCenter_Template
UliAccount|scTestTemplate
UliAccount|scTestTemplate3

FAPoc|NavstarDefaultTemplate
FAPoc|FA-Testing-Template

Script

Usage

usage: ./SimplifiedCli.sh [-a <Account Name>] [-v <vServer Name>] -u <Account User> -p <Account Password> 
[--verbose] <Command>
 -a <Account Name> Name of the Account that contains the Specified vServer.
 -u <Account User> User that is allowed to access the specified account the default is root
 -p <Account Password> password of the specified user
 -v <vServer Name> vServer to be templatised or cloned.
 -h This message.

Commands

 --list-vservers
 List all the vServers in the specified Account. If no Account is specified then it
 will loop through all Accounts within the vDC listing the vServers. To successfully
 achieve this the mandatory Username and Password must have access to all the accounts.
 If --verbose is also specified the all available vServer information will be listed.

 --status-vservers
 List the status all the vServers in the specified Account. If no Account is specified then it
 will loop through all Accounts within the vDC listing the vServers. To successfully
 achieve this the mandatory Username and Password must have access to all the accounts.

 --start-vservers
 Start all or the named -v vServer(s) in the specified Account. If no Account is specified
 then it will loop through all Accounts within the vDC starting the vServers.

 --stop-vservers
 Stop all or the named -v vServer(s) in the specified Account. If no Account is specified
 then it will loop through all Accounts within the vDC stoping the vServers.

Download

 

#!/bin/bash

################################################################################
#
#  Exalogic EL X2-2 2.0.0.4 (Linux x86-64) Configuration Script.
#
#  HEADER START
# 
#  THIS SCRIPT IS PROVIDED ON AN �AS IS� BASIS, WITHOUT WARRANTY OF ANY KIND, 
#  EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT 
#  THE COVERED SCRIPT IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR 
#  PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE 
#  OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE 
#  DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER 
#  CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION.
#  NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS 
#  DISCLAIMER.
#
#  When distributing this Code, include this HEADER in each file.
#  If applicable, add the following below this this HEADER, with the fields
#  enclosed by brackets "[]" replaced with your own identifying information:
#       Portions Copyright [yyyy] [name of copyright owner]
# 
#  HEADER END
# 
# 
#       Copyright 2011 Andrew Hopkinson, Oracle Corporation UK Ltd.
#
################################################################################

export OCCLI=/opt/sun/occli/bin
export IAAS_HOME=/opt/oracle/iaas/cli
export IAAS_BASE_URL=https://localhost
export BASE_IAAS_ACCESS_KEY_FILE=iaas_access.key
export BASE_KEY_NAME=cli.asset.create
export BASE_KEY_FILE=iaas_access.pub
export RUN_DATE=`date +"%Y%m%d-%H%M"`
#CloudUser used to create vServers & Volumes
export IAAS_USER=root
export IAAS_PASSWORD_FILE=root.pwd
export INPUT_FILE=CreateAssets.in

export ACCOUNTS_FILE=accounts.out
export VOLUMES_FILE=volumes.out
export DISTGRPS_FILE=distgrp.out
export VNETS_FILE=vnets.out
export VSERVER_TYPES_FILE=vstype.out
export VSERVER_FILE=vserver.out
export VSERVER_TEMPLATES=template.out
export NETWORK_STATIC_IPS=staticips.out
export KEY_PAIRS=keypairs.out



function getAccounts() {
 accountsArray=( $($IAAS_HOME/bin/akm-describe-accounts --sep "|" | sed 's/ /_/g') )
}

function getVServers() {
 vserversArray=( $($IAAS_HOME/bin/iaas-describe-vservers --sep "|" | sed 's/ /_/g') )
}

function getNetworks() {
 vnetsArray=( $($IAAS_HOME/bin/iaas-describe-vnets --sep "|" | sed 's/ /_/g') )
}

function getDistributionGroups() {
 distGrpsArray=( $($IAAS_HOME/bin/iaas-describe-distribution-groups --sep "|" | sed 's/ /_/g') )
}

function getTemplates() {
 templatesArray=( $($IAAS_HOME/bin/iaas-describe-server-templates --sep "|" | sed 's/ /_/g') )
}

function getVolumes() {
 volumesArray=( $($IAAS_HOME/bin/iaas-describe-volumes --sep "|" | sed 's/ /_/g') )
}



function connectToAccount() {
 # Set run specific key information
 export IAAS_ACCESS_KEY_FILE=$ACCOUNT_NAME"."$RUN_DATE"."$BASE_IAAS_ACCESS_KEY_FILE
 export KEY_NAME=$ACCOUNT_NAME"."$RUN_DATE"."$BASE_KEY_NAME
 export KEY_FILE=$ACCOUNT_NAME"."$RUN_DATE"."$BASE_KEY_FILE
 #echo "IAAS_ACCESS_KEY_FILE=$IAAS_ACCESS_KEY_FILE"
 #echo "KEY_NAME=$KEY_NAME"
 #echo "KEY_FILE=$KEY_FILE"
 #echo "Found Account $line"
 AK=`$IAAS_HOME/bin/akm-create-access-key --account $ACCOUNT_ID --access-key-file $IAAS_ACCESS_KEY_FILE`
 KEYPAIR=`$IAAS_HOME/bin/iaas-create-key-pair --key-name $KEY_NAME --key-file $KEY_FILE`
 #echo "Connected to $ACCOUNT_NAME"
}

function disconnectFromAccount() {
  $IAAS_HOME/bin/iaas-delete-key-pair --key-name $KEY_NAME --access-key-file $IAAS_ACCESS_KEY_FILE
  $IAAS_HOME/bin/akm-delete-access-key $AK
  rm -f $KEY_FILE $IAAS_ACCESS_KEY_FILE
}

#############################################################
##
## stopVServers
## ============
##
## Stop one or more vServers running within the currently
## connected Account. If a specific vServer Name is passed in
## $VSERVER as specified on the command line using -v then 
## this will be the one stopped. If no VSERVER is specified
## then all vServers in the Account will be stopped.
##
#############################################################

function stopVServers() {
 getVServers
 VSERVER_IDS=""
 VSERVER_NAMES=""
 for vserver in "${vserversArray[@]}"
 do
  VSERVER_ID=${vserver%%|*}
  vserver=${vserver#*|}
  VSERVER_NAME=${vserver%%|*}
  if [[ "$VSERVER" == "" || "$VSERVER" == "$VSERVER_NAME" ]]
  then
   if [[ "$VSERVER_IDS" == "" ]]
   then
    VSERVER_IDS=$VSERVER_ID
    VSERVER_NAMES=$VSERVER_NAME
   else
    VSERVER_IDS=$VSERVER_IDS","$VSERVER_ID
    VSERVER_NAMES=$VSERVER_NAMES","$VSERVER_NAME
   fi
  fi
 done
 if [[ "$VSERVER_IDS" != "" ]]
 then
  echo "Stopping vServer(s) [$VSERVER_NAMES]"
  $IAAS_HOME/bin/iaas-stop-vservers --vserver-ids $VSERVER_IDS --force
 else
  echo "No vServers to stop"
 fi
}

#############################################################
##
## startVServers
## =============
##
## Start one or more vServers stopped within the currently
## connected Account. If a specific vServer Name is passed in
## $VSERVER as specified on the command line using -v then 
## this will be the one started. If no VSERVER is specified
## then all vServers in the Account will be started.
##
#############################################################

function startVServers() {
 getVServers
 VSERVER_IDS=""
 VSERVER_NAMES=""
 for vserver in "${vserversArray[@]}"
 do
  VSERVER_ID=${vserver%%|*}
  vserver=${vserver#*|}
  VSERVER_NAME=${vserver%%|*}
  if [[ "$VSERVER" == "" || "$VSERVER" == "$VSERVER_NAME" ]]
  then
   if [[ "$VSERVER_IDS" == "" ]]
   then
    VSERVER_IDS=$VSERVER_ID
    VSERVER_NAMES=$VSERVER_NAME
   else
    VSERVER_IDS=$VSERVER_IDS","$VSERVER_ID
    VSERVER_NAMES=$VSERVER_NAMES","$VSERVER_NAME
   fi
  fi
 done
 if [[ "$VSERVER_IDS" != "" ]]
 then
  echo "Starting vServer(s) [$VSERVER_NAMES]"
  $IAAS_HOME/bin/iaas-start-vservers --vserver-ids $VSERVER_IDS
 else
  echo "No vServers to start"
 fi
}

#############################################################
##
## listVServers
## ============
##
## List the vServers running on the specified Account is 
## the verbose flag is set then all vServer details will be 
## displayed otherwise simple the Acc and Name.
##
#############################################################

function listVServers() {
 getVServers
 for vserver in "${vserversArray[@]}"
 do
  VSERVER_ID=${vserver%%|*}
  vserver=${vserver#*|}
  VSERVER_NAME=${vserver%%|*}
  if [[ "$VSERVER" == "" || "$VSERVER" == "$VSERVER_NAME" ]]
  then
   if [[ "$VERBOSE" == "true" ]]
   then
    echo "$ACCOUNT_NAME|$VSERVER_NAME|$VSERVER_ID|"$(echo $vserver | sed 's/_/ /g')
   else
    echo "$ACCOUNT_NAME|$VSERVER_NAME"
   fi
  fi
 done
}

#############################################################
##
## listVServerStatus
## =================
##
## List the Status of the vServers within an Account.
##
#############################################################

function listVServerStatus() {
 getVServers
 for vserver in "${vserversArray[@]}"
 do
  VSERVER_ID=${vserver%%|*}
  vserver=${vserver#*|}
  VSERVER_NAME=${vserver%%|*}
  vserver=${vserver#*|}
  VSERVER_DESC=${vserver%%|*}
  vserver=${vserver#*|}
  VSERVER_STATUS=${vserver%%|*}
  if [[ "$VSERVER" == "" || "$VSERVER" == "$VSERVER_NAME" ]]
  then
   echo "$ACCOUNT_NAME|$VSERVER_NAME|$VSERVER_STATUS"
  fi
 done
}

#############################################################
##
## listVNets
## =========
##
## List the Networks within an Account.
##
#############################################################

function listVNets() {
 getNetworks
 for vnet in "${vnetsArray[@]}"
 do
  VNET_ID=${vnet%%|*}
  vnet=${vnet#*|}
  VNET_NAME=${vnet%%|*}
  vnet=${vnet#*|}
  if [[ "$VERBOSE" == "true" ]]
  then
   echo "$ACCOUNT_NAME|$VNET_NAME|$VNET_ID|"$(echo $vnet | sed 's/_/ /g')
  else
   VNET_DESC=${vnet%%|*}
   vnet=${vnet#*|}
   VNET_STATUS=${vnet%%|*}
   vnet=${vnet#*|}
   VNET_IP=${vnet%%|*}
   echo "$ACCOUNT_NAME|$VNET_NAME|$VNET_IP"
  fi
 done
}

#############################################################
##
## listDistributionGroups
## ======================
##
## List the Distribution Groups within an Account.
##
#############################################################

function listDistributionGroups() {
 getDistributionGroups
 for distGrp in "${distGrpsArray[@]}"
 do
  DG_ID=${distGrp%%|*}
  distGrp=${distGrp#*|}
  DG_NAME=${distGrp%%|*}
  distGrp=${distGrp#*|}
  if [[ "$VERBOSE" == "true" ]]
  then
   echo "$ACCOUNT_NAME|$DG_NAME|$DG_ID|"$(echo $distGrp | sed 's/_/ /g')
  else
   DG_DESC=${distGrp%%|*}
   distGrp=${distGrp#*|}
   DG_STATUS=${distGrp%%|*}
   echo "$ACCOUNT_NAME|$DG_NAME|$VNET_IP"
  fi
 done
}

#############################################################
##
## listTemplates
## =============
##
## List the Templates within an Account.
##
#############################################################

function listTemplates() {
 getTemplates
 for template in "${templatesArray[@]}"
 do
  TEMPLATE_ID=${template%%|*}
  template=${template#*|}
  TEMPLATE_NAME=${template%%|*}
  template=${template#*|}
  if [[ "$VERBOSE" == "true" ]]
  then
   echo "$ACCOUNT_NAME|$TEMPLATE_NAME|$TEMPLATE_ID|"$(echo $template | sed 's/_/ /g')
  else
   TEMPLATE_DESC=${template%%|*}
   template=${template#*|}
   TEMPLATE_STATUS=${template%%|*}
   echo "$ACCOUNT_NAME|$TEMPLATE_NAME"
  fi
 done
}

#############################################################
##
## listVolumes
## ===========
##
## List the Volumes within an Account.
##
#############################################################

function listVolumes() {
 getVolumes
 for volume in "${volumesArray[@]}"
 do
  VOLUME_ID=${volume%%|*}
  volume=${volume#*|}
  VOLUME_NAME=${volume%%|*}
  volume=${volume#*|}
  if [[ "$VERBOSE" == "true" ]]
  then
   echo "$ACCOUNT_NAME|$VOLUME_NAME|$VOLUME_ID|"$(echo $volume | sed 's/_/ /g')
  else
   VOLUME_DESC=${volume%%|*}
   volume=${volume#*|}
   VOLUME_STATUS=${volume%%|*}
   volume=${volume#*|}
   VOLUME_SIZE=${volume%%|*}
   echo "$ACCOUNT_NAME|$VOLUME_NAME|$VOLUME_SIZE"
  fi
 done
}



#############################################################
##
## usage
## =====
##
## Show usage.
##
#############################################################

function usage() {
 echo ""
 echo >&2 "usage: $0 [-a <Account Name>] [-v <vServer Name>] -u <Account User> -p <Account Password> [--verbose] <Command>"
 echo >&2 "  -a <Account Name> Name of the Account that contains the Specified vServer."
 echo >&2 "  -u <Account User> User that is allowed to access the specified account the default is root"
 echo >&2 "  -p <Account Password> password of the specified user"
 echo >&2 "  -v <vServer Name> vServer to be templatised or cloned."
 echo >&2 "  -url <IAAS Base URL> URL to access the EMOC interface the default is https://localhost."
 echo >&2 "  -h This message."
 echo >&2 " "
 echo >&2 "Commands "
 echo >&2 " "
 echo >&2 "          --list-vservers"
 echo >&2 "                List all the vServers in the specified Account. If no Account is specified then it"
 echo >&2 "                will loop through all Accounts within the vDC listing the vServers. To successfully"
 echo >&2 "                achieve this the mandatory Username and Password must have access to all the accounts."
 echo >&2 "                If --verbose is also specified the all available vServer information will be listed."
 echo >&2 " "
 echo >&2 "          --status-vservers"
 echo >&2 "                List the status all the vServers in the specified Account. If no Account is specified then it"
 echo >&2 "                will loop through all Accounts within the vDC listing the vServers. To successfully"
 echo >&2 "                achieve this the mandatory Username and Password must have access to all the accounts."
 echo >&2 " "
 echo >&2 "          --start-vservers"
 echo >&2 "                Start all or the named -v vServer(s) in the specified Account. If no Account is specified"
 echo >&2 "                then it will loop through all Accounts within the vDC starting the vServers."
 echo >&2 " "
 echo >&2 "          --stop-vservers"
 echo >&2 "                Stop all or the named -v vServer(s) in the specified Account. If no Account is specified"
 echo >&2 "                then it will loop through all Accounts within the vDC stoping the vServers."
 echo >&2 " "
 echo >&2 "          --list-vnets"
 echo >&2 "                List all the vNets in the specified Account. If no Account is specified then it"
 echo >&2 "                will loop through all Accounts within the vDC listing the vNets. To successfully"
 echo >&2 "                achieve this the mandatory Username and Password must have access to all the accounts."
 echo >&2 "                If --verbose is also specified the all available vNet information will be listed."
 echo >&2 " "
 echo >&2 "          --list-distgroups"
 echo >&2 "                List all the Distribution Groups in the specified Account. If no Account is specified then it"
 echo >&2 "                will loop through all Accounts within the vDC listing the Distribution Groups. To successfully"
 echo >&2 "                achieve this the mandatory Username and Password must have access to all the accounts."
 echo >&2 "                If --verbose is also specified the all available Distribution Group information will be listed."
 echo >&2 " "
 echo >&2 "          --list-volumes"
 echo >&2 "                List all the Volumes in the specified Account. If no Account is specified then it"
 echo >&2 "                will loop through all Accounts within the vDC listing the Volumes. To successfully"
 echo >&2 "                achieve this the mandatory Username and Password must have access to all the accounts."
 echo >&2 "                If --verbose is also specified the all available Volumes information will be listed."
 echo >&2 " "
 echo >&2 "          --list-templates"
 echo >&2 "                List all the Templates in the specified Account. If no Account is specified then it"
 echo >&2 "                will loop through all Accounts within the vDC listing the Templates. To successfully"
 echo >&2 "                achieve this the mandatory Username and Password must have access to all the accounts."
 echo >&2 "                If --verbose is also specified the all available Template information will be listed."
 echo""
 exit 1
}

###############################################################
##
## Simple start for the script that will extract the parameters
## and call the appriate start function.
##
###############################################################

export ACCOUNT_USER="root"
export ACCOUNT_PASSWORD="welcome1"
export SYSTEMIMGDIR=/mnt/elsystem

while [ $# -gt 0 ]
do
 case "$1" in 
  -a) ACCOUNT="$2"; shift;;
  -v) VSERVER="$2"; shift;;
  -u) ACCOUNT_USER="$2"; shift;;
  -p) ACCOUNT_PASSWORD="$2"; shift;;
  -url) IAAS_BASE_URL="$2"; shift;;
  --verbose) VERBOSE=true;;
  --list-vservers) LIST_VSERVERS=true;;  
  --stop-vservers) STOP_VSERVERS=true;;  
  --start-vservers) START_VSERVERS=true;;  
  --status-vservers) STATUS_VSERVERS=true;;  
  --list-vnets) LIST_VNETS=true;;  
  --list-distgroups) LIST_DISTGRPS=true;;  
  --list-templates) LIST_TEMPLATES=true;;  
  --list-volumes) LIST_VOLUMES=true;;  
  *) usage;;
  *) break;;
 esac
 shift
done

IAAS_USER=$ACCOUNT_USER
echo "$ACCOUNT_PASSWORD" > $IAAS_PASSWORD_FILE



# Check if the JAVA_HOME is set
if [[ "$JAVA_HOME" == "" ]]
then
 export JAVA_HOME=/usr/java/latest
 echo "JAVA_HOME is not defined using $JAVA_HOME"
fi

getAccounts

for account in "${accountsArray[@]}"
do
 ACCOUNT_ID=${account%%|*}
 account=${account#*|}
 ACCOUNT_NAME=${account%%|*}
 if [[ ("$ACCOUNT" == "" || "$ACCOUNT" == "$ACCOUNT_NAME") && "$ACCOUNT_ID" == ACC-* ]]
 then
  connectToAccount
  if [[ "$STOP_VSERVERS" == "true" ]]
  then
   stopVServers
  elif [[ "$START_VSERVERS" == "true" ]]
  then
   startVServers
  elif [[ "$LIST_VSERVERS" == "true" ]]
  then
   listVServers
  elif [[ "$STATUS_VSERVERS" == "true" ]]
  then
   listVServerStatus
  elif [[ "$LIST_VNETS" == "true" ]]
  then
   listVNets
  elif [[ "$LIST_DISTGRPS" == "true" ]]
  then
   listDistributionGroups
  elif [[ "$LIST_TEMPLATES" == "true" ]]
  then
   listTemplates
  elif [[ "$LIST_VOLUMES" == "true" ]]
  then
   listVolumes
  fi
  disconnectFromAccount
 fi
done

Exalogic Installation Series -13- Cloning an existing vServer

Following on from my Blog entry “Scripted Template Generation from an existing vServer” I have built a wrapper script that can be used to execute the Template Generation script or Clone a specific vServer. This script was not incorporated into the original script because it must be executed on a Compute Node with access to the /OVS/Repositories directory and the Compute Node are a minimal install and hence do not have all the required software available. As part of the Cloning process this new script will create an Assets input file that can be used with the CreateAssets.sh describe in the blog “Scripting Asset Creation” and optionally execute the result to create the clone.

To successfully run the script you will need the following 3 scripts located in the same directory on a machine with the EMOC cli/api rms installed.

  1. CloneOrTemplateVServer.sh.
  2. CreateTemplateFromVServer.sh.
  3. CreateAssets.sh.

During execute, of the CloneOrTemplateVServer.sh, the script will connect to EMOC and stop the specified vServer before scping the CreateTemplateFromVServer.sh to the specified Compute Node and executing it. Once the vServer has been converted to a Template the script will restart the specified vServer and then retrieve the following information for the vServers and build the Clone Asset file.

  1. Connected Networks
  2. VServer Type

In addition the template that was built, and assumed to be located on the ZFS below /export/common/images/<Sub Dir based on Name>, will have an upload entry, in the Asset file, and then used within the vServer entry. Because during execute we do not know the number of networks associated with the vServer the Clone Asset file will be created with “*” in the IP Address section indicating that the IP should be allocated Automatically. A future enhancement will provide the “-b” flag to indicate a Backup Asset file must be created and this will contain the IP allocated to the current server.

If the opt to execute has been specified, “-e” the CreateAsset.sh script will be executed passing in the Clone Asset file thus importing the template and creating the server.

Usage

usage: ./CloneOrTemplateVServer.sh -a  -n  -u  -p  -t|-b|-c [-e] -i  [-r ] [-w ] [-d ] [-f ]
       -a  Name of the Account that contains the Specified vServer.
       -u  User that is allowed to access the specified account the default is root
       -p  password of the specified user
       -n  vServer to be templatised or cloned.
       -f  (Default is CreateAssets.in) Defines the file that will be built during the clode operation.
       -t|-b|-c Indicates if only a template should be created (-t) or if the cloning file should be generated 
       as well (-c). Specifying -b will cause the current IP Addresses to be used in the Asset File
             -e If the action is to clone then the presence of this flag indicates that the resulting 
             AssetsFile should be executed
       -r  Location of the repository the default is /OVS/Repositories/*
       -w  Working directory where intermediate files will be copied.
       -d  Directory where the template tgz will be created. Default is current directory
       -i  Address of Compute Node to run the Template functionality from.

Script

Download

 
#!/bin/bash

################################################################################
#
#  Exalogic EL X2-2 2.0.0.4 (Linux x86-64) Configuration Script.
#
#  HEADER START
# 
#  THIS SCRIPT IS PROVIDED ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, 
#  EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT 
#  THE COVERED SCRIPT IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR 
#  PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE 
#  OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE 
#  DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER 
#  CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION.
#  NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS 
#  DISCLAIMER.
#
#  When distributing this Code, include this HEADER in each file.
#  If applicable, add the following below this this HEADER, with the fields
#  enclosed by brackets "[]" replaced with your own identifying information:
#       Portions Copyright [yyyy] [name of copyright owner]
# 
#  HEADER END
# 
# 
#       Copyright 2011 Andrew Hopkinson, Oracle Corporation UK Ltd.
#
################################################################################

export OCCLI=/opt/sun/occli/bin
export IAAS_HOME=/opt/oracle/iaas/cli
export IAAS_BASE_URL=https://localhost
export BASE_IAAS_ACCESS_KEY_FILE=iaas_access.key
export BASE_KEY_NAME=cli.asset.create
export BASE_KEY_FILE=iaas_access.pub
export RUN_DATE=`date +"%Y%m%d-%H%M"`
#CloudUser used to create vServers & Volumes
export IAAS_USER=root
export IAAS_PASSWORD_FILE=root.pwd
export INPUT_FILE=CreateAssets.in

export ACCOUNTS_FILE=accounts.out
export VOLUMES_FILE=volumes.out
export DISTGRPS_FILE=distgrp.out
export VNETS_FILE=vnets.out
export VSERVER_TYPES_FILE=vstype.out
export VSERVER_FILE=vserver.out
export VSERVER_TEMPLATES=template.out
export NETWORK_STATIC_IPS=staticips.out
export KEY_PAIRS=keypairs.out


## **********************************************************

PROCESSING_ACCOUNT=""

function connectToAccount() {
 if [[ "$ACCOUNT" != "$PROCESSING_ACCOUNT" ]]
 then
  if [[ "" != "$PROCESSING_ACCOUNT" ]]
  then
   $IAAS_HOME/bin/iaas-delete-key-pair --key-name $KEY_NAME --access-key-file $IAAS_ACCESS_KEY_FILE
   $IAAS_HOME/bin/akm-delete-access-key $AK
  fi
  # Set run specific key information
  export IAAS_ACCESS_KEY_FILE=$ACCOUNT"."$RUN_DATE"."$BASE_IAAS_ACCESS_KEY_FILE
  export KEY_NAME=$ACCOUNT"."$RUN_DATE"."$BASE_KEY_NAME
  export KEY_FILE=$ACCOUNT"."$RUN_DATE"."$BASE_KEY_FILE
  #echo "IAAS_ACCESS_KEY_FILE=$IAAS_ACCESS_KEY_FILE"
  #echo "KEY_NAME=$KEY_NAME"
  echo "KEY_FILE=$KEY_FILE"
  # Save current processing account
  PROCESSING_ACCOUNT=$ACCOUNT
  IAAS_USER=$ACCOUNT_USER
  echo "$ACCOUNT_PASSWORD" > $IAAS_PASSWORD_FILE
  $IAAS_HOME/bin/akm-describe-accounts --sep "|" > $ACCOUNTS_FILE
  while read line
  do
   ACCOUNT_ID=${line%%|*}
   line=${line#*|}
   ACCOUNT_NAME=${line%%|*}
 #  echo "Id = $ACCOUNT_ID"
 #  echo "Name = $ACCOUNT_NAME"
   if [[ "$ACCOUNT_NAME" == "$ACCOUNT" ]]
   then
    #echo "Found Account $line"
    AK=`$IAAS_HOME/bin/akm-create-access-key --account $ACCOUNT_ID --access-key-file $IAAS_ACCESS_KEY_FILE`
    KEYPAIR=`$IAAS_HOME/bin/iaas-create-key-pair --key-name $KEY_NAME --key-file $KEY_FILE`
    echo "Connected to $ACCOUNT_NAME"
    
    #cp $IAAS_ACCESS_KEY_FILE $ACCOUNT_NAME$IAAS_ACCESS_KEY_FILE
    #cp $KEY_FILE $ACCOUNT_NAME$KEY_FILE
    break
   fi    
  done < $ACCOUNTS_FILE 
 fi
}

function disconnectFromAccount() {
  $IAAS_HOME/bin/iaas-delete-key-pair --key-name $KEY_NAME --access-key-file $IAAS_ACCESS_KEY_FILE
  $IAAS_HOME/bin/akm-delete-access-key $AK
  PROCESSING_ACCOUNT=""
}

function getDistributionGroups() {
 $IAAS_HOME/bin/iaas-describe-distribution-groups --sep "|" > $DISTGRPS_FILE
}

function getNetworks() {
 $IAAS_HOME/bin/iaas-describe-vnets --sep "|" > $VNETS_FILE
}

function getVSTypes() {
 $IAAS_HOME/bin/iaas-describe-vserver-types --sep "|" > $VSERVER_TYPES_FILE
}

function getTemplates() {
 $IAAS_HOME/bin/iaas-describe-server-templates --sep "|" > $VSERVER_TEMPLATES
}

function getVolumes() {
 $IAAS_HOME/bin/iaas-describe-volumes --sep "|" > $VOLUMES_FILE
}

function getVServers() {
 $IAAS_HOME/bin/iaas-describe-vservers --sep "|" > $VSERVER_FILE
}

function getVServerId() {
 while read line
 do
  VSERVER_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$VSERVER_NAME" == "$NAME" ]]
  then
   break;
  fi
  VSERVER_ID=""
 done < $VSERVER_FILE
}


function getVServerState() {
 getVServers
 while read line
 do
  VSERVER_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  line=${line#*|}
  line=${line#*|}
  VSERVER_STATE=${line%%|*}
  if [[ "$VSERVER_NAME" == "$NAME" ]]
  then
   break;
  fi
 done < $VSERVER_FILE
}

function pauseUntilVServerRunning() {
 # Wait until the Server is running before creating the next
 echo "Pausing until vServer is Running"
  getVServerState
  while [[ "$VSERVER_STATE" != "RUNNING" ]]
  do
   echo "$NAME $VSERVER_STATE"
   if [[ "$VSERVER_STATE" != "RUNNING" ]]
   then
    echo "Sleeping......."
    sleep 30
   fi
   getVServerState
  done
  echo "$NAME $VSERVER_STATE"
  # Lets pause for a minute or two
  echo "Just Chilling......"
  sleep 30
}

## **********************************************************




function pauseUntilVServerShutdown() {
 # Wait until the Server is running before creating the next
 echo "Pausing until vServer has Shutdown"
  getVServerState
  while [[ "$VSERVER_STATE" != "SHUTDOWNDETACHED" ]]
  do
   echo "$NAME $VSERVER_STATE"
   if [[ "$VSERVER_STATE" != "SHUTDOWNDETACHED" ]]
   then
    echo "Sleeping......."
    sleep 30
   fi
   getVServerState
  done
  echo "$NAME $VSERVER_STATE"
  # Lets pause for a minute or two
  echo "Just Chilling......"
  sleep 30
}

#############################################################
##
## stopVServer
## ===========
##
## Find and stop a vServer.
##
#############################################################

function stopVServer() {
 echo "Stopping vServer $VSERVER_NAME"
 getVServers
 getVServerId
 $IAAS_HOME/bin/iaas-stop-vservers --vserver-ids $VSERVER_ID --force
 pauseUntilVServerShutdown
}

#############################################################
##
## startVServer
## ============
##
## Find and stop a vServer.
##
#############################################################

function startVServer() {
 echo "Starting vServer $VSERVER_NAME"
 getVServers
 getVServerId
 $IAAS_HOME/bin/iaas-start-vservers --vserver-ids $VSERVER_ID
 pauseUntilVServerRunning
}

#############################################################
##
## executeRemoteCreateTemplate
## ===========================
##
## Execute the CreateTemplateFromVServer.sh on the specified 
## Compute Node. This is required because the Repository is
## not accessible from the EC VM. It's assumed we will not 
## need to enter a password.
##
#############################################################

function executeRemoteCreateTemplate() {
 echo "Executing Remote Functions"
 if [[ "$CN_IP_ADDRESS" != "" ]]
 then
  #ssh root@$CN_IP_ADDRESS "bash -s" < CreateTemplateFromVServer.sh -n $VSERVER_NAME -r $REPOSITORY_DIR 
  -w $WORKING_DIR -d $DESTINATION_DIR
  #ssh root@$CN_IP_ADDRESS "bash -s -n $VSERVER_NAME -r $REPOSITORY_DIR -w $WORKING_DIR -d 
  $DESTINATION_DIR" < CreateTemplateFromVServer.sh
  #cat CreateTemplateFromVServer.sh | ssh root@$CN_IP_ADDRESS "bash -s -n $VSERVER_NAME -r $REPOSITORY_DIR 
  -w $WORKING_DIR -d $DESTINATION_DIR"
  echo "Copying script to $CN_IP_ADDRESS"
  scp CreateTemplateFromVServer.sh root@$CN_IP_ADDRESS:/tmp
  ssh root@$CN_IP_ADDRESS "chmod a+x /tmp/CreateTemplateFromVServer.sh"
  ssh root@$CN_IP_ADDRESS "/tmp/CreateTemplateFromVServer.sh -n $VSERVER_NAME -r $REPOSITORY_DIR -w 
  $WORKING_DIR -d $DESTINATION_DIR"
  ssh root@$CN_IP_ADDRESS "rm -f /tmp/CreateTemplateFromVServer.sh"
  
  TEMPLATE_TGZ=$DESTINATION_DIR/el_template_$VSERVER_NAME.tgz
 fi
}

#############################################################
##
## createTemplate
## ==============
##
## High level template creation function that will call the 
## required processing function in the necessary sequence.
##
#############################################################

function createTemplate() {
 stopVServer
 executeRemoteCreateTemplate
 startVServer
 echo ""
 echo ""
 echo "****************************************************"
 echo "**"
 echo "** $TEMPLATE_TGZ has been created from"
 echo "** vServer $VSERVER_NAME "
 echo "**"
 echo "****************************************************"
 echo ""
 echo ""
}

#############################################################
##
## getNetworkName
## ==============
##
## Gets the name of a network based on the Id.
##
#############################################################

function getNetworkName() {
  NETWORK_NAME=""
  while read line
  do
   ID=${line%%|*}
   line=${line#*|}
   NAME=${line%%|*}
   if [[ "$ID" == "$NETWORK_ID" ]]
   then
    NETWORK_NAME=$NAME
    break
   fi
  done < $VNETS_FILE
}

#############################################################
##
## getVSTypeName
## =============
##
## Gets the name of a vServer Type based on the Id.
##
#############################################################

function getVSTypeName() {
  VSTYPE_NAME=""
  while read line
  do
   ID=${line%%|*}
   line=${line#*|}
   NAME=${line%%|*}
   if [[ "$ID" == "$VSTYPE_ID" ]]
   then
    VSTYPE_NAME=$NAME
    break
   fi
  done < $VSERVER_TYPES_FILE
}

#############################################################
##
## generateAssetFile
## =================
##
## Generates a Input script that can be used with the 
## CreateAssets.sh to create a server based on the new 
## template.
##
#############################################################

function generateAssetFile() {
 echo "Generating Clones CreateAsset input file"
 if [[ "$ASSET_FILE" == "" ]]
 then
  if [[ "$BACKUP" == "true" ]]
  then
   ASSET_FILE=$VSERVER_NAME"BackupAsset.in"
  else
   ASSET_FILE=$VSERVER_NAME"CreateCloneAsset.in"
  fi
 fi
 echo "$ACCOUNT:Connect|$ACCOUNT_USER|$ACCOUNT_PASSWORD" > $ASSET_FILE
 # Here we are assuming that we have used the recommended mount
 SN_TEMPLATE_FILE=${TEMPLATE_TGZ/u01/export}
 echo "$ACCOUNT:Upload|ServerTemplate|$VSERVER_NAME-Template|http://$SN_IP_ADDRESS/shares$SN_TEMPLATE_FILE" >> 
 $ASSET_FILE
 # Get VServer specific information
 getVServers
 getNetworks
 getVSTypes
 
 while read line
 do
  VSERVER_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  line=${line#*|}
  if [[ "$NAME" == "$VSERVER_NAME" ]]
  then
   URL=${line%%|*}
   line=${line#*|}
   STATE=${line%%|*}
   line=${line#*|}
   NETWORK_IDS=${line%%|*}
   line=${line#*|}
   NETWORK_IPS=${line%%|*}
   line=${line#*|}
   TEMPLATE_ID=${line%%|*}
   line=${line#*|}
   SSH_KEY=${line%%|*}
   line=${line#*|}
   VSTYPE_ID=${line%%|*}
   line=${line#*|}
   
   NETWORK_NAMES=""
   #NETWORK_IPS=""
   for NETWORK_ID in ${NETWORK_IDS//,/ }
   do
    getNetworkName
    if [[ "$NETWORK_NAMES" == "" ]]
    then
     NETWORK_NAMES=$NETWORK_NAME
     if [[ "$BACKUP" != "true" ]]
     then
      NETWORK_IPS="*"
     fi
    else
     NETWORK_NAMES=$NETWORK_NAMES","$NETWORK_NAME
     if [[ "$BACKUP" != "true" ]]
     then
      NETWORK_IPS=$NETWORK_IPS",*"
     fi
    fi
   done
   
   # Get VServer Type Name
   getVSTypeName
   
   echo "$ACCOUNT:Create|vServer|$VSERVER_NAME-Clone|$VSTYPE_NAME|$VSERVER_NAME-Template|$NETWORK_NAMES|$NETWORK_IPS" >> $ASSET_FILE
   
   break
  fi
 done < $VSERVER_FILE

 echo "$ACCOUNT:Disconnect" >> $ASSET_FILE
 
 echo "Generated Asset File $ASSET_FILE"
 
}

#############################################################
##
## executeAssetFile
## =================
##
## Execute the CreateAssets.sh script using the generated 
## Asset file. We assume it is in the same directory.
##
#############################################################

function executeAssetFile() {
 echo "Executing the Generated $ASSET_FILE file"
 echo ""
 ./CreateAssets.sh -f $ASSET_FILE -r
}

#############################################################
##
## usage
## =====
##
## Show usage.
##
#############################################################

function usage() {
 echo ""
 echo >&2 "usage: $0 -a <Account Name> -n <vServer Name> -u <Account User> -p <Account Password> -t|-b|-c [-e] -i
 <Compute Node IP> [-r <Repository Directory>] [-w <Working Directory>] [-d <Destination Directory>] 
 [-f <Asset Definition File>]"
 echo >&2 "          -a <Account Name> Name of the Account that contains the Specified vServer."
 echo >&2 "                     -u <Account User> User that is allowed to access the specified account the default 
 is root"
 echo >&2 "                     -p <Account Password> password of the specified user"
 echo >&2 "                     -n <vServer Name> vServer to be templatised or cloned."
 echo >&2 "          -f <Asset Definition File> (Default is CreateAssets.in) Defines the file that will be built 
 during the clode operation."
 echo >&2 "          -t|-b|-c Indicates if only a template should be created (-t) or if the cloning file should 
 be generated as well (-c). Specifying -b will cause the current IP Addresses to be used in the Asset File"
 echo >&2 "                     -e If the action is to clone then the presence of this flag indicates that the 
resulting AssetsFile should be executed"
 echo >&2 "          -r <Repository Directory> Location of the repository the default is /OVS/Repositories/*"
 echo >&2 "          -w <Working Directory> Working directory where intermediate files will be copied."
 echo >&2 "          -d <Destination Directory> Directory where the template tgz will be created. Default is 
 current directory"
 echo >&2 "          -i <Compute Node IP> Address of Compute Node to run the Template functionality from."
 echo""
 exit 1
}

###############################################################
##
## Simple start for the script that will extract the parameters
## and call the appriate start function.
##
###############################################################

export CLONE=""
export BACKUP=""
export TEMPLATE=""
export EXECUTE=""
export WORKING_DIR="/u01/common/images/vServerTemplateWIP"
export DESTINATION_DIR="/u01/common/images/vServerTemplates"
export REPOSITORY_DIR="/OVS/Repositories/*"
export ACCOUNT_USER="root"
export ACCOUNT_PASSWORD="welcome1"
export SYSTEMIMGDIR=/mnt/elsystem
export CN_IP_ADDRESS=""
export SN_IP_ADDRESS="172.17.0.9"

while [ $# -gt 0 ]
do
 case "$1" in 
  -f) ASSET_FILE="$2"; shift;;
  -a) ACCOUNT="$2"; shift;;
  -n) VSERVER_NAME="$2"; shift;;
  -r) REPOSITORY_DIR="$2"; shift;;
  -d) DESTINATION_DIR="$2"; shift;;
  -u) ACCOUNT_USER="$2"; shift;;
  -p) ACCOUNT_PASSWORD="$2"; shift;;
  -w) WORKING_DIR="$2"; shift;;
  -i) CN_IP_ADDRESS="$2"; shift;;
  -s) SN_IP_ADDRESS="$2"; shift;;
  -c) CLONE=true;;
  -b) BACKUP=true;;
  -t) TEMPLATE=true;;  
  -e) EXECUTE=true;;  
  *) usage;;
  *) break;;
 esac
 shift
done


# Check if the JAVA_HOME is set
if [[ "$JAVA_HOME" == "" ]]
then
 export JAVA_HOME=/usr/java/latest
 echo "JAVA_HOME is not defined using $JAVA_HOME"
fi

# Processing function call
if [[ "$VSERVER_NAME" == "" || "$REPOSITORY_DIR" == "" || "$CN_IP_ADDRESS" == "" ]]
then
 usage
elif [[ "$TEMPLATE" == "true" || "$CLONE" == "true" || "$BACKUP" == "true" ]]
then
 connectToAccount
 createTemplate
 if [[ "$CLONE" == "true" || "$BACKUP" == "true" ]]
 then
  generateAssetFile
 fi
 disconnectFromAccount
 if [[ "$EXECUTE" == "true" && "$BACKUP" != "true" ]]
 then
  executeAssetFile
 fi
fi



echo "****************************************"
echo "*****  Finished Processing Assets  *****"
echo "****************************************"

Exalogic Installation Series -12- Scripted Template Generation from an existing vServer

As part of your Exalogic Virtual environment you may want to build vServer that will be used, going forwards, as a template for future vServers. Currently the “Exalogic Elastic Cloud Administrator’s Guide” has an appendix describing how this can be achieved using the OVMM interface. Based on internal A-Team work it is now possible to achieve this directly from a compute nodes command-line without accessing OVMM.

As a result of this I have built the script below that will take the files associated with a “Stopped” vServer and converts them to a template.

For this templating process to work the script will need to be executed on a machine with access to the /OVS/Repositories/* directories and this means running directly on one of the Compute Nodes (I generally run it on Compute Node 1).

Because of the space and resource limitations of the Compute Node (minimal OS) we will need to create a and mount a Share from the internal ZFS to save the working files and ultimately the Template. To this end the script will take a number of parameters that will specification of these directories. If these are not specified the script assumes we have the ZFS /export/common/images mounted on /u01/common/images.

As can been seen from the Usage section below the script only mandates the Name of the vServer to be copied but assumes that the user has stopped the vServer previously. Once the template has been created, or post copy, the vServer can be restarted.

CreateTemplateFromVServer.sh

Usage

usage: ./CreateTemplateFromVServer.sh -n <vServer Name> [-r <Repository Directory>] [-w <Working Directory>] [-d <Destination Directory>]

 -n <vServer Name> vServer to be templatised or cloned.
 -r <Repository Directory> Location of the repository the default is /OVS/Repositories/*
 -w <Working Directory> Working directory where intermediate files will be copied default /u01/common/images/vServerTemplateWIP.
 -d <Destination Directory> Directory where the template tgz will be created. Default is /u01/common/images/vServerTemplates
 -h This information.

Script

Download

#!/bin/bash

################################################################################
#
#  Exalogic EL X2-2 2.0.0.4 (Linux x86-64) Configuration Script.
#
#  HEADER START
# 
#  THIS SCRIPT IS PROVIDED ON AN ?AS IS? BASIS, WITHOUT WARRANTY OF ANY KIND, 
#  EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT 
#  THE COVERED SCRIPT IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR 
#  PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE 
#  OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE 
#  DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER 
#  CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION.
#  NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS 
#  DISCLAIMER.
#
#  When distributing this Code, include this HEADER in each file.
#  If applicable, add the following below this this HEADER, with the fields
#  enclosed by brackets "[]" replaced with your own identifying information:
#       Portions Copyright [yyyy] [name of copyright owner]
# 
#  HEADER END
# 
# 
#       Copyright 2011 Andrew Hopkinson, Oracle Corporation UK Ltd.
#
################################################################################

export RUN_DATE=`date +"%Y%m%d-%H%M"`

#############################################################
##
## copyServerFiles
## ===============
##
## Copy the vServer img files to working location.
##
#############################################################

function copyServerFiles() {
 echo "Copying vServer Files"
 
 TEMPLATE_DIR=$WORKING_DIR/$VSERVER_NAME/template/BASE
 VIRTUAL_MACHINES_DIR=$REPOSITORY_DIR/VirtualMachines
 VIRTUAL_DISKS_DIR=$REPOSITORY_DIR/VirtualDisks
 ROOT_IMG_FILE=""
 
 GREP_VM_CFG=`grep "'$VSERVER_NAME'" $VIRTUAL_MACHINES_DIR/*/vm.cfg`
 VM_CFG=${GREP_VM_CFG%%:*}
 
 mkdir -p $TEMPLATE_DIR
 cp $VM_CFG $TEMPLATE_DIR
 
 DISKS=`grep disk $VM_CFG`
 FILES=${DISKS#*:}
 while [[ "$DISKS" != "$FILES" ]]
 do
  #echo "FILES = $FILES"
  #echo "DISKS = $DISKS"
  IMG_FILE=${FILES%%,*}
  echo "Copying $IMG_FILE"
  cp $IMG_FILE $TEMPLATE_DIR
  # Set root imag we assume the first
  if [[ "$ROOT_IMG_FILE" == "" ]]
  then
   SYSTEM_IMG=${IMG_FILE#*VirtualDisks/}
   ROOT_IMG_FILE=$TEMPLATE_DIR/$SYSTEM_IMG
   echo "Root Image $ROOT_IMG_FILE"
  fi
  # Shuffle line for next disk
  DISKS=${DISKS#*:}
  FILES=${DISKS#*:}
 done
}

#############################################################
##
## unconfigureVM
## =============
##
## Remove / edit the files that a created / modified when the
## template has been used to created a vServer.
##
#############################################################

function unconfigureVM() {
 echo "Unconfiguring Root Image $ROOT_IMG_FILE"
 cd $WORKING_DIR
 # Mount the Image file
 export LOOP=`losetup -f`
 # Make Temp Mount Directory
 mkdir -p $SYSTEMIMGDIR
 # Create Loop for the System Image
 losetup $LOOP $ROOT_IMG_FILE
 kpartx -a $LOOP
 mount /dev/mapper/`basename $LOOP`p2 $SYSTEMIMGDIR
 #Change Dir into mounted Image
 cd $SYSTEMIMGDIR
 
 # Unconfigure
 cp etc/sysconfig/ovmd etc/sysconfig/ovmd.orig
 sed 's/INITIAL_CONFIG=no/INITIAL_CONFIG=yes/g' etc/sysconfig/ovmd.orig > etc/sysconfig/ovmd
 rm -v etc/sysconfig/ovmd.orig
 
 sed -i '/.*/d' etc/resolv.conf
 
 # Remove existing ssh information
 rm -v root/.ssh/*
 rm -v etc/ssh/ssh_host*
 
 # Clean up networking
 sed -i '/^GATEWAY/d' etc/sysconfig/network
 
 # Clean up hosts
 sed -i '/localhost/!d' etc/hosts
 sed -i '/localhost/!d' etc/sysconfig/networking/profiles/default/hosts
 
 # Remove Network scripts
 rm -v etc/sysconfig/network-scripts/ifcfg-*eth*
 rm -v etc/sysconfig/network-scripts/ifcfg-ib*
 rm -v etc/sysconfig/network-scripts/ifcfg-bond*
 
 # Remove log files
 rm -v var/log/messages*
 rm -v var/log/ovm-template-config.log
 rm -v var/log/ovm-network.log
 rm -v var/log/boot.log*
 rm -v var/log/cron*
 rm -v var/log/maillog*
 rm -v var/log/rpmpkgs*
 rm -v var/log/secure*
 rm -v var/log/spooler*
 rm -v var/log/yum.log*
 
 # Remove Kernel Messages
 
 rm -v var/log/dmesg
 
 # Edit modprobe file
 sed -i '/bond/d' etc/modprobe.conf
 
 # Edit hwconf file
 cp etc/sysconfig/hwconf etc/sysconfig/hwconf.orig
 sed 's/mlx4_en/mlx4_core/' etc/sysconfig/hwconf.orig > etc/sysconfig/hwconf
 rm -v etc/sysconfig/hwconf.orig
 
 # Remove Exalogic Config file
 rm -v etc/exalogic.conf
 
 #Remove bash history
 rm -v root/.bash_history
 
 # Unmount the image file
 cd $WORKING_DIR
 umount $SYSTEMIMGDIR
 kpartx -d $LOOP
 losetup -d $LOOP
 rm -rf $SYSTEMIMGDIR
}

function buildTemplateTgz() {
 echo "Creating the Template tgz file"
 mkdir -p $DESTINATION_DIR
 cd $TEMPLATE_DIR
 TEMPLATE_TGZ=$DESTINATION_DIR/el_template_$VSERVER_NAME.tgz
 tar -zcvf $TEMPLATE_TGZ *
 echo "Template $TEMPLATE_TGZ file created"
}

function cleanWorkingDir() {
 echo "Cleaning Working Directory"
 cd $WORKING_DIR
 rm -rfv $VSERVER_NAME
}

#############################################################
##
## createTemplate
## ==============
##
## High level template creation function that will call the 
## required processing function in the necessary sequence.
##
#############################################################

function createTemplate() {
 copyServerFiles
 unconfigureVM
 buildTemplateTgz
 cleanWorkingDir
 echo ""
 echo ""
 echo "****************************************************"
 echo "**"
 echo "** $TEMPLATE_TGZ has been created from"
 echo "** vServer $VSERVER_NAME "
 echo "**"
 echo "****************************************************"
 echo ""
 echo ""
}


function usage() {
 echo ""
 echo >&2 "usage: $0 -n <vServer Name> [-r <Repository Directory>] [-w <Working Directory>] 
 [-d <Destination Directory>] "
 echo >&2 ""
 echo >&2 "          -n <vServer Name> vServer to be templatised or cloned."
 echo >&2 "          -r <Repository Directory> Location of the repository the default is $REPOSITORY_DIR"
 echo >&2 "          -w <Working Directory> Working directory where intermediate files will be copied default 
 $WORKING_DIR."
 echo >&2 "          -d <Destination Directory> Directory where the template tgz will be created. Default is 
 $DESTINATION_DIR"
 echo ""
 exit 1
}

###############################################################
##
## Simple start for the script that will extract the parameters
## and call the appriate start function.
##
###############################################################

export WORKING_DIR="/u01/common/images/vServerTemplateWIP"
export DESTINATION_DIR="/u01/common/images/vServerTemplates"
export REPOSITORY_DIR="/OVS/Repositories/*"
export SYSTEMIMGDIR=/mnt/elsystem

while [ $# -gt 0 ]
do
 case "$1" in 
  -n) VSERVER_NAME="$2"; shift;;
  -r) REPOSITORY_DIR="$2"; shift;;
  -d) DESTINATION_DIR="$2"; shift;;
  -w) WORKING_DIR="$2"; shift;;
  *) usage;;
  *) break;;
 esac
 shift
done


# Processing function call
if [[ "$VSERVER_NAME" == "" || "$REPOSITORY_DIR" == "" ]]
then
 usage
else
 createTemplate
fi



echo "****************************************"
echo "*****  Finished Creating Template  *****"
echo "****************************************"

Exalogic Installation Series -11- Some Simple ZFS Scripts

Whilst working on an Exalogic Upgrade I was working with the ZFS storage and having executed the same commands a number of times I decided to script them. This short blog entry, although it will grow over time, contains the scripts I find useful. For each of the scripts I will simply provide a brief description and the source of the script and occasionally add the output assuming it is not too long. Where I need to pass the Hostname / IP Address of the storage heads the scripts will use the flags:

  • -p <Primary – first storage head>
  • -s <Secondary – Second storage head>

I will be using a combinations of simple bash scripts and the more function ZFS scripting language.

Show Config

Executing this script against one of the storage heads will read and show all the properties that are current set on the specified storage head. Simply redirecting the output to a file provides me with a backup before I execute any modifications.

To run the script you will need to execute the following:

ssh root@<Storage IP> < showConfig.aksh > storageConfig.log

showConfig.aksh

script
function processNode(node) {
    run('cd /');
    run(node);
    printf("*****************************************************\n");
    printf("%s\n", node);
    printf("*****************************************************\n\n");

    printf("%s", run('list'));

    printf("\n\n*****************************************************\n\n");

    var nodeChildren = children();
    for (var i = 0; i < nodeChildren.length; i++) {
        processNode(node + " " + nodeChildren[i]);
        run('cd ..');
    }
}

processNode('');

Show Shares

This script, modified from the ZFS Admin Guide, will display a list of all Projects/Shares on the storage along with the amount of spece used and available.

To run the script you will need to execute the following:

ssh root@<Storage IP> < showShares.aksh

showShares.aksh

script
    run('shares');
    projects = list();
    printf("%-50s %-10s %-10s\n", "Project/Share", "Used", "Available");
    printf("%-50s %-10s %-10s\n", "=============", "====", "=========");
    for (i = 0; i < projects.length; i++) {
        run('select ' + projects[i]);
        shares = list();
        for (j = 0; j < shares.length; j++) {
            run('select ' + shares[j]);
            share = projects[i] + '/' + shares[j];
            used = run('get space_data').split(/\s+/)[3];
            available = run('get space_available').split(/\s+/)[3];
            printf("%-50s %-10s %-10s\n", share, used, available);
            run('cd ..');
        }
        run('cd ..');
    }

showShares.aksh

[root@slce50cn01 ~]# ssh root@slce50sn01 < showShares.aksh
Pseudo-terminal will not be allocated because stdin is not a terminal.
Project/Share Used Available
============= ==== =========
ExalogicControl/ExalogicControl 312G 21.9T
ExalogicControl/ExalogicPool1 1.28G 21.9T
ExalogicControl/ExalogicPool2 31.5K 21.9T
ExalogicControl/ExalogicPool3 31.5K 21.9T
ExalogicControl/ExalogicPool4 31.5K 21.9T
ExalogicControl/ExalogicRepo 1.01T 21.9T
ExalogicControl/Exalogic_EnterpriseController 37.5K 21.9T
ExalogicControl/Exalogic_OVAB 31.5K 21.9T
ExalogicControl/Exalogic_ProxyController 31.5K 21.9T
ExalogicControl/Exalogic_RDBMS 31.5K 21.9T

Set NFSv4 Delegation

The following script will set the NFSv4 Delegation flag to false (recommended) and also the appropriate IPMP values. If you know the location of the value to set then the following should be easy to modify.

To run the script you will need to execute the following:

./setIPMPAndNFSV4Delegation.sh [-s <Secondary Storage Node hostname/IP>] [-p <Primary Storage Node hostname/IP>]

setIPMPAndNFSV4Delegation.sh

#!/bin/bash

PRIMARY=
SECONDARY=

while [ $# -gt 0 ]
do
 case "$1" in 
   -p) PRIMARY="$2"; shift;;
   -s) SECONDARY="$2"; shift;;
   *) echo ""; echo >&2 \
      "usage: $0 [-s <Secondary Storage Node hostname/IP>] [-p <Primary Storage Node hostname/IP>] "
      echo""; exit 1;;
    *) break;;
 esac
 shift
done

function updateStorage {
ssh root@$1 << EOF
cd /
configuration services ipmp
show
set interval=5000
set failback=false
commit
cd /
configuration services nfs
show
set enable_delegation=false
commit
quit
EOF
}

if [ "$PRIMARY" != "" ]
then
 updateStorage $PRIMARY
fi

if [ "$SECONDARY" != "" ]
then
 updateStorage $SECONDARY
fi

Snapshot ZFS Project or Share

This script will allow you to create a snapshot of a ZFS Project or Share on the internal storage. You have the option of specifying the Snapshot name but if this is not supplied it will default to a date stamped name.

To run the script you will need to execute the following:

snapshotZFS.sh -ip <Storage Node hostname/IP> -p <Project Name> [-s <Share Name>] [-n <Snapshot Name>]

snapshotZFS.sh

#!/bin/bash

BAK_EXT=`date +"%Y%m%d-%H%M%S"`
PROJECT=""
SHARE=""
IPADDRESS=""
SNAPSHOTNAME="SnapShot-$BAK_EXT"

while [ $# -gt 0 ]
do
    case "$1" in 
        -ip) IPADDRESS="$2"; shift;;
        -p) PROJECT="$2"; shift;;
        -s) SHARE="$2"; shift;;
        -n) SNAPSHOTNAME="$2"; shift;;
        *) echo ""; echo >&2 \
            "usage: $0 -ip <Storage Node hostname/IP> -p <Project Name> [-s <Share Name>] [-n <Snapshot Name>] "
            echo""; exit 1;;
        *) break;;
    esac
    shift
done

if [ "$IPADDRESS" == "" ]
then
    echo "IP Address or Hostname of the Storage must be provided"
    exit 1
fi

if [ "$PROJECT" == "" ]
then
    echo "Project name must be provided"
    exit 1
fi

echo $SNAPSHOTNAME

ssh root@$IPADDRESS <<EOF
script
    try {
        run('cd /');
        run('shares');
        run('select $PROJECT');
        printf('%s\n', run('list'));
        try {
            run('select $SHARE');
        } catch (e) {
        }
        run('snapshots');
        run('snapshot $SNAPSHOTNAME');

    } catch (err) {
        if (err.code == EAKSH_ENTITY_BADSELECT) {
            printf('ERROR: "$SHARE" is not a share in the "$PROJECT" project\n');
        } else {
            printf('ERROR: (%s)\n', err.message);
        }
    }
EOF

Exalogic Installation Series -10- Scripting Asset Creation

So far in this series we have looked at creating asset within the EMOC BUI but the Exalogic 2.0.1 installation also provide the Iaas cli as an alternative to most of the common functionality available within EMOC. The IaaS cli interface provides access to the functions that are available to a user logged into the BUI with the CloudUser Role.

As such not all functionality is available from the command line interface however having said that the IaaS cli provides all the functionality required to create the Assets within a specific Account (Tenure). Because these action are common and repeatable I decided to wrap the functionality within a simple script that takes a simple input file and creates the Asset.

Following the Script through will show us the required steps needed to create the various Assets within an Account and hence I will work through the various functions within the script below describing the steps.

You will note from the various steps within the script that it is designed to pause between actions allowing the proceeding action to complete. The reason for this is because we could swamp EMOC with a series of actions and may end up with a situation where we are trying to action a Volume attached before the creation of the vServer and Volume have completed.

processAssets()

This function simply reads through the passed input file identifying what assets need to be created. An example of the input file can be found below. It can be seen that the input file can be used to create Assets in multiple Accounts during a single run. The order of the entries define the functions that need to be actioned as follows:

Input Command Iaas Actions Parameters
Production:Connect
  1. akm-describe-accounts
  2. akm-create-access-key
  3. iaas-create-key-pair
  4. iaas-describe-vnets
  5. iaas-describe-vserver-types
  6. iaas-describe-server-templates
  1. Username
  2. Password
Production:Upload|ServerTemplate
  1. iaas-create-server-template-from-url
  1. Template Name
  2. URL to the template (best if placed on the internal ZFS)
Production:Create|VirtualNetwork
  1. iaas-create-vnet
  1. Network Name
  2. Size (Number of IPs)
Production:Create|DistributionGroup
  1. iaas-create-distribution-group
  1. Distribution Group Name

When creating Distribution Groups from the command line they will have a size of 50,000.

Production:Create|vServer
  1. iaas-run-vserver
  1. vServer Name
  2. vServer Type Name
  3. Template Name
  4. Comma separated list of network names which the vServer will connect to.
  5. Comma separated list of IPs for the specified networks. If the IP is to be assigned automaticallty the a “*” should be entered.
  6. Distribution Group [Optional]
Production:Create|Volume
  1. iaas-create-volume
  1. Volume Name
  2. Volume Size
Production:Attach|Volume
  1. iaas-attach-volumes-to-vserver
  1. vServer Name
  2. Comma separated list of volume names
Production:Disconnect
  1. iaas-delete-key-pair
  2. akm-delete-access-key
None

 

connectToAccount()

It can be seen from the connectToAccount function that before we can execute any Asset creation we must first connect to the appropriate account. To do this we will need the ID associated with the Account. This can be found by executing the akm-describe-accounts cli command which will return a list of all Accounts and there IDs. Once we have the Account ID we generate and Access key using the akm-create-access-key command and then a keypair with the iaas-create-key-pair command.

At this point we now have all the information we need to access the specific named account.

createDistributionGroup()

Here we simply retrive the name of the Distribution Group from the input line and create a group. The size of the group is not specified and will always be 50000.

createVServer()

This function simply retrieved the information from the input line and then will create the vServer using the iaas-run-vserver cli command. Reading the function you will notice that it takes the various input names for vServer Type, Template and Networks and converts them into the appropriate IDs. The IaaS cli will not work directly with component names and hence all IDs need to be found.

createVolume()

Function that simply takes the Volume name and Size then executes the iaas-create-volume command to create the volume.

attachVolume()

Takes the name of the Volume, which we may have just created, and a Volume then identifies the appropriate IDs before assigning the Volume to the vServer with the iaas-attach-volumes-to-vserver.

disconnectFromAccount()

Once we have finished connecting to the Account we simply remove the key pair with iaas-delete-key-pair and the access key with akm-delete-access-key although it may be useful to keep this if ssh is required and you do not subsequently modify the sshd information to allow unsecured access. By default the key is required for ssh access when a vServer is created from the command-line.

CreateAssets.sh

Usage

usage: ./CreateAssets.sh [-f <Asset Definition File>] [-r]

 -f <Asset Definition File> (Default is CreateAssets.in)
 -r Indicates that the ssh keys should be removed
 -h This message

Script

Download

#!/bin/bash

################################################################################
#
#  Exalogic EL X2-2 2.0.0.4 (Linux x86-64) Configuration Script.
#
#  HEADER START
# 
#  THIS SCRIPT IS PROVIDED ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, 
#  EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT 
#  THE COVERED SCRIPT IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR 
#  PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE 
#  OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE 
#  DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER 
#  CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION.
#  NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS 
#  DISCLAIMER.
#
#  When distributing this Code, include this HEADER in each file.
#  If applicable, add the following below this this HEADER, with the fields
#  enclosed by brackets "[]" replaced with your own identifying information:
#       Portions Copyright [yyyy] [name of copyright owner]
# 
#  HEADER END
# 
# 
#       Copyright 2011 Andrew Hopkinson, Oracle Corporation UK Ltd.
#
################################################################################

export OCCLI=/opt/sun/occli/bin
export IAAS_HOME=/opt/oracle/iaas/cli
export IAAS_BASE_URL=https://127.0.0.1
export BASE_IAAS_ACCESS_KEY_FILE=iaas_access.key
export BASE_KEY_NAME=cli.asset.create
export BASE_KEY_FILE=iaas_access.pub
export RUN_DATE=`date +"%Y%m%d-%H%M"`
#CloudUser used to create vServers & Volumes
export IAAS_USER=exaprod
export IAAS_PASSWORD_FILE=root.pwd
export INPUT_FILE=CreateAssets.in

export ACCOUNTS_FILE=accounts.out
export VOLUMES_FILE=volumes.out
export DISTGRPS_FILE=distgrp.out
export VNETS_FILE=vnets.out
export VSERVER_TYPES_FILE=vstype.out
export VSERVER_FILE=vserver.out
export VSERVER_TEMPLATES=template.out
export NETWORK_STATIC_IPS=staticips.out
export KEY_PAIRS=keypairs.out


PROCESSING_ACCOUNT=""

function cleanTempFiles() {
 rm -f $ACCOUNTS_FILE $VOLUMES_FILE $DISTGRPS_FILE $VNETS_FILE $VSERVER_TYPES_FILE $VSERVER_FILE 
$VSERVER_TEMPLATES $KEY_PAIRS $IAAS_PASSWORD_FILE $IAAS_ACCESS_KEY_FILE
 #$KEY_FILE
}

function connectToAccount() {
 if [[ "$ACCOUNT" != "$PROCESSING_ACCOUNT" ]]
 then
  if [[ "" != "$PROCESSING_ACCOUNT" ]]
  then
   $IAAS_HOME/bin/iaas-delete-key-pair --key-name $KEY_NAME --access-key-file $IAAS_ACCESS_KEY_FILE
   $IAAS_HOME/bin/akm-delete-access-key $AK
  fi
  # Set run specific key information
  export IAAS_ACCESS_KEY_FILE=$ACCOUNT"."$RUN_DATE"."$BASE_IAAS_ACCESS_KEY_FILE
  export KEY_NAME=$ACCOUNT"."$RUN_DATE"."$BASE_KEY_NAME
  export KEY_FILE=$ACCOUNT"."$RUN_DATE"."$BASE_KEY_FILE
  #echo "IAAS_ACCESS_KEY_FILE=$IAAS_ACCESS_KEY_FILE"
  #echo "KEY_NAME=$KEY_NAME"
  echo "KEY_FILE=$KEY_FILE"
  # Save current processing account
  PROCESSING_ACCOUNT=$ACCOUNT
  IAAS_USER=$ACCOUNT_USER
  echo "$ACCOUNT_PASSWORD" > $IAAS_PASSWORD_FILE
  $IAAS_HOME/bin/akm-describe-accounts --sep "|" > $ACCOUNTS_FILE
  while read line
  do
   ACCOUNT_ID=${line%%|*}
   line=${line#*|}
   ACCOUNT_NAME=${line%%|*}
 #  echo "Id = $ACCOUNT_ID"
 #  echo "Name = $ACCOUNT_NAME"
   if [[ "$ACCOUNT_NAME" == "$ACCOUNT" ]]
   then
    #echo "Found Account $line"
    AK=`$IAAS_HOME/bin/akm-create-access-key --account $ACCOUNT_ID --access-key-file $IAAS_ACCESS_KEY_FILE`
    KEYPAIR=`$IAAS_HOME/bin/iaas-create-key-pair --key-name $KEY_NAME --key-file $KEY_FILE`
    echo "Connected to $ACCOUNT_NAME"
    
    #cp $IAAS_ACCESS_KEY_FILE $ACCOUNT_NAME$IAAS_ACCESS_KEY_FILE
    #cp $KEY_FILE $ACCOUNT_NAME$KEY_FILE
    break
   fi    
  done < $ACCOUNTS_FILE 
 fi
}

function disconnectFromAccount() {
  $IAAS_HOME/bin/iaas-delete-key-pair --key-name $KEY_NAME --access-key-file $IAAS_ACCESS_KEY_FILE
  $IAAS_HOME/bin/akm-delete-access-key $AK
  PROCESSING_ACCOUNT=""
  # Clean Up
  cleanTempFiles
}

function getDistributionGroups() {
 $IAAS_HOME/bin/iaas-describe-distribution-groups --sep "|" > $DISTGRPS_FILE
}

function getNetworks() {
 $IAAS_HOME/bin/iaas-describe-vnets --sep "|" > $VNETS_FILE
}

function getVSTypes() {
 $IAAS_HOME/bin/iaas-describe-vserver-types --sep "|" > $VSERVER_TYPES_FILE
}

function getTemplates() {
 $IAAS_HOME/bin/iaas-describe-server-templates --sep "|" > $VSERVER_TEMPLATES
}

function getVolumes() {
 $IAAS_HOME/bin/iaas-describe-volumes --sep "|" > $VOLUMES_FILE
}

function getVServers() {
 $IAAS_HOME/bin/iaas-describe-vservers --sep "|" > $VSERVER_FILE
}

function getNetworkStaticIPs() {
 $IAAS_HOME/bin/iaas-describe-ip-addresses --filters vnet=$NETWORK_ID --sep "|" > $NETWORK_STATIC_IPS
}

#############################################################
##
## getDistributionGroupId
## ======================
##
## Get the Distribution Group id based on the supplied name.
##
#############################################################

function getDistributionGroupId() {
 while read line
 do
  DISTGROUP_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$NAME" == "$DISTGROUP_NAME" ]]
  then
   break
  fi
  DISTGROUP_ID=""
 done < $DISTGRPS_FILE
}

#############################################################
##
## getNetworkId
## ============
##
## Get the Network id based on the supplied name.
##
#############################################################

function getNetworkId() {
 while read line
 do
  NETWORK_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$NAME" == "$NETWORK_NAME" ]]
  then
   break
  fi
  NETWORK_ID=""
 done < $VNETS_FILE
}

#############################################################
##
## getIPAddress
## ============
##
## Get a static IP Address for a given network if an * is 
## supplied. If an IP Address is supplied it simple returns
## specified IP.
##
#############################################################

function getIPAddress() {
 echo "Checking IP Address $IP_ADDRESS"
 if [[ "$IP_ADDRESS" == "*" ]]
 then
  allocateIPAddress
#  getFirstAllocatedIPAddress
 fi
 echo "Returning IP Address $IP_ADDRESS"
}

#############################################################
##
## allocateIPAddress
## =================
##
## Allocate a single IP Address from a specified Network.
##
#############################################################

function allocateIPAddress() {
 IP_ADDRESS=`$IAAS_HOME/bin/iaas-allocate-ip-addresses --vnet $NETWORK_ID --num 1`
}

function allocateIPAddresses() {
 $IAAS_HOME/bin/iaas-allocate-ip-addresses --vnet $NETWORK_ID --num $IP_COUNT
}

#############################################################
##
## getFirstAllocatedIPAddress
## ==========================
##
## Get the first static IP Address for a given Network Id.
##
#############################################################

function getFirstAllocatedIPAddress() {
 getNetworkStaticIPs
 while read line
 do
  IP_ADDRESS=${line%%|*}
  break
 done < $NETWORK_STATIC_IPS
}

#############################################################
##
## getVSTypeId
## ===========
##
## Get the VServer Type id based on the supplied name.
##
#############################################################

function getVSTypeId() {
 while read line
 do
  VSTYPE_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$VSTYPE_NAME" == "$NAME" ]]
  then
   break
  fi
  VSTYPE_ID=""
 done < $VSERVER_TYPES_FILE
}

#############################################################
##
## getTemplateId
## =============
##
## Get the Template id based on the supplied name.
##
#############################################################

function getTemplateId() {
 while read line
 do
  TEMPLATE_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$TEMPLATE_NAME" == "$NAME" ]]
  then
   break
  fi
  TEMPLATE_ID=""
 done < $VSERVER_TEMPLATES
}

#############################################################
##
## getVolumeId
## ===========
##
## Get the Volume id based on the supplied name.
##
#############################################################

function getVolumeId() {
 while read line
 do
  VOLUME_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$NAME" == "$VOLUME_NAME" ]]
  then
   break;
  fi
  VOLUME_ID=""
 done < $VOLUMES_FILE
}

#############################################################
##
## getVServerId
## ============
##
## Get the VServer id based on the supplied name.
##
#############################################################

function getVServerId() {
 while read line
 do
  VSERVER_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  if [[ "$VSERVER_NAME" == "$NAME" ]]
  then
   break;
  fi
  VSERVER_ID=""
 done < $VSERVER_FILE
}

function getVServerState() {
 getVServers
 while read line
 do
  VSERVER_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  line=${line#*|}
  DESCRIPTION=${line%%|*}
  line=${line#*|}
  VSERVER_STATE=${line%%|*}
  if [[ "$VSERVER_NAME" == "$NAME" ]]
  then
   break;
  fi
 done < $VSERVER_FILE
}

function pauseUntilVServerRunning() {
 # Wait until the Server is running before creating the next
 echo "Pausing until vServer is Running"
  getVServerState
  while [[ "$VSERVER_STATE" != "RUNNING" ]]
  do
   echo "$NAME $VSERVER_STATE"
   if [[ "$VSERVER_STATE" != "RUNNING" ]]
   then
    echo "Sleeping......."
    sleep 30
   fi
   if [[ "$VSERVER_STATE" == "FAILED" ]]
   then
    echo "$NAME Will Delete Automatically after remaining Failed for a period....."
    #echo "Will Delete $NAME in 5 Minutes....."
    #sleep 300
    #deleteVServer
    #echo "Deleted $NAME waiting 5 Minutes....."
    #sleep 300
    break
   fi
   getVServerState
   #echo "Description: [$DESCRIPTION]"
  done
  echo "$NAME $VSERVER_STATE"
  # Lets pause for a minute or two
  echo "Just Chilling......"
  sleep 30
  echo "Ahhhhh we're getting there......."
  sleep 30
  echo "I'm almost at one with the universe......."
  sleep 30
  echo "Bong Reality Check !"
}

function deleteVServer() {
 $IAAS_HOME/bin/iaas-terminate-vservers --force --vserver-ids $VSERVER_ID
}

function createVServer() {
 VSERVER_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 VSTYPE_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 TEMPLATE_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 NETWORK_NAMES=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 IP_ADDRESSES=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 DISTGROUP_NAME=${ASSET_DETAILS%%|*}
 
 echo "Creating vServer $VSERVER_NAME"
 
 # Get Ids associated with names
 getVSTypeId
 getTemplateId
 # Convert Network Names to Ids
 NETWORK_IDS=""
 # Validated IPs
 NETWORK_IPS=""
 # Reset SSH IP Address it will be used to disable SSH Key
 SSH_IP_ADDRESS=""
 while true
 do
  # Get ID and add to list
  NETWORK_NAME=${NETWORK_NAMES%%,*}
  NETWORK_NAMES=${NETWORK_NAMES#*,}
  getNetworkId
  if [[ "$NETWORK_IDS" != "" ]]
  then
   NETWORK_IDS="$NETWORK_IDS,$NETWORK_ID"
  else
   NETWORK_IDS=$NETWORK_ID
  fi
  # Check IPs
  IP_ADDRESS=${IP_ADDRESSES%%,*}
  IP_ADDRESSES=${IP_ADDRESSES#*,}
  getIPAddress
  if [[ "$NETWORK_IPS" != "" ]]
  then
   NETWORK_IPS="$NETWORK_IPS,$IP_ADDRESS"
  else
   NETWORK_IPS=$IP_ADDRESS
  fi
  # Set the SSH IP to the first IP addres we will assume the server is accessible via this IP
  if [[ "$SSH_IP_ADDRESS" == "" ]]
  then
   SSH_IP_ADDRESS=$IP_ADDRESS
  elif [[ "$NETWORK_NAME" == "IPoIB-vserver-shared-storage" ]]
  then
   # Prefer the IPoIB-vserver-shared-storage if this is used
   SSH_IP_ADDRESS=$IP_ADDRESS
  fi
  # If I've processed all then exit
  if [[ "$NETWORK_NAME" == "$NETWORK_NAMES" ]]
  then
   break
  fi
 done
 getDistributionGroupId
 
 # Create vServer
 if [[ "$DISTGROUP_ID" != "" ]]
 then
  echo "About to execute : $IAAS_HOME/bin/iaas-run-vserver --name $VSERVER_NAME --key-name $KEY_NAME 
--vserver-type $VSTYPE_ID --server-template-id $TEMPLATE_ID --vnets $NETWORK_IDS --ip-addresses $NETWORK_IPS 
--dist-group $DISTGROUP_ID"
  
  $IAAS_HOME/bin/iaas-run-vserver --name $VSERVER_NAME --key-name $KEY_NAME --vserver-type $VSTYPE_ID 
--server-template-id $TEMPLATE_ID --vnets $NETWORK_IDS --ip-addresses $NETWORK_IPS --dist-group $DISTGROUP_ID 
--desc "Created By CreateAsset.sh"
 else
  echo "About to execute : $IAAS_HOME/bin/iaas-run-vserver --name $VSERVER_NAME --key-name $KEY_NAME 
--vserver-type $VSTYPE_ID --server-template-id $TEMPLATE_ID --vnets $NETWORK_IDS --ip-addresses $NETWORK_IPS"
  
  $IAAS_HOME/bin/iaas-run-vserver --name $VSERVER_NAME --key-name $KEY_NAME --vserver-type $VSTYPE_ID 
--server-template-id $TEMPLATE_ID --vnets $NETWORK_IDS --ip-addresses $NETWORK_IPS 
--desc "Created By CreateAsset.sh"
 fi
 pauseUntilVServerRunning
 if [[ "$REMOVE_SSH_KEYS" == "true" ]]
 then
  removeSshKeyRequirement
 fi
 
 echo "vServer $VSERVER_NAME has been created"
}

function removeSshKeyRequirement() {
 SSH_FLAGS="-i $KEY_FILE -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
 SSH_FLAGS="-i $KEY_FILE -o StrictHostKeyChecking=no"
 # Create Variables as environment variables
 #export NETWORK_IPS=$NETWORK_IPS
 #export VSERVER_NAME=$VSERVER_NAME

 SSH_IP_ADDRESS=""
 for IP in ${NETWORK_IPS//,/ }
 do
  SSH_RESULT=$(ssh $SSH_FLAGS root@$IP "hostname")
  echo "SSH Result $SSH_RESULT"
  if [[ "$SSH_RESULT" == "$VSERVER_NAME" ]]
  then
   echo "$IP Address works for ssh"
   SSH_IP_ADDRESS=$IP
   break;
  else
   echo "$IP Address does not work for ssh"
  fi
 done
 
 if [[ "$SSH_IP_ADDRESS" != "" ]]
 then
  echo "Removing ssh key requirement for $VSERVER_NAME on $SSH_IP_ADDRESS"
  
  ssh $SSH_FLAGS root@$SSH_IP_ADDRESS "cp /etc/ssh/sshd_config /etc/ssh/sshd_config.orig"
  ssh $SSH_FLAGS root@$SSH_IP_ADDRESS "sed 's/PasswordAuthentication no/PasswordAuthentication yes/g' 
/etc/ssh/sshd_config.orig > /etc/ssh/sshd_config"
  ssh $SSH_FLAGS root@$SSH_IP_ADDRESS "service sshd restart"

  echo "Removed ssh key requirement for $VSERVER_NAME"
 else
  echo "Unable to find a route to $VSERVER_NAME to remove the ssh key requirement you will need to do the following"
  echo ""
  echo "1. ssh into the vServer using: ssh -i $KEY_FILE -l root <IP Address>"
  echo "2. Edit /etc/ssh/sshd_config and replace \"PasswordAuthentication no\" with \"PasswordAuthentication yes\""
  echo "3. Restart sshd service: service sshd restart"
  echo ""
  echo "cp /etc/ssh/sshd_config /etc/ssh/sshd_config.orig"
  echo "sed \'s/PasswordAuthentication no/PasswordAuthentication yes/\' /etc/ssh/sshd_config.orig > 
  /etc/ssh/sshd_config"
  echo "service sshd restart"
  echo ""
 fi
}

function pauseUntilDistributionGroupCreated() {
 getDistributionGroups
 getDistributionGroupId
 while [[ "$DISTGROUP_ID" == "" ]]
  do
   # Lets pause
   echo "Just Waiting 30 Seconds......"
   sleep 30
   getDistributionGroups
   getDistributionGroupId
  done
}

function createDistributionGroup() {
 DISTGROUP_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 # Size is never specified
 # DISTGROUP_SIZE=${ASSET_DETAILS%%|*}
 # Create Volume
 echo "About to execute : $IAAS_HOME/bin/iaas-create-distribution-group --name $DISTGROUP_NAME"
 $IAAS_HOME/bin/iaas-create-distribution-group --name $DISTGROUP_NAME
 # Lets pause
 pauseUntilDistributionGroupCreated
}

function pauseUntilVolumeCreated() {
 getVolumes
 getVolumeId
 while [[ "$VOLUME_ID" == "" ]]
  do
   # Lets pause
   echo "Just Waiting 30 Seconds......"
   sleep 30
   getVolumes
   getVolumeId
  done

}

function createVolume() {
 VOLUME_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 VOLUME_SIZE=${ASSET_DETAILS%%|*}
 # Create Volume
 echo "About to execute : $IAAS_HOME/bin/iaas-create-volume --name $VOLUME_NAME --size $VOLUME_SIZE"
 $IAAS_HOME/bin/iaas-create-volume --name $VOLUME_NAME --size $VOLUME_SIZE
  # Lets pause
  pauseUntilVolumeCreated
}

function attachVolume() {
 VSERVER_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 VOLUME_NAMES=${ASSET_DETAILS%%|*}
 # Get vServer Id
 getVServerId
 # Convert Volume Names to Ids
 VOLUME_IDS=""
 while true
 do
  VOLUME_NAME=${VOLUME_NAMES%%,*}
  VOLUME_NAMES=${VOLUME_NAMES#*,}
  getVolumeId
  if [[ "$VOLUME_IDS" != "" ]]
  then
   VOLUME_IDS="$VOLUME_IDS,$VOLUME_ID"
  else
   VOLUME_IDS=$VOLUME_ID
  fi
  if [[ "$VOLUME_NAME" == "$VOLUME_NAMES" ]]
  then
   break
  fi
 done
 # Attach Volumes
 echo "About to execute : $IAAS_HOME/bin/iaas-attach-volumes-to-vserver --vserver-id $VSERVER_ID --volume-ids
 $VOLUME_IDS"
 $IAAS_HOME/bin/iaas-attach-volumes-to-vserver --vserver-id $VSERVER_ID --volume-ids $VOLUME_IDS
  # Lets pause
  echo "Just Waiting 30 Seconds......"
  sleep 30
}

#############################################################
##
## getTemplateState
## ================
##
## Loop through the Template associated with the Account 
## checking to see if the upload has completed and the 
## template has a status of OK. At this point return.
##
#############################################################

function getTemplateState() {
 getTemplates
 while read line
 do
  TEMPLATE_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  line=${line#*|}
  line=${line#*|}
  TEMPLATE_STATE=${line%%|*}
  if [[ "$TEMPLATE_NAME" == "$NAME" ]]
  then
   break;
  fi
 done < $VSERVER_TEMPLATES
}

#############################################################
##
## pauseUntilServerTemplateUploaded
## ================================
##
## Pause the script until the Template file has been uploaded
## to the Account.
##
#############################################################

function pauseUntilServerTemplateUploaded() {
 echo "Pausing until Template upload has completed"
  getTemplateState
  while [[ "$TEMPLATE_STATE" != "OK" ]]
  do
   echo "$NAME $TEMPLATE_STATE"
   if [[ "$TEMPLATE_STATE" != "SCHEDULED" ]]
   then
    echo "Sleeping......."
    sleep 30
   elif [[ "$TEMPLATE_STATE" != "RUNNING" ]]
   then
    echo "Sleeping......."
    sleep 30
   elif [[ "$TEMPLATE_STATE" != "FAILED" ]]
   then
    deleteServerTemplate
    echo "Sleeping......."
    sleep 30
   fi
   getTemplateState
  done
}

#############################################################
##
## uploadServerTemplate
## ====================
##
## Upload a tgz file that defines a server template. It is 
## recommended these be copied to the ZFS first and then the
## appropriate URL from the ZFS be used.
##
#############################################################

function uploadServerTemplate() {
 TEMPLATE_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 TEMPLATE_URL=${ASSET_DETAILS%%|*}
 # Upload Template
 echo "About to execute : $IAAS_HOME/bin/iaas-create-server-template-from-url --name $TEMPLATE_NAME 
--url $TEMPLATE_URL"
 $IAAS_HOME/bin/iaas-create-server-template-from-url --name $TEMPLATE_NAME --url $TEMPLATE_URL
  # Lets pause
 pauseUntilServerTemplateUploaded
}

function deleteServerTemplate() {
 $IAAS_HOME/bin/iaas-delete-server-template --force --server-template-id $TEMPLATE_ID
}

#############################################################
##
## getVNetworkState
## ================
##
## Loop through the Networks associated with the Account 
## checking to see if the creation has completed and the 
## network has a status of OK. At this point return.
##
#############################################################

function getVNetworkState() {
 getNetworks
 while read line
 do
  NETWORK_ID=${line%%|*}
  line=${line#*|}
  NAME=${line%%|*}
  line=${line#*|}
  line=${line#*|}
  NETWORK_STATE=${line%%|*}
  if [[ "$NETWORK_NAME" == "$NAME" ]]
  then
   break;
  fi
 done < $VNETS_FILE
}

#############################################################
##
## pauseUntilVirtualNetworkCreated
## ===============================
##
## Pause the script until the Virtual Private Network has
## been created.
##
#############################################################

function pauseUntilVirtualNetworkCreated() {
 echo "Pausing until Virtual Network creation has completed"
  getVNetworkState
  while [[ "$NETWORK_STATE" != "OK" ]]
  do
   echo "$NAME $NETWORK_STATE"
   if [[ "$NETWORK_STATE" != "SCHEDULED" ]]
   then
    echo "Sleeping......."
    sleep 30
   elif [[ "$NETWORK_STATE" != "RUNNING" ]]
   then
    echo "Sleeping......."
    sleep 30
   fi
   getVNetworkState
  done
}

#############################################################
##
## createVirtualNetwork
## ====================
##
## Create a Virtual Private Network based on the name 
## supplied.
##
#############################################################

function createVirtualNetwork() {
 NETWORK_NAME=${ASSET_DETAILS%%|*}
 ASSET_DETAILS=${ASSET_DETAILS#*|}
 NETWORK_IPS=${ASSET_DETAILS%%|*}
 # 
 echo "About to execute : $IAAS_HOME/bin/iaas-create-vnet --name $NETWORK_NAME --size $NETWORK_IPS "
 $IAAS_HOME/bin/iaas-create-vnet --name $NETWORK_NAME --size $NETWORK_IPS
  # Lets pause
 pauseUntilVirtualNetworkCreated
}

#############################################################
##
## processAssets
## =============
##
## This function loops through the information defined in
## the input file looking for actions to be executed. It will
## process the entries sequentially and simply call the
## appropriate sub-function to execute the iaas commands.
## Entries with invalid Actions will simply be ignored along
## with blank lines.
##
#############################################################

function processAssets() {
 # Read Entries into an Array
 assetArray=( $(grep ":" $INPUT_FILE) )
 # Process Array
 for line in "${assetArray[@]}"
 #while read line
 do
  #echo "Processing Line: $line"
  ACCOUNT=${line%%:*}
  line=${line#*:}
  ACTION=${line%%|*}
  line=${line#*|}
  if [[ "$ACTION" == "Connect" ]]
  then
   ACCOUNT_USER=${line%%|*}
   line=${line#*|}
   ACCOUNT_PASSWORD=${line%%|*}
   connectToAccount
   
   ## Account Info
   getNetworks
   getVSTypes
   getTemplates
  elif [[ "$ACTION" == "Create" ]]
  then
   ASSET=${line%%|*}
   line=${line#*|}
   ASSET_DETAILS=$line
   if [[ "$ASSET" == "vServer" ]]
   then
    getDistributionGroups
    createVServer
   elif [[ "$ASSET" == "vServers" ]]
   then
    getDistributionGroups
    createVServers
   elif [[ "$ASSET" == "Volume" ]]
   then
    createVolume
   elif [[ "$ASSET" == "DistributionGroup" ]]
   then
    createDistributionGroup
   elif [[ "$ASSET" == "VirtualNetwork" ]]
   then
    createVirtualNetwork
   fi
#   continue
  elif [[ "$ACTION" == "Upload" ]]
  then
   ASSET=${line%%|*}
   line=${line#*|}
   ASSET_DETAILS=$line
   if [[ "$ASSET" == "ServerTemplate" ]]
   then
    uploadServerTemplate
   fi
#   continue
  elif [[ "$ACTION" == "Attach" ]]
  then
   ASSET=${line%%|*}
   line=${line#*|}
   ASSET_DETAILS=$line
   if [[ "$ASSET" == "Volume" ]]
   then
    getVolumes
    getVServers
    attachVolume
   fi
#   continue
  elif [[ "$ACTION" == "Disconnect" ]]
  then
   disconnectFromAccount
#   continue
  fi
 #done < $INPUT_FILE
 done
}

#############################################################
##
## usage
## =====
##
## Show usage.
##
#############################################################

function usage() {
 echo ""
 echo >&2 "usage: $0 [-f <Asset Definition File>] [-r]"
 echo >&2 ""
 echo >&2 "          -f <Asset Definition File> (Default is CreateAssets.in)"
 echo >&2 "          -r Indicates that the ssh keys should be removed"
 echo ""
 exit 1
}

###############################################################
##
## Simple start for the script that will extract the parameters
## and call the appriate start function.
##
###############################################################

REMOVE_SSH_KEYS=false
while [ $# -gt 0 ]
do
 case "$1" in 
  -f) INPUT_FILE="$2"; shift;;
  -r) REMOVE_SSH_KEYS=true;;
  *) usage;;
  *) break;;
 esac
 shift
done

# Check if the JAVA_HOME is set
if [[ "$JAVA_HOME" == "" ]]
then
 export JAVA_HOME=/usr/java/latest
 echo "JAVA_HOME is not defined using $JAVA_HOME"
fi
# Processing function call
processAssets

echo "**************************************"
echo "*****  Finished Creating Assets  *****"
echo "**************************************"

CreateAssetsProd.in

Production:Connect|clouduser|welcome1

Production:Upload|ServerTemplate|Navstar40GBRootTemplate|http://172.17.0.9/shares/export/common/images/ah-templates/el_40gb_root_linux_vm_template_2.0.4.0.0_64.tgz

Production:Create|VirtualNetwork|VN001|96

Production:Create|DistributionGroup|DG001

Production:Create|vServer|VS006|VSTProduction|Navstar40GBRootTemplate|EoIB1-client-access,IPoIB-vserver
-shared-storage,VN001|10.242.96.69,172.17.0.34,*|DG001
Production:Create|vServer|VS007|VSTProduction|Navstar40GBRootTemplate|EoIB1-client-access,IPoIB-vserver
-shared-storage,VN001|10.242.96.68,172.17.0.35,*|DG001
Production:Create|vServer|VS002|VSTProduction|Navstar40GBRootTemplate|EoIB1-client-access,IPoIB-vserver
-shared-storage|10.242.96.72,*
Production:Create|vServer|VS003|VSTProduction|Navstar40GBRootTemplate|EoIB1-client-access,IPoIB-vserver
-shared-storage|10.242.96.75,*

Production:Create|Volume|VS006|5
Production:Create|Volume|VS007|5
Production:Create|Volume|VS002|5
Production:Create|Volume|VS003|5

Production:Attach|Volume|VS006|VS006
Production:Attach|Volume|VS007|VS007
Production:Attach|Volume|VS002|VS002
Production:Attach|Volume|VS003|VS003

Production:Disconnect

Post Creation

By default the vServers are created, for security, with Public key Authentication enabled. If you want to turn this functionality off you will need to use the “-r” flag. If this fails because the script can not access the vServer from the location where it has been executed then you will need to do this manually as follows. Open a console started from EMOC to modify the sshd_config paramters; as follows:

  1. Open EMOC.
  2. Right-click on your new vServer and select “Launch Virtual Console” and wait until it opens.
  3. Edit the /etc/ssh/sshd_config file and set the following values:
    1. PasswordAuthentication yes
  4. Restart the sshd using:

    /etc/init.d/sshd reload

Follow

Get every new post delivered to your Inbox.

Join 528 other followers