utils.sh 23.9 KB
Newer Older
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
1 2 3 4 5 6 7 8
#!/bin/bash

#
# database utility scripts
#

#
# "we've been properly sourced" flag function
9
function check_properly_sourced() {
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
10 11
  return 0
}
Michał 'rysiek' Woźniak's avatar
bugfix  
Michał 'rysiek' Woźniak committed
12
export -f check_properly_sourced
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

#
# display a general error message
# $1 -- additional error msg to display
function display_error {
  echo
  echo "########################################"
  echo "###   AN ERROR OCCURED, ABORTING!    ###"
  echo "###   ---------------------------    ###"
  echo "### inspect the log output carefully ###"
  echo "########################################"
  echo
  # if we have an additional error msg set, use it
  [ -z ${1+x} ] || {
    echo "$1"
    echo
  }
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

  echo "ZABBIX_ERROR"
  # check dbb, rsyncb, remoteb
  [ -z ${dbb+x} ] || {
    echo "ZABBIX_ERROR_MSG ${dbb}"
  }
  [ -z ${rsyncb+x} ] || {
    echo "ZABBIX_ERROR_MSG ${rsyncb}"
  }
  [ -z ${remoteb+x} ] || {
    echo "ZABBIX_ERROR_MSG ${remoteb}"
  }

  # increment the global counter
  ZABBIX_ERRORS_CNT=$(( $ZABBIX_ERRORS_CNT+1 ))
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
}
export -f display_error


#
# rudimentary error handling -- exit the script
function display_error_and_quit {
  if [ -z ${1+x} ]; then
    display_error
  else
    display_error "$1"
  fi
  read
  exit 1
}
export -f display_error_and_quit


#
# rudimentary error handling -- continue with next iteration of a loop
function display_error_and_continue {
  if [ -z ${1+x} ]; then
    display_error
  else
    display_error "$1"
  fi
  read
  continue
}
export -f display_error_and_continue


#
# rudimentary error handling -- break the loop
function display_error_and_break {
  if [ -z ${1+x} ]; then
    display_error
  else
    display_error "$1"
  fi
  read
  break
}
export -f display_error_and_break


#
# utility -- clean the variables used in the dump_*_scripts
function clean_db_vars {
    unset DATABASES
    unset DBUSERS
    unset DBGRANTS
}


