source: repoman/bin/importimage @ 1952845

918-git-images-111dconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 1952845 was 7218162, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#873: Fix SQL sentence in importimage script.

  • Property mode set to 100755
File size: 6.6 KB
Line 
1#!/bin/bash
2#/**
3#@file    importimage
4#@usage   importimage [str_user] str_repo str_imagename
5#@brief   Imports an image file from other repository
6#@param   str_user      username to access the remote repository (local user, by default)
7#@param   str_repo      repository IP address or hostaname
8#@param   str_imagename image name to download
9#@warning Program will request the repository REST token.
10#@version 1.1.1 - Initial version
11#@author  Ramón M. Gómez, ETSII Universidad de Sevilla
12#@date    2018-10-08
13#@version 1.1.1b - Fix some bugs.
14#@author  Ramón M. Gómez, ETSII Universidad de Sevilla
15#@date    2020-02-17
16#*/
17
18
19# Variables.
20PROG="$(basename "$0")"
21OPENGNSYS="/opt/opengnsys"
22REPODIR="$OPENGNSYS/images"
23REPOCONF="$OPENGNSYS/etc/ogAdmRepo.cfg"
24SERVERCONF="$OPENGNSYS/etc/ogAdmServer.cfg"
25DEFAULTFILE="/etc/default/opengnsys"
26let BACKUP=0
27source $DEFAULTFILE
28source $REPOCONF &>/dev/null
29[ "$RUN_OGADMSERVER" == "yes" ] && source $SERVERCONF &>/dev/null
30
31# Functions.
32source $OPENGNSYS/lib/ogfunctions.sh
33
34
35# Main program.
36
37# Error control.
38[ "$USER" == "root" ] || raiseError access "Need to be root."
39[ "$RUN_OGADMREPO" == "yes" ] || raiseError access "This server is not defined as image repository."
40[ -w "$REPODIR" ] || raiseError access "Cannot write in local repository."
41[ -n "$IPlocal" ] || raiseError access "Cannot read repository configuration file."
42case $# in
43    2)  USERNAME="$SUDO_USER"; REPO="$1"; IMAGE="$2" ;;
44    3)  USERNAME="$1"; REPO="$2"; IMAGE="$3" ;;
45    *)  [ "$*" == "help" ] && help || raiseError usage
46esac
47[ "${REPO,,}" == "${HOSTNAME,,}" ] || [ "${REPO,,}" == "localhost" ] || [[ ${REPO} =~ ^127\. ]] || [ "${REPO,,}" == "${IPlocal,,}" ] && raiseError access "Cannot import from local repository."
48
49# Fetching image info from the repository.
50read -rp "Enter repository API token: " APITOKEN
51IMAGEINFO="$(curl -k -H "Authorization: $APITOKEN" "https://$REPO/opengnsys/rest/repository/image/$IMAGE" 2> /dev/null | jq -r .)"
52IMAGENAME="$(jq -r '.name' <<< "$IMAGEINFO" 2>/dev/null)"
53case "$IMAGEINFO" in
54    "") # Connection error.
55        raiseError access "Cannot connect to $REPO" ;;
56    "[]") # Image not found.
57        raiseError notfound "Image $IMAGE in remote repository $REPO" ;;
58    *)  # Checking REST error.
59        MESSAGE="$(jq -r '.message' <<< "$IMAGEINFO" 2>/dev/null)"
60        [ -n "$MESSAGE" ] && raiseError access "$MESSAGE"
61esac
62IMAGETYPE="$(jq -r '.type' <<< "$IMAGEINFO" 2>/dev/null)"
63IMAGELOCKED="$(jq -r '.locked' <<< "$IMAGEINFO" 2>/dev/null)"
64[ "$IMAGELOCKED" == "true" ] && raiseError access "Image locked by remote repository."
65IMAGESIZE="$(jq -r '.size' <<< "$IMAGEINFO" 2>/dev/null)"
66[ -z "$IMAGESIZE" ] && raiseError access "Cannot retrieve image size"
67# Checking if local image exists.
68IMAGEPATH="$REPODIR/$IMAGENAME.$IMAGETYPE"
69LOCKFILE="$IMAGEPATH.lock"
70if [ -e "$IMAGEPATH" ]; then
71    # Checking if local image is locked.
72    [ -f "$LOCKFILE" ] && raiseError access "Local image is locked, cannot write."
73    # Confirm image download.
74    read -rp "Image $IMAGENAME exists in the local repository. Do you want to continue? (y/N): " ANSWER
75    [ "${ANSWER,,}" = "y" ]  || exit
76    BACKUP=1
77    REMOTEDATE=$(jq -r '.modified' <<< "$IMAGEINFO" 2>/dev/null)
78    LOCALDATE=$(stat -c "%y" "$IMAGEPATH" | cut -f1 -d.)
79    if [[ "$REMOTEDATE" < "$LOCALDATE" ]]; then
80        read -rp "Remote image seems older than the local one. Do you want to continue? (y/N): " ANSWER
81        [ "${ANSWER,,}" = "y" ]  || exit
82    fi
83fi
84
85# Trapping signal to unlock image before exit.
86trap "rm -f $LOCKFILE" 1 2 3 6 9 15
87# Creating lock file.
88touch $LOCKFILE
89# Backing up local image.
90if [ $BACKUP -eq 1 ]; then
91    mv -vf "$IMAGEPATH" "$IMAGEPATH.ant" 2>/dev/null
92    mv -vf "$IMAGEPATH.torrent" "$IMAGEPATH.torrent.ant" 2>/dev/null
93    mv -vf "$IMAGEPATH.sum" "$IMAGEPATH.sum.ant" 2>/dev/null
94    mv -vf "$IMAGEPATH.full.sum" "$IMAGEPATH.full.sum.ant" 2>/dev/null
95fi
96# Downloading image file.
97[[ $IMAGEPATH =~ / ]] && mkdir -p "$(dirname "$IMAGEPATH")"
98if scp "$USERNAME@$REPO:$IMAGEPATH" $REPODIR; then
99    # Cheking image size.
100    DOWNLOADSIZE=$(stat -c "%s" "$IMAGEPATH")
101    [ $IMAGESIZE -ne $DOWNLOADSIZE ] && echo "Warning: image sizes differ: source=$IMAGESIZE, target=$DOWNLOADSIZE."
102    # Storing creation info.
103    jq -r '.clonator+":"+.compressor+":"+.filesystem+":"+(.datasize|tostring)+":"' <<<"$IMAGEINFO" > "$IMAGEPATH.info"
104    # Updating the database when the repo is also configured as Administration Server.
105    if [ "$RUN_OGADMSERVER" == "yes" ]; then
106        if [ $BACKUP -eq 1 ]; then
107            # If the image exists, increase its revision number.
108            dbexec "UPDATE imagenes SET revision = revision + 1 WHERE nombreca = '$IMAGE';"
109        else
110            # Obtaining defined Organizational Units.
111            while read -re DATA; do
112                OUS[${#OUS[@]}]="$DATA"
113            done <<<$(dbexec "SELECT idcentro, nombrecentro FROM centros;")
114            if [ ${#OUS[@]} -eq 1 ]; then
115                # Only 1 OU is defined.
116                let OUID="${OUS%%       *}"
117            else
118                # Choose image OU.
119                echo "Choose Organization Unit:"
120                PS3="Enter number: "
121                select opt in "${OUS[@]#* }"; do
122                    [ -n "$opt" ] && let OUID="${OUS[REPLY-1]%% *}" && break
123                done
124            fi
125            # Creating a new image associated with an empty software profile.
126            dbexec "
127SET @repoid = (SELECT idrepositorio FROM repositorios
128                WHERE ip='$IPlocal' LIMIT 1),
129    @profname = '$IMAGE imported from $REPO';
130INSERT INTO perfilessoft (descripcion, idcentro, grupoid)
131       SELECT @profname, '$OUID', 0
132         FROM DUAL
133        WHERE NOT EXISTS
134              (SELECT descripcion
135                 FROM perfilessoft
136                WHERE descripcion = @profname AND idcentro = '$OUID')
137        LIMIT 1;
138SET @profid = LAST_INSERT_ID();
139INSERT INTO imagenes
140            (nombreca, revision, descripcion, idperfilsoft, idcentro,
141             comentarios, grupoid, idrepositorio, tipo, fechacreacion)
142       VALUES ('$IMAGE', 1, '$IMAGE imported', @profid, '$OUID',
143               'Image imported from repo $REPO', 0, @repoid, 1, NOW());"
144        fi
145    fi
146else
147    # On download error, trying to recover backup.
148    raiseError download "$USERNAME@$REPO:$IMAGEPATH"
149    if [ $BACKUP -eq 1 ]; then
150        mv -vf "$IMAGEPATH.ant" "$IMAGEPATH" 2>/dev/null
151        mv -vf "$IMAGEPATH.torrent.ant" "$IMAGEPATH.torrent" 2>/dev/null
152        mv -vf "$IMAGEPATH.sum.ant" "$IMAGEPATH.sum" 2>/dev/null
153        mv -vf "$IMAGEPATH.full.sum.ant" "$IMAGEPATH.full.sum" 2>/dev/null
154    fi
155fi
156
157# Unlocking image and removing temporary file.
158rm -f $LOCKFILE
159
Note: See TracBrowser for help on using the repository browser.