Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading
        container
160613
async def handle_student_job_closing(self, container_id, retval):
        
        try:
            self._logger.debug("Closing student %s", container_id)
            try:
                job_id, parent_container_id, socket_id, write_stream = self._student_containers_running[container_id]
                del self._student_containers_running[container_id]
            except asyncio.CancelledError:
                raise
            except:
                self._logger.warning("Student container %s that has finished(p1) was not launched by this agent", str(container_id), exc_info=True)
                return

            # Delete remaining student containers
            if job_id in self._student_containers_for_job:  # if it does not exists, then the parent container has closed
                self._student_containers_for_job[job_id].remove(container_id)

            killed = await self._timeout_watcher.was_killed(container_id)
            if container_id in self._containers_killed:
                killed = self._containers_killed[container_id]
                del self._containers_killed[container_id]

            if killed == "timeout":
                retval = 253
            elif killed == "overflow":
                retval = 252

            try:
                await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": retval, "socket_id": socket_id})
            except asyncio.CancelledError:
                raise
            except:
                pass  # parent container closed

            # Do not forget to remove the container
            try:
                await self._docker.remove_container(container_id)
            except asyncio.CancelledError:
                raise
            except:
                pass  # ignore
        except asyncio.CancelledError:
            raise
        except:
            self._logger.exception("Exception in handle_student_job_closing")
35211
def handle_abort(e)
      if log.level == ::Logger::DEBUG
        raise e
      elsif e.class != SystemExit
        @log.error e.message.red
        @log.info 'cleaning up...'

        task_manager.invoke_task_oneshot(:cleanup_local)
      end
      
      Kernel.exit(true)
    end
637907
private function handleClose()
    {
        foreach ($this->timer as $timer) {
            $this->loop->cancelTimer($timer);
        }

        $connection = $this->connection;

        $this->isConnecting = false;
        $this->isDisconnecting = false;
        $this->isConnected = false;
        $this->connection = null;
        $this->stream = null;

        if ($connection !== null) {
            $this->emit('close', [$connection, $this]);
        }
    }
808968
@Override
    protected void handleClose() throws QueryEvaluationException {
        try {
            super.handleClose();
        }catch(Exception e){
            logger.error("MarkLogicBackgroundGraphResult handleClose() stream closed exception",e);
            throw new QueryEvaluationException(e);
        }
    }
232203
protected void closeFile() {
	if (this.qw != null) {
	    try {
		this.qw.close();
	    }
	    catch (java.io.IOException e) {
		// Exceptionally, it does not make sense to delegate to an
		// ErrorHandler. Since a closed appender is basically dead.
		LogLog.error("Could not close " + qw, e);
	    }
	}
    }
1247485
async def _handle_container(self, message):
        
        self._log.debug('Handling container')
        for inner_message in message.obj.messages:
            await self._process_message(inner_message)
354901
void shutdown() throws IOException {
        synchronized (this) {
            for (BdbEnvironmentInfo envInfo : this.envInfos) {
                try {
                    envInfo.getClassCatalog().close();
                } catch (DatabaseException ignore) {
                    LOGGER.log(Level.SEVERE, "Failure closing class catalog", ignore);
                }
                envInfo.closeAndRemoveAllDatabaseHandles();
                
                try (Environment env = envInfo.getEnvironment()) {
                    if (this.deleteOnExit) {
                        FileUtil.deleteDirectory(env.getHome());
                    }
                }
            }
            this.envInfos.clear();
        }
    }
155856
ManagementRequestHandler<Void, Void> getCloseHandler() {
        return new AbstractAttachmentHandler() {
            @Override
            void handleRequest(TimedStreamEntry entry, FlushableDataOutput output) throws IOException {
                // no-op as AbstractAttachmentHandler will close the entry after calling this
            }

            @Override
            void handleMissingStream(int requestId, int index, FlushableDataOutput output) throws IOException {
                // no-op as there's nothing to do
            }
        };
    }
1072287
def cleanup(self, force=False, delete=False):
        
        # TODO: this method could be part of API, like:
        try:
            self.stop()
        except subprocess.CalledProcessError as stop:
            logger.debug("unable to stop container via stop", stop)
            if not force:
                raise stop
            try:
                self.kill()
            except subprocess.CalledProcessError as kill:
                logger.debug("unable to stop container via kill", kill)
                pass
        if delete:
            self.delete(force=force)
195845
def close(self):
        
        if self.bOwnership and self.value not in (None, INVALID_HANDLE_VALUE):
            if Handle.__bLeakDetection:     # XXX DEBUG
                print("CLOSE HANDLE (%d) %r" % (self.value, self))
            try:
                self._close()
            finally:
                self._value = None
227419
def close(self):
        

        if self._closed:
            raise ValueError('scope is already marked as closed')

        # By letting parent know which symbols this scope has leaked, it
        # will let them reserve all lowest identifiers first.
        if self.parent:
            for symbol, c in self.leaked_referenced_symbols.items():
                self.parent.reference(symbol, c)

        self._closed = True
1285538
function handleFileDelete() {
        var entry = ProjectManager.getSelectedItem();
        Dialogs.showModalDialog(
            DefaultDialogs.DIALOG_ID_EXT_DELETED,
            Strings.CONFIRM_DELETE_TITLE,
            StringUtils.format(
                entry.isFile ? Strings.CONFIRM_FILE_DELETE : Strings.CONFIRM_FOLDER_DELETE,
                StringUtils.breakableUrl(entry.name)
            ),
            [
                {
                    className : Dialogs.DIALOG_BTN_CLASS_NORMAL,
                    id        : Dialogs.DIALOG_BTN_CANCEL,
                    text      : Strings.CANCEL
                },
                {
                    className : Dialogs.DIALOG_BTN_CLASS_PRIMARY,
                    id        : Dialogs.DIALOG_BTN_OK,
                    text      : Strings.DELETE
                }
            ]
        )
            .done(function (id) {
                if (id === Dialogs.DIALOG_BTN_OK) {
                    ProjectManager.deleteItem(entry);
                }
            });
    }
