OSDN Git Service

It's 2011 now.
[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 "maemodeviceconfigurations.h"
39 #include "maemoglobal.h"
40 #include "maemoremotemounter.h"
41 #include "maemoremotemountsmodel.h"
42 #include "maemorunconfiguration.h"
43 #include "maemousedportsgatherer.h"
44
45 #include <coreplugin/ssh/sshconnection.h>
46 #include <coreplugin/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 Core;
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."));
102         return;
103     }
104     if (!m_devConfig.isValid()) {
105         emitError(tr("Cannot run: No device configuration set."));
106         return;
107     }
108
109     setState(Connecting);
110     m_exitStatus = -1;
111     m_freePorts = m_initialFreePorts;
112     if (m_connection)
113         disconnect(m_connection.data(), 0, this, 0);
114     const bool reUse = isConnectionUsable();
115     if (!reUse)
116         m_connection = SshConnection::create();
117     connect(m_connection.data(), SIGNAL(connected()), this,
118         SLOT(handleConnected()));
119     connect(m_connection.data(), SIGNAL(error(Core::SshError)), this,
120         SLOT(handleConnectionFailure()));
121     if (reUse) {
122         handleConnected();
123     } else {
124         emit reportProgress(tr("Connecting to device..."));
125         m_connection->connectToHost(m_devConfig.server);
126     }
127 }
128
129 void MaemoSshRunner::stop()
130 {
131     if (m_state == PostRunCleaning || m_state == StopRequested
132         || m_state == Inactive)
133         return;
134     if (m_state == Connecting) {
135         setState(Inactive);
136         emit remoteProcessFinished(InvalidExitCode);
137         return;
138     }
139
140     setState(StopRequested);
141     cleanup();
142 }
143
144 void MaemoSshRunner::handleConnected()
145 {
146     ASSERT_STATE(QList<State>() << Connecting << StopRequested);
147     if (m_state == StopRequested) {
148         setState(Inactive);
149     } else {
150         setState(PreRunCleaning);
151         cleanup();
152     }
153 }
154
155 void MaemoSshRunner::handleConnectionFailure()
156 {
157     if (m_state == Inactive)
158         qWarning("Unexpected state %d in %s.", m_state, Q_FUNC_INFO);
159
160     const QString errorMsg = m_state == Connecting
161         ? MaemoGlobal::failedToConnectToServerMessage(m_connection, m_devConfig)
162         : tr("Connection error: %1").arg(m_connection->errorString());
163     emitError(errorMsg);
164 }
165
166 void MaemoSshRunner::cleanup()
167 {
168     ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
169         << StopRequested);
170
171     emit reportProgress(tr("Killing remote process(es)..."));
172
173     // pkill behaves differently on Fremantle and Harmattan.
174     const char *const killTemplate = "pkill -%2 '^%1$'; pkill -%2 '/%1$';";
175     QString niceKill;
176     QString brutalKill;
177     foreach (const QString &proc, m_procsToKill) {
178         niceKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGTERM");
179         brutalKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGKILL");
180     }
181     QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
182     remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
183
184     m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
185     connect(m_cleaner.data(), SIGNAL(closed(int)), this,
186         SLOT(handleCleanupFinished(int)));
187     m_cleaner->start();
188 }
189
190 void MaemoSshRunner::handleCleanupFinished(int exitStatus)
191 {
192     Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
193         || exitStatus == SshRemoteProcess::KilledBySignal
194         || exitStatus == SshRemoteProcess::ExitedNormally);
195
196     ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
197         << StopRequested << Inactive);
198
199     if (m_state == Inactive)
200         return;
201     if (m_state == StopRequested || m_state == PostRunCleaning) {
202         unmount();
203         return;
204     }
205
206     if (exitStatus != SshRemoteProcess::ExitedNormally) {
207         emitError(tr("Initial cleanup failed: %1")
208             .arg(m_cleaner->errorString()));
209     } else {
210         m_mounter->setConnection(m_connection);
211         unmount();
212     }
213 }
214
215 void MaemoSshRunner::handleUnmounted()
216 {
217     ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
218         << PostRunCleaning << StopRequested);
219
220     switch (m_state) {
221     case PreRunCleaning: {
222         for (int i = 0; i < m_mountSpecs.count(); ++i)
223             m_mounter->addMountSpecification(m_mountSpecs.at(i), false);
224         setState(PreMountUnmounting);
225         unmount();
226         break;
227     }
228     case PreMountUnmounting:
229         setState(GatheringPorts);
230         m_portsGatherer->start(m_connection, m_freePorts);
231         break;
232     case PostRunCleaning:
233     case StopRequested: {
234         m_mounter->resetMountSpecifications();
235         const bool stopRequested = m_state == StopRequested;
236         setState(Inactive);
237         if (stopRequested) {
238             emit remoteProcessFinished(InvalidExitCode);
239         } else if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
240             emit remoteProcessFinished(m_runner->exitCode());
241         } else {
242             emit error(tr("Error running remote process: %1")
243                 .arg(m_runner->errorString()));
244         }
245         break;
246     }
247     default: ;
248     }
249 }
250
251 void MaemoSshRunner::handleMounted()
252 {
253     ASSERT_STATE(QList<State>() << Mounting << StopRequested);
254
255     if (m_state == Mounting) {
256         setState(ReadyForExecution);
257         emit readyForExecution();
258     }
259 }
260
261 void MaemoSshRunner::handleMounterError(const QString &errorMsg)
262 {
263     ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
264         << PreMountUnmounting << Mounting << StopRequested << Inactive);
265
266     emitError(errorMsg);
267 }
268
269 void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
270 {
271     ASSERT_STATE(ReadyForExecution);
272
273     m_runner = m_connection->createRemoteProcess(remoteCall);
274     connect(m_runner.data(), SIGNAL(started()), this,
275         SIGNAL(remoteProcessStarted()));
276     connect(m_runner.data(), SIGNAL(closed(int)), this,
277         SLOT(handleRemoteProcessFinished(int)));
278     connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
279         SIGNAL(remoteOutput(QByteArray)));
280     connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
281         SIGNAL(remoteErrorOutput(QByteArray)));
282     setState(ProcessStarting);
283     m_runner->start();
284 }
285
286 void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
287 {
288     Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
289         || exitStatus == SshRemoteProcess::KilledBySignal
290         || exitStatus == SshRemoteProcess::ExitedNormally);
291     ASSERT_STATE(QList<State>() << ProcessStarting << StopRequested << Inactive);
292
293     m_exitStatus = exitStatus;
294     if (m_state != StopRequested && m_state != Inactive) {
295         setState(PostRunCleaning);
296         cleanup();
297     }
298 }
299
300 bool MaemoSshRunner::isConnectionUsable() const
301 {
302     return m_connection && m_connection->state() == SshConnection::Connected
303         && m_connection->connectionParameters() == m_devConfig.server;
304 }
305
306 void MaemoSshRunner::setState(State newState)
307 {
308     if (newState == Inactive) {
309         m_mounter->setConnection(SshConnection::Ptr());
310         m_portsGatherer->stop();
311         if (m_connection) {
312             disconnect(m_connection.data(), 0, this, 0);
313             m_connection = SshConnection::Ptr();
314         }
315         if (m_cleaner)
316             disconnect(m_cleaner.data(), 0, this, 0);
317     }
318     m_state = newState;
319 }
320
321 void MaemoSshRunner::emitError(const QString &errorMsg)
322 {
323     if (m_state != Inactive) {
324         setState(Inactive);
325         emit error(errorMsg);
326     }
327 }
328
329 void MaemoSshRunner::mount()
330 {
331     setState(Mounting);
332     if (m_mounter->hasValidMountSpecifications()) {
333         emit reportProgress(tr("Mounting host directories..."));
334         m_mounter->mount(freePorts(), m_portsGatherer);
335     } else {
336         handleMounted();
337     }
338 }
339
340 void MaemoSshRunner::unmount()
341 {
342     ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
343         << PostRunCleaning << StopRequested);
344     if (m_mounter->hasValidMountSpecifications()) {
345         QString message;
346         switch (m_state) {
347         case PreRunCleaning:
348             message = tr("Unmounting left-over host directory mounts...");
349             break;
350         case PreMountUnmounting:
351             message = tr("Potentially unmounting left-over host directory mounts...");
352         case StopRequested: case PostRunCleaning:
353             message = tr("Unmounting host directories...");
354             break;
355         default:
356             break;
357         }
358         emit reportProgress(message);
359         m_mounter->unmount();
360     } else {
361         handleUnmounted();
362     }
363 }
364
365 void MaemoSshRunner::handlePortsGathererError(const QString &errorMsg)
366 {
367     emitError(errorMsg);
368 }
369
370 void MaemoSshRunner::handleUsedPortsAvailable()
371 {
372     ASSERT_STATE(QList<State>() << GatheringPorts << StopRequested);
373
374     if (m_state == StopRequested) {
375         setState(Inactive);
376     } else {
377         mount();
378     }
379 }
380
381 const qint64 MaemoSshRunner::InvalidExitCode
382     = std::numeric_limits<qint64>::min();
383
384 } // namespace Internal
385 } // namespace Qt4ProjectManager
386