ClickHouse/base/poco/Foundation/src/PurgeStrategy.cpp
Robert Schulze b79ead9c84
Move poco to base/poco/ (#46075)
* Replicate poco into base/poco/

* De-register poco submodule

* Build poco from ClickHouse

* Exclude poco from stylecheck

* Exclude poco from whitespace check

* Exclude poco from typo check

* Remove x bit from sources/headers (the style check complained)

* Exclude poco from duplicate include check

* Fix fasttest

* Remove contrib/poco-cmake/*

* Simplify poco build descriptions

* Remove poco stuff not used by ClickHouse

* Glob poco sources

* Exclude poco from clang-tidy
2023-02-08 12:04:11 +01:00

155 lines
2.4 KiB
C++

//
// PurgeStrategy.cpp
//
// Library: Foundation
// Package: Logging
// Module: FileChannel
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/PurgeStrategy.h"
#include "Poco/Path.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/Timestamp.h"
namespace Poco {
//
// PurgeStrategy
//
PurgeStrategy::PurgeStrategy()
{
}
PurgeStrategy::~PurgeStrategy()
{
}
void PurgeStrategy::list(const std::string& path, std::vector<File>& files)
{
Path p(path);
p.makeAbsolute();
Path parent = p.parent();
std::string baseName = p.getFileName();
baseName.append(".");
DirectoryIterator it(parent);
DirectoryIterator end;
while (it != end)
{
if (it.name().compare(0, baseName.size(), baseName) == 0
&& it.name().find(".incomplete") == std::string::npos)
{
files.push_back(*it);
}
++it;
}
}
//
// PurgeByAgeStrategy
//
PurgeByAgeStrategy::PurgeByAgeStrategy(const Timespan& age): _age(age)
{
}
PurgeByAgeStrategy::~PurgeByAgeStrategy()
{
}
void PurgeByAgeStrategy::purge(const std::string& path)
{
std::vector<File> files;
list(path, files);
for (std::vector<File>::iterator it = files.begin(); it != files.end(); ++it)
{
if (it->getLastModified().isElapsed(_age.totalMicroseconds()))
{
it->remove();
}
}
}
//
// PurgeByCountStrategy
//
PurgeByCountStrategy::PurgeByCountStrategy(int count): _count(count)
{
poco_assert(count > 0);
}
PurgeByCountStrategy::~PurgeByCountStrategy()
{
}
void PurgeByCountStrategy::purge(const std::string& path)
{
std::vector<File> files;
list(path, files);
while (files.size() > _count)
{
std::vector<File>::iterator it = files.begin();
std::vector<File>::iterator purgeIt = it;
Timestamp purgeTS = purgeIt->getLastModified();
++it;
while (it != files.end())
{
Timestamp md(it->getLastModified());
if (md <= purgeTS)
{
purgeTS = md;
purgeIt = it;
}
++it;
}
purgeIt->remove();
files.erase(purgeIt);
}
}
void PurgeOneFileStrategy::purge(const std::string& path)
{
std::vector<File> files;
list(path, files);
if (files.empty())
{
File(path).setSize(0);
return;
}
auto purge_it = files.begin();
auto it = files.begin();
for (++it; it != files.end(); ++it)
if (it->getLastModified() < purge_it->getLastModified())
purge_it = it;
purge_it->remove();
}
} // namespace Poco