| 44 | } // unnamed namespace |
| 45 | |
| 46 | TryLockSessionResult SessionLock::tryLockSession(const QString& sessionId, bool doLocking) |
| 47 | { |
| 48 | ///FIXME: if this is hit, someone tried to lock a non-existing session |
| 49 | /// this should be fixed by using a proper data type distinct from |
| 50 | /// QString for id's, i.e. QUuid or similar. |
| 51 | Q_ASSERT(QFile::exists(SessionController::sessionDirectory( sessionId ))); |
| 52 | |
| 53 | /* |
| 54 | * We've got two locking mechanisms here: D-Bus unique service name (based on the session id) |
| 55 | * and a plain lockfile (QLockFile). |
| 56 | * The latter is required to get the appname/pid of the locking instance |
| 57 | * in case if it's stale/hanging/crashed (to make user know which PID he needs to kill). |
| 58 | * D-Bus mechanism is the primary one. |
| 59 | * |
| 60 | * Since there is a kind of "logic tree", the code is a bit hard. |
| 61 | */ |
| 62 | const QString service = dBusServiceNameForSession( sessionId ); |
| 63 | QDBusConnection connection = QDBusConnection::sessionBus(); |
| 64 | QDBusConnectionInterface* connectionInterface = connection.interface(); |
| 65 | |
| 66 | const QString lockFilename = lockFileForSession( sessionId ); |
| 67 | QSharedPointer<QLockFile> lockFile(new QLockFile( lockFilename )); |
| 68 | |
| 69 | const bool haveDBus = connection.isConnected(); |
| 70 | const bool canLockDBus = haveDBus && connectionInterface && !connectionInterface->isServiceRegistered( service ); |
| 71 | bool lockedDBus = false; |
| 72 | |
| 73 | // Lock D-Bus if we can and we need to |
| 74 | if( doLocking && canLockDBus ) { |
| 75 | lockedDBus = connection.registerService( service ); |
| 76 | } |
| 77 | |
| 78 | // Attempt to lock file, despite the possibility to do so and presence of the request (doLocking) |
| 79 | // This is required as QLockFile::getLockInfo() works only after QLockFile::lock() is called |
| 80 | bool lockResult = lockFile->tryLock(); |
| 81 | SessionRunInfo runInfo; |
| 82 | if (lockResult) { |
| 83 | // Unlock immediately if we shouldn't have locked it |
| 84 | if( haveDBus && !lockedDBus ) { |
| 85 | lockFile->unlock(); |
| 86 | } |
| 87 | } else { |
| 88 | // If locking failed, retrieve the lock's metadata |
| 89 | lockFile->getLockInfo(&runInfo.holderPid, &runInfo.holderHostname, &runInfo.holderApp ); |
| 90 | runInfo.isRunning = !haveDBus || !canLockDBus; |
| 91 | |
| 92 | if( haveDBus && lockedDBus ) { |
| 93 | // Since the lock-file is secondary, try to force-lock it if D-Bus locking succeeded |
| 94 | forceRemoveLockfile(lockFilename); |
| 95 | lockResult = lockFile->tryLock(); |
| 96 | Q_ASSERT(lockResult); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | // Set the result by D-Bus status |
| 101 | if (doLocking && (haveDBus ? lockedDBus : lockResult)) { |
| 102 | return TryLockSessionResult(QSharedPointer<ISessionLock>(new SessionLock(sessionId, lockFile))); |
| 103 | } else { |
nothing calls this directly
no test coverage detected