# cloud-init-no-net
# the purpose of this job is
#  * to block running of cloud-init until all network interfaces
#    configured in /etc/network/interfaces are up
#  * timeout if they all do not come up in a reasonable amount of time
start on mounted MOUNTPOINT=/ and stopped cloud-init-local
stop on static-network-up
task

console output

script
   set +e  # you cannot trap TERM reliably with 'set -e'
   SLEEP_CHILD=""

   static_network_up() {
      local emitted="/run/network/static-network-up-emitted"
      # /run/network/static-network-up-emitted is written by
      # upstart (via /etc/network/if-up.d/upstart). its presense would
      # indicate that static-network-up has already fired.
      [ -e "$emitted" -o -e "/var/$emitted" ]
   }
   msg() {
      local uptime="" idle=""
      if [ -r /proc/uptime ]; then
         read uptime idle < /proc/uptime
      fi
      echo "$UPSTART_JOB${uptime:+[${uptime}]}:" "$1"
   }

   handle_sigterm() {
      # if we received sigterm and static networking is up then it probably
      # came from upstart as a result of 'stop on static-network-up'
      if [ -n "$SLEEP_CHILD" ]; then
          if ! kill $SLEEP_CHILD 2>/dev/null; then
              [ ! -d "/proc/$SLEEP_CHILD" ] ||
                  msg "hm.. failed to kill sleep pid $SLEEP_CHILD"
          fi
      fi
      if static_network_up; then
         msg "static networking is now up"
         exit 0
      fi
      msg "recieved SIGTERM, networking not up"
      exit 2
   }

   dowait() {
      [ $# -eq 2 ] || msg "waiting $1 seconds for network device"
      sleep "$1" &
      SLEEP_CHILD=$!
      wait $SLEEP_CHILD
      SLEEP_CHILD=""
   }

   trap handle_sigterm TERM

   # static_network_up already occurred
   static_network_up && exit 0

   dowait 5 silent
   dowait 10
   dowait 115
   msg "gave up waiting for a network device."
   : > /var/lib/cloud/data/no-net
end script