808420
public void finish() throws IOException 
    {
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
            logger.logp(Level.FINE, CLASS_NAME,"finish", "finish");
        } 
        // PM18453 start
        WebContainerRequestState requestState = WebContainerRequestState.getInstance(false);
        if (requestState != null && (Boolean.valueOf((String)requestState.getAttribute("InputStreamEarlyReadCompleted"))).booleanValue()) {
            if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
                logger.logp(Level.FINE, CLASS_NAME,"finish", "Skip read because data has already been read and destroyed.");
            } 
            total=limit;
        }
        // PM18453 End
        else if (!SRTServletResponse.isSkipInputStreamRead() &&  length != -1 )        {
            // if content length set then skip remaining bytes in message body
            long remaining = limit - total;   // PK79219
            while ( remaining > 0 )
            {
                long n = skip(remaining);   // PM03146
                if ( n == 0 )
                {
                    // begin 280584.3    6021: Cleanup of  defect 280584.2    WAS.webcontainer
                    //logger.logp(Level.SEVERE, CLASS_NAME,"finish", nls.getString("Invalid.Content.Length"));
                    // end 280584.3    6021: Cleanup of  defect 280584.2    WAS.webcontainer
                    throw new IOException(nls.getString("Invalid.Content.Length","Invalid content length"));
                }
                remaining -= n;
            }
        }
    }
638422
async def create_student_container(self, job_id, parent_container_id, sockets_path, student_path, systemfiles_path,
                                       course_common_student_path, socket_id,  environment_name, memory_limit,
                                       time_limit, hard_time_limit, share_network, write_stream):
        
        try:
            self._logger.debug("Starting new student container... %s %s %s %s", environment_name, memory_limit, time_limit, hard_time_limit)

            if environment_name not in self._containers:
                self._logger.warning("Student container asked for an unknown environment %s (not in aliases)", environment_name)
                await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": 254, "socket_id": socket_id})
                return

            environment = self._containers[environment_name]["id"]

            try:
                socket_path = path_join(sockets_path, str(socket_id) + ".sock")
                container_id = await self._docker.create_container_student(parent_container_id, environment, share_network,
                                                                           memory_limit, student_path, socket_path,
                                                                           systemfiles_path, course_common_student_path)
            except Exception as e:
                self._logger.exception("Cannot create student container!")
                await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": 254, "socket_id": socket_id})

                if isinstance(e, asyncio.CancelledError):
                    raise

                return

            self._student_containers_for_job[job_id].add(container_id)
            self._student_containers_running[container_id] = job_id, parent_container_id, socket_id, write_stream

            # send to the container that the sibling has started
            await self._write_to_container_stdin(write_stream, {"type": "run_student_started", "socket_id": socket_id})

            try:
                await self._docker.start_container(container_id)
            except Exception as e:
                self._logger.exception("Cannot start student container!")
                await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": 254, "socket_id": socket_id})

                if isinstance(e, asyncio.CancelledError):
                    raise

                return

            # Verify the time limit
            await self._timeout_watcher.register_container(container_id, time_limit, hard_time_limit)
        except asyncio.CancelledError:
            raise
        except:
            self._logger.exception("Exception in create_student_container")
1263795
def close(self):
        """"""
        if self._closing or self._handle.closed:
            return
        elif self._protocol is None:
            raise TransportError('transport not started')
        # If the write buffer is empty, close now. Otherwise defer to
        # _on_write_complete that will close when the buffer is empty.
        if self._write_buffer_size == 0:
            self._handle.close(self._on_close_complete)
            assert self._handle.closed
        else:
            self._closing = True
1053239
public function stream_close()
    {
        @fclose($this->temporaryFileHandle);
        
        // Upload the file?
        if ($this->writeMode) {
            // Make sure the container exists
            if (! $this->containerExists($this->fileName)) {
                $this->getStorageClient($this->fileName)->createContainer($this->getContainerName($this->fileName));
            }
            
            $mimeTypeGuesser = MimeTypeGuesser::getInstance();
            $createBlobOptions = new CreateBlobOptions();
            $createBlobOptions->setBlobContentType($mimeTypeGuesser->guess($this->temporaryFileName));
            
            // Upload the file
            try {
                $result = $this->getStorageClient($this->fileName)->createBlockBlob($this->getContainerName($this->fileName), $this->getFileName($this->fileName), fopen($this->temporaryFileName, "r"), $createBlobOptions);
            } catch (Exception $ex) {
                $this->cleanup();
                
                throw $ex;
            }
        }
        
        $this->cleanup();
    }
393283
void close() {
        if (this.project != null) {
            Util.logger().log(Level.FINE, "Closing Protege project {0}",
                    this.projectIdentifier);

            for (Iterator<ProjectListener> itr =
                         this.projectListeners.iterator(); itr.hasNext(); ) {
                this.project.removeProjectListener(itr.next());
                itr.remove();
            }
            try {
                this.project.dispose();
                Util.logger().fine("Done closing connection.");
            } catch (IllegalStateException e) {
                /*
                 * Protege registers a shutdown hook that is removed when
                 * dispose() is called on a project. However, we might call this
                 * method during an already started shutdown process. See
                 * documentation for java.lang.Runtime.removeShutdownHook. This
                 * exception should be harmless, unless there are other reasons
                 * dispose() could throw this exception?
                 */
                Util.logger().fine("Done closing connection.");
            } finally {
                this.project = null;
            }

        }
    }