yhkylin-backup-tools/common/utils.cpp

371 lines
11 KiB
C++
Raw Normal View History

2021-08-06 10:20:03 +08:00
#include "utils.h"
#include <QByteArray>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QRegularExpression>
2021-08-17 10:07:35 +08:00
#include <QThread>
2021-08-06 10:20:03 +08:00
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "mylittleparse.h"
QString Utils::m_sysRootPath = "/";
/**
* @brief initSysRootPath,
* @param qsAppPath
* @note
* /usr/bin中
* 1. grub引导中根目录为/root
* 2. livecd中根目录为/target
* 3. 使/
*/
void Utils::initSysRootPath(const QString& qsAppPath)
{
QString sysRootPath = qsAppPath;
if (sysRootPath.contains(DEFAULT_APP_PATH)) {
sysRootPath.replace(DEFAULT_APP_PATH, "/");
} else {
sysRootPath = "/";
}
m_sysRootPath = sysRootPath;
}
/**
* @brief customMessageHandler
* @param type debug等
* @param context
* @param msg
*/
void Utils::customMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
QByteArray localMsg = msg.toLocal8Bit();
QString strMsg("");
switch (type) {
case QtDebugMsg:
strMsg = QString("[Debug]");
break;
case QtWarningMsg:
strMsg = QString("[Warning]");
break;
case QtCriticalMsg:
strMsg = QString("[Critical]");
break;
case QtFatalMsg:
strMsg = QString("[Fatal]");
break;
default:
strMsg = QString("[Debug]");
break;
}
// 设置输出信息格式
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
2021-08-17 10:07:35 +08:00
QString strMessage = strMsg + QString("DateTime:%1 ThreadId:%2 Message:%3 File:%4(%5)")
.arg(strDateTime).arg(QString::number(quintptr(QThread::currentThreadId()))).arg(localMsg.constData()).arg(context.file).arg(context.line);
2021-08-06 10:20:03 +08:00
std::cout << strMessage.toUtf8().data() << std::endl;
// 输出信息至文件中(读写、追加形式)
2021-08-17 10:07:35 +08:00
QString fileName = m_sysRootPath + PROC_LOG;
2021-08-06 10:20:03 +08:00
fileName.replace("//", "/");
QFile file(fileName);
file.open(QIODevice::ReadWrite | QIODevice::Append);
QTextStream stream(&file);
stream << strMessage << endl;
file.flush();
file.close();
}
/**
* @brief
* @param frontUidid
* @return
* @note 使QLockFile
* /tmp/lock路径下的锁文件xx程序在运行不允许关机等
*/
int Utils::lockProgram(int frontUid)
{
2021-08-17 10:07:35 +08:00
QDir dir(LOCK_FILE_PATH);
2021-08-06 10:20:03 +08:00
if (!dir.exists()) {
2021-08-17 10:07:35 +08:00
dir.mkdir(LOCK_FILE_PATH);
chmod(LOCK_FILE_PATH, S_IRWXU | S_IRWXG | S_IRWXO);
2021-08-06 10:20:03 +08:00
}
int lock_file_fd = ::open(LOCK_FILE, O_CREAT | O_RDWR, 0666);
if (0 > lock_file_fd) {
return -2;
}
fchmod(lock_file_fd, S_IRWXU | S_IRWXG | S_IRWXO);
int lock_ret = flock(lock_file_fd, LOCK_EX | LOCK_NB);
if (0 > lock_ret) {
return -11;
}
ftruncate(lock_file_fd, 0);
char write_string[PID_STRING_LEN] = { 0 };
snprintf(write_string, PID_STRING_LEN, "%d\n%s\n", frontUid, BACKUP_CLI_NAME);
write(lock_file_fd, write_string, strlen(write_string));
fdatasync(lock_file_fd);
return lock_file_fd;
}
/**
* @brief
* @param lock_file_fd
* @return 01
*/
int Utils::unLockProgram(int lock_file_fd)
{
int lock_ret = flock(lock_file_fd, LOCK_UN);
if (lock_ret < 0) {
qCritical("unlock fail!");
return 1;
}
qDebug("unlock success!");
rmLockFile();
return 0;
}
/**
* @brief
* @return bool
*/
bool Utils::rmLockFile()
{
bool res = QFile::remove(LOCK_FILE);
if (!res)
qCritical() << QString("remove %s fail").arg(LOCK_FILE);
return res;
}
/**
* @brief /etc/.bootinfo是否存在并可读UUID等信息
* @return bool
*/
bool Utils::checkBootInfoExists()
{
QString bootinfoPath = Utils::m_sysRootPath + BOOTINFO_PATH;
bootinfoPath.replace("//", "/");
QFile bootinfoFile(bootinfoPath);
if (!bootinfoFile.exists()) {
qCritical("%s is not exists!", qUtf8Printable(bootinfoPath));
return false;
}
if (!bootinfoFile.open(QIODevice::ReadOnly)) {
qCritical("%s file can't open!", qUtf8Printable(bootinfoPath));
return false;
}
bootinfoFile.close();
return true;
}
/**
* @brief UUID
2021-08-17 10:07:35 +08:00
* @return UUID
2021-08-06 10:20:03 +08:00
*/
QString Utils::getBackupPartitionUuid()
{
QString bootinfoPath = Utils::m_sysRootPath + BOOTINFO_PATH;
bootinfoPath.replace("//", "/");
MyLittleParse parse(bootinfoPath);
QString restoreUuid;
parse.find("RECOVERY_DEV_UUID", restoreUuid);
return restoreUuid;
}
/**
* @brief
* @param path
*/
void Utils::mkdir(const QString& path)
{
QDir dir(path);
if (!dir.exists())
dir.mkdir(path);
}
/**
* @brief
* @param path
* @return bool
*/
bool Utils::mkpath(const QString& path)
{
QDir dir(path);
if (!dir.exists()) {
return dir.mkpath(path);
}
return true;
}
/**
* @brief
* @param excludes
*/
void Utils::excludeFstabBindPath(QStringList &excludes)
{
QString fstabPath = Utils::m_sysRootPath + FSTAB_PATH;
fstabPath.replace("//", "/");
QFile file(fstabPath);
if (!file.open(QIODevice::ReadOnly))
return;
QTextStream in(&file);
while (!in.atEnd()) {
const QString &line = in.readLine();
if (line.startsWith("#"))
continue ;
if (line.startsWith("UUID="))
continue ;
if (line.isEmpty())
continue ;
if (!line.contains("bind"))
continue ;
// 配置文件/etc/fstab每行6个域: <file system> <mount point> <type> <options> <dump> <pass>, 形如:
// UUID=232f5fb4-53e0-46b9-ba9b-22bfec64f2a2 /boot ext4 rw,relatime 0 0
QStringList list = line.split(QRegularExpression("[ \t]"));
QStringList fields;
for (int i = 0; i < list.size(); ++i) {
QString field = list.at(i);
field = field.trimmed();
if (field.isEmpty())
continue;
fields << field;
}
// 配置文件/etc/fstab每行6个域第二个域为挂载路径
if (6 == fields.size())
excludes << fields.at(1);
}
file.close();
}
/**
2021-08-17 10:07:35 +08:00
* @brief rsync --exclude-from排除路径规则文件
2021-08-06 10:20:03 +08:00
* @return
*/
bool Utils::generateExcludePathsFile()
{
QString excludeFile = Utils::m_sysRootPath + EXCLUDE_FILE_PATH;
excludeFile.replace("//", "/");
QFile excludePathFile(excludeFile);
// 暂时改为每次都重写文件内容,以便能随版本更新排除路径
if (!excludePathFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qCritical("%s create failed", qUtf8Printable(excludeFile));
return false;
}
QTextStream in(&excludePathFile);
in << "/backup" << endl; //分区
in << "/boot/efi" << endl;
2021-08-17 10:07:35 +08:00
in << "/cdrom" << endl;
in << "/dev" << endl;
2021-08-06 10:20:03 +08:00
// efi原始目录在/boot/efi备份到目标目录为/efi下再还原时已经单独处理了批量还原时应该屏蔽此目录
in << "/efi" << endl;
// 安全模块会将文件/usr/share/kysec-utils/data/readonly_list中的文件列表限制只读无法修改、备份包含扩展属性时、删除等
// 现在里面仅有/etc/uid_list先暂时排除掉等后续安全模块有其它保护方案后再进一步修改
in << "/etc/uid_list" << endl;
2021-08-17 10:07:35 +08:00
in << "/ghost" << endl; //ghost镜像文件
in << "/lost+found" << endl;
in << "/media" << endl;
in << "/mnt" << endl;
in << "/proc" << endl;
in << "/run" << endl;
in << "/swap_file" << endl;
in << "/sys" << endl; //添加*(/sys/*),表示如果/sys目录不存在则会拷贝/sys但不会拷贝/sys下的内容
in << "/tmp" << endl;
2021-08-19 19:24:49 +08:00
in << "/var/lib/docker/overlay2" << endl;
2021-08-06 10:20:03 +08:00
// 安卓兼容的这个里面很多文件都是设置了特殊扩展文件属性lsetxattr无法设置成功听取安卓兼容模块同事的意见不用管这个文件夹其实是从home下挂载的
in << "/var/lib/kmre" << endl;
2021-08-17 10:07:35 +08:00
in << "/var/lib/udisks2" << endl;
2021-08-06 10:20:03 +08:00
in << "/var/log" << endl;
// 系统安装后有的会将/data/home /data/root挂载到的/home /root上实际文件是存放在/data/home /data/root下面
QStringList excludes;
Utils::excludeFstabBindPath(excludes);
for (const QString& item : excludes) {
in << item << endl;
}
in.flush();
excludePathFile.close();
return true;
}
2021-08-17 10:07:35 +08:00
/**
* @brief
* @param
* @return true,false,
*/
bool Utils::isDirExist(const QString& fullDirName)
{
QDir dir(fullDirName);
if (dir.exists())
return true;
return false;
}
/**
* @brief , rsync --exclude-from排除路径规则文件中读取
* @return
*/
QStringList Utils::getFromExcludePathsFile()
{
QString excludeFile = Utils::m_sysRootPath + EXCLUDE_FILE_PATH;
excludeFile.replace("//", "/");
QFile excludePathFile(excludeFile);
if (!excludePathFile.open(QIODevice::ReadOnly)) {
QStringList list;
list << "/backup";
list << "/boot/efi";
list << "/cdrom";
list << "/dev";
list << "/efi";
list << "/etc/uid_list";
list << "/ghost";
list << "/lost+found";
list << "/media";
list << "/mnt";
list << "/proc";
list << "/run";
list << "/swap_file";
list << "/sys";
list << "/tmp";
2021-08-19 19:24:49 +08:00
list << "/var/lib/docker/overlay2";
2021-08-17 10:07:35 +08:00
list << "/var/lib/kmre";
list << "/var/lib/udisks2";
list << "/var/log";
// 系统安装后有的会将/data/home /data/root挂载到的/home /root上实际文件是存放在/data/home /data/root下面
QStringList excludes;
Utils::excludeFstabBindPath(excludes);
for (const QString& item : excludes) {
list << item;
}
return list;
}
QTextStream out(&excludePathFile);
QString strAll = out.readAll();
excludePathFile.close();
QStringList list = strAll.split("\n");
list.removeAll(QString(""));
return list;
}