aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/remotelinux/genericdeploystep.cpp
blob: 0002e69f5f2c2fff30c8dd68e68cf489d4a0bab9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "genericdeploystep.h"

#include "abstractremotelinuxdeploystep.h"
#include "remotelinux_constants.h"
#include "remotelinuxtr.h"

#include <projectexplorer/buildsystem.h>
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/devicesupport/devicemanager.h>
#include <projectexplorer/devicesupport/filetransfer.h>
#include <projectexplorer/devicesupport/idevice.h>
#include <projectexplorer/kitaspects.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/runconfigurationaspects.h>
#include <projectexplorer/target.h>

#include <utils/algorithm.h>
#include <utils/async.h>
#include <utils/qtcprocess.h>
#include <utils/processinterface.h>

using namespace ProjectExplorer;
using namespace Tasking;
using namespace Utils;

namespace RemoteLinux::Internal {

// RsyncDeployStep

class GenericDeployStep : public AbstractRemoteLinuxDeployStep
{
public:
    GenericDeployStep(BuildStepList *bsl, Id id)
        : AbstractRemoteLinuxDeployStep(bsl, id)
    {
        flags.setDisplayStyle(StringAspect::LineEditDisplay);
        flags.setSettingsKey("RemoteLinux.RsyncDeployStep.Flags");
        flags.setLabelText(Tr::tr("Flags for rsync:"));
        flags.setValue(FileTransferSetupData::defaultRsyncFlags());

        ignoreMissingFiles.setSettingsKey("RemoteLinux.RsyncDeployStep.IgnoreMissingFiles");
        ignoreMissingFiles.setLabelText(Tr::tr("Ignore missing files:"));
        ignoreMissingFiles.setLabelPlacement(BoolAspect::LabelPlacement::InExtraLabel);

        method.setSettingsKey("RemoteLinux.RsyncDeployStep.TransferMethod");
        method.setDisplayStyle(SelectionAspect::DisplayStyle::ComboBox);
        method.setDisplayName(Tr::tr("Transfer method:"));
        method.addOption(Tr::tr("Use rsync or sftp if available, but prefer rsync. "
                                "Otherwise use default transfer."));
        method.addOption(Tr::tr("Use sftp if available. Otherwise use default transfer."));
        method.addOption(Tr::tr("Use default transfer. This might be slow."));

        setInternalInitializer([this]() -> expected_str<void> {
            if (BuildDeviceKitAspect::device(kit()) == DeviceKitAspect::device(kit())) {
                // rsync transfer on the same device currently not implemented
                // and typically not wanted.
                return make_unexpected(
                    Tr::tr("rsync is only supported for transfers between different devices."));
            }
            return isDeploymentPossible();
        });
    }

private:
    GroupItem deployRecipe() final;
    GroupItem mkdirTask(const Storage<FilesToTransfer> &storage);
    GroupItem transferTask(const Storage<FilesToTransfer> &storage);

