-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathServerPackageRepository.cs
459 lines (389 loc) · 16.5 KB
/
ServerPackageRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
using Ninject;
using NuGet.Resources;
using NuGet.Server.DataServices;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace NuGet.Server.Infrastructure
{
/// <summary>
/// ServerPackageRepository represents a folder of nupkgs on disk. All packages are cached during the first request in order
/// to correctly determine attributes such as IsAbsoluteLatestVersion. Adding, removing, or making changes to packages on disk
/// will clear the cache.
/// </summary>
public class ServerPackageRepository : PackageRepositoryBase, IServerPackageRepository, IPackageLookup, IDisposable
{
private IDictionary<IPackage, DerivedPackageData> _packages;
private readonly object _lockObj = new object();
private readonly IFileSystem _fileSystem;
private readonly IPackagePathResolver _pathResolver;
private FileSystemWatcher _fileWatcher;
private readonly string _filter = String.Format(CultureInfo.InvariantCulture, "*{0}", Constants.PackageExtension);
private bool _monitoringFiles = false;
public ServerPackageRepository(string path)
: this(new DefaultPackagePathResolver(path), new PhysicalFileSystem(path))
{
}
public ServerPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem)
{
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
_fileSystem = fileSystem;
_pathResolver = pathResolver;
Logger = fileSystem.Logger;
}
[Inject]
public IHashProvider HashProvider { get; set; }
public override IQueryable<IPackage> GetPackages()
{
return PackageCache.Keys.AsQueryable<IPackage>();
}
public IQueryable<Package> GetPackagesWithDerivedData()
{
var cache = PackageCache;
return cache.Keys.Select(p => new Package(p, cache[p])).AsQueryable();
}
public bool Exists(string packageId, SemanticVersion version)
{
return FindPackage(packageId, version) != null;
}
public IPackage FindPackage(string packageId, SemanticVersion version)
{
return FindPackagesById(packageId).Where(p => p.Version.Equals(version)).FirstOrDefault();
}
public IEnumerable<IPackage> FindPackagesById(string packageId)
{
return GetPackages().Where(p => StringComparer.OrdinalIgnoreCase.Compare(p.Id, packageId) == 0);
}
/// <summary>
/// Gives the Package containing both the IPackage and the derived metadata.
/// The returned Package will be null if <paramref name="package" /> no longer exists in the cache.
/// </summary>
public Package GetMetadataPackage(IPackage package)
{
Package metadata = null;
// The cache may have changed, and the metadata may no longer exist
DerivedPackageData data = null;
if (PackageCache.TryGetValue(package, out data))
{
metadata = new Package(package, data);
}
return metadata;
}
public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
var cache = PackageCache;
var packages = cache.Keys.AsQueryable().Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.Where(p => p.Listed)
.AsQueryable();
if (EnableFrameworkFiltering && targetFrameworks.Any())
{
// Get the list of framework names
var frameworkNames = targetFrameworks.Select(frameworkName => VersionUtility.ParseFrameworkName(frameworkName));
packages = packages.Where(package => frameworkNames.Any(frameworkName => VersionUtility.IsCompatible(frameworkName, cache[package].SupportedFrameworks)));
}
return packages;
}
public IEnumerable<IPackage> GetUpdates(IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks, IEnumerable<IVersionSpec> versionConstraints)
{
return this.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
}
public override string Source
{
get
{
return _fileSystem.Root;
}
}
public override bool SupportsPrereleasePackages
{
get
{
return true;
}
}
/// <summary>
/// Add a file to the repository.
/// </summary>
public override void AddPackage(IPackage package)
{
string fileName = _pathResolver.GetPackageFileName(package);
if (_fileSystem.FileExists(fileName) && !AllowOverrideExistingPackageOnPush)
{
throw new InvalidOperationException(String.Format(NuGetResources.Error_PackageAlreadyExists, package));
}
lock (_lockObj)
{
using (Stream stream = package.GetStream())
{
_fileSystem.AddFile(fileName, stream);
}
InvalidatePackages();
}
}
/// <summary>
/// Unlist or delete a package
/// </summary>
public override void RemovePackage(IPackage package)
{
if (package != null)
{
string fileName = _pathResolver.GetPackageFileName(package);
lock (_lockObj)
{
if (EnableDelisting)
{
var fullPath = _fileSystem.GetFullPath(fileName);
if (File.Exists(fullPath))
{
File.SetAttributes(fullPath, File.GetAttributes(fullPath) | FileAttributes.Hidden);
}
else
{
Debug.Fail("unable to find file");
}
}
else
{
_fileSystem.DeleteFile(fileName);
}
InvalidatePackages();
}
}
}
/// <summary>
/// Remove a package from the respository.
/// </summary>
public void RemovePackage(string packageId, SemanticVersion version)
{
IPackage package = FindPackage(packageId, version);
RemovePackage(package);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
DetachEvents();
}
/// <summary>
/// *.nupkg files in the root folder
/// </summary>
private IEnumerable<string> GetPackageFiles()
{
// Check top level directory
foreach (var path in _fileSystem.GetFiles(String.Empty, _filter))
{
yield return path;
}
}
/// <summary>
/// Internal package cache containing both the packages and their metadata.
/// This data is generated if it does not exist already.
/// </summary>
private IDictionary<IPackage, DerivedPackageData> PackageCache
{
get
{
lock (_lockObj)
{
if (_packages == null)
{
if (!_monitoringFiles)
{
// attach events the first time
_monitoringFiles = true;
AttachEvents();
}
_packages = CreateCache();
}
return _packages;
}
}
}
/// <summary>
/// Sets the current cache to null so it will be regenerated next time.
/// </summary>
private void InvalidatePackages()
{
lock (_lockObj)
{
_packages = null;
}
}
/// <summary>
/// CreateCache loads all packages and determines additional metadata such as the hash, IsAbsoluteLatestVersion, and IsLatestVersion.
/// </summary>
private IDictionary<IPackage, DerivedPackageData> CreateCache()
{
ConcurrentDictionary<IPackage, DerivedPackageData> packages = new ConcurrentDictionary<IPackage, DerivedPackageData>();
ParallelOptions opts = new ParallelOptions();
opts.MaxDegreeOfParallelism = 4;
ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>> absoluteLatest = new ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>>();
ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>> latest = new ConcurrentDictionary<string, Tuple<IPackage, DerivedPackageData>>();
// get settings
bool checkFrameworks = EnableFrameworkFiltering;
bool enableDelisting = EnableDelisting;
// load and cache all packages
Parallel.ForEach(GetPackageFiles(), opts, path =>
{
OptimizedZipPackage zip = OpenPackage(path);
Debug.Assert(zip != null, "Unable to open " + path);
if (zip != null)
{
if (enableDelisting)
{
// hidden packages are considered delisted
zip.Listed = !File.GetAttributes(_fileSystem.GetFullPath(path)).HasFlag(FileAttributes.Hidden);
}
byte[] hashBytes;
long fileLength;
using (Stream stream = _fileSystem.OpenFile(path))
{
fileLength = stream.Length;
hashBytes = HashProvider.CalculateHash(stream);
}
var data = new DerivedPackageData
{
PackageSize = fileLength,
PackageHash = Convert.ToBase64String(hashBytes),
PackageSource = this.Source,
LastUpdated = _fileSystem.GetLastModified(path),
Created = _fileSystem.GetCreated(path),
Path = path,
FullPath = _fileSystem.GetFullPath(path),
// default to false, these will be set later
IsAbsoluteLatestVersion = false,
IsLatestVersion = false
};
if (checkFrameworks)
{
data.SupportedFrameworks = zip.GetSupportedFrameworks();
}
Tuple<IPackage, DerivedPackageData> entry = new Tuple<IPackage, DerivedPackageData>(zip, data);
// find the latest versions
string id = zip.Id.ToLowerInvariant();
// update with the highest version
absoluteLatest.AddOrUpdate(id, entry, (oldId, oldEntry) => oldEntry.Item1.Version < entry.Item1.Version ? entry : oldEntry);
// update latest for release versions
if (zip.IsReleaseVersion())
{
latest.AddOrUpdate(id, entry, (oldId, oldEntry) => oldEntry.Item1.Version < entry.Item1.Version ? entry : oldEntry);
}
// add the package to the cache, it should not exist already
Debug.Assert(packages.ContainsKey(zip) == false, "duplicate package added");
packages.AddOrUpdate(zip, entry.Item2, (oldPkg, oldData) => oldData);
}
});
// Set additional attributes after visiting all packages
foreach (var entry in absoluteLatest.Values)
{
entry.Item2.IsAbsoluteLatestVersion = true;
}
foreach (var entry in latest.Values)
{
entry.Item2.IsLatestVersion = true;
}
return packages;
}
private OptimizedZipPackage OpenPackage(string path)
{
OptimizedZipPackage zip = null;
if (_fileSystem.FileExists(path))
{
try
{
zip = new OptimizedZipPackage(_fileSystem, path);
}
catch (FileFormatException ex)
{
throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex);
}
// Set the last modified date on the package
zip.Published = _fileSystem.GetLastModified(path);
}
return zip;
}
// Add the file watcher to monitor changes on disk
private void AttachEvents()
{
// skip invalid paths
if (_fileWatcher == null && !String.IsNullOrEmpty(Source) && Directory.Exists(Source))
{
_fileWatcher = new FileSystemWatcher(_fileSystem.Root);
_fileWatcher.Filter = _filter;
_fileWatcher.IncludeSubdirectories = false;
_fileWatcher.Changed += FileChanged;
_fileWatcher.Created += FileChanged;
_fileWatcher.Deleted += FileChanged;
_fileWatcher.Renamed += FileChanged;
_fileWatcher.EnableRaisingEvents = true;
}
}
// clean up events
private void DetachEvents()
{
if (_fileWatcher != null)
{
_fileWatcher.EnableRaisingEvents = false;
_fileWatcher.Changed -= FileChanged;
_fileWatcher.Created -= FileChanged;
_fileWatcher.Deleted -= FileChanged;
_fileWatcher.Renamed -= FileChanged;
_fileWatcher.Dispose();
_fileWatcher = null;
}
}
private void FileChanged(object sender, FileSystemEventArgs e)
{
// invalidate the cache when a nupkg in the root folder changes
InvalidatePackages();
}
private static bool AllowOverrideExistingPackageOnPush
{
get
{
// If the setting is misconfigured, treat it as success (backwards compatibility).
return GetBooleanAppSetting("allowOverrideExistingPackageOnPush", true);
}
}
private static bool EnableDelisting
{
get
{
// If the setting is misconfigured, treat it as off (backwards compatibility).
return GetBooleanAppSetting("enableDelisting", false);
}
}
private static bool EnableFrameworkFiltering
{
get
{
// If the setting is misconfigured, treat it as off (backwards compatibility).
return GetBooleanAppSetting("enableFrameworkFiltering", false);
}
}
private static bool GetBooleanAppSetting(string key, bool defaultValue)
{
var appSettings = WebConfigurationManager.AppSettings;
bool value;
return !Boolean.TryParse(appSettings[key], out value) ? defaultValue : value;
}
}
}