Archive the history log and all results/log files.

    After archive is created optionally clear the history log.
511398
def archive(context, clear_log, items, path, name):
    
    history_log = context.obj['history_log']
    no_color = context.obj['no_color']

    with open(history_log, 'r') as f:
        # Get history items
        history_items = f.readlines()

    if items:
        # Split comma separated list and cast indices to integer.
        items = [int(item) for item in items.split(',')]

        lines = []
        for index in items:
            lines.append(history_items[len(history_items) - index])
        history_items = lines

    with tempfile.TemporaryDirectory() as temp_dir:
        for item in history_items:
            # Copy log and results file,
            # update results file with relative path.
            archive_history_item(item, temp_dir, no_color)

        file_name = ''.join([name, '.tar.gz'])
        archive_path = os.path.join(path, file_name)

        with tarfile.open(archive_path, "w:gz") as tar:
            # Create tar archive
            tar.add(temp_dir, arcname='results')

    if clear_log:
        if items:
            # Remove duplicates to prevent unwanted deletion.
            items = list(set(items))

            # Must delete items from bottom to top of history file
            # to preserve indices. (Index 0 is last item in file)
            items.sort()
            for index in items:
                context.invoke(delete, item=index)
        else:
            context.invoke(clear)

    click.echo(
        'Exported results history to archive: {0}'.format(archive_path)
    )
839521
public void close() {
        for (Iterator<Archive> i = archives.values().iterator(); i.hasNext(); ) {
            Archive a = i.next();
            i.remove();
            try {
                a.close();
            } catch (IOException e) {
            }
        }
    }
790269
def clean(self):
        
        logger.info('Cleaning up archive')
        shutil.move(
            os.path.join(
                self.data_dir,
                'var/IRS/data/scripts/pofd/download/FullDataFile.txt'
            ),
            self.final_path
        )

        shutil.rmtree(os.path.join(self.data_dir, 'var'))
        os.remove(self.zip_path)
526321
private function clearLogs()
    {
        foreach ($this->logger->getHandlers() as $handler) {
            if ($handler instanceof FingersCrossedHandler) {
                $handler->clear();
            }
        }
    }
1035756
def cleanup_log_files(outputfile):
    """"""
    d = os.path.dirname(os.path.abspath(outputfile))
    logfiles = [f for f in os.listdir(d) if f.endswith('ogg.log')]
    for f in logfiles:
        os.remove(f)
380964
public function clean() {
    $this->logger->info('%name started.', ['%name' => get_class($this)]);

    $dataToRemove = $this->wrapper->getDataToRemove();
    foreach ($dataToRemove as $locationId => $locationData) {
      foreach ($locationData as $classId) {
        $this->mappingRepo->removeByLocationIdAndClassId($locationId, $classId);
      }
    }

    $this->logger->info('%name finished.', ['%name' => get_class($this)]);
  }
20123
public function purgeAll() {
		if ($this->log != null) {
			if ($this->log instanceof LoggerInterface) {
				$this->log->info("Purging all data from no-cache. Nothing to purge.");
			} else {
				$this->log->trace("Purging all data from no-cache. Nothing to purge.");
			}
		}
	}
769954
private void cleanUpHistoryTree(HistoryNode node) {
    if (node == null || node.children == null) {
      return;
    }
    
    Iterator<HistoryNode> iterator = node.children.iterator();
    while (iterator.hasNext()) {
      HistoryNode child = iterator.next();
      
      // clean up child
      cleanUpHistoryTree(child);
      
      // clean up current node;
      if (shouldRemoveNode(child)) {
        iterator.remove();
      }
    }
  }
163565
static void cleanup() {
        LOGGER.entering();

        for (String temp : files) {
            new File(temp).delete();
        }

        // Cleaning up the files list
        files.clear();
        LOGGER.exiting();
    }
681469
def _write_history(self):
        """"""
        if self.data['history_file'] is None:
            return
        contents = '\n'.join(self.data['history_lines'])
        history = self.data['history_file']
        open(history, 'w').write(contents)
        logger.info("History file %s updated.", history)
