source: repoman/bin/importimage

lgromero-new-oglive
Last change on this file was c28eefa, checked in by Natalia Serrano <natalia.serrano@…>, 19 months ago

Log to syslog in a number of shell scripts

  • Property mode set to 100755
File size: 6.6 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
48echolog '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
67echolog '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
90echolog 'Backing up local image.'
91if [ $BACKUP -eq 1 ]; then
92    mv -vf "$IMAGEPATH" "$IMAGEPATH.ant" 2>/dev/null
93    mv -vf "$IMAGEPATH.torrent" "$IMAGEPATH.torrent.ant" 2>/dev/null
94    mv -vf "$IMAGEPATH.sum" "$IMAGEPATH.sum.ant" 2>/dev/null
95    mv -vf "$IMAGEPATH.full.sum" "$IMAGEPATH.full.sum.ant" 2>/dev/null
96fi
97
98echolog 'Downloading image file.'
99[[ $IMAGEPATH =~ / ]] && mkdir -p "$(dirname "$IMAGEPATH")"
100if scp "$USERNAME@$REPO:$IMAGEPATH" $REPODIR; then
101    echolog 'Download successful.'
102    # Cheking image size.
103    DOWNLOADSIZE=$(stat -c "%s" "$IMAGEPATH")
104    [ $IMAGESIZE -ne $DOWNLOADSIZE ] && echolog "Warning: image sizes differ: source=$IMAGESIZE, target=$DOWNLOADSIZE."
105    # Storing creation info.
106    jq -r '.clonator+":"+.compressor+":"+.filesystem+":"+(.datasize|tostring)+":"' <<<"$IMAGEINFO" > "$IMAGEPATH.info"
107    # Updating the database when the repo is also configured as Administration Server.
108    if [ "$RUN_OGADMSERVER" == "yes" ]; then
109        if [ $BACKUP -eq 1 ]; then
110            # If the image exists, increase its revision number.
111            dbexec "UPDATE imagenes SET revision = revision + 1 WHERE nombreca = '$IMAGE';"
112        else
113            # Obtaining defined Organizational Units.
114            while read -re DATA; do
115                OUS[${#OUS[@]}]="$DATA"
116            done <<<$(dbexec "SELECT idcentro, nombrecentro FROM centros;")
117            if [ ${#OUS[@]} -eq 1 ]; then
118                # Only 1 OU is defined.
119                let OUID="${OUS%%       *}"
120            else
121                # Choose image OU.
122                echo "Choose Organization Unit:"
123                PS3="Enter number: "
124                select opt in "${OUS[@]#* }"; do
125                    [ -n "$opt" ] && let OUID="${OUS[REPLY-1]%% *}" && break
126                done
127            fi
128            # Creating a new image associated with an empty software profile.
129            dbexec "
130SET @repoid = (SELECT idrepositorio FROM repositorios
131                WHERE ip='$IPlocal' LIMIT 1),
132    @profname = '$IMAGE imported from $REPO';
133INSERT INTO perfilessoft (descripcion, idcentro, grupoid)
134       SELECT @profname, '$OUID', 0
135         FROM DUAL
136        WHERE NOT EXISTS
137              (SELECT descripcion
138                 FROM perfilessoft
139                WHERE descripcion = @profname AND idcentro = '$OUID')
140        LIMIT 1;
141SET @profid = LAST_INSERT_ID();
142INSERT INTO imagenes
143            (nombreca, revision, descripcion, idperfilsoft, idcentro,
144             comentarios, grupoid, idrepositorio, tipo, fechacreacion)
145       VALUES ('$IMAGE', 1, '$IMAGE imported', @profid, '$OUID',
146               'Image imported from repo $REPO', 0, @repoid, 1, NOW());"
147        fi
148    fi
149else
150    echolog 'Download error, trying to recover backup.'
151    raiseError download "$USERNAME@$REPO:$IMAGEPATH"
152    if [ $BACKUP -eq 1 ]; then
153        mv -vf "$IMAGEPATH.ant" "$IMAGEPATH" 2>/dev/null
154        mv -vf "$IMAGEPATH.torrent.ant" "$IMAGEPATH.torrent" 2>/dev/null
155        mv -vf "$IMAGEPATH.sum.ant" "$IMAGEPATH.sum" 2>/dev/null
156        mv -vf "$IMAGEPATH.full.sum.ant" "$IMAGEPATH.full.sum" 2>/dev/null
157    fi
158fi
159
160# Unlocking image and removing temporary file.
161rm -f $LOCKFILE
162
Note: See TracBrowser for help on using the repository browser.