If it is an engine, then create a session from it. And indicate that
    this session should be closed after the job done.
326445
def ensure_session(engine_or_session):
    
    if isinstance(engine_or_session, Engine):
        ses = sessionmaker(bind=engine_or_session)()
        auto_close = True
    elif isinstance(engine_or_session, Session):
        ses = engine_or_session
        auto_close = False
    return ses, auto_close
865022
public function engineRestart()
    {
        $this->executeCommandHook(__FUNCTION__, 'before');
        $this->executeExistingCommand('env:restart');
        $this->executeCommandHook(__FUNCTION__, 'after');

        return $this;
    }
1094618
private void registerSession(long index, long timestamp, ServerSessionContext session, ServerSessionContext oldSession, CompletableFuture<Long> future, ThreadContext context) {
    if (!log.isOpen()) {
      context.executor().execute(() -> future.completeExceptionally(new IllegalStateException("log closed")));
      return;
    }

    // Trigger scheduled callbacks in the state machine.
    executor.tick(index, timestamp);

    // Update the state machine context with the register entry's index. This ensures that events published
    // within the register method will be properly associated with the unregister entry's index. All events
    // published during registration of a session are linearizable to ensure that clients receive related events
    // before the registration is completed.
    executor.init(index, Instant.ofEpochMilli(timestamp), ServerStateMachineContext.Type.COMMAND);

    // If the session overrides a previous session, expire the old session.
    if (oldSession != null) {
      oldSession.expire(0);
    }

    // Register the session and then open it. This ensures that state machines cannot publish events to this
    // session before the client has learned of the session ID.
    for (SessionListener listener : executor.context().sessions().listeners) {
      if (oldSession != null) {
        listener.expire(oldSession);
        listener.close(oldSession);
      }
      listener.register(session);
    }
    session.open();

    // Calculate the last completed index.
    long lastCompleted = calculateLastCompleted(index);

    // Once register callbacks have been completed, ensure that events published during the callbacks are
    // received by clients. The state machine context will generate an event future for all published events
    // to all sessions.
    executor.commit();
    context.executor().execute(() -> {
      setLastCompleted(lastCompleted);
      future.complete(index);
    });
  }
781064
public void engineReloaded(Object objectSent) {

    	final JsMessagingEngine engine = (JsMessagingEngine)objectSent;
    	
        final String methodName = "engineReloaded";
        if (TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, engine);
        }

        RELOADING_MESSAGING_ENGINES.remove(engine.getUuid().toString());

        // Get listeners to notify
        final Set listeners = getListeners(engine.getBusName());

        // Notify listeners
        for (final Iterator iterator = listeners.iterator(); iterator.hasNext();) {

            final SibRaMessagingEngineListener listener = (SibRaMessagingEngineListener) iterator
                    .next();
            listener.messagingEngineReloaded(engine);

        }

        if (TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }
391762
def close(self):
        """"""
        if isinstance(self._session, requests.Session):
            self._session.close()
1283162
@Override
    public void engineReloaded(Object messagingEngine)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "engineReloaded");

        // Defect 337421.1
        // Our config has been reloaded so we need to essentially
        // re-initialize so that the next time that we run start()
        // we pick up any changes.
        initialize((JsMessagingEngine) messagingEngine, true);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "engineReloaded");
    }
889378
def create_database_session(engine):
    """"""

    try:
        Session = sessionmaker(bind=engine)
        return Session()
    except OperationalError as e:
        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
1262323
private void executeClose() {
        if (initState_ != SESSION_STATE.UNINITIALISED) {
            if (!hasNetwork_) {
                // if there's no network connectivity, purge the old install/open
                ServerRequest req = requestQueue_.peek();
                if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) {
                    requestQueue_.dequeue();
                }
            } else {
                if (!requestQueue_.containsClose()) {
                    ServerRequest req = new ServerRequestRegisterClose(context_);
                    handleNewRequest(req);
                }
            }
            initState_ = SESSION_STATE.UNINITIALISED;
        }
    }
1197958
def finish(self):
        ""
        log.debug("Session disconnected.")
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except: pass
        self.session_end()
1282561
def _shutdown(self, message=None, code=0):
        """"""
        if self._shutdown_complete:
            # Make sure we don't accidentally re-run the all cleanup
            sys.exit(code)

        if self.shutdown_callback is not None:
            # Call the shutdown callback with a message suitable for
            # logging and the exit code
            self.shutdown_callback(message, code)

        if self.pidfile is not None:
            self._close_pidfile()

        self._shutdown_complete = True
        sys.exit(code)
779474
function _endSession() {
        if (!hintList) {
            return;
        }
        hintList.close();
        hintList = null;
        codeHintOpened = false;
        keyDownEditor = null;
        sessionProvider = null;
        sessionEditor = null;
        if (deferredHints) {
            deferredHints.reject();
            deferredHints = null;
        }
    }
421098
public static function Close () {
		if (!static::GetStarted()) return;
		register_shutdown_function(function () {
			foreach (static::$instances as & $instance)
				if (count((array) $_SESSION[$instance->__name]) === 0)
					// if there is nothing in namespace - destroy it. It's useless.
					$instance->Destroy();
			$metaKey = static::SESSION_METADATA_KEY;
			$_SESSION[$metaKey] = serialize(static::$meta);
			@session_write_close();
		});
	}
194366
public void onClose(Session session, CloseReason closeReason) {
        if (getOnCloseHandle() != null) {
            callMethod(getOnCloseHandle(), getOnCloseParameters(), session, true, closeReason);
        }
    }
746373
public void destroy() {
		if (configuration != null) L.d(LOG_DESTROY);
		stop();
		configuration.diskCache.close();
		engine = null;
		configuration = null;
	}
101016
function sessionCreated(err, session) {
  var agentInfo = {name: ping + "er", title: "a " + ping + "er" }

  session.createAgent(agentInfo, function(err, agent) {
    console.log(ping + " agent created")
    Agent = agent
  })

  session.on("ragentCreated", function(ragent) {
    ragentCreated(ragent, "created")
  })

  session.getRemoteAgents(function(err, ragents){
    ragents.forEach(function(ragent) {
      ragentCreated(ragent, "existed")
    })
  })
}
355503
def close(self):
        '''
        
        '''
        if self._closed:
            return
        self._closed = True
        self._worker_thread.work_queue.put(self.aiohttp_session.close())
        self._worker_thread.work_queue.put(self.worker_thread.sentinel)
        self._worker_thread.join()
1358685
public final synchronized void shutdown() {
        if (DESTROYED_UPDATER.compareAndSet(this, 0, 1)) {
            engineMap.remove(ssl);
            SSL.freeSSL(ssl);
            ssl = networkBIO = 0;

            isInboundDone = outboundClosed = true;
        }

        // On shutdown clear all errors
        SSL.clearError();
    }