listen for when we need to auto-shut down + track open server connections
489051
async function setupServer() {
  return new Promise(async (resolve, reject) => {
    config = config || (await getConfig());
    config.components.individual = [];
    config.prod = true;
    config.enableCache = true;
    config.mode = 'server';
    config.env = 'pwa';
    config.sourceMaps = false;
    config.copy = [];
    config.webpackDevServer = false;
    config.buildDir = path.join(config.wwwDir, 'build-ssr');
    config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');

    app.use(express.static(path.relative(process.cwd(), config.wwwDir)));

    // generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
    server = await app.listen(port);

    app.get('/ssr', function(req, res) {
      res.send(template(html || '', port, webpackStatsGenerated || []));
    });

    // handle cleaning up + shutting down the server instance
    process.on('SIGTERM', shutDownSSRServer);
    process.on('SIGINT', shutDownSSRServer);

    server.on('connection', connection => {
      connections.push(connection);
      connection.on(
        'close',
        // eslint-disable-next-line no-return-assign
        () => (connections = connections.filter(curr => curr !== connection)),
      );
    });

    resolve();
  });
}
1374220
def on_app_shutdown(self, app):
        ''''''

        if self.filewatcher:
            self.filewatcher.stop()
        if self.profile:
            self.upload_page.on_destroy()
            self.download_page.on_destroy()
73565
function() {

    debug('shutting down...');

    var app = this;
    var server = this.server;

    if (!server) return Promise.resolve();

    return co.wrap(function* () {
      yield this.hookFor('shutdown');
    }).call(this).then(function() {
      server.close(function() { debug('goodbye!'); });
    });

  }
580774
private void onServerLinkClose(String hostName)
  {
    ServerHeartbeat server = _root.getServer(hostName);
  
    if (server == null) {
      return;
    }
    
    if (! isHub(server) && ! isHub(_serverSelf)) {
      return;
    }
    
    if (server.onHeartbeatStop()) {
      onServerStop(server);

      if (server.getRack() != null) {
        server.getRack().update();
      }
      
      updateHeartbeats();
    }
  }
1345563
function() {
        // Important to configure later to not use UTC.
        later.date.localTime();

        // Shutdown on schedule.
        if (this.get('shutdownSchedule')) {
            this._shutdownSchedule = later.parse.cron(this.get('shutdownSchedule'));
            if (this._shutdownInterval) {
                this._shutdownInterval.clear();
            }

            this._shutdownInterval = later.setInterval(_.bind(function() {
                logger.info('App shutdown time has arrived. ' + new Date());
                this.set('restartCount', 0);
                this.shutdownApp();
            }, this), this._shutdownSchedule);
        }

        // Shutdown on schedule.
        if (this.get('shutdownPcSchedule')) {
            this._shutdownPcSchedule = later.parse.cron(this.get('shutdownPcSchedule'));
            if (this._shutdownPcInterval) {
                this._shutdownPcInterval.clear();
            }

            this._shutdownPcInterval = later.setInterval(_.bind(function() {
                logger.info('Machine shutdown time has arrived. ' + new Date());
                this.set('restartCount', 0);
                this.shutdownMachine();
            }, this), this._shutdownPcSchedule);
        }

        // Start up on schedule.
        if (this.get('startupSchedule')) {
            this._startupSchedule = later.parse.cron(this.get('startupSchedule'));
            if (this._startupInterval) {
                this._startupInterval.clear();
            }

            this._startupInterval = later.setInterval(_.bind(function() {
                logger.info('App startup time has arrived. ' + new Date());
                if (!$$serverState.get('runApp')) {
                    logger.info('Startup disabled by console.');
                    return;
                }

                this.set('restartCount', 0);
                this.startApp();
            }, this), this._startupSchedule);
        }

        // Start up on schedule.
        if (this.get('restartSchedule')) {
            this._restartSchedule = later.parse.cron(this.get('restartSchedule'));
            if (this._restartInterval) {
                this._restartInterval.clear();
            }

            this._restartInterval = later.setInterval(_.bind(function() {
                if (this._isStartingUp || this._isShuttingDown) {
                    return;
                }

                logger.info('App restart time has arrived. ' + new Date());
                if (!$$serverState.get('runApp')) {
                    logger.info('Startup disabled by console.');
                    return;
                }

                this.set('restartCount', 0);
                this.restartApp();
            }, this), this._restartSchedule);
        }

        // Restart machine on schedule.
        if (this.get('restartPcSchedule')) {
            this._restartPcSchedule = later.parse.cron(this.get('restartPcSchedule'));
            if (this._restartPcInterval) {
                this._restartPcInterval.clear();
            }

            this._restartPcInterval = later.setInterval(_.bind(function() {
                logger.info('Machine restart time has arrived. ' + new Date());

                this.restartMachine();

            }, this), this._restartPcSchedule);
        }

    }