#
# create a read-only user for a mysql database (or databases)
# $1             - database host to connect to
# $2             - user to connect as
# $3             - password for that user
# $4             - username to be created
106
# $5             - optional; password for the user to be created
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
107
#                  (if unset or an empty string, random password will be generated and printed on-screen)
108 109
# $6             - optional; hostname of the user to be created
#                  (if unset or an empty string, '%' will be used)
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
#
# the user gets SELECT, SHOW DATABASES, LOCK TABLES, EXECUTE, SHOW VIEW privileges on *all databases*
function create_readonly_mysql_user() {
    
    echo
    echo "creating a read-only user..."
    echo "+-- connection details:"
    echo "    +-- db host to connect to: $1"
    echo "    +-- db user to connect as: $2"
    
    echo "+-- read-only user details:"
    # the read-only user name -- simple enough
    RUSER_NAME="$4"
    echo "    +-- username: $RUSER_NAME"
    
    # read-only user hostname
    RUSER_HOST="%"
127 128
    if [ ! -z ${6+x} ]; then
        RUSER_HOST="$6"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
129 130 131 132 133
    fi
    echo "    +-- hostname: $RUSER_HOST"
    
    # read-only user password
    # if supplied, use it
134 135
    if [ ! -z ${5+x} ]; then
        RUSER_PW="$5"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
136 137 138
        echo "    +-- password: (provided on the command line)"
    # otherwise, create a random one
    else
139
        RUSER_PW="$( pwgen -s 24 1 )" || { display_error "Error generating password; is pwgen installed and in \$PATH?"; return 1; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
140 141 142 143 144
        echo "    +-- password: $RUSER_PW"
    fi
    
    # do the magic
    mysql -h "$1" -u "$2" --password="$3" --batch -e "GRANT SELECT, SHOW DATABASES, LOCK TABLES, EXECUTE, SHOW VIEW ON *.* TO '$RUSER_NAME'@'$RUSER_HOST' IDENTIFIED BY '$RUSER_PW';" \
145
        || { display_error "Error creating a read-only user."; return 1; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
146 147 148 149 150
}
export -f create_readonly_mysql_user

#
# this assumes we have *at least* read-only access to databases we want to dump
151 152 153 154
# $1             - database host to connect to
# $2             - user to connect as
# $3             - password for that user
# $4             - targed directory; the directory and structure within ($4/, $4/schemas/, $4/dumps/) will be made sure to exist
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
155 156 157 158 159
# $5 and further - optional, the databases to dump (dumping all if empty)
#
# relevant: https://dev.mysql.com/doc/refman/5.6/en/mysqldump.html
# 
# databases are dumped as schema (containing grants related to the database and CREATE statements) and data dump spearately,
160
# put in $4/schemas/$database_name.schema.sql and $4/dumps/$database_name.dump.sql respectively
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
161 162 163 164 165 166 167 168
# 
# this does *not* dump internal MySQL information_schema and performance_schema databases.
function dump_mysql_dbs {
    
    # clean the vars
    clean_db_vars
    
    # create the directory structure
169 170 171
    mkdir -p "$4"
    mkdir -p "$4/schemas"
    mkdir -p "$4/dumps"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
172 173 174 175 176 177 178 179 180 181
    
    #
    # - if we have no additional arguments (5th and onwards), we need to dump all the databases (well, apart from information_schema and performance_schema)
    # - if we have such arguments, we can use WHERE `Database` IN ('$5', ...)
    DATABASES_WHERE=""
    if [ ! -z ${5+x} ]; then
        DATABASES_WHERE="WHERE \`Database\` IN ( '` echo "${@:5}" | sed -r -e "s/ /', '/g" ` )"
    fi
    
    # get the list of databases
182
    DATABASES="$( mysql -h "$1" -u "$2" --password="$3" --batch -e "SHOW DATABASES $DATABASES_WHERE;" | egrep -v '(Database|information_schema|performance_schema)' )"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
183 184
    
    # either the code is 0, or the command failed; act accordingly.
185
    [ $? -eq 0 ] || { display_error; return 1; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
186 187 188 189 190 191 192 193 194 195 196
    
    # did we find anything?
    if [[ "$DATABASES" == "" ]]; then
        echo "        +-- no databases found."
        return 0
    fi
    
    #
    # if we had a list of databases, did we find all of them?
    # rationale: if we have a specific list of databases, we *expect* them to be dumped
    #            if we cannot find some of them, that should be clearly signalled
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
197 198
    if [ ! -z ${5+x} ] && [ "$5" != "" ]; then
        DATABASES_MISSING="$( echo "${@:5} $DATABASES" | tr ' ' '\n' | sort | uniq -u | tr '\n' ' ' )"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
199 200
        if [[ "$DATABASES_MISSING" != "" ]]; then
            # if not, complain and exit
201 202
            display_error "Not all databases found; missing: $DATABASES_MISSING"
            return 2
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
203 204 205 206 207 208 209
        fi
    fi
    
    # whoo hoo, found *something*
    echo "        +-- found `echo "$DATABASES" | wc -l` databases..."
    
    # is the db using authentication_string, or password for user passwords?
210
    if [[ "$( mysql -h "$1" -u "$2" --password="$3" --batch --skip-column-names -e "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'mysql' AND TABLE_NAME = 'user' AND COLUMN_NAME = 'password';" )" == "0" ]]; then
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
211 212 213 214 215 216 217
        PWCOL="authentication_string"
    else
        PWCOL="password"
    fi
    echo "        +-- password column: $PWCOL"
    
    # get the list of users
218
    DBUSERS="$( mysql -h "$1" -u "$2" --password="$3" --batch --skip-column-names -e "SELECT CONCAT('',QUOTE(user),'@',QUOTE(host),':',$PWCOL) FROM mysql.user WHERE user<>'';")"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
219
    
220
    [ $? -eq 0 ] || { display_error; return 3; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
221 222 223 224 225 226 227 228 229 230 231 232
    echo "        +-- found `echo "$DBUSERS" | wc -l` users..."
    
    # get all grants for said users
    DBGRANTS=""
    for user_host_pass in ${DBUSERS}; do
        # ignore root
        if echo "$user_host_pass" | grep "'root'@" >/dev/null; then
            continue
        fi
        DBUSER="$( echo "$user_host_pass" | cut -d ':' -f 1 )"
        DBUSERPW="$( echo "$user_host_pass" | cut -d ':' -f 2 )"
        # get the grants                                                                                                                                  # add IDENTIFIED BY <password>, but only when there was no IDENTIFIED BY there already
233
        DBGRANTS=`echo -ne "$DBGRANTS\n$( mysql -h "$1" -u "$2" --password="$3" --batch --skip-column-names -e "SHOW GRANTS FOR $DBUSER;" | sed -r -e "s/(IDENTIFIED BY.*)$/ IDENTIFIED BY PASSWORD '$DBUSERPW'/g" )"`
234
        [ $? -eq 0 ] || { display_error; return 4; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
235 236 237 238 239 240 241
    done
    
    # iterate through databases
    for db in ${DATABASES}; do
        echo "        +-- working on db: $db"
        
        # files
242
        SCHEMA_FILE="$4/schemas/$db.schema.sql"
243
        DUMP_FILE="$4/dumps/$db.dump.sql.gz"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
244 245 246 247 248
        echo "        +-- schema file : $SCHEMA_FILE"
        echo "        +-- dump file   : $DUMP_FILE"
    
        # schema
        echo "            +-- schema..."
249
        mysqldump -h "$1" -u "$2" --password="$3" --add-drop-database --no-data --databases "$db" > "$SCHEMA_FILE"
250
        [ $? -eq 0 ] || display_error_and_continue
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
251 252 253 254 255 256 257 258 259 260 261
        
        # grants
        echo "            +-- grants..."
        echo '-- ------ --' >> "$SCHEMA_FILE"
        echo '-- GRANTS --' >> "$SCHEMA_FILE"
        echo '-- ------ --' >> "$SCHEMA_FILE"
        
        # TODO FIXME lacking password information...
        # SET PASSWORD FOR ... = HASH_STRING
        
        echo "${DBGRANTS}" | grep "ON \*." | sed -r -e 's/$/;/' >> "$SCHEMA_FILE"
262
        [ $? -lt 2 ] || display_error_and_continue # less than 2 here, because 0 on "found", 1 on "not found", 2 and above on "error"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
263
        echo "${DBGRANTS}" | grep "ON \`${db}\`" | sed -r -e 's/$/;/' >> "$SCHEMA_FILE"
264
        [ $? -lt 2 ] || display_error_and_continue # less than 2 here, because 0 on "found", 1 on "not found", 2 and above on "error"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
265 266 267 268 269
        # we need this for the privs to work after restore
        echo "FLUSH PRIVILEGES;" >> "$SCHEMA_FILE"
        
        # dump
        echo "            +-- dump..."
270
        mysqldump -h "$1" -u "$2" --password="$3" --no-create-info --no-create-db --databases "$db" | gzip -c > "$DUMP_FILE"
271
        [ $? -eq 0 ] || display_error_and_continue
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
272 273 274 275 276 277 278
        
        echo "            +-- done."
    done
    
    # set the permissions so that 
    # this will not stop a root user from using these, but should make them stand out well enough
    echo "        +-- setting permissions on mysql.*"
279
    chmod a= "$4"/*/mysql.*.sql
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
280 281 282 283 284 285 286 287 288 289 290 291 292
    
    # we're done
    echo "        +-- done."
}
export -f dump_mysql_dbs


#
# create a read-only user for a postgresql database (or databases)
# $1             - database host to connect to
# $2             - user to connect as
# $3             - password for that user
# $4             - username to be created
293
# $5             - optional; password for the user to be created
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
294 295 296 297
#                  (if unset or an empty string, random password will be generated and printed on-screen)
#
# not as simple as the mysql version; we need to make sure that:
# a). given role is created...
298 299
# b). ...and granted SELECT on pg_authid...
# c). ...and granted CONNECT on all databases...
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
300 301 302
# d). ...and granted USAGE on all schemas in all databases...
# e). ...and granted SELECT on all tables and sequences in all schemas in all databases...
# f). ...and granted EXECUTE on all functions in all schemas in all databases...
303 304
# g). ...and that the default privileges for all roles grant the new read-only role
#     SELECT on tables and sequences, and EXECUTE on functions created in the future.
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
305 306 307 308
#
# ref. https://wiki.postgresql.org/images/d/d1/Managing_rights_in_postgresql.pdf
function create_readonly_postgres_user() {

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    # get the details
    PG_HOST="$1"
    PG_USER="$2"
    PG_PASS="$3"
    RUSER_NAME="$4"
    
    # read-only user password
    # if supplied, use it
    if [ ! -z ${5+x} ]; then
        RUSER_PW="$5"
        echo "    +-- password: (provided on the command line)"
    # otherwise, create a random one
    else
        RUSER_PW="$( pwgen -s 24 1 )" || display_error_and_quit "Error generating password; is pwgen installed and in \$PATH?"
        echo "    +-- password: $RUSER_PW"
    fi

326
    # make sure the role exists
327
    PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -c "
328
        CREATE ROLE $RUSER_NAME NOSUPERUSER NOCREATEDB NOCREATEROLE LOGIN NOREPLICATION PASSWORD '$RUSER_PW';" postgres \
329
        || { display_error "Error creating the $RUSER_NAME role."; read -P "Hit Enter to continue or Ctrl-C to abort" ; }
330 331 332 333
        
    # make sure the role has the basic required privileges (and lacks the unneeded ones)
    PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -c "GRANT SELECT ON pg_authid TO $RUSER_NAME;" postgres \
        || { display_error "Error granting $RUSER_NAME role SELECT on pg_authid."; return 1; }
334
    
335
    # get the list of roles
336
    ROLES="$( PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -qt -c '\dg' postgres | grep '|' | cut -d '|' -f 1 | tr -d ' ' | egrep -v '^$' )" \
337
        || { display_error "Error getting list of roles"; return 2; }
338 339 340 341 342 343 344
    
    # and for each role
    for ROLE in $ROLES; do
        # set default privileges on tables/sequences/function
        PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -c "
            ALTER DEFAULT PRIVILEGES FOR ROLE $ROLE GRANT SELECT ON TABLES TO $RUSER_NAME;
            ALTER DEFAULT PRIVILEGES FOR ROLE $ROLE GRANT SELECT ON SEQUENCES TO $RUSER_NAME;
345
            ALTER DEFAULT PRIVILEGES FOR ROLE $ROLE GRANT EXECUTE ON FUNCTIONS TO $RUSER_NAME;" postgres \
346
            || { display_error "Error altering default privileges for role $ROLE"; return 3; }
347 348 349
    done
    
    
350
    # get the list of databases
351
    DATABASES="$( PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -lAqt postgres | grep '|' | cut -d '|' -f 1 | egrep -v "template[0-9]" )" \
352
        || { display_error "Error getting list of databases"; return 4; }
353 354 355 356 357 358 359 360 361 362 363

    # do we have any databases?
    if [[ "$DATABASES" == "" ]]; then
        echo "        +-- no databases found."
        return 0
    fi
    
    # and for each one of them
    for DATABASE in $DATABASES; do
        
        # grant CONNECT
364
        PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -c "GRANT CONNECT ON DATABASE $DATABASE TO $RUSER_NAME;" postgres \
365
            || { display_error "Error granting CONNECT on database $DATABASE"; return 5; }
366 367
        
        # get all schemas
368
        SCHEMAS="$( PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -Aqt -c '\dn' postgres | grep '|' | cut -d '|' -f 1 )" \
369
            || { display_error "Error getting list of schemas"; return 6; }
370 371 372 373 374
        
        # let's go through the schemas, then
        for SCHEMA in $SCHEMAS; do
            # grant USAGE on the schema
            PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -c "GRANT USAGE ON SCHEMA $SCHEMA TO $RUSER_NAME;" "$DATABASE" \
375
                || { display_error "Error granting USAGE on schema $SCHEMA"; return 7; }
376 377 378 379 380 381
        
            # grant SELECT on all tables and sequences, and EXECUTE on all functions, in the schema
            PGPASSWORD="$PG_PASS" psql -h "$PG_HOST" -U "$PG_USER" -c "
                GRANT SELECT ON ALL TABLES IN SCHEMA $SCHEMA TO $RUSER_NAME;
                GRANT SELECT ON ALL SEQUENCES IN SCHEMA $SCHEMA TO $RUSER_NAME;
                GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA $SCHEMA TO $RUSER_NAME;" "$DATABASE" \
382
                || { display_error "Error granting USAGE on schema $SCHEMA"; return 8; }
383 384
        done
    done
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
385 386 387 388 389 390 391

}
export -f create_readonly_postgres_user


#
# this assumes we have *at least* read-only access to databases we want to dump
392 393 394 395
# $1             - database host
# $2             - user to connect as
# $3             - password for that user
# $4             - targed directory; the directory and structure within ($4/, $4/schemas/, $4/dumps/) will be made sure to exist
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
396 397 398 399 400
# $5 and further - optional, the databases to dump (dumping all if empty)
#
# relevant: http://www.postgresql.org/docs/current/static/app-pgdump.html
#
# databases are dumped as schema (containing grants related to the database and CREATE statements) and data dump spearately,
401
# put in $4/schemas/$database_name.schema.sql and $4/dumps/$database_name.dump.sql respectively
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
402 403 404 405 406 407
function dump_postgres_dbs {

    # clean the vars
    clean_db_vars

    # create the directory
408 409 410
    mkdir -p "$4"
    mkdir -p "$4/schemas"
    mkdir -p "$4/dumps"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
411 412 413 414 415 416 417
    
    # get the list of databases
    # -l/--list         List all available databases,then exit. Other non-connection
    # -A/--no-align     Switches to unaligned output mode.
    # -q/--quiet        Specifies that psql should do its work quietly.
    # -t/--tuples-only  Turn off printing of column names and result row count footers, etc.
    # ref. http://linuxcommand.org/man_pages/psql1.html
418
    DATABASES="$( PGPASSWORD="$3" psql -h "$1" -U "$2" -lAqt | grep '|' | cut -d '|' -f 1 | egrep -v "template[0-9]" )"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
419 420
    
    # either the code is 0, or the command failed; act accordingly.
421
    [ $? -eq 0 ] || { display_error; return 1; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
422 423 424 425 426 427 428 429 430 431 432

    # do we have any databases?
    if [[ "$DATABASES" == "" ]]; then
        echo "        +-- no databases found."
        return 0
    fi
    
    #
    # if we had a list of databases, did we find all of them?
    # rationale: if we have a specific list of databases, we *expect* them to be dumped
    #            if we cannot find some of them, that should be clearly signalled
Michał 'rysiek' Woźniak's avatar
bugfix  
Michał 'rysiek' Woźniak committed
433
    if [ ! -z ${5+x} ] && [ "$5" != "" ]; then
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
434
        DATABASES_MISSING="$( echo "${@:5} $DATABASES" | tr ' ' '\n' | sort | uniq -u | tr '\n' ' ' )"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
435 436
        if [[ "$DATABASES_MISSING" != "" ]]; then
            # if not, complain and exit
437 438
            display_error "Not all databases found; missing: $DATABASES_MISSING"
            return 2
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
439 440 441 442
        fi
    fi
    
    # list of users
443
    DBUSERS="$( PGPASSWORD="$3" pg_dumpall -h "$1" --globals-only -U "$2" | egrep '(CREATE|ALTER) ROLE' )"
444
    [ $? -eq 0 ] || { display_error; return 3; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
445 446 447 448 449 450 451 452
    echo "        +-- found `echo "$DBUSERS" | egrep "^CREATE" | wc -l` users..."
    
    
    # iterate through databases
    for db in ${DATABASES}; do
        echo "        +-- working on db: $db"
        
        # files
453
        SCHEMA_FILE="$4/schemas/$db.schema.sql"
454
        DUMP_FILE="$4/dumps/$db.dump.sql.gz"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
455 456 457
        echo "        +-- schema file : $SCHEMA_FILE"
        echo "        +-- dump file   : $DUMP_FILE"
        
458 459
        # clear the schema file
        echo > "$SCHEMA_FILE"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
460 461 462 463 464 465 466 467 468 469 470
        
        # grants
        echo "            +-- grants..."
        echo '-- ------ --' >> "$SCHEMA_FILE"
        echo '-- GRANTS --' >> "$SCHEMA_FILE"
        echo '-- ------ --' >> "$SCHEMA_FILE"
        
        USERS_GREP="$( cat "$SCHEMA_FILE" | grep 'GRANT' | sed -r -e 's/^GRANT.+TO ([^;]+);/\1/' | sort | uniq )"
        USERS_GREP="$( echo $USERS_GREP | tr ' ' '|' )"
        echo "$DBUSERS" | egrep " ($USERS_GREP)[; ]" >> "$SCHEMA_FILE"
        
471 472 473 474 475 476 477 478 479
        # schema
        echo "            +-- schema..."
        
        echo '-- ------ --' >> "$SCHEMA_FILE"
        echo '-- SCHEMA --' >> "$SCHEMA_FILE"
        echo '-- ------ --' >> "$SCHEMA_FILE"
        PGPASSWORD="$3" pg_dump -h "$1" --create --clean --schema-only -U "$2" "$db" >> "$SCHEMA_FILE"
        [ $? -eq 0 ] || display_error_and_continue
        
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
480 481
        # dump
        echo "            +-- dump..."
482
        PGPASSWORD="$3" pg_dump -h "$1" --format plain --compress 9 -U "$2" "$db" > "$DUMP_FILE"
483
        [ $? -eq 0 ] || display_error_and_continue
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        
        echo "            +-- done."
    done
    
    # we're done
    echo "        +-- done."
}
export -f dump_postgres_dbs


#
# elasticsearch
# 
# info:
#  https://www.elastic.co/guide/en/elasticsearch/guide/master/backing-up-your-cluster.html
# restoring:
#  https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html#_restoring_to_a_different_cluster
#
502 503
# $1             - database host
# $2             - targed directory
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
# $3             - optional; location where the temporary backup directory will be created;
#                  if not set, /tmp will be used
#
# we're cheating here a bit:
#  - create a new backup repository
#  - make a snapshot
#  - copy the snapshot data to the right location, outside the repository directory
#  - remove the snapshot
#  - remove the backup repository
#
# NOTICE: this will *ONLY* work on a single-node cluster, or on a cluster where all the nodes
#         have access to the tmp snapshot directory!
#         
# NOTICE: the temporary dump directory has to be accessible both to the elasticsearch server, and to this script
#         (for instance, if they're running in separate docker containers,
#          this directory has to be volume-mounted in both)
function dump_elasticsearch_dbs {
    
    # name of the backup
    BACKUP_NAME="temp_backup_$( date +%F )"
    
    # the temporary backup location
    # this location has to be accessible to the elasticsearch server, and to this script
    # (for instance, if they're running in separate docker containers, this directory has to be volume-mounted in both)
    if [ -z ${3+x} ]; then
        BACKUP_TEMP_DIR="$( mktemp -d --tmpdir="/tmp" )"
    else
        BACKUP_TEMP_DIR="$( mktemp -d --tmpdir="$3" )"
    fi
    
    # let's make sure we have the right perms to create the snapshot
    chmod a+rwX "$BACKUP_TEMP_DIR"
    
    # clean the vars
    clean_db_vars

    # create the directory
    echo "        +-- setup..."
542 543
    echo "            +-- directory: $2"
    mkdir -p "$2"
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
544 545 546
                               
    # create the temporary backup repository
    echo "            +-- ES snapshot repository in: $BACKUP_TEMP_DIR"
547
    curl -X PUT -H "Content-Type: application/json" "http://$1:9200/_snapshot/$BACKUP_NAME" -d "{
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
548 549 550 551 552 553 554 555 556
        \"type\": \"fs\", 
        \"settings\": {
            \"location\": \"$BACKUP_TEMP_DIR\" 
        }
    }"
    echo
    
    # create a snapshot, blocking until it's done
    echo "        +-- dump..."
557
    curl -X PUT "http://$1:9200/_snapshot/$BACKUP_NAME/snapshot?wait_for_completion=true" || { display_error 'Error while generating the snapshot!'; return 1; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
558 559 560
    echo
    
    # copy the backup to a less temporary location
561
    cp -a "$BACKUP_TEMP_DIR"/* "$2/"  || { display_error 'Error while copying the snapshot data to the target directory!'; return 2; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
562 563 564
    
    # cleanup
    echo "        +-- cleanup..."
565
    curl -X DELETE "http://$1:9200/_snapshot/$BACKUP_NAME/snapshot" || { display_error 'Error while cleaning up the snapshot!'; return 3; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
566
    echo
567
    curl -X DELETE "http://$1:9200/_snapshot/$BACKUP_NAME/" || { display_error 'Error while cleaning up the backup repository!'; return 4; }
Michał 'rysiek' Woźniak's avatar
Michał 'rysiek' Woźniak committed
568 569 570 571
    echo
    rm -rf "$BACKUP_TEMP_DIR/*"
    echo "        +-- done..."
}
572
export -f dump_elasticsearch_dbs
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

#
# encrypt data from stdin to stdout using an SSH RSA pubkey
# ECDSA and Ed25519 keys are not supported, sadly
# 
# $1 - path to the SSH RSA key to use (optional, by default /etc/ssh/ssh_host_rsa_key.pub is used)
# 
# based on:
# https://superuser.com/questions/576506/how-to-use-ssh-rsa-public-key-to-encrypt-a-text/576558#576558
function ssh_rsa_encrypt {
    
    # default
    PUBKEY="/etc/ssh/ssh_host_rsa_key.pub"
    
    # let's check if we have a $1
    [ "$1" != "" ] && PUBKEY="$1"
    
    # reality checks -- does the file exist, is it a file, is it readable
591 592
    [ -e "$PUBKEY" ] || { >&2 display_error "The specified SSH RSA public key '$PUBKEY' does not exist."; return 1; }
    [ -r "$PUBKEY" ] || { >&2 display_error "The specified SSH RSA public key '$PUBKEY' is not readable to this user."; return 2; }
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    
    # temporary file for the pubkey in OpenSSL-compatible PEM format
    PUBKEY_PEM="$( mktemp )"
    
    # generate the OpenSSL-compatible PEM key
    ssh-keygen -f "$PUBKEY" -e -m PKCS8 > "$PUBKEY_PEM"
    
    # decrypt from stdin to stdout
    openssl pkeyutl -encrypt -pubin -inkey "$PUBKEY_PEM"
}
export -f ssh_rsa_encrypt


#
# decrypt data from stdin to stdout using an SSH RSA private key
# ECDSA and Ed25519 keys are not supported, sadly
# 
# $1 - path to the SSH RSA private key to use (optional, by default /etc/ssh/ssh_host_rsa_key is used)
# 
# Caveat: the key file has to be readable to the user running the command (duh!); also,
#         password-protected SSH RSA private keys are not supported at this time
# 
# based on:
# https://superuser.com/questions/576506/how-to-use-ssh-rsa-public-key-to-encrypt-a-text/576558#576558
function ssh_rsa_decrypt {
    
    # default
    PRIVKEY="/etc/ssh/ssh_host_rsa_key"
    
    # let's check if we have a $1
    [ "$1" != "" ] && PRIVKEY="$1"
    
    # reality checks -- does the file exist, is it a file, is it readable
626 627
    [ -e "$PRIVKEY" ] || { >&2 display_error "The specified SSH RSA public key '$PRIVKEY' does not exist."; return 1; }
    [ -r "$PRIVKEY" ] || { >&2 display_error "The specified SSH RSA public key '$PRIVKEY' is not readable to this user."; return 2; }
628 629 630 631

    # decrypt from stdin to stdout
    openssl pkeyutl -decrypt -inkey "$PRIVKEY"
}
632
export -f ssh_rsa_decrypt