Пример #1
0
 // Add a volume to the current snapshot.
 public void AddVolume(string volumeName)
 {
     if (_backup.IsVolumeSupported(volumeName))
     {
         _snapshotVolumeId = _backup.AddToSnapshotSet(volumeName);
     }
     else
     {
         LogService.LogEvent("Error: Snapshot.AddVolume - Vss Volume Not Supported");
     }
 }
Пример #2
0
 /// <summary>
 /// Adds a volume to the current snapshot.
 /// </summary>
 /// <param name="volumeName">Name of the volume to add (eg. "C:\").</param>
 /// <remarks>
 /// Note the IsVolumeSupported check prior to adding each volume.
 /// </remarks>
 public void AddVolume(string volumeName)
 {
     if (_backup.IsVolumeSupported(volumeName))
     {
         _snap_id = _backup.AddToSnapshotSet(volumeName);
     }
     else
     {
         throw new VssVolumeNotSupportedException(volumeName);
     }
 }
Пример #3
0
 public void AddVolume(string volumeName)
 {
     Debug.Write("Adding volume");
     if (thisBackup.IsVolumeSupported(volumeName))
     {
         _snap_id = thisBackup.AddToSnapshotSet(volumeName);
     }
     else
     {
         throw new VssVolumeNotSupportedException(volumeName);
     }
 }
Пример #4
0
        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));
            }
        }
Пример #5
0
        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);
        }
Пример #6
0
        public void CheckSupportedVolumes(IEnumerable <string> sources)
        {
            //Figure out which volumes are in the set
            _volumes = new Dictionary <string, Guid>(StringComparer.OrdinalIgnoreCase);
            foreach (var s in sources)
            {
                var drive = SystemIO.IO_WIN.GetPathRoot(s);
                if (!_volumes.ContainsKey(drive))
                {
                    if (!_vssBackupComponents.IsVolumeSupported(drive))
                    {
                        throw new VssVolumeNotSupportedException(drive);
                    }

                    _volumes.Add(drive, _vssBackupComponents.AddToSnapshotSet(drive));
                }
            }
        }
Пример #7
0
 public void AddVolume(string volumeName)
 {
     try
     {
         snapShotsGuids.Keys.First(vol => vol.Equals(volumeName));
     }
     catch
     {
         if (backup.IsVolumeSupported(volumeName))
         {
             var snapGuid = backup.AddToSnapshotSet(volumeName);
             snapShotsGuids.Add(volumeName, snapGuid);
         }
         else
         {
             throw new VssVolumeNotSupportedException(volumeName);
         }
     }
 }
Пример #8
0
        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);
            }
        }
Пример #9
0
        /// <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>
        /// 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");

                var excludedWriters = new Guid[0];
                if (options.ContainsKey("vss-exclude-writers"))
                {
                    excludedWriters = options["vss-exclude-writers"].Split(';').Where(x => !string.IsNullOrWhiteSpace(x) && x.Trim().Length > 0).Select(x => new Guid(x)).ToArray();
                }

                //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);
                m_backup.SetContext(VssSnapshotContext.Backup);
                m_backup.SetBackupState(false, true, VssBackupType.Full, false);

                if (excludedWriters.Length > 0)
                {
                    m_backup.DisableWriterClasses(excludedWriters.ToArray());
                }

                m_sourcepaths = sourcepaths.Select(x => Directory.Exists(x) ? Utility.Utility.AppendDirSeparator(x) : x).ToList();

                List <string> hypervPaths;

                try
                {
                    m_backup.GatherWriterMetadata();

                    hypervPaths = PrepareHyperVBackup(options, m_backup.WriterMetadata.FirstOrDefault(o => o.WriterId.Equals(HyperVWriterGuid)));
                }
                finally
                {
                    m_backup.FreeWriterMetadata();
                }

                if (hypervPaths != null)
                {
                    m_sourcepaths.AddRange(hypervPaths);
                }

                //Sanity check for duplicate files/folders
                var pathDuplicates = m_sourcepaths.GroupBy(x => x, Utility.Utility.ClientFilenameStringComparer)
                                     .Where(g => g.Count() > 1).Select(y => y.Key).ToList();

                foreach (var pathDuplicate in pathDuplicates)
                {
                    Logging.Log.WriteMessage(string.Format("Removing duplicate source: {0}", pathDuplicate), Logging.LogMessageType.Information);
                }

                if (pathDuplicates.Count > 0)
                {
                    m_sourcepaths = m_sourcepaths.Distinct(Utility.Utility.ClientFilenameStringComparer).OrderBy(a => a).ToList();
                }

                //Sanity check for multiple inclusions of the same files/folders
                var pathIncludedPaths = m_sourcepaths.Where(x => m_sourcepaths.Where(y => y != x).Any(z => x.StartsWith(z, Utility.Utility.ClientFilenameStringComparision))).ToList();

                foreach (var pathIncluded in pathIncludedPaths)
                {
                    Logging.Log.WriteMessage(string.Format("Removing already included source: {0}", pathIncluded), Logging.LogMessageType.Information);
                }

                if (pathIncludedPaths.Count > 0)
                {
                    m_sourcepaths = m_sourcepaths.Except(pathIncludedPaths, Utility.Utility.ClientFilenameStringComparer).ToList();
                }

                m_backup.StartSnapshotSet();

                //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));
                    }
                }

                //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;
            }
        }
