Welcome to mirror list, hosted at ThFree Co, Russian Federation.

VssBackupComponents.cs « IO « Library « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0368310a9850503d239b96e0e98ec04419b73954 (plain)
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
//  Copyright (C) 2018, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Alphaleonis.Win32.Vss;

namespace Duplicati.Library.IO
{
    public class WriterMetaData
    {
        public string Name { get; set;  }
        public string LogicalPath { get; set; }
        public Guid Guid { get; set; }
        public List<string> Paths { get; set; }
    }

    public class VssBackupComponents : IDisposable
    {
        /// <summary>
        /// The tag used for logging messages
        /// </summary>
        public static readonly string LOGTAG = Logging.Log.LogTagFromType<VssBackupComponents>();


        private IVssBackupComponents _vssBackupComponents;

        /// <summary>
        /// The list of snapshot ids for each volume, key is the path root, eg C:\.
        /// The dictionary is case insensitive
        /// </summary>
        private Dictionary<string, Guid> _volumes;

        /// <summary>
        /// The mapping of snapshot sources to their snapshot entries , key is the path root, eg C:\.
        /// The dictionary is case insensitive
        /// </summary>
        private Dictionary<string, string> _volumeMap;

        /// <summary>
        /// Reverse mapping for speed up.
        /// </summary>
        private Dictionary<string, string> _volumeReverseMap;

        /// <summary>
        /// A list of mapped drives
        /// </summary>
        private List<DefineDosDevice> _mappedDrives;

        public VssBackupComponents()
        {
            _vssBackupComponents = VssBackupComponentsHelper.GetVssBackupComponents();
        }

        public void SetupWriters(Guid[] includedWriters, Guid[] excludedWriters)
        {
            if (includedWriters != null && includedWriters.Length > 0)
                _vssBackupComponents.EnableWriterClasses(includedWriters);

            if (excludedWriters != null && excludedWriters.Length > 0)
                _vssBackupComponents.DisableWriterClasses(excludedWriters.ToArray());

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

            // check if writers got enabled
            foreach (var writerGUID in includedWriters)
            {
                if (!_vssBackupComponents.WriterMetadata.Any(o => o.WriterId.Equals(writerGUID)))
                {
                    throw new Exception(string.Format("Writer with GUID {0} was not added to VSS writer set.", writerGUID.ToString()));
                }
            }
        }

        public void MapDrives()
        {
            _mappedDrives = new List<DefineDosDevice>();
            foreach (var k in new List<string>(_volumeMap.Keys))
            {
                try
                {
                    DefineDosDevice d = new DefineDosDevice(_volumeMap[k]);
                    _mappedDrives.Add(d);
                    _volumeMap[k] = Util.AppendDirSeparator(d.Drive);
                }
                catch (Exception ex)
                {
                    Logging.Log.WriteVerboseMessage(LOGTAG, "SubstMappingfailed", ex, "Failed to map VSS path {0} to drive", k);
                }
            }
        }

        public void MapVolumesToSnapShots()
        {
            _volumeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (var kvp in _volumes)
            {
                _volumeMap.Add(kvp.Key, _vssBackupComponents.GetSnapshotProperties(kvp.Value).SnapshotDeviceObject);
            }

            _volumeReverseMap = _volumeMap.ToDictionary(x => x.Value, x => x.Key);
        }

        public Dictionary<string, string> SnapshotDeviceAndVolumes
        {
            get {
                return _volumeReverseMap;
            }

        }

        private List<string> GetPathsFromComponent(IVssWMComponent component)
        {
            var paths = new List<string>();

            foreach (var file in component.Files)
            {
                if (file.FileSpecification.Contains("*"))
                {
                    if (Directory.Exists(Util.AppendDirSeparator(file.Path)))
                        paths.Add(Util.AppendDirSeparator(file.Path));
                }
                else
                {
                    var fileWithSpec = SystemIO.IO_WIN.PathCombine(file.Path, file.FileSpecification);
                    if (File.Exists(fileWithSpec))
                        paths.Add(fileWithSpec);
                }
            }
            return paths;

        }

        /// <summary>
        /// Enumerable to iterate over components of the given writers.
        /// Returns an WriterMetaData object containing GUID, component name, logical path and paths of the component.
        /// </summary>
        /// <returns>Anonymous object containing GUID, component name, logical path and paths of the component.</returns>
        /// <param name="writers">Writers.</param>
        public IEnumerable<WriterMetaData> ParseWriterMetaData(Guid[] writers)
        {
            // check if writers got enabled
            foreach (var writerGUID in writers)
            {
                var writer = _vssBackupComponents.WriterMetadata.First(o => o.WriterId.Equals(writerGUID));
                foreach (var component in writer.Components)
                {
                    yield return new WriterMetaData{ Guid = writerGUID,
                        Name = component.ComponentName,
                        LogicalPath = component.LogicalPath,
                        Paths = GetPathsFromComponent(component) };
                }
            }
        }


        public void InitShadowVolumes(IEnumerable<string> sources)
        {
            _vssBackupComponents.StartSnapshotSet();

            CheckSupportedVolumes(sources);

            //Make all writers aware that we are going to do the backup
            _vssBackupComponents.PrepareForBackup();

            //Create the shadow volumes
            _vssBackupComponents.DoSnapshotSet();
        }

        public string GetVolumeFromCache(string path)
        {
            if (!_volumeMap.TryGetValue(path, out var volumePath))
                throw new InvalidOperationException();

            return volumePath;
        }


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

        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 class VssBackupComponentsHelper
    {
        public static IVssBackupComponents GetVssBackupComponents()
        {
            //Prepare the backup
            IVssBackupComponents m_backup = CreateVssBackupComponents();
            m_backup.InitializeForBackup(null);
            m_backup.SetContext(VssSnapshotContext.Backup);
            m_backup.SetBackupState(false, true, VssBackupType.Full, false);

            return m_backup;
        }

        public static IVssBackupComponents CreateVssBackupComponents()
        {
            // 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();

            //Here we don't need a custom Path.Combine: we need unconditional access to alphaFS
            var alphadll = Path.Combine(assemblyLocation, "alphavss", VssUtils.GetPlatformSpecificAssemblyShortName() + ".dll");
            var vss = (IVssImplementation)System.Reflection.Assembly.LoadFile(alphadll).CreateInstance("Alphaleonis.Win32.Vss.VssImplementation");
            if (vss == null)
                throw new InvalidOperationException();

            return vss.CreateVssBackupComponents();
        }
    }
}