61244
function ProcessWatcher(pid, parent) {
    var self = this;

    this.dead = false;

    // check first if process is alive
    if (exports.alive(pid) === false) {
      process.nextTick(function () {
        self.dead = true;
        self.emit('dead');
      });
      return self;
    }

    // use disconnect to detect parent death
    if (parent && exports.support.disconnect) {
      var listen = function() {
        self.dead = true;
        self.stop();
        self.emit('dead');
      }

      parent.once('disconnect', listen);
      this.stop = parent.removeListener.bind(null, 'disconnect', listen);

      this.on('newListener', function (eventName) {
        if (eventName !== 'cycle') return;

        process.nextTick(function () {
          self.emit('cycle');
        });
      });

      return self;
    }

    // fallback to an setInterval try/catch check
    var timer = setInterval(function () {
      if (exports.alive(pid) === false) {
        self.dead = true;
        self.stop();
        self.emit('dead');
      }
      self.emit('cycle');
    });
    this.stop = clearInterval.bind(null, timer);
  }
577314
def on_shutdown(self, broker):
        """"""
        _v and LOG.debug('%r.on_shutdown()', self)
        if not IS_WSL:
            # #333: WSL generates invalid readiness indication on shutdown()
            self._wsock.shutdown(socket.SHUT_WR)
        self._wsock.close()
        self.transmit_side.close()
728894
def delayed_close(self):
        """"""
        self.state = CLOSING
        self.server.io_loop.add_callback(self.close)
434826
async def on_open(self):
        """"""

        self.__ensure_barrier()
        while self.connected:
            try:
                if self.__lastping > self.__lastpong:
                    raise IOError("Last ping remained unanswered")

                self.send_message("2")
                self.send_ack()
                self.__lastping = time.time()
                await asyncio.sleep(self.ping_interval)
            except Exception as ex:
                LOGGER.exception("Failed to ping")
                try:
                    self.reraise(ex)
                except Exception:
                    LOGGER.exception(
                        "failed to force close connection after ping error"
                    )
                break
980879
def _log_disconnect(self):
        """"""
        if self.logged:
            self.server.stats.on_conn_closed()
            self.logged = False
229123
function(connect) {
      var t = this,
          triggeredBy = t.get('triggeredBy'),
          onTrigger = t.onTrigger.bind(t);

      // Default to listen on changes to all monitors
      if (!triggeredBy) {
        for (var monitorName in t.monitors) {
          t.monitors[monitorName][connect ? 'on' : 'off']('change', t.onTrigger, t);
        }
        return;
      }

      // Process the elements in triggeredBy
      for (var name in triggeredBy) {
        var value = triggeredBy[name];

        // Construct a new cron job
        if (name === 'cron') {
          if (connect) {
            t.cronJob = new Cron.CronJob(value, onTrigger);
          }
          else {
            if (t.cronJob.initiated) {
              clearInterval(t.CronJob.timer);
            }
            else {
              setTimeout(function(){clearInterval(t.cronJob.timer);}, 1000);
            }
          }
        }

        // Set a polling interval
        else if (name === 'interval') {
          if (connect) {
            t.interval = setInterval(onTrigger, value);
          }
          else {
            clearInterval(t.interval);
            t.interval = null;
          }
        }

        // Must be a monitor name
        else {
          t.monitors[name][connect ? 'on' : 'off'](value, onTrigger);
        }
      }
    }
1230034
private static boolean waitForServerDown(int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
      try {
        Socket sock = new Socket("localhost", port);
        try {
          OutputStream outstream = sock.getOutputStream();
          outstream.write("stat".getBytes());
          outstream.flush();
        } finally {
          sock.close();
        }
      } catch (IOException e) {
        return true;
      }

      if (System.currentTimeMillis() > start + timeout) {
        break;
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return false;
  }
213536
async def on_shutdown(app):
    
    # Remove webhook.
    await bot.delete_webhook()

    # Close Redis connection.
    await dp.storage.close()
    await dp.storage.wait_closed()
342982
def on_shutdown(self, broker):
        """"""
        LOG.debug('%r closing CALL_FUNCTION channel', self)
        self._send(
            mitogen.core.Message(
                src_id=mitogen.context_id,
                dst_id=self.remote_id,
                handle=mitogen.core.SHUTDOWN,
            )
        )
1020850
def wait_for_running(self):
        """"""
        self.server_attrs = self.consul.find_running(
                self.server_attrs,
                self.launch_timeout_s,
                )
684163
def listen_init(self):
        """"""
        self.dispatcher = ObjectDispatch(self)
        self.factory = MsgPackProtocolFactory(self.dispatcher)
        self.server = UnixServer(self.loop, self.factory, self.path)
        self.server.start()
254031
def _monitor(last_ping, stop_plugin, is_shutting_down, timeout=5):
    
    _timeout_count = 0
    _last_check = time.time()
    _sleep_interval = 1
    # set _sleep_interval if less than the timeout
    if timeout < _sleep_interval:
        _sleep_interval = timeout
    while True:
        time.sleep(_sleep_interval)
        # Signals that stop_plugin has been called
        if is_shutting_down():
            return
        # have we missed a ping during the last timeout duration
        if ((time.time() - _last_check) > timeout) and ((time.time() - last_ping()) > timeout):
            # reset last_check
            _last_check = time.time()
            _timeout_count += 1
            LOG.warning("Missed ping health check from the framework. " +
                        "({} of 3)".format(_timeout_count))
            if _timeout_count >= 3:
                stop_plugin()
                return
        elif (time.time() - last_ping()) <= timeout:
            _timeout_count = 0