aboutsummaryrefslogtreecommitdiffhomepage
path: root/files/clever-wait-deploy.sh
blob: a95c96fffcb30fb5a48c70967555a4fbf84f9bad (plain) (blame)
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
#!/usr/bin/env bash

set -ueo pipefail

VERBOSE=${VERBOSE:-}
lastCleverActivity=""
timeout=2300 # 100 seconds less than the Ansible tasks' timeout
startTime=$(date +%s)

function cleverActivity {
  lastCleverActivity=$(clever activity)
}

function ensure {
  local lastReturnCode="$?"

  VERBOSE=true
  verbose

  if isNotTimeout
  then
    if [ "$lastReturnCode" == "0" ]
    then
      echo "✓ Deployment done."
    else
      echo "✗ Deployment failed!"
    fi
  else
    echo "⁈ Deployment timeout... Please check clever logs"
    exit 1
  fi
}

function isNotTimeout {
  [ $(($(date +%s) - startTime)) -lt $timeout ]
}

trap ensure EXIT ERR

function deploying {
  checkStatus "$1" "IN PROGRESS"
}

function deployed {
  checkStatus "$1" "OK"
}

function inactive {
  checkStatus "$1" "" "-v"
}

function checkStatus {
  local commit="$1"
  local status="$2"

  cleverActivity
  echo "${lastCleverActivity}" | tail -n1 | grep ${3:+ "${3}"} -q -E "${status}.*DEPLOY.*${commit}"
}

function verbose {
  if [ -n "${VERBOSE}" ]; then
    echo -e "\\nLast clever activity:"
    echo -e "${lastCleverActivity}\\n"
  fi
}

function check {
  local commit="$1"
  local samplingTime=5

  echo "️▫ Waiting for deployment to start..."
  while inactive "$commit" && isNotTimeout
  do
    verbose
    sleep $samplingTime
  done

  # Wait for completion
  echo "▪ Deployment in progress..."
  while deploying "$commit" && isNotTimeout
  do
    verbose
    sleep $samplingTime
  done

  deployed "$commit"
}

function getHeadRev {
  local chdir="$1/.git"

  git --git-dir="$chdir" rev-parse HEAD
}

workdir="$(pwd)"
check "$(getHeadRev "${workdir}")"