OSDN Git Service

79be7d9f9a437b1bc63abe7054db6da586224530
[qt-creator-jp/qt-creator-jp.git] / src / plugins / qt4projectmanager / qt-maemo / maemosshrunner.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the Qt Creator.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file.  Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 **
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 ** $QT_END_LICENSE$
32 **
33 ****************************************************************************/
34
35 #include "maemosshrunner.h"
36
37 #include "maemodeploystep.h"
38 #include "maemoglobal.h"
39 #include "maemoqemumanager.h"
40 #include "maemoremotemounter.h"
41 #include "maemoremotemountsmodel.h"
42 #include "maemorunconfiguration.h"
43 #include "maemousedportsgatherer.h"
44
45 #include <utils/ssh/sshconnection.h>
46 #include <utils/ssh/sshremoteprocess.h>
47
48 #include <QtCore/QFileInfo>
49
50 #include <limits>
51
52 #define ASSERT_STATE(state) ASSERT_STATE_GENERIC(State, state, m_state)
53
54 using namespace Utils;
55
56 namespace Qt4ProjectManager {
57 namespace Internal {
58
59 MaemoSshRunner::MaemoSshRunner(QObject *parent,
60     MaemoRunConfiguration *runConfig, bool debugging)
61     : QObject(parent),
62       m_mounter(new MaemoRemoteMounter(this)),
63       m_portsGatherer(new MaemoUsedPortsGatherer(this)),
64       m_devConfig(runConfig->deviceConfig()),
65       m_remoteExecutable(runConfig->remoteExecutableFilePath()),
66       m_appArguments(runConfig->arguments()),
67       m_userEnvChanges(runConfig->userEnvironmentChanges()),
68       m_initialFreePorts(runConfig->freePorts()),
69       m_mountSpecs(runConfig->remoteMounts()->mountSpecs()),
70       m_state(Inactive)
71 {
72     m_connection = runConfig->deployStep()->sshConnection();
73     m_mounter->setBuildConfiguration(runConfig->activeQt4BuildConfiguration());
74     if (debugging && runConfig->useRemoteGdb()) {
75         m_mountSpecs << MaemoMountSpecification(runConfig->localDirToMountForRemoteGdb(),
76             runConfig->remoteProjectSourcesMountPoint());
77     }
78
79     m_procsToKill << QFileInfo(m_remoteExecutable).fileName();
80     connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
81     connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
82     connect(m_mounter, SIGNAL(error(QString)), this,
83         SLOT(handleMounterError(QString)));
84     connect(m_mounter, SIGNAL(reportProgress(QString)), this,
85         SIGNAL(reportProgress(QString)));
86     connect(m_mounter, SIGNAL(debugOutput(QString)), this,
87         SIGNAL(mountDebugOutput(QString)));
88     connect(m_portsGatherer, SIGNAL(error(QString)), this,
89         SLOT(handlePortsGathererError(QString)));
90     connect(m_portsGatherer, SIGNAL(portListReady()), this,
91         SLOT(handleUsedPortsAvailable()));
92 }
93
94 MaemoSshRunner::~MaemoSshRunner() {}
95
96 void MaemoSshRunner::start()
97 {
98     ASSERT_STATE(QList<State>() << Inactive << StopRequested);
99
100     if (m_remoteExecutable.isEmpty()) {
101         emitError(tr("Cannot run: No remote executable set."), true);
102         return;
103     }
104     if (!m_devConfig) {
105         emitError(tr("Cannot run: No device configuration set."), true);
106         return;
107     }
108
109     if (m_devConfig->type() == MaemoDeviceConfig::Emulator
110             && !MaemoQemuManager::instance().qemuIsRunning()) {
111         MaemoQemuManager::instance().startRuntime();
112         emitError(tr("Cannot run: Qemu was not running. "
113             "It has now been started up for you, but it will take "
114             "a bit of time until it is ready."), true);
115         return;
116     }
117
118     setState(Connecting);
119     m_exitStatus = -1;
120     m_freePorts = m_initialFreePorts;
121     if (m_connection)
122         disconnect(m_connection.data(), 0, this, 0);
123     const bool reUse = isConnectionUsable();
124     if (!reUse)
125         m_connection = SshConnection::create();
126     connect(m_connection.data(), SIGNAL(connected()), this,
127         SLOT(handleConnected()));
128     connect(m_connection.data(), SIGNAL(error(Utils::SshError)), this,
129         SLOT(handleConnectionFailure()));
130     if (reUse) {
131         handleConnected();
132     } else {
133         emit reportProgress(tr("Connecting to device..."));
134         m_connection->connectToHost(m_devConfig->sshParameters());
135     }
136 }
137
138 void MaemoSshRunner::stop()
139 {
140     if (m_state == PostRunCleaning || m_state == StopRequested
141         || m_state == Inactive)
142         return;
143     if (m_state == Connecting) {
144         setState(Inactive);
145         emit remoteProcessFinished(InvalidExitCode);
146         return;
147     }
148
149     setState(StopRequested);
150     cleanup();
151 }
152
153 void MaemoSshRunner::handleConnected()
154 {
155     ASSERT_STATE(QList<State>() << Connecting << StopRequested);
156     if (m_state == StopRequested) {
157         setState(Inactive);
158     } else {
159         setState(PreRunCleaning);
160         cleanup();
161     }
162 }
163
164 void MaemoSshRunner::handleConnectionFailure()
165 {
166     if (m_state == Inactive)
167         qWarning("Unexpected state %d in %s.", m_state, Q_FUNC_INFO);
168
169     const QString errorMsg = m_state == Connecting
170         ? MaemoGlobal::failedToConnectToServerMessage(m_connection, m_devConfig)
171         : tr("Connection error: %1").arg(m_connection->errorString());
172     emitError(errorMsg);
173 }
174
175 void MaemoSshRunner::cleanup()
176 {
177     ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
178         << StopRequested);
179
180     emit reportProgress(tr("Killing remote process(es)..."));
181
182     // pkill behaves differently on Fremantle and Harmattan.
183     const char *const killTemplate = "pkill -%2 '^%1$'; pkill -%2 '/%1$';";
184     QString niceKill;
185     QString brutalKill;
186     foreach (const QString &proc, m_procsToKill) {
187         niceKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGTERM");
188         brutalKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGKILL");
189     }
190     QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
191     remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
192
193     m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
194     connect(m_cleaner.data(), SIGNAL(closed(int)), this,
195         SLOT(handleCleanupFinished(int)));
196     m_cleaner->start();
197 }
198
199 void MaemoSshRunner::handleCleanupFinished(int exitStatus)
200 {
201     Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
202         || exitStatus == SshRemoteProcess::KilledBySignal
203         || exitStatus == SshRemoteProcess::ExitedNormally);
204
205     ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
206         << StopRequested << Inactive);
207
208     if (m_state == Inactive)
209         return;
210     if (m_state == StopRequested || m_state == PostRunCleaning) {
211         unmount();
212         return;
213     }
214
215     if (exitStatus != SshRemoteProcess::ExitedNormally) {
216         emitError(tr("Initial cleanup failed: %1")
217             .arg(m_cleaner->errorString()));
218     } else {
219         m_mounter->setConnection(m_connection);
220         unmount();
221     }
222 }
223
224 void MaemoSshRunner::handleUnmounted()
225 {
226     ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
227         << PostRunCleaning << StopRequested);
228
229     switch (m_state) {
230     case PreRunCleaning: {
231         for (int i = 0; i < m_mountSpecs.count(); ++i)
232             m_mounter->addMountSpecification(m_mountSpecs.at(i), false);
233         setState(PreMountUnmounting);
234         unmount();
235         break;
236     }
237     case PreMountUnmounting:
238         setState(GatheringPorts);
239         m_portsGatherer->start(m_connection, m_freePorts);
240         break;
241     case PostRunCleaning:
242     case StopRequested: {
243         m_mounter->resetMountSpecifications();
244         const bool stopRequested = m_state == StopRequested;
245         setState(Inactive);
246         if (stopRequested) {
247             emit remoteProcessFinished(InvalidExitCode);
248         } else if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
249             emit remoteProcessFinished(m_runner->exitCode());
250         } else {
251             emit error(tr("Error running remote process: %1")
252                 .arg(m_runner->errorString()));
253         }
254         break;
255     }
256     default: ;
257     }
258 }
259
260 void MaemoSshRunner::handleMounted()
261 {
262     ASSERT_STATE(QList<State>() << Mounting << StopRequested);
263
264     if (m_state == Mounting) {
265         setState(ReadyForExecution);
266         emit readyForExecution();
267     }
268 }
269
270 void MaemoSshRunner::handleMounterError(const QString &errorMsg)
271 {
272     ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
273         << PreMountUnmounting << Mounting << StopRequested << Inactive);
274
275     emitError(errorMsg);
276 }
277
278 void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
279 {
280     ASSERT_STATE(ReadyForExecution);
281
282     m_runner = m_connection->createRemoteProcess(remoteCall);
283     connect(m_runner.data(), SIGNAL(started()), this,
284         SIGNAL(remoteProcessStarted()));
285     connect(m_runner.data(), SIGNAL(closed(int)), this,
286         SLOT(handleRemoteProcessFinished(int)));
287     connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
288         SIGNAL(remoteOutput(QByteArray)));
289     connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
290         SIGNAL(remoteErrorOutput(QByteArray)));
291     setState(ProcessStarting);
292     m_runner->start();
293 }
294
295 void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
296 {
297     Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
298         || exitStatus == SshRemoteProcess::KilledBySignal
299         || exitStatus == SshRemoteProcess::ExitedNormally);
300     ASSERT_STATE(QList<State>() << ProcessStarting << StopRequested << Inactive);
301
302     m_exitStatus = exitStatus;
303     if (m_state != StopRequested && m_state != Inactive) {
304         setState(PostRunCleaning);
305         cleanup();
306     }
307 }
308
309 bool MaemoSshRunner::isConnectionUsable() const
310 {
311     return m_connection && m_connection->state() == SshConnection::Connected
312         && m_connection->connectionParameters() == m_devConfig->sshParameters();
313 }
314
315 void MaemoSshRunner::setState(State newState)
316 {
317     if (newState == Inactive) {
318         m_mounter->setConnection(SshConnection::Ptr());
319         m_portsGatherer->stop();
320         if (m_connection) {
321             disconnect(m_connection.data(), 0, this, 0);
322             m_connection = SshConnection::Ptr();
323         }
324         if (m_cleaner)
325             disconnect(m_cleaner.data(), 0, this, 0);
326     }
327     m_state = newState;
328 }
329
330 void MaemoSshRunner::emitError(const QString &errorMsg, bool force)
331 {
332     if (m_state != Inactive) {
333         setState(Inactive);
334         emit error(errorMsg);
335     } else if (force) {
336         emit error(errorMsg);
337     }
338 }
339
340 void MaemoSshRunner::mount()
341 {
342     setState(Mounting);
343     if (m_mounter->hasValidMountSpecifications()) {
344         emit reportProgress(tr("Mounting host directories..."));
345         m_mounter->mount(freePorts(), m_portsGatherer);
346     } else {
347         handleMounted();
348     }
349 }
350
351 void MaemoSshRunner::unmount()
352 {
353     ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
354         << PostRunCleaning << StopRequested);
355     if (m_mounter->hasValidMountSpecifications()) {
356         QString message;
357         switch (m_state) {
358         case PreRunCleaning:
359             message = tr("Unmounting left-over host directory mounts...");
360             break;
361         case PreMountUnmounting:
362             message = tr("Potentially unmounting left-over host directory mounts...");
363         case StopRequested: case PostRunCleaning:
364             message = tr("Unmounting host directories...");
365             break;
366         default:
367             break;
368         }
369         emit reportProgress(message);
370         m_mounter->unmount();
371     } else {
372         handleUnmounted();
373     }
374 }
375
376 void MaemoSshRunner::handlePortsGathererError(const QString &errorMsg)
377 {
378     emitError(errorMsg);
379 }
380
381 void MaemoSshRunner::handleUsedPortsAvailable()
382 {
383     ASSERT_STATE(QList<State>() << GatheringPorts << StopRequested);
384
385     if (m_state == StopRequested) {
386         setState(Inactive);
387     } else {
388         mount();
389     }
390 }
391
392 const qint64 MaemoSshRunner::InvalidExitCode
393     = std::numeric_limits<qint64>::min();
394
395 } // namespace Internal
396 } // namespace Qt4ProjectManager
397