source: repoman/bin/importimage

qndtest
Last change on this file was 1f6fd06, checked in by Ramón M. Gómez <ramongomez@…>, 4 years ago

#957: Script importimage can use the version function.

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