aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/FSE/Tango.FSE.UI/RemoteUpgrade/DefaultRemoteUpgradeManager.cs
blob: bb808e6859a8145057b1957071b83e91f920557d (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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Core.Components;
using Tango.Core.DB;
using Tango.Core.DI;
using Tango.Core.ExtensionMethods;
using Tango.FSE.BL.Web;
using Tango.FSE.Common;
using Tango.FSE.Common.Authentication;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.MachineUpdates;
using Tango.FSE.Common.RemoteUpgrade;
using Tango.FSE.Web.Messages;
using Tango.PPC.Common.Publish;
using Tango.PPC.Shared.Updates;
using Tango.SQLExaminer;
using Tango.Transport;
using Tango.Transport.Web;
using Tango.Web;

namespace Tango.FSE.UI.RemoteUpgrade
{
    /// <summary>
    /// Represents the <see cref="IMachineUpdatesProvider"/> default implementation.
    /// </summary>
    /// <seealso cref="Tango.FSE.Common.MachineUpdates.IMachineUpdatesProvider" />
    public class DefaultRemoteUpgradeManager : FSEExtendedObject, IRemoteUpgradeManager
    {
        private bool _isGeneratingTup;
        private IMachineProvider MachineProvider { get; set; }
        private FSEWebClient WebClient { get; set; }
        private IAuthenticationProvider AuthenticationProvider { get; set; }

        /// <summary>
        /// Occurs when a TUP creation has made progress.
        /// </summary>
        public event EventHandler<RemoteUpgradeProgressEventArgs> Progress;

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultRemoteUpgradeManager"/> class.
        /// </summary>
        /// <param name="authenticationProvider">The authentication provider.</param>
        /// <param name="machineProvider">The machine provider.</param>
        /// <param name="webClient">The web client.</param>
        public DefaultRemoteUpgradeManager(IAuthenticationProvider authenticationProvider, IMachineProvider machineProvider, FSEWebClient webClient)
        {
            AuthenticationProvider = authenticationProvider;
            MachineProvider = machineProvider;
            WebClient = webClient;
        }

        /// <summary>
        /// Creates a Tango Update Package for the current connected machine.
        /// </summary>
        /// <param name="tangoVersion">The tango version.</param>
        /// <param name="filePath">The file path.</param>
        /// <returns></returns>
        public Task CreateTupFile(TangoVersion tangoVersion, string filePath)
        {
            if (MachineProvider.Machine == null)
            {
                throw new InvalidOperationException("Could not create a TUP file while machine is disconnected.");
            }

            return CreateTupFile(tangoVersion, MachineProvider.Machine.SerialNumber);
        }

        /// <summary>
        /// Creates a Tango Update Package for specified machine.
        /// </summary>
        /// <param name="tangoVersion">The tango version.</param>
        /// <param name="serialNumber">The machine serial number.</param>
        /// <param name="targetFilePath">The file path.</param>
        /// <returns></returns>
        public Task CreateTupFile(TangoVersion tangoVersion, string serialNumber, string targetFilePath)
        {
            if (_isGeneratingTup)
            {
                throw new InvalidOperationException("Only one TUP file can be created at a time.");
            }

            _isGeneratingTup = true;

            return Task.Factory.StartNew(() =>
            {
                String tempDbName = "Tango_TUP";
                var tempPackageFolder = TemporaryManager.CreateFolder();
                String tempBackupFolder = "C:\\FSE_TUP";
                String tempBackupFile = Path.Combine(tempBackupFolder, tempDbName + ".bak");
                var tempZipFile = TemporaryManager.CreateImaginaryFile();
                DbManager dbManager = null;

                LogManager.Log("Generating tup file...");
                LogManager.Log($"Tup file: '{targetFilePath}.'");
                LogManager.Log($"Temporary db name: '{tempDbName}'.");
                LogManager.Log($"Temporary package folder: '{tempPackageFolder}'.");
                LogManager.Log($"Temporary db backup folder: '{tempBackupFolder}'.");
                LogManager.Log($"Temporary db backup file: '{tempBackupFile}'.");
                LogManager.Log($"Temporary zip file: '{tempZipFile}'.");

                try
                {
                    LogManager.Log("Initializing...");

                    OnProgress("Initializing...");

                    Tango.Core.DataSource localDataSource = new Tango.Core.DataSource()
                    {
                        Address = "localhost\\SQLEXPRESS",
                        IntegratedSecurity = true,
                        Type = DataSourceType.SQLServer,
                        Catalog = null,
                    };

                    try
                    {
                        LogManager.Log($"Trying to connect via SQLEXPRESS:\n{localDataSource.ToJsonString()}");
                        dbManager = DbManager.FromDataSource(localDataSource);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            LogManager.Log(ex, "Could not connect using SQLEXPRESS. Trying local DB...");

                            CmdCommand command = new CmdCommand("sqllocaldb", "start \"MSSQLLocalDB\"");
                            var result = command.Run().Result;

                            command = new CmdCommand("sqllocaldb", "info \"MSSQLLocalDB\"");
                            result = command.Run().Result;

                            String pattern = "np:.+";
                            Regex reg = new Regex(pattern);
                            var match = reg.Match(result.StandardOutput);
                            String address = match.ToString();
                            if (address.Contains("np:"))
                            {
                                localDataSource.Address = address;
                                address = address.Trim().Replace("\r", "");
                            }
                            else
                            {
                                throw new ArgumentException("Could not parse LocalDB address string.");
                            }

                            LogManager.Log($"Trying to connect via LocalDB:\n{localDataSource.ToJsonString()}");
                            dbManager = DbManager.FromDataSource(localDataSource);
                        }
                        catch (Exception x)
                        {
                            LogManager.Log(x, "Could not find any database service for this operation.");
                            throw x;
                        }
                    }



                    OnProgress($"Downloading Tango version '{tangoVersion.Version}'...");

                    LogManager.Log("Connecting to machine service...");

                    LogManager.Log("Requesting version download from machine service...");
                    var response = WebClient.DownloadTangoVersion(new DownloadTangoVersionRequest() { TangoVersionGuid = tangoVersion.Guid }).Result;

                    LogManager.Log($"Machine service response:\n{response.ToJsonString()}");

                    var remoteDataSource = response.DataSource;

                    using (AutoFileDownloader downloader = new AutoFileDownloader(response.BlobAddress, response.CdnAddress, tempZipFile))
                    {
                        downloader.Progress += (x, e) =>
                        {
                            OnProgress($"Downloading Tango version '{response.Version}'...", false, e.Current, e.Total);
                        };

                        downloader.ResolveMode().GetAwaiter().GetResult();

                        LogManager.Log($"Downloading Tango version from: '{downloader.Address}'");

                        downloader.Download().Wait();
                    }

                    LogManager.Log("Extracting version package...");

                    OnProgress("Extracting package...");

                    using (ZipFile zip = new ZipFile(tempZipFile))
                    {
                        int currentEntry = 0;

                        zip.ExtractProgress += (x, args) =>
                        {
                            if (args.EventType == ZipProgressEventType.Extracting_AfterExtractEntry)
                            {
                                OnProgress("Extracting package...", false, currentEntry++, zip.Entries.Count);
                            }
                        };

                        zip.ExtractAll(tempPackageFolder);
                    }

                    OnProgress("Extracting version information...");
                    LogManager.Log("Extracting publish information...");
                    PublishInfo publishInfo = PublishInfo.FromJson(File.ReadAllText(Path.Combine(tempPackageFolder, "version.json")));
                    LogManager.Log($"Publish Information:\n{publishInfo}");

                    LogManager.Log("Modifying publish information to custom tup file...");
                    publishInfo.IsMachineTupPackage = true;
                    publishInfo.MachineSerialNumber = serialNumber;
                    publishInfo.MachineDeploymentSlot = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), AuthenticationProvider.CurrentEnvironment.Name);

                    OnProgress("Creating temporary database...");

                    LogManager.Log($"Creating temporary db backup directory '{tempBackupFolder}'");

                    Directory.CreateDirectory(tempBackupFolder);

                    LogManager.Log($"Creating new database: '{tempDbName}'");

                    //Create temp db
                    dbManager.Create(tempDbName, Path.Combine(tempBackupFolder, tempDbName + ".mdf"));

                    OnProgress("Generating database snapshot...");

                    LogManager.Log("Starting database synchronization...");

                    Thread.Sleep(2000);

                    localDataSource.Catalog = tempDbName;

                    ExaminerSequenceConfigurationRunner runner = new ExaminerSequenceConfigurationRunner(
                        Path.Combine(tempPackageFolder, "Provision Scripts", "config.xml"),
                        Path.Combine(tempPackageFolder, "Provision Scripts"),
                            remoteDataSource,
                            localDataSource,
                            serialNumber);

                    runner.ScriptExecuting += (x, item) =>
                    {
                        LogManager.Log($"Executing script '{item.FileName}'...");
                        OnProgress($"{item.Name}...");
                    };

                    runner.Log += (x, log) =>
                    {
                        LogManager.Log(log);
                    };

                    runner.Run().GetAwaiter().GetResult();

                    OnProgress("Generating database snapshot...");

                    if (File.Exists(tempBackupFile))
                    {
                        LogManager.Log($"Deleting file '{tempBackupFile}'");
                        File.Delete(tempBackupFile);
                    }

                    LogManager.Log($"Generating backup for '{tempDbName}' to '{tempBackupFile}'...");

                    dbManager.Backup(tempDbName, tempBackupFile);

                    OnProgress("Injecting database snapshot to PPC package...");

                    using (ZipFile zip = new ZipFile(tempZipFile))
                    {
                        LogManager.Log($"Injecting file '{tempBackupFile}' to original package at '{tempZipFile}'...");
                        zip.AddFile(tempBackupFile, "/");

                        LogManager.Log($"Injecting modified publish information...");
                        zip.UpdateEntry("version.json", publishInfo.ToJson());

                        zip.Save();
                    }

                    LogManager.Log($"Copying '{tempZipFile}' to '{targetFilePath}'...");

                    File.Copy(tempZipFile, targetFilePath, true);

                    OnProgress("Completed", false, 100, 100);

                    LogManager.Log("TUP file generation completed successfully.");
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "TUP file generation failed.");
                    OnProgress("Failed", false, 0, 100);
                    throw ex;
                }
                finally
                {
                    _isGeneratingTup = false;
                    LogManager.Log($"Removing '{tempZipFile}'.");
                    tempZipFile.Delete();
                    LogManager.Log($"Removing '{tempPackageFolder}'.");
                    tempPackageFolder.Delete();

                    try
                    {
                        LogManager.Log($"Removing database '{tempDbName}'.");
                        dbManager.SetOffline(tempDbName);
                        dbManager.SetOnline(tempDbName);
                        dbManager.Delete(tempDbName);
                        dbManager.Dispose();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, $"Error removing temp database '{tempDbName}'.");
                    }

                    try
                    {
                        LogManager.Log($"Removing '{tempBackupFolder}'.");
                        Directory.Delete(tempBackupFolder, true);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, $"Error removing folder '{tempBackupFolder}'.");
                    }
                }
            });
        }

        /// <summary>
        /// Called when the TUP creation has made some progress.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="isIntermediate">if set to <c>true</c> [is intermediate].</param>
        /// <param name="progress">The progress.</param>
        /// <param name="total">The total.</param>
        protected virtual void OnProgress(String message, bool isIntermediate = true, double progress = 0, double total = 100)
        {
            Progress?.Invoke(this, new RemoteUpgradeProgressEventArgs()
            {
                Message = message,
                IsIntermediate = isIntermediate,
                Progress = progress,
                Total = total,
            });
        }
    }
}