summaryrefslogtreecommitdiffstats
path: root/scripts/sources/common
blob: 2473477ef8bd6a7c74f45e711035358c3406a5fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
##
# This is the file all (build and destroy) scripts have in 'common'.
#
# It loads the config, provides many helping functions and chooses which
# project-build script to include depending on the projects type (see bottom).
##

# Load config.
source "$DIRECTORY/config"

# Include prepare script.
source "$DIRECTORY/sources/prepare"

##
# Reads a value from a .info file
#
# @param $1
#  Info filepath to read from.
# @param $2
#  Name of value to read.
s_info_file_get() {
  # Make sure info files are unix encoded before reading them.
  dos2unix -q "$1"
  # Cut out the value.
  grep -m 1 "$2[ ]*=" "$1" | sed 's/^ *//g' | sed -n "s/$2[^=]*=[ ]*//p" | sed "s/[\"|\']//g"
}

##
# Reads all values from a .info file.
#
# @param $1
#  Info filepath to read from.
# @param $2
#  Name of value to read.
s_info_file_get_all() {
  # Make sure info files are unix encoded before reading them.
  dos2unix -q "$1"
  # Cut out the values.
  cat "$1" | grep "$2\[\][ ]*" | sed 's/^ *//g' | sed -n "s/$2[^=]*=[ ]*//p" | sed "s/[\"|\']//g"
}

##
# Resets the owner and permission of the environment files.
#
# @param $1
#  The submission id.
s_reset_environment_files() {
  # Make sure PHP upload tempdir exists and is writeable.
  if [[ ! -d "/home/$S_ID/www/tmp" ]]; then
    mkdir "/home/$S_ID/www/tmp"
  fi
  chmod 777 "/home/$S_ID/www/tmp"
  # Make sure all files and directory have the correct group and user.
  chown --recursive $1 "/home/$1/www"/*
  chgrp --recursive nogroup "/home/$1/www"/*
}

##
# Clones/Fetches a project in project cache.
#
# @param $1
#  Project shortname to fetch.
# @param $2
#  Git url to clone from.
# @param $3
#  Path to download it to.
s_fetch_project() {
  # Clone if project is not in cache yet.
  if [[ ! -r "$S_DRUSHCACHE/$1.git" ]]; then
    timeout 500 git clone --mirror "$2" "$S_DRUSHCACHE/$1.git"
  fi
  timeout 350 git clone --reference "$S_DRUSHCACHE/$1.git" --recursive "$2" "$3" || s_ste 9
  # Update repo by fetching newest changes.
  cd "$3" || s_ste 9
  git fetch || s_ste 9
  git pull
}

##
# Execute a SQL query.
#
# @param $1
#  SQL query to execute.
s_sqlquery() {
  mysql -u $S_SQLUSR "-p$S_SQLPWD" -e "$1" || s_ste 10
}

##
# Setup temporary database.
#
# @param $1
#  Name of database and user to setup for.
s_db_setup() {
  s_sqlquery "#CREATE USER '$1'@'localhost' IDENTIFIED BY  '$1';"
  s_sqlquery "GRANT USAGE ON * . * TO  '$1'@'localhost' IDENTIFIED BY  '$1' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;"
  s_sqlquery "CREATE DATABASE IF NOT EXISTS $1 ;"
  s_sqlquery "GRANT ALL PRIVILEGES ON $1 . * TO  '$1'@'localhost';"
}

##
# Set a timeout to execute a command.
#
# @param $1
#  Command to execute.
# @param $2
#  Minutes until execution.
s_settimeout() {
  # Create an ´at´ job but give an extra minute to compensate time
  # differences with snippet script.
  echo "$1" | at now + $(($2 + 1)) minutes
}

##
# Checkout specified version and remove git.
#
# @param $1
#  Path to check the project out at.
# @param $2
#  Version to check out.
s_set_version() {
  cd $1
  timeout 350 git checkout $2 || s_ste 9
  rm -r "$1/.git"
}

##
# Tries to find out the project real filename.
#
# This is necessary to compensate things like
# shortname: cck -> filename: content.
#
# @param $1
#  Path to the projects directory.
s_get_project_filename() {
  ls -l "$1" | grep -m 1 -o "[_a-zA-Z0-9]*.info$" | sed -n 's/.info//p'
}

##
# Tries to find out the core version of a project.
#
# @param $1
#  Path to the project's info file to determine core version of.
#
# @return
#  The core version determined.
s_get_project_coreversion() {
  s_info_file_get "$1" "core" | sed "s/\..*//g"
}