Пример #11
0
        /// <summary>
        /// Constructs a new backup snapshot, using all the required disks
        /// </summary>
        /// <param name="sources">Sources to determine which volumes to include in snapshot</param>
        /// <param name="options">A set of commandline options</param>
        public WindowsSnapshot(IEnumerable <string> sources, IDictionary <string, string> options)
        {
            try
            {
                // Substitute for calling VssUtils.LoadImplementation(), as we have the dlls outside the GAC
                var assemblyLocation = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                if (assemblyLocation == null)
                {
                    throw new InvalidOperationException();
                }

                var alphadir = Path.Combine(assemblyLocation, "alphavss");
                var alphadll = Path.Combine(alphadir, VssUtils.GetPlatformSpecificAssemblyShortName() + ".dll");
                var vss      = (IVssImplementation)System.Reflection.Assembly.LoadFile(alphadll).CreateInstance("Alphaleonis.Win32.Vss.VssImplementation");
                if (vss == null)
                {
                    throw new InvalidOperationException();
                }

                var excludedWriters = new Guid[0];
                if (options.ContainsKey("vss-exclude-writers"))
                {
                    excludedWriters = options["vss-exclude-writers"].Split(';').Where(x => !string.IsNullOrWhiteSpace(x) && x.Trim().Length > 0).Select(x => new Guid(x)).ToArray();
                }

                //Check if we should map any drives
                var useSubst = Utility.Utility.ParseBoolOption(options, "vss-use-mapping");

                //Prepare the backup
                m_backup = vss.CreateVssBackupComponents();
                m_backup.InitializeForBackup(null);
                m_backup.SetContext(VssSnapshotContext.Backup);
                m_backup.SetBackupState(false, true, VssBackupType.Full, false);

                if (excludedWriters.Length > 0)
                {
                    m_backup.DisableWriterClasses(excludedWriters.ToArray());
                }

                try
                {
                    m_backup.GatherWriterMetadata();
                }
                finally
                {
                    m_backup.FreeWriterMetadata();
                }

                m_backup.StartSnapshotSet();

                //Figure out which volumes are in the set
                m_volumes = new Dictionary <string, Guid>(StringComparer.OrdinalIgnoreCase);
                foreach (var s in sources)
                {
                    var drive = AlphaFS.Path.GetPathRoot(s);
                    if (!m_volumes.ContainsKey(drive))
                    {
                        //TODO: that seems a bit harsh... we could fall-back to not using VSS for that volume only
                        if (!m_backup.IsVolumeSupported(drive))
                        {
                            throw new VssVolumeNotSupportedException(drive);
                        }

                        m_volumes.Add(drive, m_backup.AddToSnapshotSet(drive));
                    }
                }

                //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.OrdinalIgnoreCase);
                foreach (var kvp in m_volumes)
                {
                    m_volumeMap.Add(kvp.Key, m_backup.GetSnapshotProperties(kvp.Value).SnapshotDeviceObject);
                }

                m_volumeReverseMap = m_volumeMap.ToDictionary(x => x.Value, x => x.Key);

                //If we should map the drives, we do that now and update the volumeMap
                if (useSubst)
                {
                    m_mappedDrives = new List <DefineDosDevice>();
                    foreach (var 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 (Exception ex)
                        {
                            Logging.Log.WriteVerboseMessage(LOGTAG, "SubstMappingfailed", ex, "Failed to map VSS path {0} to drive", k);
                        }
                    }
                }
            }
            catch
            {
                //In case we fail in the constructor, we do not want a snapshot to be active
                try
                {
                    Dispose();
                }
                catch (Exception ex)
                {
                    Logging.Log.WriteVerboseMessage(LOGTAG, "VSSCleanupOnError", ex, "Failed during VSS error cleanup");
                }

                throw;
            }
        }
