-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
VssBackup.cs
427 lines (389 loc) · 18.5 KB
/
VssBackup.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#region Copyright Notice
/*
* AlphaVSS Sample Code
* Written by Jay Miller
*
* This code is hereby released into the public domain, This applies
* worldwide.
*/
#endregion
using System;
using System.Diagnostics;
using System.Collections.Generic;
//using System.IO;
using Alphaleonis.Win32.Vss;
using Alphaleonis.Win32.Filesystem;
namespace FolderSync
{
/// <summary>
/// This class encapsulates some simple VSS logic. Its goal is to allow
/// a user to backup a single file from a shadow copy (presumably because
/// that file is otherwise unavailable on its home volume).
/// </summary>
public class VssBackup : IDisposable
{
/// <summary>
/// Setting this flag to true will enable 'component mode', which
/// does not, in this example, do much of any substance.
/// </summary>
/// <remarks>
/// VSS has the ability to selectively disable VSS-compatible
/// components according to the specifics of the current backup. One
/// might, for example, only quiesce Outlook if only the Outlook PST
/// file is intended to be backed up. The ExamineComponents() method
/// provides a framework for this sort of mode if you're interested.
/// Otherwise, this example code quiesces all VSS-compatible components
/// before making its shadow copy.
/// </remarks>
bool ComponentMode = false;
/// <summary>A reference to the VSS context.</summary>
IVssBackupComponents _backup;
/// <summary>Some persistent context for the current snapshot.</summary>
Snapshot _snap;
/// <summary>
/// Constructs a VssBackup object and initializes some of the necessary
/// VSS structures.
/// </summary>
public VssBackup()
{
InitializeBackup();
}
/// <summary>
/// Sets up a shadow copy against the specified volume.
/// </summary>
/// <remarks>
/// This methods is separated out from the constructor because if it
/// throws, we still want the Dispose() method to be called.
/// </remarks>
/// <param name="volumeName">Name of the volume to copy.</param>
public void Setup(string volumeName)
{
Discovery(volumeName);
PreBackup();
}
/// <summary>
/// The disposal of this object involves sending completion notices
/// to the writers, removing the shadow copies from the system and
/// finally releasing the BackupComponents object. This method must
/// be called when this class is no longer used.
/// </summary>
public void Dispose()
{
try { Complete(true); } catch { }
if (_snap != null)
{
_snap.Dispose();
_snap = null;
}
if (_backup != null)
{
_backup.Dispose();
_backup = null;
}
}
/// <summary>
/// This stage initializes both the requester (this program) and
/// any writers on the system in preparation for a backup and sets
/// up a communcation channel between the two.
/// </summary>
void InitializeBackup()
{
// Here we are retrieving an OS-dependent object that encapsulates
// all of the VSS functionality. The OS indepdence that this single
// factory method provides is one of AlphaVSS's major strengths!
IVssFactory vss = VssFactoryProvider.Default.GetVssFactory();
// Now we create a BackupComponents object to manage the backup.
// This object will have a one-to-one relationship with its backup
// and must be cleaned up when the backup finishes (ie. it cannot
// be reused).
//
// Note that this object is a member of our class, as it needs to
// stick around for the full backup.
_backup = vss.CreateVssBackupComponents();
// Now we must initialize the components. We can either start a
// fresh backup by passing null here, or we could resume a previous
// backup operation through an earlier use of the SaveXML method.
_backup.InitializeForBackup(null);
// At this point, we're supposed to establish communication with
// the writers on the system. It is possible before this step to
// enable or disable specific writers via the BackupComponents'
// Enable* and Disable* methods.
_backup.GatherWriterMetadata();
}
/// <summary>
/// This stage involes the requester (us, again) processing the
/// information it received from writers on the system to find out
/// which volumes - if any - must be shadow copied to perform a full
/// backup.
/// </summary>
void Discovery(string fullPath)
{
if (ComponentMode)
// In component mode, we would need to enumerate through each
// component and decide whether it should be added to our
// backup document.
ExamineComponents(fullPath);
else
// Once we are finished with the writer metadata, we can dispose
// of it. If we were in component mode, we would want to keep it
// around so that we could notify the writers of our success or
// failure when we finish the backup.
_backup.FreeWriterMetadata();
// Now we use our helper class to add the appropriate volume to the
// shadow copy set.
_snap = new Snapshot(_backup);
_snap.AddVolume(Path.GetPathRoot(fullPath));
}
/// <summary>
/// This method is optional in this implementation, and in fact does
/// nothing of substance. It does demonstrate how one might parse
/// through the various writers on the system and add them to the
/// backup document if necessary.
/// </summary>
/// <param name="fullPath">The full path of the file to back up.</param>
void ExamineComponents(string fullPath)
{
// At this point it is the requester's duty to examine what the
// writers have prepared for us. The WriterMetadata property
// (in place of the C API's 'GetWriterMetadata' function) collects
// metadata from each writer behind a list interface.
IList<IVssExamineWriterMetadata> writer_mds = _backup.WriterMetadata;
// If you receive a "bad state" error when enumerating, you might
// have a registry inconsistency from a program that improperly
// uninstalled itself. If your event log is showing an error like,
// "ContentIndexingService called routine RegQueryValueExW which
// failed," you'll want to read Microsoft's KB article #907574.
foreach (IVssExamineWriterMetadata metadata in writer_mds)
{
// We can see the name of the writer, if we like.
Trace.WriteLine("Examining metadata for " + metadata.WriterName);
// The important bit of the writers' metadata is the list of
// components each writer is broken into. These components are
// responsible for some number of files, so going through this
// data allows us to construct an initial list of files for our
// shadow copies.
foreach (IVssWMComponent cmp in metadata.Components)
{
// Print out some info for each component.
Trace.WriteLine(" Component: " + cmp.ComponentName);
Trace.WriteLine(" Component info: " + cmp.Caption);
// If a component is available for backup, it's then up to us to
// decide whether it is relevant to the current backup. To do
// this, we may examine the files each component manages.
foreach (VssWMFileDescriptor file in cmp.Files)
{
// The idea here is to find out whether these files are
// relevant to whatever purpose your application holds. If
// they are, you should a) add this component to your backup
// set so VSS involves it in the shadow copy operation, and
// b) record the files' volume names so you know later which
// volumes need to be shadow copied.
// I'm not worried about that stuff for this example, though,
// so instead I'm printing out the stuff you might need to
// examine if you have requirements of that sort.
Trace.WriteLine(" Path: " + file.Path);
Trace.WriteLine(" Spec: " + file.FileSpecification);
// Here we might insert some logic to:
//
// 1. Check whether the AlternateLocation property is valid.
// 2. Expand environment vairables in either Path.or
// AlternateLocation, as appropriate.
// 3. Considering the FileSpecification and the IsRecursive
// properties, decide whether this component manages
// the file(s) you wish to backup (in this case, the
// fullPath argument).
//
// If this component is relevant, add it with AddComponent().
// (The FileToPathSpecification method below might help with
// some of these steps.)
}
}
}
}
/// <summary>
/// This phase of the backup is focused around creating the shadow copy.
/// We will notify writers of the impending snapshot, after which they
/// have a short period of time to get their on-disk data in order and
/// then quiesce writing.
/// </summary>
void PreBackup()
{
Debug.Assert(_snap != null);
// This next bit is a way to tell writers just what sort of backup
// they should be preparing for. The important parts for us now
// are the first and third arguments: we want to do a full,
// backup and, depending on whether we are in component mode, either
// a full-volume backup or a backup that only requires specific
// components.
_backup.SetBackupState
(
ComponentMode,
true,
VssBackupType.Copy, //VssBackupType.Full,
false
);
// From here we just need to send messages to each writer that our
// snapshot is imminent,
// We simply block while the writers to complete their background preparations.
_backup.PrepareForBackup();
// It's now time to create the snapshot. Each writer will have to
// freeze its I/O to the selected volumes for up to 10 seconds
// while this process takes place.
_snap.Copy();
}
/// <summary>
/// This simple method uses a bit of string manipulation to turn a
/// full, local path into its corresponding snapshot path. This
/// method may help users perform full file copies from the snapsnot.
/// </summary>
/// <remarks>
/// Note that the System.IO methods are not able to access files on
/// the snapshot. Instead, you will need to use the AlphaFS library
/// as shown in the example.
/// </remarks>
/// <example>
/// This code creates a shadow copy and copies a single file from
/// the new snapshot to a location on the D drive. Here we're
/// using the AlphaFS library to make a full-file copy of the file.
/// <code>
/// string source_file = @"C:\Windows\system32\config\sam";
/// string backup_root = @"D:\Backups";
/// string backup_path = Path.Combine(backup_root,
/// Path.GetFilename(source_file));
///
/// // Initialize the shadow copy subsystem.
/// using (VssBackup vss = new VssBackup())
/// {
/// vss.Setup(Path.GetPathRoot(source_file));
/// string snap_path = vss.GetSnapshotPath(source_file);
///
/// // Here we use the AlphaFS library to make the copy.
/// Alphaleonis.Win32.Filesystem.File.Copy(snap_path, backup_path);
/// }
/// </code>
/// </example>
/// <seealso cref="GetStream"/>
/// <param name="localPath">The full path of the original file.</param>
/// <returns>A full path to the same file on the snapshot.</returns>
public string GetSnapshotPath(string localPath)
{
Trace.WriteLine("New volume: " + _snap.Root);
// This bit replaces the file's normal root information with root
// info from our new shadow copy.
if (Path.IsPathRooted(localPath))
{
string root = Path.GetPathRoot(localPath);
localPath = localPath.Replace(root, String.Empty);
}
string slash = Path.DirectorySeparatorChar.ToString();
if (!_snap.Root.EndsWith(slash) && !localPath.StartsWith(slash))
localPath = localPath.Insert(0, slash);
localPath = localPath.Insert(0, _snap.Root);
Trace.WriteLine("Converted path: " + localPath);
return localPath;
}
#if true
/// <summary>
/// This method opens a stream over the shadow copy of the specified
/// file.
/// </summary>
/// <example>
/// This code creates a shadow copy and opens a stream over a file
/// on the new snapshot volume.
/// <code>
/// string source_file = @"C:\Windows\system32\config\sam";
///
/// // Initialize the shadow copy subsystem.
/// using (VssBackup vss = new VssBackup())
/// {
/// vss.Setup(Path.GetPathRoot(filename));
///
/// // We can now access the shadow copy by either retrieving a stream:
/// using (Stream s = vss.GetStream(filename))
/// {
/// Debug.Assert(s.CanRead == true);
/// Debug.Assert(s.CanWrite == false);
/// }
/// }
/// </code>
/// </example>
public System.IO.Stream GetStream(string localPath)
{
// GetSnapshotPath() returns a very funky-looking path. The
// System.IO methods can't handle these sorts of paths, so instead
// we're using AlphaFS, another excellent library by Alpha Leonis.
// Note that we have no 'using System.IO' at the top of the file.
// (The Stream it returns, however, is just a System.IO stream.)
return File.OpenRead(GetSnapshotPath(localPath));
}
#endif
/// <summary>
/// The final phase of the backup involves some cleanup steps.
/// If we're in component mode, we're supposed to notify each of the
/// writers of the outcome of the backup. Once that's done, or if
/// we're not in component mode, we send the BackupComplete event to
/// all of the writers.
/// </summary>
/// <param name="succeeded">Success value for all of the writers.</param>
void Complete(bool succeeded)
{
if (ComponentMode)
{
// As before, we iterate through all of the writers on the system.
// A more efficient method might only iterate through those writers
// that were actually involved in this backup.
IList<IVssExamineWriterMetadata> writers = _backup.WriterMetadata;
foreach (IVssExamineWriterMetadata metadata in writers)
{
foreach (IVssWMComponent component in metadata.Components)
{
// The BackupSucceeded call should mirror the AddComponent
// call that was called during the discovery phase.
_backup.SetBackupSucceeded(
metadata.InstanceId, metadata.WriterId,
component.Type, component.LogicalPath,
component.ComponentName, succeeded);
}
}
// Finally, we can dispose of the writer metadata.
_backup.FreeWriterMetadata();
}
try
{
// The BackupComplete event must be sent to all of the writers.
_backup.BackupComplete();
}
// Not sure why, but this throws a VSS_BAD_STATE on XP and W2K3.
// Per some forum posts about this, I'm just ignoring it.
catch (VssBadStateException) { }
}
/// <summary>
/// This method takes the information in a file description and
/// converts it to a full path specification - with wildcards.
/// </summary>
/// <remarks>
/// Using the wildcard-to-regex library found at
/// http://www.codeproject.com/KB/string/wildcmp.aspx on the
/// output of this method might be very helpful.
/// </remarks>
/// <param name="file">Object describing a component's file.</param>
/// <returns>
/// Returns a full path, potentially including DOS wildcards. Eg.
/// 'c:\windows\config\*'.
/// </returns>
string FileToPathSpecification(VssWMFileDescriptor file)
{
// Environment variables (eg. "%windir%") are common.
string path = Environment.ExpandEnvironmentVariables(file.Path);
// Use the alternate location if it's present.
if (!String.IsNullOrEmpty(file.AlternateLocation))
path = Environment.ExpandEnvironmentVariables(
file.AlternateLocation);
// Normalize wildcard usage.
string spec = file.FileSpecification.Replace("*.*", "*");
// Combine the file specification and the directory name.
return Path.Combine(path, file.FileSpecification);
}
}
}