-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathExporter.cs
More file actions
342 lines (281 loc) · 12 KB
/
Copy pathExporter.cs
File metadata and controls
342 lines (281 loc) · 12 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Aquarius.TimeSeries.Client;
using Aquarius.TimeSeries.Client.ServiceModels.Publish;
using Common;
using FieldDataPluginFramework;
using FieldDataPluginFramework.Context;
using FieldDataPluginFramework.Serialization;
using Humanizer;
using log4net;
using ServiceStack;
using ServiceStack.Text;
using Attachment = Aquarius.TimeSeries.Client.ServiceModels.Publish.Attachment;
using ILog = log4net.ILog;
namespace FieldVisitHotFolderService
{
public class Exporter
{
private static readonly ILog Log4NetLog = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public Context Context { get; set; }
private FileLogger Log { get; } = new FileLogger(Log4NetLog);
public List<IFieldDataPlugin> Plugins { get; set; }
public IAquariusClient Client { get; set; }
private List<LocationInfo> LocationCache { get; } = new List<LocationInfo>();
public ReferencePointCache ReferencePointCache { get; set; }
public MethodLookup MethodLookup { get; set; }
public ParameterIdLookup ParameterIdLookup { get; set; }
private ArchivedVisitMapper Mapper { get; set; }
private int VisitCount { get; set; }
private int ErrorCount { get; set; }
private int MissingAttachmentCount { get; set; }
private int SkipCount { get; set; }
public void Run()
{
Validate();
var locationIdentifiers = GetLocationsToExport()
.OrderBy(s => s)
.ToList();
var stopwatch = Stopwatch.StartNew();
var summary = new StringBuilder("Exporting");
if (!Context.ExportBefore.HasValue && !Context.ExportAfter.HasValue)
{
summary.Append(" all visits");
}
else
{
if (Context.ExportBefore.HasValue)
summary.Append($" before {Context.ExportBefore:O}");
if (Context.ExportAfter.HasValue)
{
if (Context.ExportBefore.HasValue)
summary.Append(" and");
summary.Append($" after {Context.ExportAfter:O}");
}
}
if (!Context.ExportLocations.Any())
{
summary.Append($" from {"location".ToQuantity(locationIdentifiers.Count)} ...");
}
Log.Info(summary.ToString());
foreach (var locationIdentifier in locationIdentifiers)
{
ExportVisitsFromLocation(locationIdentifier);
}
if (MissingAttachmentCount > 0)
Log.Warn($"{"missing attachments".ToQuantity(MissingAttachmentCount)} were detected. Check your app server's BLOB storage configuration.");
Log.Info($"Exported {"visit".ToQuantity(VisitCount)}, skipping {"visit".ToQuantity(SkipCount)}, with {"error".ToQuantity(ErrorCount)} detected in {stopwatch.Elapsed.Humanize(2)}");
}
private void Validate()
{
if (!Directory.Exists(Context.ExportFolder))
throw new ExpectedException($"Export folder '{Context.ExportFolder}' does not exist.");
var appender = new FieldDataResultsAppender
{
Client = Client,
LocationCache = LocationCache,
LocationAliases = Context.LocationAliases,
Log = Log
};
Mapper = new ArchivedVisitMapper
{
Appender = appender,
Plugins = Plugins,
ReferencePointCache = ReferencePointCache,
ParameterIdLookup = ParameterIdLookup,
MethodLookup = MethodLookup
};
}
private IEnumerable<string> GetLocationsToExport()
{
return Context.ExportLocations.Any()
? Context.ExportLocations
: Client.Publish.Get(new LocationDescriptionListServiceRequest())
.LocationDescriptions
.Select(ld => ld.Identifier);
}
private void ExportVisitsFromLocation(string locationIdentifier)
{
var visitDescriptions = GetVisitsToExport(locationIdentifier);
Log.Info($"Exporting {"visit".ToQuantity(visitDescriptions.Count)} from '{locationIdentifier}' ...");
var locationPath = Path.Combine(Context.ExportFolder, FileProcessor.SanitizeFilename(locationIdentifier));
Directory.CreateDirectory(locationPath);
foreach (var visitDescription in visitDescriptions)
{
ExportVisit(locationPath, visitDescription);
}
}
private List<FieldVisitDescription> GetVisitsToExport(string locationIdentifier)
{
try
{
return Client.Publish.Get(new FieldVisitDescriptionListServiceRequest
{
LocationIdentifier = locationIdentifier,
QueryFrom = Context.ExportAfter,
QueryTo = Context.ExportBefore
})
.FieldVisitDescriptions
.OrderBy(v => v.StartTime)
.ToList();
}
catch (WebServiceException exception)
{
if (exception.ErrorCode != "PermissionException")
throw;
Log.Warn($"Skipping export of location '{locationIdentifier}': {exception.ErrorCode} {exception.ErrorMessage}");
++ErrorCount;
return new List<FieldVisitDescription>();
}
}
private void ExportVisit(string locationPath, FieldVisitDescription fieldVisitDescription)
{
var visitPath = Path.Combine(locationPath, FileProcessor.SanitizeFilename($"{fieldVisitDescription.LocationIdentifier}@{fieldVisitDescription.StartTime:yyyy-MM-dd_HH_MM}.json"));
var zipPath = Path.ChangeExtension(visitPath, ".zip");
var targetPath = File.Exists(zipPath)
? zipPath
: visitPath;
if (!Context.ExportOverwrite && File.Exists(targetPath))
{
Log.Info($"Skipping existing '{targetPath}'");
++SkipCount;
return;
}
var archivedVisit = new ArchivedVisit
{
Summary = fieldVisitDescription,
Activities = Client.Publish.Get(new FieldVisitDataServiceRequest
{
FieldVisitIdentifier = fieldVisitDescription.Identifier,
IncludeNodeDetails = true,
IncludeInvalidActivities = true,
IncludeCrossSectionSurveyProfile = true,
IncludeVerticals = true
})
};
try
{
ExportVisit(visitPath, zipPath, archivedVisit);
++VisitCount;
}
catch (Exception exception)
{
++ErrorCount;
var errorPath = Path.ChangeExtension(visitPath, ".error.json");
File.WriteAllText(errorPath, archivedVisit.ToJson().IndentJson());
Log.Error(exception is ExpectedException
? $"'{visitPath}': {exception.Message}"
: $"'{visitPath}': {exception.Message}\n{exception.StackTrace}");
}
}
private void ExportVisit(string visitPath, string zipPath, ArchivedVisit archivedVisit)
{
File.Delete(visitPath);
File.Delete(zipPath);
if (!archivedVisit.Activities.Attachments.Any())
{
Log.Info($"Saving '{visitPath}' ...");
File.WriteAllText(visitPath, TransformToJson(archivedVisit));
return;
}
Log.Info($"Saving '{zipPath}' ...");
var deleteZipOnCleanup = true;
try
{
ExportVisitAndAttachments(visitPath, zipPath, archivedVisit);
deleteZipOnCleanup = false;
}
finally
{
if (deleteZipOnCleanup)
File.Delete(zipPath);
}
}
private void ExportVisitAndAttachments(string visitPath, string zipPath, ArchivedVisit archivedVisit)
{
using (var stream = File.OpenWrite(zipPath))
using (var zipArchive = new ZipArchive(stream, ZipArchiveMode.Create))
{
var rootJsonEntry = zipArchive.CreateEntry(Path.GetFileName(visitPath), CompressionLevel.Fastest);
using (var writer = new StreamWriter(rootJsonEntry.Open()))
{
writer.Write(TransformToJson(archivedVisit));
}
var attachmentCount = 0;
foreach (var attachment in archivedVisit.Activities.Attachments)
{
++attachmentCount;
var attachmentEntry =
zipArchive.CreateEntry($"Attachment{attachmentCount}/{Path.GetFileName(attachment.FileName)}");
var contentBytes = DownloadAttachmentContent(attachmentEntry.FullName, attachment);
using (var writer = new BinaryWriter(attachmentEntry.Open()))
{
writer.Write(contentBytes);
}
}
}
}
private byte[] DownloadAttachmentContent(string downloadPath, Attachment attachment)
{
Log.Info($"Downloading {downloadPath} ...");
try
{
using (var httpResponse = Client.Publish.Get<HttpWebResponse>(attachment.Url))
{
return httpResponse.GetResponseStream().ReadFully();
}
}
catch (WebServiceException exception)
{
if (!IsAttachmentNotFound(exception))
throw;
++MissingAttachmentCount;
throw new ExpectedException($"{exception.StatusCode}: {exception.StatusDescription}: {exception.ErrorMessage}");
}
}
private static bool IsAttachmentNotFound(WebServiceException exception)
{
const string amazonS3NotFound = "AmazonS3Exception";
return exception.IsNotFound()
|| (exception.ErrorCode == amazonS3NotFound && exception.StatusCode == 500);
}
private string TransformToJson(ArchivedVisit archivedVisit)
{
var json = Transform(archivedVisit).ToJson();
if (Context.ExportUtcOverride.HasValue)
{
var adjustedUtcOffset = FormatUtcOffset(Context.ExportUtcOverride.Value);
json = DateTimeOffsetRegex.Replace(json, match => $"\"{match.Groups["datetime"].Value}{adjustedUtcOffset}\"");
}
return json.IndentJson();
}
private static string FormatUtcOffset(TimeSpan timeSpan)
{
return timeSpan >= TimeSpan.Zero
? $"+{timeSpan:hh\\:mm}"
: $"-{timeSpan:hh\\:mm}";
}
// "2016-02-05T10:30:00.0000000-08:00"
private static Regex DateTimeOffsetRegex = new Regex(@"""(?<datetime>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,7})?)(?<utcOffset>[-+]\d{2}:\d{2})""");
private AppendedResults Transform(ArchivedVisit archivedVisit)
{
return new AppendedResults
{
FrameworkAssemblyQualifiedName = typeof(IFieldDataPlugin).AssemblyQualifiedName,
PluginAssemblyQualifiedTypeName = Mapper.GetJsonPluginAQFN(),
AppendedVisits = new List<FieldVisitInfo>
{
Mapper.Map(archivedVisit)
}
};
}
}
}