-
Notifications
You must be signed in to change notification settings - Fork 4
/
Program.cs
313 lines (281 loc) · 13.8 KB
/
Program.cs
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
// Copyright © Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the
// Apache License, Version 2.0 (http://opensource.org/licenses/Apache-2.0)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Text;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Security.AccessControl;
using System.Security.Principal;
namespace FileSystemDurabilityPlugin
{
class WindowsAzureBlob2FileSystemSync
{
// Main thread handle
static Thread _mainThread = null;
static void Main(string[] args)
{
string accountName = null;
string accountKey = null;
string containerName = null;
string localPathName = null;
string excludePaths = null;
string fileNameIncludesToSync = null;
string excludeSubDirectories = null;
string syncFrequencyInSeconds = null;
CloudStorageAccount storageAccount = null;
FileSyncScopeFilter filter = null;
try
{
try
{
if (RoleEnvironment.IsAvailable)
{
// Store main thread handle
WindowsAzureBlob2FileSystemSync._mainThread = Thread.CurrentThread;
// Read configuration settings
accountName = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.StorageAccountName");
accountKey = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.StorageAccountPrimaryKey");
containerName = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.SyncContainerName");
// FileSystemDurabilityPlugin.LocalFolderToSync must be relative to web site root or approot
// Check if sitesroot\0 exists. We only synchronize the firt web site
string appRootDir = Environment.GetEnvironmentVariable("RoleRoot") + @"\sitesroot\0";
if (!Directory.Exists(appRootDir))
{
// May be WorkerRole
appRootDir = Environment.GetEnvironmentVariable("RoleRoot") + @"\approot";
}
try
{
// Make appRootDir writable.
DirectorySecurity sec = Directory.GetAccessControl(appRootDir);
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone,
FileSystemRights.Modify | FileSystemRights.Synchronize,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
Directory.SetAccessControl(appRootDir, sec);
}
catch (Exception ex)
{
Trace.TraceError("Failed to make directory {0} writable. Error: {1}", appRootDir, ex.Message);
Environment.Exit(-1);
}
// Set sync folder on local VM
localPathName = Path.Combine(appRootDir, RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.LocalFolderToSync"));
fileNameIncludesToSync = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.FileNameIncludesToSync");
excludePaths = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.ExcludePathsFromSync");
excludeSubDirectories = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.ExcludeSubDirectories");
syncFrequencyInSeconds = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.SyncFrequencyInSeconds");
}
else
{
// Outside role envionment, read command line argument
Trace.TraceError("Outside role envionment. Synchronization not possible.");
Environment.Exit(-1);
}
}
catch (Exception ex)
{
Trace.TraceError("Failed to read configuration settings. Error: {0}", ex.Message);
Environment.Exit(-1);
}
if (!Directory.Exists(localPathName))
{
Trace.TraceError("Please ensure that the local target directory exists.");
Environment.Exit(-1);
}
//
// Setup Store
//
if (accountName.Equals("devstoreaccount1"))
{
storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
}
else
{
storageAccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, accountKey), true);
}
//
// Create container if needed
//
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
blobClient.GetContainerReference(containerName).CreateIfNotExist();
// Whether to include specific files only
if (!string.IsNullOrEmpty(fileNameIncludesToSync))
{
if (filter == null)
{
filter = new FileSyncScopeFilter();
}
string[] fileNameIncludesToSyncInfo = fileNameIncludesToSync.Split(',');
foreach (string fileIncludes in fileNameIncludesToSyncInfo)
{
filter.FileNameIncludes.Add(fileIncludes);
}
}
// Set exclude path filter
if (!string.IsNullOrEmpty(excludePaths))
{
if (filter == null)
{
filter = new FileSyncScopeFilter();
}
string[] excludePathInfo = excludePaths.Split(',');
foreach (string excludePath in excludePathInfo)
{
filter.SubdirectoryExcludes.Add(excludePath);
}
}
// Whether to exclude directoraries
if (excludeSubDirectories.Equals("true"))
{
if (filter == null)
{
filter = new FileSyncScopeFilter();
}
filter.AttributeExcludeMask = FileAttributes.Directory;
}
if (syncFrequencyInSeconds.Equals("-1"))
{
SynchronizeOnce(filter, localPathName, containerName, storageAccount);
}
else
{
// Need to synchronize periodically
// Register event handler for roleinstance stopping and changed events
RoleEnvironment.Stopping += WindowsAzureBlob2FileSystemSync.RoleEnvironmentStopping;
RoleEnvironment.Changed += WindowsAzureBlob2FileSystemSync.RoleEnvironmentChanged;
int frequencyInSecond = int.Parse(syncFrequencyInSeconds, System.Globalization.NumberStyles.Integer);
if (frequencyInSecond > 0)
{
// Start Synchronization periodically
while (true)
{
try
{
SynchronizeOnce(filter, localPathName, containerName, storageAccount);
}
catch (Exception ex)
{
Trace.TraceError("Failed to Synchronize. Error: {0}", ex.Message);
}
// Check new value for SyncFrequencyInSeconds, it can be modified
syncFrequencyInSeconds = RoleEnvironment.GetConfigurationSettingValue("FileSystemDurabilityPlugin.SyncFrequencyInSeconds");
int currentFrequencyInSecond = int.Parse(syncFrequencyInSeconds, System.Globalization.NumberStyles.Integer);
if (frequencyInSecond != currentFrequencyInSecond)
{
Trace.TraceInformation("Changing sync frequency to {0} seconds.", currentFrequencyInSecond);
frequencyInSecond = currentFrequencyInSecond;
}
try
{
if (frequencyInSecond > 0)
{
Thread.Sleep(TimeSpan.FromSeconds(frequencyInSecond));
}
else
{
// Pause the thread
Thread.Sleep(Timeout.Infinite);
}
}
catch (ThreadInterruptedException)
{
Trace.TraceInformation("File Synchronization thread interrupted. Configuration settings might have changed.");
}
}
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
}
}
// Event handler for roleinstance stopping event
private static void RoleEnvironmentStopping(object sender, RoleEnvironmentStoppingEventArgs e)
{
Trace.TraceError("Roleinstance stopping, hence terminating file synchronization.");
Environment.Exit(-1);
}
// Event handler for roleenvironment changed event
private static void RoleEnvironmentChanged(object sender, RoleEnvironmentChangedEventArgs e)
{
if (WindowsAzureBlob2FileSystemSync._mainThread != null)
{
Trace.TraceInformation("Rolenvironment changed. Interrupting Synchronization thread that might be sleeping");
WindowsAzureBlob2FileSystemSync._mainThread.Interrupt();
}
}
// Main sync happens here
private static void SynchronizeOnce(
FileSyncScopeFilter filter,
string localPathName,
string containerName,
CloudStorageAccount storageAccount)
{
// Setup Provider
AzureBlobStore blobStore = new AzureBlobStore(containerName, storageAccount);
AzureBlobSyncProvider azureProvider = new AzureBlobSyncProvider(containerName, blobStore);
azureProvider.ApplyingChange += new EventHandler<ApplyingBlobEventArgs>(UploadingFile);
FileSyncProvider fileSyncProvider = null;
if (filter == null)
{
try
{
fileSyncProvider = new FileSyncProvider(localPathName);
}
catch (ArgumentException)
{
fileSyncProvider = new FileSyncProvider(Guid.NewGuid(), localPathName);
}
}
else
{
try
{
fileSyncProvider = new FileSyncProvider(localPathName, filter, FileSyncOptions.None);
}
catch (ArgumentException)
{
fileSyncProvider = new FileSyncProvider(Guid.NewGuid(), localPathName, filter, FileSyncOptions.None);
}
}
fileSyncProvider.ApplyingChange += new EventHandler<ApplyingChangeEventArgs>(WindowsAzureBlob2FileSystemSync.DownloadingFile);
try
{
SyncOrchestrator orchestrator = new SyncOrchestrator();
orchestrator.LocalProvider = fileSyncProvider;
orchestrator.RemoteProvider = azureProvider;
orchestrator.Direction = SyncDirectionOrder.DownloadAndUpload;
orchestrator.Synchronize();
}
catch (Exception ex)
{
Trace.TraceError("Failed to Synchronize. Error: {0}", ex.Message);
}
finally
{
fileSyncProvider.Dispose();
}
}
public static void DownloadingFile(object sender, ApplyingChangeEventArgs args)
{
}
public static void UploadingFile(object sender, ApplyingBlobEventArgs args)
{
}
}
}