Пример #12
0
        /// <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;
            }
        }
Пример #13
0
        public ISnapshot[] CreateVolumeSnapShot(List <FileSystem> volumes, string[] spoPaths, SnapshotSupportedLevel level)
        {
            using (new Alphaleonis.Win32.Security.PrivilegeEnabler(Privilege.Backup, Privilege.Restore)){
                //PrivilegesManager pm = new PrivilegesManager();
                //pm.Grant();
                VssBackupType vssLevel = VssBackupType.Full;
                if (level == SnapshotSupportedLevel.Full)
                {
                    vssLevel = VssBackupType.Full;
                }
                else if (level == SnapshotSupportedLevel.Incremental)
                {
                    vssLevel = VssBackupType.Incremental;
                }
                else if (level == SnapshotSupportedLevel.Differential)
                {
                    vssLevel = VssBackupType.Differential;
                }
                else if (level == SnapshotSupportedLevel.TransactionLog)
                {
                    vssLevel = VssBackupType.Log;
                }
                ArrayList snapshots = new ArrayList();
                Metadata = new SPOMetadata();
                bool snapshotSuccedeed = false;
                try{
                    IVssImplementation vss = VssUtils.LoadImplementation();
                    backup = vss.CreateVssBackupComponents();
                    Logger.Append(Severity.DEBUG, "0/6 Initializing Snapshot (" + ((spoPaths == null)? "NON-component mode" : "component mode") + ", level " + level + ")");
                    backup.InitializeForBackup(null);
                    if (spoPaths == null)            // component-less snapshot set
                    {
                        backup.SetBackupState(false, true, VssBackupType.Full, false);
                    }
                    else
                    {
                        backup.SetBackupState(true, true, vssLevel, (vssLevel == VssBackupType.Full)?false:true);
                    }
                    if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                    {
                        // The only context supported on Windows XP is VssSnapshotContext.Backup
                        backup.SetContext(VssSnapshotContext.AppRollback /*|VssSnapshotContext.All*/);
                    }
                    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();
                    }
                    Logger.Append(Severity.DEBUG, "2/6 Adding writers and components");
                    // Now we add the components (vss writers, writer paths/params) of this snapshot set
                    if (spoPaths != null)
                    {
                        foreach (IVssExamineWriterMetadata writer in backup.WriterMetadata)
                        {
                            foreach (string spo in spoPaths)
                            {
                                //Logger.Append (Severity.TRIVIA, "Searching writer and/or component matching "+spo);
                                int index = spo.IndexOf(writer.WriterName);
                                if (index < 0 && spo != "*")
                                {
                                    continue;
                                }
                                bool found = false;
                                Logger.Append(Severity.TRIVIA, "Found matching writer " + writer.WriterName + ", instance name=" + writer.InstanceName);
                                // First we check that the writer's status is OK, else we don't add it to avoid failure of complete snapshot if it's not
                                bool writerOk = false;
                                foreach (VssWriterStatusInfo status in backup.WriterStatus)
                                {
                                    if (status.Name == writer.WriterName)
                                    {
                                        Logger.Append(Severity.TRIVIA, "Checking required writer " + status.Name
                                                      + ", status=" + status.State.ToString() + ", error state=" + status.Failure.ToString());
                                        if (status.State == VssWriterState.Stable && status.Failure == VssError.Success)                                // if we get there it means that we are ready to add the wanted component to VSS set
                                        {
                                            writerOk = true;
                                        }
                                        else
                                        {
                                            Logger.Append(Severity.ERROR, "Cannot add writer " + status.Name + " to snapshot set,"
                                                          + " status=" + status.State.ToString() + ". Backup data  managed by this writer may not be consistent");
                                            if (LogEvent != null)
                                            {
                                                LogEvent(this, new LogEventArgs(820, Severity.WARNING, status.Name + ", Status=" + status.State.ToString() + ", Failure=" + status.Failure.ToString()));
                                            }
                                        }
                                    }
                                }
                                if (!writerOk)
                                {
                                    if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                                    {
                                        backup.DisableWriterClasses(new Guid[] { writer.WriterId });
                                    }
                                    continue;
                                }
                                bool addAllComponents = false;
                                if (spo.Length == index + writer.WriterName.Length || spo == "*" || spo == "" + writer.WriterName + @"\*")
                                {
                                    addAllComponents = true;
                                }
                                foreach (IVssWMComponent component in writer.Components)
                                {
                                    found = false;
                                    //Console.WriteLine("createvolsnapshot : current component is :"+component.LogicalPath+@"\"+component.ComponentName);
                                    if ((!addAllComponents) && spo.IndexOf(component.LogicalPath + @"\" + component.ComponentName) < 0)
                                    {
                                        continue;
                                    }
                                    //Logger.Append (Severity.TRIVIA, "Asked to recursively select all '"+writer.WriterName+"' writer's components");
                                    if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                                    {
                                        foreach (VssWMDependency dep in  component.Dependencies)
                                        {
                                            Logger.Append(Severity.TRIVIA, "Component " + component.ComponentName + " depends on component " + dep.ComponentName);
                                        }
                                    }
                                    if (component.Selectable)
                                    {
                                        backup.AddComponent(writer.InstanceId, writer.WriterId, component.Type, component.LogicalPath, component.ComponentName);
                                    }
                                    Logger.Append(Severity.INFO, "Added writer '" + writer.WriterName + "' component " + component.ComponentName);
                                    found = true;

                                    // Second we need to find every drive containing files necessary for writer's backup
                                    // and add them to drives list, in case they weren't explicitely selected as part of backuppaths
                                    List <VssWMFileDescription> componentFiles = new List <VssWMFileDescription>();
                                    componentFiles.AddRange(component.Files);
                                    componentFiles.AddRange(component.DatabaseFiles);
                                    componentFiles.AddRange(component.DatabaseLogFiles);
                                    foreach (VssWMFileDescription file in componentFiles)
                                    {
                                        if (string.IsNullOrEmpty(file.Path))
                                        {
                                            continue;
                                        }
                                        //Console.WriteLine ("component file path="+file.Path+", alt backuplocation="+file.AlternateLocation
                                        //		+", backuptypemask="+file.BackupTypeMask.ToString()+", spec="+file.FileSpecification+", recursive="+file.IsRecursive);
                                        // TODO : Reuse GetInvolvedDrives (put it into VolumeManager class)
                                        string drive = file.Path.Substring(0, 3).ToUpper();
                                        if (drive.Contains(":") && drive.Contains("\\"))
                                        {
                                            var searchedVol = from FileSystem vol in volumes
                                                              where vol.MountPoint.Contains(drive)
                                                              select vol;
                                            //if(!volumes.Contains(drive)){
                                            if (searchedVol == null)
                                            {
                                                Logger.Append(Severity.INFO, "Select VSS component " + component.LogicalPath
                                                              + @"\" + component.ComponentName + " requires snapshotting of drive " + drive + ", adding it to the list.");
                                                volumes.Add(searchedVol.First());
                                            }
                                            break;
                                        }
                                    }

                                    //Logger.Append(Severity.TRIVIA, "Added writer/component "+spo);
                                    //break;
                                }
                                //metadata.Metadata.Add(writer.SaveAsXml());
                                Metadata.Metadata.Add(writer.WriterName, writer.SaveAsXml());
                                if (found == false)
                                {
                                    Logger.Append(Severity.WARNING, "Could not find VSS component " + spo + " which was part of backup paths");
                                }
                            }
                        }
                    }
                    Logger.Append(Severity.DEBUG, "3/6 Preparing Snapshot ");
                    //backup.SetBackupState(false,  true, VssBackupType.Full, false);
                    Guid snapID = backup.StartSnapshotSet();
                    //Guid volID = new Guid();
                    foreach (FileSystem volume in volumes)
                    {
                        VSSSnapshot snapshot = new VSSSnapshot();
                        snapshot.Type = this.Name;
                        Logger.Append(Severity.DEBUG, "Preparing Snapshot of " + volume.MountPoint);
                        if (volume.MountPoint != null && backup.IsVolumeSupported(volume.MountPoint))
                        {
                            snapshot.Id = backup.AddToSnapshotSet(volume.MountPoint);

                            snapshot.Path = volume.MountPoint;
                        }
                        else                  // return the fake provider to get at least a degraded backup, better than nothing
                        {
                            Logger.Append(Severity.WARNING, "Volume '" + volume.MountPoint + "' is not snapshottable (or null). Backup will be done without snapshot, risks of data inconsistancy.");
                            ISnapshotProvider fakeSnapProvider = SnapshotProvider.GetProvider("NONE");
                            List <FileSystem> fakeList         = new List <FileSystem>();
                            fakeList.Add(volume);
                            snapshot = (VSSSnapshot)fakeSnapProvider.CreateVolumeSnapShot(fakeList, null, SnapshotSupportedLevel.Full)[0];
                        }
                        if (snapshot.Id == System.Guid.Empty)
                        {
                            Logger.Append(Severity.ERROR, "Unable to add drive " + volume.MountPoint + " to snapshot set (null guid)");
                        }
                        else
                        {
                            Logger.Append(Severity.TRIVIA, "Drive " + volume.MountPoint + " will be snapshotted to " + snapshot.Id);
                        }
                        snapshots.Add(snapshot);
                    }
                    Logger.Append(Severity.DEBUG, "4/6 Calling Prepare...");
                    using (IVssAsync async = backup.PrepareForBackup()){
                        async.Wait();
                        async.Dispose();
                    }
                    Logger.Append(Severity.DEBUG, "5/6 Snapshotting volumes");
                    using (IVssAsync async = backup.DoSnapshotSet()){
                        async.Wait();
                        async.Dispose();
                    }
                    //if(OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                    foreach (IVssExamineWriterMetadata w in backup.WriterMetadata)
                    {
                        foreach (IVssWMComponent comp in w.Components)
                        {
                            try{
                                backup.SetBackupSucceeded(w.InstanceId, w.WriterId, comp.Type, comp.LogicalPath, comp.ComponentName, true);
                                Logger.Append(Severity.TRIVIA, "Component " + comp.ComponentName + " has been notified about backup success.");
                            }
                            catch (Exception) {
                                //Logger.Append (Severity.WARNING, "Could not notify component "+comp.ComponentName+" about backup completion : "+se.Message);
                            }
                        }
                    }
                    //Node.Misc.VSSObjectHandle.StoreObject(backup);
                    try{
                        //on XP backupcomplete consider that we have done with the snapshot and releases it.
                        //if(OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003)){
                        backup.BackupComplete();

                        Metadata.Metadata.Add("_bcd_", backup.SaveAsXml());
                        //}
                    }catch (Exception bce) {
                        Logger.Append(Severity.WARNING, "Error calling VSS BackupComplete() : " + bce.Message);
                    }

                    using (IVssAsync async = backup.GatherWriterStatus()){
                        async.Wait();
                        async.Dispose();
                    }

                    Logger.Append(Severity.DEBUG, "6/6 Successfully shapshotted volume(s) ");

                    foreach (ISnapshot sn in snapshots)
                    {
                        if (sn.Id == Guid.Empty)
                        {
                            continue;
                        }
                        sn.MountPoint = backup.GetSnapshotProperties(sn.Id).SnapshotDeviceObject;
                        sn.TimeStamp  = Utilities.Utils.GetUtcUnixTime(backup.GetSnapshotProperties(sn.Id).CreationTimestamp.ToUniversalTime());

                        /*
                         * DirectoryInfo snapMountPoint = Directory.CreateDirectory( Path.Combine(Utilities.ConfigManager.GetValue("Backups.TempFolder"), "snapshot_"+sn.Id));
                         * Logger.Append(Severity.DEBUG, "Mounting shapshotted volume '"+sn.Name+"' to '"+snapMountPoint.FullName+"'");
                         * backup.ExposeSnapshot(sn.Id, null, VssVolumeSnapshotAttributes.ExposedLocally, snapMountPoint.FullName);
                         * //sn.Path = snapMountPoint.FullName+Path.DirectorySeparatorChar;
                         * //sn.Path = @"\\?\Volume{"+sn.Id+"}"+Path.DirectorySeparatorChar;*/
                    }
                }
                catch (Exception e) {
                    try{
                        //backup.BackupComplete();
                        backup.AbortBackup();
                    }
                    catch (Exception ae) {
                        Logger.Append(Severity.ERROR, "Error trying to cancel VSS snapshot set : " + ae.Message);
                    }

                    // TODO !! report snapshoty failure to hub task
                    Logger.Append(Severity.ERROR, "Error creating snapshot :'" + e.Message + " ---- " + e.StackTrace + "'. Backup will continue without snapshot. Backup of VSS components will fail. !TODO! report that to hub");
                    backup.Dispose();
                    throw new Exception(e.Message);
                }
                finally{
                    // TODO !!! reactivate dispose
                    //backup.Dispose();

                    //pm.Revoke();
                }

                return((ISnapshot[])snapshots.ToArray(typeof(ISnapshot)));
            }
        }
Пример #14
0
            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");
                }
            }