##
# Tries to find out the core version in docroot.
#
# @todo find a more reliable way to determine a core version.
#
# @return
#  The core version determined, or "X" for unknown.
s_get_coreversion() {
  # Check for Drupal 8.
  if [ -e "/home/$S_ID/www/core/install.php" ] # Core files were moved from root to core/.
  then
    echo "8"
  
  # Check for Drupal 7.
  elif [ -e "/home/$S_ID/www/authorize.php" ] # authorize.php for module ftp upload/installation was added.
  then
    echo "7"
  
  # Check for Drupal 6.
  elif [ -e "/home/$S_ID/www/misc/tabledrag.js" ] # Tabledrag was added.
  then
    echo "6"
  
  # Unknown version.
  else
    echo "X"
  fi
}

##
# Installs a drupal 8 core in docroot.
#
# @param $1
#  Core project version.
# @param $2
#  Install profile to use.
s_install_drupal_8() {
  # Setup directories and permissions.
  mkdir "/home/$S_ID/www/sites/default/files"
  mkdir "/home/$S_ID/www/sites/default/files/tmp"
  cp "/home/$S_ID/www/sites/default/default.settings.php" "/home/$S_ID/www/sites/default/settings.php" || s_ste 10
  chmod --recursive 555 "/home/$S_ID/www"
  chmod --recursive 777 "/home/$S_ID/www/sites/default/files"
  chmod --recursive 777 "/home/$S_ID/www/sites/default/settings.php"
  chown --recursive $S_ID "/home/$S_ID/www"/* || s_ste 10
  chgrp --recursive nogroup "/home/$S_ID/www"/* || s_ste 10
  chown --recursive $S_ID "/home/$S_ID/www/.htaccess" || s_ste 10
  chgrp --recursive nogroup "/home/$S_ID/www/.htaccess" || s_ste 10
  # Drush's not ready for d8.
}

##
# Installs a drupal 7 core in docroot.
#
# @param $1
#  Core project version.
# @param $2
#  Install profile to use.
s_install_drupal_7() {
  # Setup directories and permissions.
  mkdir "/home/$S_ID/www/sites/default/files"
  mkdir "/home/$S_ID/www/sites/default/files/tmp"
  cp "/home/$S_ID/www/sites/default/default.settings.php" "/home/$S_ID/www/sites/default/settings.php" || s_ste 10
  chown --recursive $S_ID "/home/$S_ID/www"/*
  chgrp --recursive nogroup "/home/$S_ID/www"/*

  cd "/home/$S_ID/www" || s_ste 10

  # Start drupal installation.
  timeout 350 sudo -u $S_ID drush site-install $2 --locale=en -y --db-url=mysql://$S_ID:$S_ID@localhost/$S_ID --account-name=$S_DUSR --account-pass=$S_DPWD --account-mail="$S_ID-$S_DMAIL_SUFFIX" --site-mail="$S_ID-$S_DMAIL_SUFFIX" --site-name="Drupal $1" || s_ste 10

  # Set temporary path to files dir.
  timeout 350 sudo -u $S_ID drush vset --always-set file_temporary_path "sites/default/files/tmp"

  chmod --recursive 555 "/home/$S_ID/www"
  chmod --recursive 777 "/home/$S_ID/www/sites/default/files"
  chown --recursive $S_ID "/home/$S_ID/www"/* || s_ste 10
  chgrp --recursive nogroup "/home/$S_ID/www"/* || s_ste 10
  chown --recursive $S_ID "/home/$S_ID/www/.htaccess" || s_ste 10
  chgrp --recursive nogroup "/home/$S_ID/www/.htaccess" || s_ste 10
}

##
# Installs a drupal 6 core in docroot.
#
# @param $1
#  Core project version.
# @param $2
#  Install profile to use.
s_install_drupal_6() {
  mkdir "/home/$S_ID/www/sites/default/files"
  mkdir "/home/$S_ID/www/sites/default/files/tmp"
  cp "/home/$S_ID/www/sites/default/default.settings.php" "/home/$S_ID/www/sites/default/settings.php" || s_ste 10
  cd "/home/$S_ID/www" || s_ste 10
  chown --recursive $S_ID "/home/$S_ID/www"/*
  chgrp --recursive nogroup "/home/$S_ID/www"/*

  # Set mysql default settings for installation.
  echo "\$db_url = 'mysql://$S_ID:$S_ID@localhost/$S_ID';" >> "/home/$S_ID/www/sites/default/settings.php"
  # Start drupal installation.
  timeout 350 sudo -u $S_ID  drush site-install $2 --locale=en -y --db-url=mysql://$S_ID:$S_ID@localhost/$S_ID --account-name=$S_DUSR --account-pass=$S_DPWD --account-mail="$S_ID-$S_DMAIL_SUFFIX" --site-mail="$S_ID-$S_DMAIL_SUFFIX" --site-name="Drupal $1" || s_ste 10

  # Set temporary path to files dir.
  timeout 350 sudo -u $S_ID  drush vset --always-set file_directory_temp "sites/default/files/tmp"

  # Fixing PHP backwardcompatibility issue.
  sed -i 's/return call_user_func_array($function, $args);/return call_user_func_array($function, \&$args);/g' "/home/$S_ID/www/includes/module.inc"

  # Setup directories and permissions.
  chmod --recursive 555 "/home/$S_ID/www"
  chmod --recursive 777 "/home/$S_ID/www/sites/default/files"
  chown --recursive $S_ID "/home/$S_ID/www"/* || s_ste 10
  chgrp --recursive nogroup "/home/$S_ID/www"/* || s_ste 10
  chown --recursive $S_ID "/home/$S_ID/www/.htaccess" || s_ste 10
  chgrp --recursive nogroup "/home/$S_ID/www/.htaccess" || s_ste 10
}

##
# Installs a drupal core in docroot.
#
# @param $1
#  Major core version.
# @param $2
#  Used core version.
# @param $3 (Optional)
#  Installation profile.
s_install_drupal() {
  case "$1" in
    # Install a drupal 8 core.
    '8')
        if [[ -z "$3" ]]; then
          profile="standard"
        else
          profile=$3
        fi
        s_install_drupal_8 $2 $profile
        ;;
    # Install a drupal 7 core.
    '7')
        if [[ -z "$3" ]]; then
          profile="standard"
        else
          profile=$3
        fi
        s_install_drupal_7 $2 $profile
        ;;
    # Install a drupal 6 core.
    '6')
        if [[ -z "$3" ]]; then
          profile="default"
        else
          profile=$3
        fi
        s_install_drupal_6 $2 $profile
        ;;
    # Unknown version, do at least some basic setups.
    *)
        # Give crazy rights for crazy versions.
        chmod --recursive 777 "/home/$S_ID/www"
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
  esac
}

##
# Installs a drupal module.
#
# @param $1
#  Path to the modules files.
# @param $2
#  Project file-shortname.
# @param $3
#  Major core version.
s_install_module() {
  case "$3" in
    '8')
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
        ;;
    '7')
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
        timeout 350 sudo -u $S_ID drush en $2 -y
        ;;
    '6')
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
        timeout 350 sudo -u $S_ID drush en $2 -y
        ;;
    *)
        s_ste 8
  esac
}

##
# Installs a drupal theme.
#
# @param $1
#  Path to the theme files.
# @param $2
#  Project file-shortname.
# @param $3
#  Major core version.
s_install_theme() {
  case "$3" in
    '8')
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
        ;;
    '7')
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
        timeout 350 sudo -u $S_ID drush en $2 -y
        if [[ -n $(drush pm-list --pipe --status=enabled --no-core | grep "$2") ]]; then
          timeout 350 sudo -u $S_ID drush vset theme_default $2 --yes --always-set
        fi
        ;;
    '6')
        chown --recursive $S_ID "/home/$S_ID/www"/*
        chgrp --recursive nogroup "/home/$S_ID/www"/*
        timeout 350 sudo -u $S_ID drush en $2 -y
        if [[ -n $(drush pm-list --pipe --status=enabled --no-core | grep "$2") ]]; then
          timeout 350 sudo -u $S_ID drush vset theme_default $2 --yes --always-set
        fi
        ;;
    *)
        s_ste 8
  esac
}

##
# Add infobar script snippet to docroot, it'll be automatically appended by php.ini.
#
# @todo ugly php code within shell script - uuhhh.
s_addsnippet() {
  S_TIMESTAMP=$(date +%s)
  echo "<?php
    \$simplytest_snippet = array(
      'id' => \"$S_ID\",
      'created_timestamp' => $S_TIMESTAMP,
      'timeout' => $S_TIMEOUT,
      'admin_user' => \"$S_DUSR\",
      'admin_password' => \"$S_DPWD\",
      'mysql' => \"$S_ID\",
      'project' => \"$S_PROJECT\",
      'version' => \"$S_VERSION\",
      'mail_suffix' => \"$S_DMAIL_SUFFIX\",
    );
    ?>" >> "/home/$S_ID/www/snippet.php"
  cat "$DIRECTORY/snippet.php" >> "/home/$S_ID/www/snippet.php"
}

##
# Rewrites all .info files in the specified directory.
#
# @param $1
#  Directory to rewrite all .info files from.
# @param $2
#  Version value to insert.
# @param $3
#  Project value to insert.
s_rewrite_info_files() {
  # Find all info files within the path.
  local info_files=$(find "$1" -name '*.info')
  for info_file in $info_files; do
    echo "

; Information added by simplytest.me build script
version = \"$2\"
project = \"$3\"
" >> "$info_file"
  done
}

##
# Reads all dependencies out of the specified .info file
#
# @param $1
#  Info file to read dependencies of.
s_read_dependencies() {
  s_info_file_get_all "$1" "dependencies"
  s_info_file_get_all "$1" "test_dependencies"
  s_info_file_get_all "$1" "simplytest_dependencies"
  s_info_file_get "$1" "base theme"
}

##
# Resolves all dependencies within the given path.
#
# @todo Version specific dependencies not fetched #1836012.
#
# @param $1
#  Root path, for searching resolved dependencies in.
# @param $2
#  Path to resolve dependencies for.
#
# For this function we need some static dependency container:
declare -A __RESOLVED_DEPENDENCIES
#
s_resolve_dependencies() {
  cd "$2"
  # Find all info files within the path.
  local info_files=$(find . -name '*.info')
  for info_file in $info_files; do
    # Read out dependencies (dependencies = "", base theme = "").
    local cur_dependencies=$(s_read_dependencies "$info_file")
    # Iterate through all dependencies.
    for cur_dependency in $cur_dependencies; do
      # 1. Make sure it's not empty, 2. Make sure it's not resolved yet, 3. Version definitions aren't modules.
      if [[ -n $cur_dependency && -z ${__RESOLVED_DEPENDENCIES[$cur_dependency]} && ${cur_dependency:0:1} != '(' ]]; then
        cd "$1"
        lg "$(basename $info_file) depends on \"$cur_dependency\""
        # Mark current dependency as resolved.
        __RESOLVED_DEPENDENCIES[$cur_dependency]="1"
        # Dependency is not already resolved? (prevent infinite recursion).
        if [[ -z $(find . -name "$cur_dependency.info") ]]; then
          local cur_real_dependency=$cur_dependency
          local cur_recursive_dependency=$cur_dependency
          # Try to resolve dependency by project alias list (eg. content -> cck).
          if [[ -n ${__PROJECT_ALIASES[$cur_dependency]} ]]; then
            cur_dependency=${__PROJECT_ALIASES[$cur_dependency]}
          fi
          local result=$(timeout 350 drush dl --gitinfofile --pipe -y $cur_dependency)
          # If that failed, the dependency is still missing, try to guess and download the main module.
          # eg. entity_token -> doesn't exist ----> entity|_token -----> entity -> does exist!
          if [[ -z "$result" ]]; then
            cur_dependency=${cur_dependency%_*}
            local cur_recursive_dependency=$cur_dependency
            local result=$(timeout 350 drush dl --gitinfofile --pipe -y $cur_dependency)
          fi
          # If that succeeded, resolve dependencies of the dependency (recursion).
          if [[ -n "$result" ]]; then
            lg "-> Successfully resolved $cur_real_dependency (Project: $cur_dependency)."
            s_resolve_dependencies "$1" $(dirname $(find "$1" -name "$cur_recursive_dependency.info" | sort | head -n 1))
          fi
        fi
        # Back to root dir.
        cd "$2"
      fi
    done
  done
}

##
# Tries to find a main info file within the given path.
#
# @param $1
#  Path to search within.
#
# @return
#  Relative path to the found info file.
s_discover_info_file() {
  find "$1" -name '*.info' | head -n 1
}

##
# Destructs the specified sandbox.
#
# @param $1
#  ID of the environment to destruct.
s_destruct() {
  # We don't want to set any states within destruction.
  s_ste() {
    :
  }

  # Disable vhost.
  lg "Disable vhost.."
  a2dissite $S_ID

  # Delete vhost.
  lg "Delete vhost.."
  rm -f "/etc/apache2/sites-available/$S_ID"

  # Reload config.
  lg "Reload apache config.."
  service apache2 reload

  # Remove user.
  lg "Remove user.."
  userdel --force --remove $S_ID

  # Delete cgi wrapper.
  lg "Delete CGI wrapper.."
  rm -R /var/www/wrappers/$S_ID

  # Delete mysql user and database.
  lg "Cleanup database.."
  s_sqlquery "DROP USER '$S_ID'@'localhost';"
  s_sqlquery "DROP DATABASE $S_ID;"
}

##
# Logs a message to stdout.
#
# @param $1
#  Message to log.
lg() {
  echo "::: `date` :  $1"
}

##
# Sets a progress state on simplytest.me.
#
# @param $1
#  State to set.
#   ENQUEUE           0
#   PREPARE           1
#   DOWNLOAD          2
#   INSTALLING        3
#   FINALIZE          4
#   FINISHED          5
#   TERMINATED        6
#   ERROR_SERVER      7
#   ERROR_PREPARE     8
#   ERROR_DOWNLOAD    9
#   ERROR_INSTALLING 10
s_ste() {
  # Set the new state by querying the site's callback.
  wget -qO /dev/null "$S_CALLBACK/$S_ID/$1"
  # Destroy and exit on error state.
  if [[ $1 -ge 7 ]]; then
     echo "FAILED ON STATE $1"
     s_destruct "$S_ID"
     # Before sending the terminated state, we need some time
     # to make sure the user was informed about the error state.
     # @todo figure out a better solution here, maybe better
     # error logging system
     sleep 30
     # Tell the server that a slot has become free.
     wget -qO /dev/null "$S_CALLBACK/$S_ID/6"
     exit 1
  fi
}

# Figure out which type of project to set up and include the proper source.
case "$S_TYPE" in
  'Drupal core')
      lg "Building a drupal core project."
      source "$DIRECTORY/sources/type-drupal-core"
      ;;
  'Module')
      lg "Building a drupal module project."
      source "$DIRECTORY/sources/type-module"
      ;;
  'Theme')
      lg "Building a drupal theme project."
      source "$DIRECTORY/sources/type-theme"
      ;;
  'Distribution')
      lg "Building a drupal distribution project."
      source "$DIRECTORY/sources/type-distribution"
      ;;
esac