source: repoman/bin/importimage @ 0befd93

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 0befd93 was 2f1a232, checked in by Irina Gómez <irinagomez@…>, 6 years ago

Fixes bugs in 'importimage': it only created the lockfile if target repository content a image with same name that imported image.

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