@@ -297,7 +297,13 @@ protected LocalNode(
297297 heartbeatPeriod .getSeconds (),
298298 TimeUnit .SECONDS );
299299
300- Runtime .getRuntime ().addShutdownHook (new Thread (this ::stopAllSessions ));
300+ Runtime .getRuntime ()
301+ .addShutdownHook (
302+ new Thread (
303+ () -> {
304+ stopAllSessions ();
305+ drain ();
306+ }));
301307 new JMXHelper ().register (this );
302308 }
303309
@@ -316,7 +322,6 @@ private void stopTimedOutSession(RemovalNotification<SessionId, SessionSlot> not
316322 }
317323 // Attempt to stop the session
318324 slot .stop ();
319- this .sessionToDownloadsDir .invalidate (id );
320325 // Decrement pending sessions if Node is draining
321326 if (this .isDraining ()) {
322327 int done = pendingSessions .decrementAndGet ();
@@ -473,8 +478,6 @@ public Either<WebDriverException, CreateSessionResponse> newSession(
473478 sessionToDownloadsDir .put (session .getId (), uuidForSessionDownloads );
474479 currentSessions .put (session .getId (), slotToUse );
475480
476- checkSessionCount ();
477-
478481 SessionId sessionId = session .getId ();
479482 Capabilities caps = session .getCapabilities ();
480483 SESSION_ID .accept (span , sessionId );
@@ -513,6 +516,8 @@ public Either<WebDriverException, CreateSessionResponse> newSession(
513516 span .addEvent ("Unable to create session with the driver" , attributeMap );
514517 return Either .left (possibleSession .left ());
515518 }
519+ } finally {
520+ checkSessionCount ();
516521 }
517522 }
518523
@@ -765,6 +770,10 @@ public HttpResponse uploadFile(HttpRequest req, SessionId id) {
765770 public void stop (SessionId id ) throws NoSuchSessionException {
766771 Require .nonNull ("Session ID" , id );
767772
773+ if (sessionToDownloadsDir .getIfPresent (id ) != null ) {
774+ sessionToDownloadsDir .invalidate (id );
775+ }
776+
768777 SessionSlot slot = currentSessions .getIfPresent (id );
769778 if (slot == null ) {
770779 throw new NoSuchSessionException ("Cannot find session with id: " + id );
0 commit comments