最近,我需要创建一个Groovy脚本来删除Linux机器中的某些目录。原因如下:
- 我们有一台服务器来执行预定的作业。从一个数据库到另一个数据库的ETL之类的工作,从文件到数据库的工作,等等。服务器激活客户端,这些客户端位于我们要对其执行操作的机器中。大多数(几乎所有)作业都是用普通脚本编写的。
- CI流程的一部分是将WAR部署到专用服务器中。然后,我们有了一个脚本,该脚本除其他外还使用软链接将“ webapps”定向到新创建的目录。该部署每小时进行一次,这将很快填满专用服务器。 因此,我需要创建一个脚本来检查正确位置中的所有目录并删除旧目录。我决定保留最新的4个目录。当前是脚本中的可变数字。如果我想要/需要,可以将其作为输入参数。但是我决定从简单开始。
我决定做的很简单:
在已知位置列出所有前缀为webapp的目录
按时间,降序对它们进行排序,从第四个索引开始执行删除操作。
def numberOfDirectoriesToKeep = 4
def webappsDir = new File('/usr/local/tomcat/tomcat_aps')
def webDirectories = webappsDir.listFiles().grep(~/.*webapps_.*/)
def numberOfWeappsDirectories = webDirectories.size();
if (numberOfWeappsDirectories >= numberOfDirectoriesToKeep) {
webDirectories.sort{it.lastModified() }.reverse()[numberOfDirectoriesToKeep..numberOfWeappsDirectories-1].each {
logger.info("Deleteing ${it}");
// here we'll delete the file. First try was doing a Java/groovy command of deleting directories
}
} else {
logger.info("Too few web directories")
}
没用!!!文件未删除。 碰巧代理程序以与运行tomcat的用户不同的身份运行。该代理无权删除目录。
我的解决方案是使用运行shell命令sudo。
长话短说,这是完整的脚本:
import org.slf4j.Logger
import com.my.ProcessingJobResult
def Logger logger = jobLogger
//ProcessingJobResult is proprietary
def ProcessingJobResult result = jobResult
try {
logger.info("Deleting old webapps from CI - START")
def numberOfDirectoriesToKeep = 4 // Can be externalized to input parameter
def webappsDir = new File('/usr/local/tomcat/tomcat_aps')
def webDirectories = webappsDir.listFiles().grep(~/.*webapps_.*/)
def numberOfWeappsDirectories = webDirectories.size();
if (numberOfWeappsDirectories >= numberOfDirectoriesToKeep) {
webDirectories.sort{it.lastModified() }.reverse()[numberOfDirectoriesToKeep..numberOfWeappsDirectories-1].each {
logger.info("Deleteing ${it}");
def deleteCommand = "sudo -u tomcat rm -rf " + it.toString();
deleteCommand.execute();
}
} else {
logger.info("Too few web directories")
}
result.status = Boolean.TRUE
result.resultDescription = "Deleting old webapps from CI ended"
logger.info("Deleting old webapps from CI - DONE")
} catch (Exception e) {
logger.error(e.message, e)
result.status = Boolean.FALSE
result.resultError = e.message
}
return result
顺便说一句,有一个较小的索引错误,由于我们总是有更多目录,所以我决定不修复。
技术类文章精选
- java一行代码打印心形
- Linux性能监控软件netdata中文汉化版
- 接口测试代码覆盖率(jacoco)方案分享
- 性能测试框架
- 如何在Linux命令行界面愉快进行性能测试
- 图解HTTP脑图
- 如何测试概率型业务接口
- httpclient处理多用户同时在线
- 将swagger文档自动变成测试代码
- 五行代码构建静态博客
- httpclient如何处理302重定向
- 基于java的直线型接口测试框架初探
- Tcloud 云测平台--集大成者
- 如何测试概率型业务接口
- python plotly处理接口性能测试数据方法封装
- 单点登录性能测试方案
非技术文章精选
- 为什么选择软件测试作为职业道路?
- 成为杰出Java开发人员的10个步骤
- 写给所有人的编程思维
- 自动化测试的障碍
- 自动化测试的问题所在
- 测试之《代码不朽》脑图
- 成为优秀自动化测试工程师的7个步骤
- 优秀软件开发人员的态度
- 如何正确执行功能API测试
- 未来10年软件测试的新趋势-上
- 未来10年软件测试的新趋势-上
- 自动化测试解决了什么问题
- 17种软件测试人员常用的高效技能-上
- 17种软件测试人员常用的高效技能-下
- 手动测试存在的重要原因