public static void CopyFile(string from, string to) { FileInfo MyFileInfo = new FileInfo(from); String _Volume = MyFileInfo.Directory.Root.Name; // VSS step 1: Initialize IVssImplementation _vssImplementation = VssUtils.LoadImplementation(); IVssBackupComponents _backup = _vssImplementation.CreateVssBackupComponents(); _backup.InitializeForBackup(null); // VSS step 2: Getting Metadata from all the VSS writers _backup.GatherWriterMetadata(); // VSS step 3: VSS Configuration _backup.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease); _backup.SetBackupState(false, true, Alphaleonis.Win32.Vss.VssBackupType.Full, false); // VSS step 4: Declaring the Volumes that we need to use in this beckup. // The Snapshot is a volume element (Here come the name "Volume Shadow-Copy") // For each file that we nee to copy we have to make sure that the propere volume is in the "Snapshot Set" Guid MyGuid01 = _backup.StartSnapshotSet(); Guid MyGuid02 = _backup.AddToSnapshotSet(_Volume, Guid.Empty); // VSS step 5: Preparation (Writers & Provaiders need to start preparation) _backup.PrepareForBackup(); // VSS step 6: Create a Snapshot For each volume in the "Snapshot Set" _backup.DoSnapshotSet(); _backup.ExposeSnapshot(MyGuid02, null, VssVolumeSnapshotAttributes.ExposedLocally, "L:"); // VSS step 8: Copy Files! /*********************************** * /* Now we start to copy the files/folders/disk! * /* Execution time can depend on what we are copying * /* We can copy one element or several element. * /* As long as we are working under the same snapshot, * /* the element should be in consist state from the same point-in-time * /***********************************/ String sVSSFile1 = from.Replace(_Volume, @"L:\"); if (File.Exists(sVSSFile1)) { System.IO.File.Copy(sVSSFile1, to + @"\" + System.IO.Path.GetFileName(from), true); } // VSS step 9: Delete the snapshot (using the Exposed Snapshot name) foreach (VssSnapshotProperties prop in _backup.QuerySnapshots()) { if (prop.ExposedName == @"L:\") { Console.WriteLine("prop.ExposedNam Found!"); _backup.DeleteSnapshot(prop.SnapshotId, true); } } _backup = null; }
public void Delete(ISnapshot sn) { Logger.Append(Severity.DEBUG, "Deleting snapshot " + sn.Path + " (id " + sn.Id + ")"); if (!OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003)) { // Deleting is unnecessary on XP since snaps are non-persistent // and automatically released on Disposing VSS objects. return; } try{ IVssImplementation vssi = VssUtils.LoadImplementation(); using (IVssBackupComponents oVSS = vssi.CreateVssBackupComponents()){ oVSS.InitializeForBackup(null); oVSS.SetContext(VssSnapshotContext.All); oVSS.DeleteSnapshot(sn.Id, true); } Logger.Append(Severity.INFO, "Deleted snapshot " + sn.Path + " (id " + sn.Id + ")"); } catch (Exception vsse) { Logger.Append(Severity.WARNING, "Unable to delete snapshot " + sn.Path + " (id " + sn.Id + "): " + vsse.Message); //backup.Dispose(); throw vsse; } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { BackupComplete(); if (snapShotSet != Guid.Empty) { backup.DeleteSnapshotSet(snapShotSet, true); snapShotSet = Guid.Empty; } if (backup != null) { backup.Dispose(); backup = null; } } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
public void DoSnapshot() { try { logger.Debug("Doing snapshot..."); IVssImplementation vssImplementation = VssUtils.LoadImplementation(); backup = vssImplementation.CreateVssBackupComponents(); backup.InitializeForBackup(null); backup.SetBackupState(false, false, VssBackupType.Copy, false); backup.EnableWriterClasses(); backup.GatherWriterMetadata(); backup.GatherWriterStatus(); backup.SetContext(VssSnapshotContext.AppRollback); snapshotSetId = backup.StartSnapshotSet(); String rootPath = Volume.GetUniqueVolumeNameForPath(path); logger.Debug("RootPath: {0}.", rootPath); snapshotId = backup.AddToSnapshotSet(rootPath); backup.PrepareForBackup(); backup.DoSnapshotSet(); //File.WriteAllText(@"d:" + Path.DirectorySeparatorChar + "Document.xml", backup.SaveAsXml()); backup.BackupComplete(); } catch (Exception e) { logger.Error("Error occurred when doing snapshot, info: {0}.", e); } }
private void CreateVssSnapshotOfSystemVolume(IVssBackupComponents backupComponents) { try { logger.LogInformation($"Creating VSS snapshot for drive {migrationData.OperatingSystemDriveLetter}:\\"); backupComponents.InitializeForBackup(null); backupComponents.GatherWriterMetadata(); backupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease); this.vssSnapshotSetId = backupComponents.StartSnapshotSet(); this.vssSnapshotId = backupComponents.AddToSnapshotSet($"{migrationData.OperatingSystemDriveLetter}:\\"); backupComponents.SetBackupState(false, true, VssBackupType.Differential, false); backupComponents.PrepareForBackup(); backupComponents.DoSnapshotSet(); VssSnapshotProperties snapshotInfo = backupComponents.GetSnapshotProperties(this.vssSnapshotId); logger.LogDebug($"VSS snapshot created. Root Path: {snapshotInfo.SnapshotDeviceObject}"); } catch (Exception ex) { logger.LogError(ex, "An error occured during VSS snapshot creation"); if (this.vssSnapshotId != Guid.Empty) { backupComponents.DeleteSnapshot(this.vssSnapshotId, true); this.vssSnapshotId = Guid.Empty; this.vssSnapshotSetId = Guid.Empty; } throw; } }
/// <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! IVssImplementation vss = VssUtils.LoadImplementation(); // 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(); }
public void Dispose() { try { if (_mappedDrives != null) { foreach (var d in _mappedDrives) { d.Dispose(); } _mappedDrives = null; } } catch (Exception ex) { Logging.Log.WriteVerboseMessage(LOGTAG, "MappedDriveCleanupError", ex, "Failed during VSS mapped drive unmapping"); } try { _vssBackupComponents?.BackupComplete(); } catch (Exception ex) { Logging.Log.WriteVerboseMessage(LOGTAG, "VSSTerminateError", ex, "Failed to signal VSS completion"); } try { if (_vssBackupComponents != null) { foreach (var g in _volumes.Values) { try { _vssBackupComponents.DeleteSnapshot(g, false); } catch (Exception ex) { Logging.Log.WriteVerboseMessage(LOGTAG, "VSSSnapShotDeleteError", ex, "Failed to close VSS snapshot"); } } } } catch (Exception ex) { Logging.Log.WriteVerboseMessage(LOGTAG, "VSSSnapShotDeleteCleanError", ex, "Failed during VSS esnapshot closing"); } if (_vssBackupComponents != null) { _vssBackupComponents.Dispose(); _vssBackupComponents = null; } }
public static IVssBackupComponents GetVssBackupComponents() { //Prepare the backup IVssBackupComponents vssBackupComponents = CreateVssBackupComponents(); vssBackupComponents.InitializeForBackup(null); vssBackupComponents.SetContext(VssSnapshotContext.Backup); vssBackupComponents.SetBackupState(false, true, VssBackupType.Full, false); return(vssBackupComponents); }
public void Dispose(bool ok) { try { Complete(ok); Delete(); } catch { } if (_backup != null) { _backup.Dispose(); _backup = null; } }
private void Initialize(string Volume, bool IncludeBootableSystemState) { //string filename = @"C:\Windows\system32\config\sam"; //FileInfo fiSource = new FileInfo(filename); //String Volume = fiSource.Directory.Root.Name; // VSS step 1: Initialize IVssImplementation vss = VssUtils.LoadImplementation(); IVssBackupComponents backup = vss.CreateVssBackupComponents(); backup.InitializeForBackup(null); // VSS step 2: Getting Metadata from all the VSS writers backup.GatherWriterMetadata(); // VSS step 3: VSS Configuration backup.SetContext((VssVolumeSnapshotAttributes)0); backup.SetBackupState(false, IncludeBootableSystemState, Alphaleonis.Win32.Vss.VssBackupType.Full, false); // VSS step 4: Declaring the Volumes that we need to use in this beckup. // The Snapshot is a volume element (hence the name "Volume Shadow-Copy"). // For each file that we nee to copy we have to make sure that the proper volume is included in the "Snapshot Set". Guid SetGuid = backup.StartSnapshotSet(); Guid VolumeGuid = backup.AddToSnapshotSet(Volume, Guid.Empty); // VSS step 5: Preparation (Writers & Provaiders need to start preparation) backup.PrepareForBackup(); // VSS step 6: Create a Snapshot For each volume in the "Snapshot Set" backup.DoSnapshotSet(); /*********************************** * /* At this point we have a snapshot! * /* This action should not take more then 60 second, regardless of file or disk size. * /* The snapshot is not a backup or any copy! * /* please more information at http://technet.microsoft.com/en-us/library/ee923636.aspx * /***********************************/ // VSS step 7: Expose Snapshot /*********************************** * /* Snapshot path look like: * \\?\Volume{011682bf-23d7-11e2-93e7-806e6f6e6963}\ * The build in method System.IO.File.Copy do not work with path like this, * Therefore, we are going to Expose the Snapshot to our application, * by mapping the Snapshot to new virtual volume * - Make sure that you are using a volume that is not already exist * - This is only for learning purposes. usually we will use the snapshot directly as i show in the next example in the blog * /***********************************/ VssSnapshotProperties SnapshotProperties = backup.GetSnapshotProperties(VolumeGuid); DirectoryInfo diShadowRoot = new DirectoryInfo(SnapshotProperties.SnapshotDeviceObject); DirectoryInfo[] Folders = diShadowRoot.GetDirectories(); }
public VSSService() { backup = VssUtils.LoadImplementation().CreateVssBackupComponents(); backup.InitializeForBackup(null); snapShotSet = backup.StartSnapshotSet(); // TODO : per component backup //backup.GatherWriterMetadata(); }
void InitializeBackup() { IVssImplementation vss = VssUtils.LoadImplementation(); _backup = vss.CreateVssBackupComponents(); _backup.InitializeForBackup(null); using (IVssAsync async = _backup.GatherWriterMetadata()) { async.Wait(); } }
public bool IsVolumeSnapshottable(string volumeName) { IVssImplementation vssImplementation = VssUtils.LoadImplementation(); using (IVssBackupComponents backup = vssImplementation.CreateVssBackupComponents()){ backup.InitializeForBackup(null); using (IVssAsync async = backup.GatherWriterMetadata()){ async.Wait(); async.Dispose(); } return(backup.IsVolumeSupported(volumeName)); } }
private static VssSnapshotProperties GetSnapshotProperties(IVssBackupComponents backupComponents, Guid snapshotId) { VssSnapshotProperties props = new VssSnapshotProperties(); IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VssSnapshotProperties))); backupComponents.GetSnapshotProperties(snapshotId, buffer); Marshal.PtrToStructure(buffer, props); NativeMethods.VssFreeSnapshotProperties(buffer); return(props); }
// This stage initializes both the requester and any writers on the system in // preparation for a backup, and sets up a communication channel between the two. private void InitializeBackup() { // Retrieving an OS-dependent object that encapsulates all of the VSS functionality. IVssImplementation vss = VssUtils.LoadImplementation(); // Now we create a BackupComponents object to manage the backup. _backup = vss.CreateVssBackupComponents(); // Now we must initialize the components. We can either start a fresh backup by passing null here. _backup.InitializeForBackup(null); // 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(); }
public VSS(BackupLevel level) { this.RestorePosition = RestoreOrder.AfterStorage; this.ExplodedComponents = new List <string>(); Metadata = new SPOMetadata(); BasePaths = new List <BasePath>(); IVssImplementation vss = VssUtils.LoadImplementation(); backup = vss.CreateVssBackupComponents(); //Logger.Append(Severity.DEBUG, "0/6 Initializing Snapshot ("+ ((BasePaths == null)? "NON-component mode" : "component mode")+")"); backup.InitializeForBackup(null); VssBackupType vssLevel = VssBackupType.Full; if (level == BackupLevel.Full) { vssLevel = VssBackupType.Full; } else if (level == BackupLevel.Refresh) { vssLevel = VssBackupType.Incremental; } /* else if (level == BackupLevel.Differential) * vssLevel = VssBackupType.Differential;*/ else if (level == BackupLevel.TransactionLog) { vssLevel = VssBackupType.Log; } //if(spoPaths == null) // component-less snapshot set // backup.SetBackupState(false, true, VssBackupType.Full, false); //else backup.SetBackupState(true, true, vssLevel, false); if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003)) { // The only context supported on Windows XP is VssSnapshotContext.Backup backup.SetContext(VssSnapshotContext.AppRollback); } //Logger.Append(Severity.DEBUG, "1/6 Gathering writers metadata and status"); using (IVssAsync async = backup.GatherWriterMetadata()){ async.Wait(); async.Dispose(); } // gather writers status before adding backup set components using (IVssAsync async = backup.GatherWriterStatus()){ async.Wait(); async.Dispose(); } }
private void RemoveVssSnapshotOfSystemVolume(IVssBackupComponents backupComponents) { if (this.vssSnapshotId != Guid.Empty) { try { backupComponents.BackupComplete(); } catch (VssBadStateException) { } VssSnapshotProperties snapshotInfo = backupComponents.GetSnapshotProperties(this.vssSnapshotId); logger.LogDebug($"Removing snapshot {snapshotInfo.SnapshotDeviceObject}"); backupComponents.DeleteSnapshot(this.vssSnapshotId, true); } }
public void Dispose() { try { Complete(true); } catch { } if (thisSnap != null) { thisSnap.Dispose(); thisSnap = null; } if (thisBackup != null) { thisBackup.Dispose(); thisBackup = null; } }
public void Dispose() { if (bkpComponents != null) { if (_needsCleanup) { Program.LogAction("Deleting VSS snapshots and cleaning up..."); bkpComponents.BackupComplete(); EnsureNoWritersFailed(bkpComponents, writers); _needsCleanup = false; Program.LogAction(" done."); } bkpComponents.Dispose(); bkpComponents = null; } }
/// <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; } }
private static void SelectExplicitelyIncludedComponents(IVssBackupComponents bkpComponents, List <VssWriterDescriptor> writers) { Program.LogDebug("Select explicitly included components ..."); foreach (VssWriterDescriptor writer in writers.Where(w => !w.IsExcluded)) { Program.LogDebug($" * Writer '{writer.WriterMetadata.WriterName}':"); // Compute the roots of included components foreach (var component in writer.ComponentDescriptors.Where(c => c.IsExplicitlyIncluded)) { Program.LogDebug($" - Add component {component.FullPath}"); bkpComponents.AddComponent(writer.WriterMetadata.InstanceId, writer.WriterMetadata.WriterId, component.ComponentType, component.LogicalPath, component.ComponentName); } } }
void InitializeBackup() { IVssImplementation vss = VssUtils.LoadImplementation(); Debug.WriteLine("vss interface implementation called - vssutils.loadimplementation() called"); thisBackup = vss.CreateVssBackupComponents(); Debug.WriteLine("backup component created"); //try //{ thisBackup.InitializeForBackup(null); thisBackup.GatherWriterMetadata(); //} //catch (Alphaleonis.Win32.Vss.VssUnexpectedErrorException ue) //{ // Debug.WriteLine("AlphaVss Unexpected Error: " + ue); // } }
public override void PerformStep() { logger.LogInformation("Cloning operating system."); using (IVssBackupComponents backupComponents = vss.CreateVssBackupComponents()) { this.CreateVssSnapshotOfSystemVolume(backupComponents); try { logger.LogInformation("Copying system partition data..."); using (PrivilegeEnabler privEnabler = new PrivilegeEnabler(Privilege.Backup, Privilege.Restore)) { VssSnapshotProperties snapshotInfo = backupComponents.GetSnapshotProperties(this.vssSnapshotId); using (Stream rawVolStream = this.fileSystemHelper.OpenRawDiskStream(snapshotInfo.SnapshotDeviceObject)) { string vhdFullName = $"{migrationData.VhdFileTemporaryFolder}\\{migrationData.VhdFileName}"; using (VirtualDiskDecorator disk = this.fileSystemHelper.OpenVhdx(vhdFullName)) { var partitionTable = disk.Partitions; if (partitionTable != null) { int partIndex = partitionTable.CreatePrimaryBySector(1, (rawVolStream.Length / disk.Geometry.BytesPerSector), BiosPartitionTypes.Ntfs, false); PartitionInfoDecorator partition = disk.Partitions[partIndex]; using (var vhdPartitionStream = partition.Open()) { this.fileSystemHelper.CloneNtfsFileSystem(rawVolStream, vhdPartitionStream, logger); } } else { logger.LogError("VHD disk does not contain BIOS partition table. Other partitions tables are not supported."); } } } } } finally { this.RemoveVssSnapshotOfSystemVolume(backupComponents); //always remove the VSS snapshot, either after success or failure } logger.LogInformation("Cloning operating system completed."); } return; }
public override bool CheckPrerequisities(ref string[] messages) { List <string> messageList = new List <string>(); logger.LogDebug("Checking vss requirements."); using (IVssBackupComponents backupComponents = vss.CreateVssBackupComponents()) { backupComponents.InitializeForBackup(null); if (!backupComponents.IsVolumeSupported($"{migrationData.OperatingSystemDriveLetter}:\\")) { messageList.Add($"System volume does not support VSS."); } } messages = messageList.ToArray(); return(messageList.Count == 0); }
static void Main(string[] args) { IVssFactory vssImplementation = VssFactoryProvider.Default.GetVssFactory(); using (IVssBackupComponents backup = vssImplementation.CreateVssBackupComponents()) { backup.InitializeForBackup(null); backup.SetContext(VssSnapshotContext.All); foreach (VssSnapshotProperties prop in backup.QuerySnapshots()) { Console.WriteLine("Snapshot ID: {0:B}", prop.SnapshotId); Console.WriteLine("Snapshot Set ID: {0:B}", prop.SnapshotSetId); Console.WriteLine("Original Volume Name: {0}", prop.OriginalVolumeName); Console.WriteLine(); } } }
static void BackupFile(string srcPath, string destPath) { srcPath = Path.GetFullPath(srcPath); IVssImplementation vssImpl = VssUtils.LoadImplementation(); using (IVssBackupComponents vss = vssImpl.CreateVssBackupComponents()) { vss.InitializeForBackup(null); vss.SetBackupState(true, true, VssBackupType.Full, false); vss.SetContext(VssSnapshotContext.FileShareBackup); using (IVssAsync async = vss.GatherWriterMetadata()) async.Wait(); Guid vssSet = vss.StartSnapshotSet(); var rootPath = Path.GetPathRoot(srcPath); var snapshotId = vss.AddToSnapshotSet(rootPath, Guid.Empty); using (IVssAsync async = vss.DoSnapshotSet()) async.Wait(); try { var snapshotPath = vss.GetSnapshotProperties(snapshotId).SnapshotDeviceObject; var pathNoRoot = srcPath.Substring(rootPath.Length); var path = Path.Combine(snapshotPath, pathNoRoot); if (File.Exists(destPath)) { File.Delete(destPath); } Alphaleonis.Win32.Filesystem.File.Copy(path, destPath); } finally { vss.DeleteSnapshotSet(vssSet, true); } } }
private Guid CreateSnapshotSet(List <CloneVolume> cloneVolumes, IVssBackupComponents backupCmpnts) { if (!Quiet) { Console.WriteLine("Snapshotting Volumes..."); } backupCmpnts.InitializeForBackup(null); backupCmpnts.SetContext(0 /* VSS_CTX_BACKUP */); backupCmpnts.SetBackupState(false, true, 5 /* VSS_BT_COPY */, false); CallAsyncMethod(backupCmpnts.GatherWriterMetadata); Guid snapshotSetId; try { backupCmpnts.StartSnapshotSet(out snapshotSetId); foreach (var vol in cloneVolumes) { backupCmpnts.AddToSnapshotSet(vol.Path, Guid.Empty, out vol.SnapshotId); } CallAsyncMethod(backupCmpnts.PrepareForBackup); CallAsyncMethod(backupCmpnts.DoSnapshotSet); } catch { backupCmpnts.AbortBackup(); throw; } foreach (var vol in cloneVolumes) { vol.SnapshotProperties = GetSnapshotProperties(backupCmpnts, vol.SnapshotId); } return(snapshotSetId); }
public bool CreateSnapshot() { try { var impl = VssUtils.LoadImplementation(); if (impl == null) { return(false); } _backup = impl.CreateVssBackupComponents(); _backup.InitializeForBackup(null); if (!_backup.IsVolumeSupported(_volumeName)) { return(false); } _backup.GatherWriterMetadata(); _backup.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease); _backup.SetBackupState(false, true, VssBackupType.Full, false); _snapshotSetId = _backup.StartSnapshotSet(); _shadowCopyId = _backup.AddToSnapshotSet(_volumeName, Guid.Empty); _backup.PrepareForBackup(); _backup.DoSnapshotSet(); _snapshotVolumeName = _backup.QuerySnapshots().First(x => x.SnapshotSetId == _snapshotSetId && x.SnapshotId == _shadowCopyId).OriginalVolumeName; return(true); } catch { Helpers.Dispose(ref _backup); return(false); } }
static void Main(string[] args) { IVssImplementation vssImplementation = VssUtils.LoadImplementation(); using (IVssBackupComponents backup = vssImplementation.CreateVssBackupComponents()) { backup.InitializeForBackup(null); if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003)) { // This does not work on Windows XP, since the only context supported // on Windows XP is VssSnapshotContext.Backup which is the default. backup.SetContext(VssSnapshotContext.All); } foreach (VssSnapshotProperties prop in backup.QuerySnapshots()) { Console.WriteLine("Snapshot ID: {0:B}", prop.SnapshotId); Console.WriteLine("Snapshot Set ID: {0:B}", prop.SnapshotSetId); Console.WriteLine("Original Volume Name: {0}", prop.OriginalVolumeName); Console.WriteLine(); } } }
private static void EnsureNoWritersFailed(IVssBackupComponents bkpComponents, List <VssWriterDescriptor> writers) { bkpComponents.GatherWriterStatus(); foreach (var writer in bkpComponents.WriterStatus) { if (!writers.Any(wr => wr.WriterMetadata.InstanceId == writer.InstanceId && !wr.IsExcluded)) { continue; } switch (writer.State) { case VssWriterState.FailedAtIdentify: case VssWriterState.FailedAtPrepareBackup: case VssWriterState.FailedAtPrepareSnapshot: case VssWriterState.FailedAtFreeze: case VssWriterState.FailedAtThaw: case VssWriterState.FailedAtPostSnapshot: case VssWriterState.FailedAtBackupComplete: case VssWriterState.FailedAtPreRestore: case VssWriterState.FailedAtPostRestore: case VssWriterState.FailedAtBackupShutdown: break; default: continue; } Program.LogError($"Selected writer '{writer.Name}' is in failed state!"); Program.LogError("Status: " + writer.State); Program.LogError("Writer Failure Code: " + writer.Failure); Program.LogError("Writer ID: " + writer.ClassId); Program.LogError("Instance ID: " + writer.InstanceId); throw new Exception(); } }
public void Dispose() { if (_backup != null) { foreach (var writers in _backup.WriterComponents) foreach (var components in writers.Components) { _backup.SetBackupSucceeded( writers.InstanceId, writers.WriterId, components.ComponentType, null, components.ComponentName, false); } _backup.FreeWriterMetadata(); _backup.Dispose(); _backup = null; } }
public bool Create(List<String> Volumes) { try { if (OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.X64 || OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.IA64) { if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\AlphaVSS.60.x64.dll")) { HelperFunctions.ShowError(Translations.Get("WrongVersion64")); Settings.ShadowCopy = false; return false; } } else { if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\AlphaVSS.60.x86.dll")) { HelperFunctions.ShowError(Translations.Get("WrongVersion32")); Settings.ShadowCopy = false; return false; } } if (GlobalData.SettingsInAppData) { _OldSnapshotSetIdsPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\RoboGapp\\SnapshotIds.dat"; } else { _OldSnapshotSetIdsPath = System.Windows.Forms.Application.StartupPath + "\\SnapshotIds.dat"; } Abort(); HelperFunctions.WriteLog(Translations.Get("LoadingVSSImplementation")); IVssImplementation VssImplementation = null; try { VssImplementation = VssUtils.LoadImplementation(); } catch (Exception ex) { HelperFunctions.ShowError(Translations.Get("ShadowCopyError") + "\n\n" + Translations.Get("Error") + "\n" + ex.Message); if (OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.X64) { HelperFunctions.ShowError(Translations.Get("VCRedist64")); } else if (OperatingSystemInfo.ProcessorArchitecture == ProcessorArchitecture.IA64) { HelperFunctions.ShowError(Translations.Get("VCRedistIA64")); } else { HelperFunctions.ShowError(Translations.Get("VCRedist32")); } return false; } HelperFunctions.WriteLog(Translations.Get("CreatingBackupComponents")); _BackupComponents = VssImplementation.CreateVssBackupComponents(); HelperFunctions.WriteLog(Translations.Get("InitializingVSSBackup")); _BackupComponents.InitializeForBackup(null); if (OperatingSystemInfo.OSVersionName > OSVersionName.WindowsServer2003) { HelperFunctions.WriteLog(Translations.Get("SettingVSSContext")); _BackupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease); } HelperFunctions.WriteLog(Translations.Get("SettingVSSBackupState")); _BackupComponents.SetBackupState(false, true, VssBackupType.Full, false); HelperFunctions.WriteLog(Translations.Get("GatheringWriterMetadata")); _BackupComponents.GatherWriterMetadata(); HelperFunctions.WriteLog(Translations.Get("CreatingSnapshotSet")); _SnapshotSetId = _BackupComponents.StartSnapshotSet(); _SnapshotIds.Clear(); for (int i = 0; i < Volumes.Count; i++) { HelperFunctions.WriteLog(Translations.Get("AddingToSnapshotSet1") + Volumes[i] + Translations.Get("AddingToSnapshotSet2")); Guid SnapshotId = _BackupComponents.AddToSnapshotSet(Volumes[i], Guid.Empty); _SnapshotIds.Add(SnapshotId); } HelperFunctions.WriteLog(Translations.Get("SavingSnapshotSetID")); SaveSnapshotSetId(); HelperFunctions.WriteLog(Translations.Get("PreparingVSSBackup")); _BackupComponents.PrepareForBackup(); HelperFunctions.WriteLog(Translations.Get("CreatingVSSSnapshots")); _BackupComponents.DoSnapshotSet(); HelperFunctions.WriteLog(Translations.Get("ExposingSnapshots")); GlobalData.ShadowCopyMounts.Clear(); List<String> FreeDriveLetters = IO.GetFreeDriveLetters(); String Path = System.Windows.Forms.Application.StartupPath; if (OperatingSystemInfo.OSVersionName > OSVersionName.WindowsServer2003) { try { if (System.IO.File.Exists(Path + "\\write.test")) File.Delete(Path + "\\write.test"); using (System.IO.File.Create(Path + "\\write.test")) { } File.Delete(Path + "\\write.test"); } catch { Path = IO.GetCommonApplicationDataPath(); if (Path == "") { HelperFunctions.ShowError(Translations.Get("ExposingSnapshotsDirError")); return false; } } } for (int i = 0; i < Volumes.Count; i++) { if (OperatingSystemInfo.OSVersionName <= OSVersionName.WindowsServer2003) { GlobalData.ShadowCopyMounts.Add(Volumes[i], FreeDriveLetters[i]); DefineDosDevice(0, FreeDriveLetters[i].Substring(0, 2), _BackupComponents.GetSnapshotProperties(_SnapshotIds[i]).SnapshotDeviceObject); } else { DriveInfo DriveInfo = null; if (Path == System.Windows.Forms.Application.StartupPath) { DriveInfo = DriveInfo.GetDrives().FirstOrDefault((DriveInfo DI) => DI.RootDirectory.ToString() == System.Windows.Forms.Application.StartupPath.Substring(0, 3)); if (DriveInfo == null || DriveInfo.DriveType == DriveType.Network) { Path = IO.GetCommonApplicationDataPath(); if (Path == "") { HelperFunctions.ShowError(Translations.Get("ExposingSnapshotsDirError")); return false; } } } GlobalData.ShadowCopyMounts.Add(Volumes[i], Path + "\\mnt" + i.ToString() + "\\"); if (System.IO.Directory.Exists(GlobalData.ShadowCopyMounts[Volumes[i]])) { try { Directory.Delete(GlobalData.ShadowCopyMounts[Volumes[i]], false); } catch (Exception ex) { HelperFunctions.ShowError(ex); return false; } } Directory.Create(GlobalData.ShadowCopyMounts[Volumes[i]]); _BackupComponents.ExposeSnapshot(_SnapshotIds[i], null, VssVolumeSnapshotAttributes.ExposedLocally, GlobalData.ShadowCopyMounts[Volumes[i]]); } } HelperFunctions.WriteLog(Translations.Get("SnapshotSuccessful")); return true; } catch (Exception ex) { HelperFunctions.ShowError(ex); return false; } }
private static VssSnapshotProperties GetSnapshotProperties(IVssBackupComponents backupComponents, Guid snapshotId) { VssSnapshotProperties props = new VssSnapshotProperties(); IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VssSnapshotProperties))); backupComponents.GetSnapshotProperties(snapshotId, buffer); Marshal.PtrToStructure(buffer, props); NativeMethods.VssFreeSnapshotProperties(buffer); return props; }
/// <summary> /// 非密封类修饰用protected virtual /// 密封类修饰用private /// </summary> /// <param name="disposing"></param> private void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { // 清理托管资源 // if (backup != null) // { // DeleteSnapshotSet(); // backup.FreeWriterMetadata(); // backup.Dispose(); // backup = null; // Console.WriteLine(ClientResources.DiskShadow_DisposeVSSComponent); // } } // 清理非托管资源 if (backup != null) { DeleteSnapshotSet(); backup.FreeWriterMetadata(); backup.Dispose(); backup = null; Console.WriteLine(ClientResources.DiskShadow_DisposeVSSComponent); } // if (nativeResource != IntPtr.Zero) // { // Marshal.FreeHGlobal(nativeResource); // nativeResource = IntPtr.Zero; // } disposed = true; }
/// <summary> /// Constructs a new backup snapshot, using all the required disks /// </summary> /// <param name="sourcepaths">The folders that are about to be backed up</param> /// <param name="options">A set of commandline options</param> public WindowsSnapshot(string[] sourcepaths, Dictionary<string, string> options) { try { //Substitute for calling VssUtils.LoadImplementation(), as we have the dlls outside the GAC string alphadir = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "alphavss"); string alphadll = System.IO.Path.Combine(alphadir, VssUtils.GetPlatformSpecificAssemblyName().Name + ".dll"); IVssImplementation vss = (IVssImplementation)System.Reflection.Assembly.LoadFile(alphadll).CreateInstance("Alphaleonis.Win32.Vss.VssImplementation"); List<Guid> excludedWriters = new List<Guid>(); if (options.ContainsKey("vss-exclude-writers")) { foreach (string s in options["vss-exclude-writers"].Split(';')) if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) excludedWriters.Add(new Guid(s)); } //Check if we should map any drives bool useSubst = Utility.Utility.ParseBoolOption(options, "vss-use-mapping"); //Prepare the backup m_backup = vss.CreateVssBackupComponents(); m_backup.InitializeForBackup(null); if (excludedWriters.Count > 0) m_backup.DisableWriterClasses(excludedWriters.ToArray()); m_snapshotId = m_backup.StartSnapshotSet(); m_sourcepaths = new string[sourcepaths.Length]; for(int i = 0; i < m_sourcepaths.Length; i++) m_sourcepaths[i] = Utility.Utility.AppendDirSeparator(sourcepaths[i]); try { //Gather information on all Vss writers using (IVssAsync async = m_backup.GatherWriterMetadata()) async.Wait(); m_backup.FreeWriterMetadata(); } catch { try { m_backup.FreeWriterMetadata(); } catch { } throw; } //Figure out which volumes are in the set m_volumes = new Dictionary<string, Guid>(StringComparer.InvariantCultureIgnoreCase); foreach (string s in m_sourcepaths) { string drive = Alphaleonis.Win32.Filesystem.Path.GetPathRoot(s); if (!m_volumes.ContainsKey(drive)) { if (!m_backup.IsVolumeSupported(drive)) throw new VssVolumeNotSupportedException(drive); m_volumes.Add(drive, m_backup.AddToSnapshotSet(drive)); } } //Signal that we want to do a backup m_backup.SetBackupState(false, true, VssBackupType.Full, false); //Make all writers aware that we are going to do the backup using (IVssAsync async = m_backup.PrepareForBackup()) async.Wait(); //Create the shadow volumes using (IVssAsync async = m_backup.DoSnapshotSet()) async.Wait(); //Make a little lookup table for faster translation m_volumeMap = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); foreach(KeyValuePair<string, Guid> kvp in m_volumes) m_volumeMap.Add(kvp.Key, m_backup.GetSnapshotProperties(kvp.Value).SnapshotDeviceObject); //If we should map the drives, we do that now and update the volumeMap if (useSubst) { m_mappedDrives = new List<DefineDosDevice>(); foreach (string k in new List<string>(m_volumeMap.Keys)) { try { DefineDosDevice d; m_mappedDrives.Add(d = new DefineDosDevice(m_volumeMap[k])); m_volumeMap[k] = Utility.Utility.AppendDirSeparator(d.Drive); } catch { } } } } catch { //In case we fail in the constructor, we do not want a snapshot to be active try { Dispose(); } catch { } throw; } }
private Guid CreateSnapshotSet(List<CloneVolume> cloneVolumes, IVssBackupComponents backupCmpnts) { if (!Quiet) { Console.WriteLine("Snapshotting Volumes..."); } backupCmpnts.InitializeForBackup(null); backupCmpnts.SetContext(0 /* VSS_CTX_BACKUP */); backupCmpnts.SetBackupState(false, true, 5 /* VSS_BT_COPY */, false); CallAsyncMethod(backupCmpnts.GatherWriterMetadata); Guid snapshotSetId; try { backupCmpnts.StartSnapshotSet(out snapshotSetId); foreach (var vol in cloneVolumes) { backupCmpnts.AddToSnapshotSet(vol.Path, Guid.Empty, out vol.SnapshotId); } CallAsyncMethod(backupCmpnts.PrepareForBackup); CallAsyncMethod(backupCmpnts.DoSnapshotSet); } catch { backupCmpnts.AbortBackup(); throw; } foreach (var vol in cloneVolumes) { vol.SnapshotProperties = GetSnapshotProperties(backupCmpnts, vol.SnapshotId); } return snapshotSetId; }
/// <summary> /// Cleans up any resources and closes the backup set /// </summary> public void Dispose() { try { if (m_mappedDrives != null) { foreach (DefineDosDevice d in m_mappedDrives) d.Dispose(); m_mappedDrives = null; m_volumeMap = null; } } catch { } try { if (m_backup != null) using (IVssAsync async = m_backup.BackupComplete()) async.Wait(); } catch { } try { if (m_backup != null) foreach (Guid g in m_volumes.Values) try { m_backup.DeleteSnapshot(g, false); } catch { } } catch { } if (m_backup != null) { m_backup.Dispose(); m_backup = null; } }
/// <summary> /// Initializes a snapshot. We save the GUID of this snap in order to /// refer to it elsewhere in the class. /// </summary> /// <param name="backup">A VssBackupComponents implementation for the current OS.</param> public Snapshot(IVssBackupComponents backup) { _backup = backup; _set_id = backup.StartSnapshotSet(); }
internal static extern int CreateVssBackupComponents64( out IVssBackupComponents vssBackupCmpnts );
public void Initialize(VssSnapshotContext context, string xmlDoc = null, bool duringRestore = false) { m_backupComponents = Implementation.CreateVssBackupComponents(); m_duringRestore = duringRestore; if (m_duringRestore) { Host.WriteVerbose("- Calling IVssBackupComponents.InitializeForRestore() {0} xml doc.", xmlDoc == null ? "without" : "with"); m_backupComponents.InitializeForRestore(xmlDoc); } else { Host.WriteVerbose("- Calling IVssBackupComponents.InitializeForBackup() {0} xml doc.", xmlDoc == null ? "without" : "with"); m_backupComponents.InitializeForBackup(xmlDoc); if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003) && context != VssSnapshotContext.Backup) { Host.WriteLine("- Setting the VSS context to: {0}", context); m_backupComponents.SetContext(context); } } m_context = (VssVolumeSnapshotAttributes)context; m_backupComponents.SetBackupState(true, true, VssBackupType.Full, false); }
public BackupProcessor(string root) { log.Info("Creating Backup Component"); _vss = VssUtils.LoadImplementation(); _backup = _vss.CreateVssBackupComponents(); _backup.InitializeForBackup(null); _backup.GatherWriterMetadata(); _backup.SetContext(VssSnapshotContext.Backup); _root = root; if (!_root.EndsWith("\\")) _root += "\\"; _volRoot = AlphaFS.Path.GetPathRoot(_root); log.DebugFormat("Path actual root is [{0}]",_volRoot); if (!_backup.IsVolumeSupported(_volRoot)) { throw new Exception("Volume îs not supported by the backup API"); } }
/// <summary> /// Constructs a new backup snapshot, using all the required disks /// </summary> /// <param name="sourcepaths">The folders that are about to be backed up</param> /// <param name="options">A set of commandline options</param> public WindowsSnapshot(string[] sourcepaths, Dictionary <string, string> options) { try { //Substitute for calling VssUtils.LoadImplementation(), as we have the dlls outside the GAC string alphadir = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "alphavss"); string alphadll = System.IO.Path.Combine(alphadir, VssUtils.GetPlatformSpecificAssemblyShortName() + ".dll"); IVssImplementation vss = (IVssImplementation)System.Reflection.Assembly.LoadFile(alphadll).CreateInstance("Alphaleonis.Win32.Vss.VssImplementation"); List <Guid> excludedWriters = new List <Guid>(); if (options.ContainsKey("vss-exclude-writers")) { foreach (string s in options["vss-exclude-writers"].Split(';')) { if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) { excludedWriters.Add(new Guid(s)); } } } //Check if we should map any drives bool useSubst = Utility.Utility.ParseBoolOption(options, "vss-use-mapping"); //Prepare the backup m_backup = vss.CreateVssBackupComponents(); m_backup.InitializeForBackup(null); if (excludedWriters.Count > 0) { m_backup.DisableWriterClasses(excludedWriters.ToArray()); } m_backup.StartSnapshotSet(); m_sourcepaths = new string[sourcepaths.Length]; for (int i = 0; i < m_sourcepaths.Length; i++) { m_sourcepaths[i] = System.IO.Directory.Exists(sourcepaths[i]) ? Utility.Utility.AppendDirSeparator(sourcepaths[i]) : sourcepaths[i]; } try { //Gather information on all Vss writers m_backup.GatherWriterMetadata(); m_backup.FreeWriterMetadata(); } catch { try { m_backup.FreeWriterMetadata(); } catch { } throw; } //Figure out which volumes are in the set m_volumes = new Dictionary <string, Guid>(StringComparer.InvariantCultureIgnoreCase); foreach (string s in m_sourcepaths) { string drive = Alphaleonis.Win32.Filesystem.Path.GetPathRoot(s); if (!m_volumes.ContainsKey(drive)) { if (!m_backup.IsVolumeSupported(drive)) { throw new VssVolumeNotSupportedException(drive); } m_volumes.Add(drive, m_backup.AddToSnapshotSet(drive)); } } //Signal that we want to do a backup m_backup.SetBackupState(false, true, VssBackupType.Full, false); //Make all writers aware that we are going to do the backup m_backup.PrepareForBackup(); //Create the shadow volumes m_backup.DoSnapshotSet(); //Make a little lookup table for faster translation m_volumeMap = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (KeyValuePair <string, Guid> kvp in m_volumes) { m_volumeMap.Add(kvp.Key, m_backup.GetSnapshotProperties(kvp.Value).SnapshotDeviceObject); } //If we should map the drives, we do that now and update the volumeMap if (useSubst) { m_mappedDrives = new List <DefineDosDevice>(); foreach (string k in new List <string>(m_volumeMap.Keys)) { try { DefineDosDevice d; m_mappedDrives.Add(d = new DefineDosDevice(m_volumeMap[k])); m_volumeMap[k] = Utility.Utility.AppendDirSeparator(d.Drive); } catch { } } } } catch { //In case we fail in the constructor, we do not want a snapshot to be active try { Dispose(); } catch { } throw; } }
/// <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; } }
public void Dispose() { if (m_backupComponents != null) { m_backupComponents.Dispose(); m_backupComponents = 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! IVssImplementation vss = VssUtils.LoadImplementation(); // 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. // // Note the 'using' construct here to dispose of the asynchronous // comm link once we no longer need it. using (IVssAsync async = _backup.GatherWriterMetadata()) { // Because allowing writers to prepare their metadata can take // a while, we are given a VssAsync object that gives us some // status on the background operation. In this case, we just // wait for it to finish. async.Wait(); } }