    StringAspect flags{this};
    BoolAspect ignoreMissingFiles{this};
    SelectionAspect method{this};
    bool m_emittedDowngradeWarning = false;
};

GroupItem GenericDeployStep::mkdirTask(const Storage<FilesToTransfer> &storage)
{
    using ResultType = expected_str<void>;

    const auto onSetup = [storage](Async<ResultType> &async) {
        FilePaths remoteDirs;
        for (const FileToTransfer &file : *storage)
            remoteDirs << file.m_target.parentDir();

        FilePath::sort(remoteDirs);
        FilePath::removeDuplicates(remoteDirs);

        async.setConcurrentCallData([remoteDirs](QPromise<ResultType> &promise) {
            for (const FilePath &dir : remoteDirs) {
                const expected_str<void> result = dir.ensureWritableDir();
                promise.addResult(result);
                if (!result)
                    promise.future().cancel();
            }
        });
    };

    const auto onError = [this](const Async<ResultType> &async) {
        const int numResults = async.future().resultCount();
        if (numResults == 0) {
            addErrorMessage(
                Tr::tr("Unknown error occurred while trying to create remote directories.") + '\n');
            return;
        }

        for (int i = 0; i < numResults; ++i) {
            const ResultType result = async.future().resultAt(i);
            if (!result.has_value())
                addErrorMessage(result.error());
        }
    };

    return AsyncTask<ResultType>(onSetup, onError, CallDoneIf::Error);
}

static FileTransferMethod effectiveTransferMethodFor(const FileToTransfer &fileToTransfer,
                                                      FileTransferMethod preferred)
{
    auto sourceDevice = ProjectExplorer::DeviceManager::deviceForPath(fileToTransfer.m_source);
    auto targetDevice = ProjectExplorer::DeviceManager::deviceForPath(fileToTransfer.m_target);
    if (!sourceDevice || !targetDevice)
        return FileTransferMethod::GenericCopy;

    const auto devicesSupportMethod = [&](Id method) {
        return sourceDevice->extraData(method).toBool() && targetDevice->extraData(method).toBool();
    };
    if (preferred == FileTransferMethod::Rsync
        && !devicesSupportMethod(ProjectExplorer::Constants::SUPPORTS_RSYNC)) {
        preferred = FileTransferMethod::Sftp;
    }
    if (preferred == FileTransferMethod::Sftp
        && !devicesSupportMethod(ProjectExplorer::Constants::SUPPORTS_SFTP)) {
        preferred = FileTransferMethod::GenericCopy;
    }
    return preferred;
}

GroupItem GenericDeployStep::transferTask(const Storage<FilesToTransfer> &storage)
{
    const auto onSetup = [this, storage](FileTransfer &transfer) {
        FileTransferMethod preferredTransferMethod = FileTransferMethod::GenericCopy;
        if (method() == 0)
            preferredTransferMethod = FileTransferMethod::Rsync;
        else if (method() == 1)
            preferredTransferMethod = FileTransferMethod::Sftp;

        FileTransferMethod transferMethod = preferredTransferMethod;
        if (transferMethod != FileTransferMethod::GenericCopy) {
            for (const FileToTransfer &fileToTransfer : *storage) {
                transferMethod = effectiveTransferMethodFor(fileToTransfer, transferMethod);
                if (transferMethod == FileTransferMethod::GenericCopy)
                    break;
            }
        }
        if (!m_emittedDowngradeWarning && transferMethod != preferredTransferMethod) {
            const QString message
                = Tr::tr("Transfer method was downgraded from \"%1\" to \"%2\". If "
                         "this is unexpected, please re-test device \"%3\".")
                      .arg(FileTransfer::transferMethodName(preferredTransferMethod),
                           FileTransfer::transferMethodName(transferMethod),
                           deviceConfiguration()->displayName());
            if (transferMethod == FileTransferMethod::GenericCopy)
                addWarningMessage(message);
            else
                addProgressMessage(message);
            m_emittedDowngradeWarning = true;
        }
        transfer.setTransferMethod(transferMethod);

        transfer.setRsyncFlags(flags());
        transfer.setFilesToTransfer(*storage);
        connect(&transfer, &FileTransfer::progress, this, &GenericDeployStep::handleStdOutData);
    };
    const auto onError = [this](const FileTransfer &transfer) {
        const ProcessResultData result = transfer.resultData();
        if (result.m_error == QProcess::FailedToStart) {
            addErrorMessage(Tr::tr("rsync failed to start: %1").arg(result.m_errorString));
        } else if (result.m_exitStatus == QProcess::CrashExit) {
            addErrorMessage(Tr::tr("rsync crashed."));
        } else if (result.m_exitCode != 0) {
            addErrorMessage(Tr::tr("rsync failed with exit code %1.").arg(result.m_exitCode)
                            + "\n" + result.m_errorString);
        }
    };
    return FileTransferTask(onSetup, onError, CallDoneIf::Error);
}

GroupItem GenericDeployStep::deployRecipe()
{
    const Storage<FilesToTransfer> storage;

    const auto onSetup = [this, storage] {
        const QList<DeployableFile> deployableFiles = target()->deploymentData().allFiles();
        FilesToTransfer &files = *storage;
        for (const DeployableFile &file : deployableFiles) {
            if (!ignoreMissingFiles() || file.localFilePath().exists()) {
                const FilePermissions permissions = file.isExecutable()
                    ? FilePermissions::ForceExecutable : FilePermissions::Default;
                files.append({file.localFilePath(),
                              deviceConfiguration()->filePath(file.remoteFilePath()), permissions});
            }
        }
        if (files.isEmpty()) {
            addSkipDeploymentMessage();
            return SetupResult::StopWithSuccess;
        }
        return SetupResult::Continue;
    };

    return Group {
        storage,
        onGroupSetup(onSetup),
        mkdirTask(storage),
        transferTask(storage)
    };
}

// Factory

GenericDeployStepFactory::GenericDeployStepFactory()
{
    registerStep<GenericDeployStep>(Constants::GenericDeployStepId);
    setDisplayName(Tr::tr("Deploy files"));
}

} // RemoteLinux::Internal