QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
RunGuard.cc
Go to the documentation of this file.
1#include "RunGuard.h"
2
3#include <QtCore/QCryptographicHash>
4#include <QtCore/QDir>
5#include <QtCore/QStandardPaths>
6
7RunGuard::RunGuard(const QString &key)
8 : _key(key)
9 , _lockFilePath(lockDir() + QLatin1String("/qgc-") + generateKeyHash(key, QLatin1String("_lock")) + QLatin1String(".lock"))
10 , _lockFile(_lockFilePath)
11{
12 // Recover instantly from stale locks after crashes.
13 _lockFile.setStaleLockTime(0);
14}
15
20
22{
23 if (_lockFile.isLocked()) {
24 return false;
25 }
26
27 if (_lockFile.tryLock(0)) {
28 _lockFile.unlock();
29 return false;
30 }
31
32 switch (_lockFile.error()) {
33 case QLockFile::NoError:
34 return false;
35 case QLockFile::LockFailedError:
36 return true;
37 case QLockFile::PermissionError:
38 qWarning() << "QLockFile PermissionError: Unable to access lock file at" << _lockFile.fileName();
39 break;
40 case QLockFile::UnknownError:
41 qWarning() << "QLockFile UnknownError: An unknown error occurred with lock file at" << _lockFile.fileName();
42 break;
43 default:
44 break;
45 }
46
47 return true;
48}
49
51{
52 return (_lockFile.isLocked() ? true : _lockFile.tryLock(0));
53}
54
56{
57 if (_lockFile.isLocked()) {
58 _lockFile.unlock();
59 }
60}
61
62QString RunGuard::generateKeyHash(const QString &key, const QString &salt)
63{
64 QByteArray data;
65 (void) data.append(key.toUtf8());
66 (void) data.append(salt.toUtf8());
67 const QByteArray hex = QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
68 return QString::fromLatin1(hex);
69}
70
71QString RunGuard::lockDir()
72{
73 QString dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
74 if (dir.isEmpty()) {
75 dir = QDir::tempPath();
76 }
77
78 if (!QDir().mkpath(dir)) {
79 qWarning() << "RunGuard: Failed to create lock directory:" << dir;
80 return QString();
81 }
82
83 return dir;
84}
~RunGuard()
Definition RunGuard.cc:16
void release()
Definition RunGuard.cc:55
bool tryToRun()
Definition RunGuard.cc:50
RunGuard(const QString &key)
Definition RunGuard.cc:7
bool isAnotherRunning()
Definition RunGuard.cc:21