1015875
public function clear()
    {
        $this->id = null;
        $this->file = null;
        $this->person_id = null;
        $this->visible = null;
        $this->position = null;
        $this->created_at = null;
        $this->updated_at = null;
        $this->alreadyInSave = false;
        $this->clearAllReferences();
        $this->applyDefaultValues();
        $this->resetModified();
        $this->setNew(true);
        $this->setDeleted(false);
    }
1327014
public function clear()
    {
        $this->id = null;
        $this->created_at = null;
        $this->updated_at = null;
        $this->alreadyInSave = false;
        $this->clearAllReferences();
        $this->resetModified();
        $this->setNew(true);
        $this->setDeleted(false);
    }
307091
private void cleanLogs() throws Exception {
        File logsDir = new File(serverOutputDir.getAbsolutePath(), "logs");
        if (logsDir.exists()) {
            cleanDir(logsDir);
            log(MessageFormat.format(messages.getString("info.element.cleaned"), "logs"));
        } else {
            log(MessageFormat.format(messages.getString("info.directory.noexist"), logsDir.getAbsolutePath()));
        }
    }
633562
def delete_archive_file(self):
        
        logger.debug("Deleting %s", self.archive_tmp_dir)
        shutil.rmtree(self.archive_tmp_dir, True)
902801
def clear_old_log_entries():
    
    if hasattr(settings, 'DJANGO_CRON_DELETE_LOGS_OLDER_THAN'):
        delta = timedelta(days=settings.DJANGO_CRON_DELETE_LOGS_OLDER_THAN)
        CronJobLog.objects.filter(end_time__lt=get_current_time() - delta).delete()
25646
protected function afterDelete()
    {
        parent::afterDelete();
        $this->clearSortingList();

        if ($this->obElement->active) {
            TaxListStore::instance()->active->clear();
        }
    }
1246835
private void cleanUpHistory() {
    long oldestAllowedTimestamp = System.currentTimeMillis() - historyLength;
    int trashedNotifications = 0;
    
    if (LOG.isDebugEnabled()) {
      LOG.debug("History cleanup: Checking old notifications to remove from history list ...");
    }
    
    HistoryTreeEntry key = new HistoryTreeEntry(oldestAllowedTimestamp, 0, (byte)0);
    int notificationsCount = 0;
    historyLock.writeLock().lock();
    try {
      notificationsCount = orderedHistoryList.size();
      LOG.warn("History cleanup: size of the history before cleanup: " + notificationsCount);

      if (!historyLimitDisabled && notificationsCount > historyLimit) {
        LOG.warn("History cleanup: Reached physical limit. Number of stored notifications: " + 
            notificationsCount + ". Clearing ...");
      }
      
      int index = Collections.binarySearch(orderedHistoryList, key, comparatorByTS);
      int toDeleteByTS = index >= 0 ? index : - (index + 1);
      int toDeleteByLimit = historyLimitDisabled ? 0 : notificationsCount - (int)historyLimit;
      toDeleteByLimit = toDeleteByLimit > 0 ? toDeleteByLimit : 0;
      
      int toDelete = Math.max(toDeleteByTS, toDeleteByLimit);
      
      // Delete items which are too old
      if (toDelete > 0) {
        LOG.warn("History cleanup: number of the history to cleanup: " + toDelete);
        for (int i = 0; i < toDelete; i++) {
          orderedHistoryList.get(i).removeFromTree();
        }
        
        orderedHistoryList.subList(0, toDelete).clear();
        
        if (toDeleteByLimit > toDeleteByTS) {
          // If we delete a notification because we don't have space left
          trashedNotifications ++;
        }
        notificationsCount = orderedHistoryList.size();
        LOG.warn("History cleanup: size of the history after cleanup: " + notificationsCount);
        
        // clean up history tree, remove the node that has no children and
        // no notifications associated with them.
        cleanUpHistoryTree(historyTree);
      }
      
    } finally {
      historyLock.writeLock().unlock();
    }
    
    core.getMetrics().trashedHistoryNotifications.inc(trashedNotifications);
    core.getMetrics().historySize.set(notificationsCount);
    core.getMetrics().historyQueues.set(historyQueuesCount);
  }