-
Notifications
You must be signed in to change notification settings - Fork 337
/
filesystem.py
1535 lines (1229 loc) · 52.4 KB
/
filesystem.py
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
"""
Filesystem-based package repository
"""
from contextlib import contextmanager
from functools import lru_cache
import os.path
import os
import stat
import errno
import time
import shutil
from rez.package_repository import PackageRepository
from rez.package_resources import PackageFamilyResource, VariantResourceHelper, \
PackageResourceHelper, package_pod_schema, \
package_release_keys, package_build_only_keys
from rez.serialise import clear_file_caches, open_file_for_write, load_from_file, \
FileFormat
from rez.package_serialise import dump_package_data
from rez.exceptions import PackageMetadataError, ResourceError, RezSystemError, \
ConfigurationError, PackageRepositoryError
from rez.utils.resources import ResourcePool
from rez.utils.formatting import is_valid_package_name
from rez.utils.resources import cached_property
from rez.utils.logging_ import print_warning, print_info
from rez.utils.memcached import memcached, pool_memcached_connections
from rez.utils.filesystem import make_path_writable, \
canonical_path, is_subdirectory
from rez.utils.platform_ import platform_
from rez.utils.yaml import load_yaml
from rez.config import config
from rez.vendor.schema.schema import Schema, Optional, And, Use, Or
from rez.version import Version, VersionRange
debug_print = config.debug_printer("resources")
# ------------------------------------------------------------------------------
# format version
#
# 1:
# Initial format.
# 2:
# Late binding functions added.
# ------------------------------------------------------------------------------
format_version = 2
def check_format_version(filename, data):
format_version_ = data.pop("format_version", None)
if format_version_ is not None:
try:
format_version_ = int(format_version_)
except:
return
if format_version_ > format_version:
print_warning(
"Loading from %s may fail: newer format version (%d) than current "
"format version (%d)" % (filename, format_version_, format_version))
# ------------------------------------------------------------------------------
# utilities
# ------------------------------------------------------------------------------
# this is set when the package repository is instantiated, otherwise an infinite
# loop is caused to to config loading this plugin, loading config ad infinitum
_settings = None
class PackageDefinitionFileMissing(PackageMetadataError):
pass
# ------------------------------------------------------------------------------
# resources
# ------------------------------------------------------------------------------
class FileSystemPackageFamilyResource(PackageFamilyResource):
key = "filesystem.family"
repository_type = "filesystem"
def _uri(self):
return self.path
@cached_property
def path(self):
return os.path.join(self.location, self.name)
def get_last_release_time(self):
# this repository makes sure to update path mtime every time a
# variant is added to the repository
try:
return os.path.getmtime(self.path)
except OSError:
return 0
def iter_packages(self):
# check for unversioned package
if config.allow_unversioned_packages:
filepath, _ = self._repository._get_file(self.path)
if filepath:
package = self._repository.get_resource(
FileSystemPackageResource.key,
location=self.location,
name=self.name)
yield package
return
# versioned packages
for version_str in self._repository._get_version_dirs(self.path):
if _settings.check_package_definition_files:
path = os.path.join(self.path, version_str)
if not self._repository._get_file(path)[0]:
continue
package = self._repository.get_resource(
FileSystemPackageResource.key,
location=self.location,
name=self.name,
version=version_str)
yield package
class FileSystemPackageResource(PackageResourceHelper):
key = "filesystem.package"
variant_key = "filesystem.variant"
repository_type = "filesystem"
schema = package_pod_schema
def _uri(self):
return self.filepath
@cached_property
def parent(self):
family = self._repository.get_resource(
FileSystemPackageFamilyResource.key,
location=self.location,
name=self.name)
return family
@cached_property
def state_handle(self):
if self.filepath:
return os.path.getmtime(self.filepath)
return None
@property
def base(self):
# Note: '_redirected_base' is a special attribute set by the build
# process in order to perform pre-install/release package testing. See
# `LocalBuildProcess._run_tests()`
#
redirected_base = self._data.get("_redirected_base")
return redirected_base or self.path
@cached_property
def path(self):
path = os.path.join(self.location, self.name)
ver_str = self.get("version")
if ver_str:
path = os.path.join(path, ver_str)
return path
@cached_property
def filepath(self):
return self._filepath_and_format[0]
@cached_property
def file_format(self):
return self._filepath_and_format[1]
@cached_property
def _filepath_and_format(self):
return self._repository._get_file(self.path)
def _load(self):
if self.filepath is None:
raise PackageDefinitionFileMissing(
"Missing package definition file: %r" % self)
data = load_from_file(
self.filepath,
self.file_format,
disable_memcache=self._repository.disable_memcache
)
check_format_version(self.filepath, data)
if "timestamp" not in data: # old format support
data_ = self._load_old_formats()
if data_:
data.update(data_)
return data
# TODO: Deprecate? How could we add deprecation warnings without flooding the user?
def _load_old_formats(self):
data = None
filepath = os.path.join(self.path, "release.yaml")
if os.path.isfile(filepath):
# rez<2.0.BETA.16
data = load_from_file(filepath, FileFormat.yaml,
update_data_callback=self._update_changelog)
else:
path_ = os.path.join(self.path, ".metadata")
if os.path.isdir(path_):
# rez-1
data = {}
filepath = os.path.join(path_, "changelog.txt")
if os.path.isfile(filepath):
data["changelog"] = load_from_file(
filepath, FileFormat.txt,
update_data_callback=self._update_changelog)
filepath = os.path.join(path_, "release_time.txt")
if os.path.isfile(filepath):
value = load_from_file(filepath, FileFormat.txt)
try:
data["timestamp"] = int(value.strip())
except:
pass
return data
@staticmethod
def _update_changelog(file_format, data):
# this is to deal with older package releases. They can contain long
# changelogs (more recent rez versions truncate before release), and
# release.yaml files can contain a list-of-str changelog.
maxlen = config.max_package_changelog_chars
if not maxlen:
return data
# TODO: Deprecate
if file_format == FileFormat.yaml:
changelog = data.get("changelog")
if changelog:
changed = False
if isinstance(changelog, list):
changelog = '\n'.join(changelog)
changed = True
if len(changelog) > (maxlen + 3):
changelog = changelog[:maxlen] + "..."
changed = True
if changed:
data["changelog"] = changelog
else:
assert isinstance(data, str)
if len(data) > (maxlen + 3):
data = data[:maxlen] + "..."
return data
class FileSystemVariantResource(VariantResourceHelper):
key = "filesystem.variant"
repository_type = "filesystem"
@cached_property
def parent(self):
package = self._repository.get_resource(
FileSystemPackageResource.key,
location=self.location,
name=self.name,
version=self.get("version"))
return package
# -- 'combined' resource types
class FileSystemCombinedPackageFamilyResource(PackageFamilyResource):
key = "filesystem.family.combined"
repository_type = "filesystem"
schema = Schema({
Optional("versions"): [
And(str, Use(Version))
],
Optional("version_overrides"): {
And(str, Use(VersionRange)): dict
}
})
@property
def ext(self):
return self.get("ext")
@property
def filepath(self):
filename = "%s.%s" % (self.name, self.ext)
return os.path.join(self.location, filename)
def _uri(self):
return self.filepath
def get_last_release_time(self):
try:
return os.path.getmtime(self.filepath)
except OSError:
return 0
def iter_packages(self):
# unversioned package
if config.allow_unversioned_packages and not self.versions:
package = self._repository.get_resource(
FileSystemCombinedPackageResource.key,
location=self.location,
name=self.name,
ext=self.ext)
yield package
return
# versioned packages
for version in self.versions:
package = self._repository.get_resource(
FileSystemCombinedPackageResource.key,
location=self.location,
name=self.name,
ext=self.ext,
version=str(version))
yield package
def _load(self):
# TODO: Deprecate: What is self.ext?
format_ = FileFormat[self.ext]
data = load_from_file(
self.filepath,
format_,
disable_memcache=self._repository.disable_memcache
)
check_format_version(self.filepath, data)
return data
class FileSystemCombinedPackageResource(PackageResourceHelper):
key = "filesystem.package.combined"
variant_key = "filesystem.variant.combined"
repository_type = "filesystem"
schema = package_pod_schema
def _uri(self):
ver_str = self.get("version", "")
return "%s<%s>" % (self.parent.filepath, ver_str)
@cached_property
def parent(self):
family = self._repository.get_resource(
FileSystemCombinedPackageFamilyResource.key,
location=self.location,
name=self.name,
ext=self.get("ext"))
return family
@property
def base(self):
return None # combined resource types do not have 'base'
@cached_property
def state_handle(self):
return os.path.getmtime(self.parent.filepath)
def iter_variants(self):
num_variants = len(self._data.get("variants", []))
if num_variants == 0:
indexes = [None]
else:
indexes = range(num_variants)
for index in indexes:
variant = self._repository.get_resource(
self.variant_key,
location=self.location,
name=self.name,
ext=self.get("ext"),
version=self.get("version"),
index=index)
yield variant
def _load(self):
data = self.parent._data.copy()
if "versions" in data:
del data["versions"]
version_str = self.get("version")
data["version"] = version_str
version = Version(version_str)
overrides = self.parent.version_overrides
if overrides:
for range_, data_ in overrides.items():
if version in range_:
data.update(data_)
del data["version_overrides"]
return data
class FileSystemCombinedVariantResource(VariantResourceHelper):
key = "filesystem.variant.combined"
repository_type = "filesystem"
@cached_property
def parent(self):
package = self._repository.get_resource(
FileSystemCombinedPackageResource.key,
location=self.location,
name=self.name,
ext=self.get("ext"),
version=self.get("version"))
return package
def _root(self):
return None # combined resource types do not have 'root'
# ------------------------------------------------------------------------------
# repository
# ------------------------------------------------------------------------------
class FileSystemPackageRepository(PackageRepository):
"""A filesystem-based package repository.
TODO: Deprecate YAML
Packages are stored on disk, in either 'package.yaml' or 'package.py' files.
These files are stored into an organised directory structure like so:
/LOCATION/pkgA/1.0.0/package.py
/1.0.1/package.py
/pkgB/2.1/package.py
/2.2/package.py
Another supported storage format is to store all package versions within a
single package family in one file, like so:
/LOCATION/pkgC.yaml
/LOCATION/pkgD.py
These 'combined' package files allow for differences between package
versions via a 'package_overrides' section:
name: pkgC
versions:
- '1.0'
- '1.1'
- '1.2'
version_overrides:
'1.0':
requires:
- python-2.5
'1.1+':
requires:
- python-2.6
"""
schema_dict = {"file_lock_timeout": int,
"file_lock_dir": Or(None, str),
"file_lock_type": Or("default", "link", "mkdir", "symlink"),
"package_filenames": [str]}
building_prefix = ".building"
ignore_prefix = ".ignore"
package_file_mode = (
None if os.name == "nt" else
# These aren't supported on Windows
# https://docs.python.org/2/library/os.html#os.chmod
(stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
)
@classmethod
def name(cls):
return "filesystem"
def __init__(self, location, resource_pool, disable_memcache=None,
disable_pkg_ignore=False):
"""Create a filesystem package repository.
Args:
location (str): Path containing the package repository.
disable_memcache (bool): Don't use memcache memcache if True
disable_pkg_ignore (bool): If True, .ignore* files have no effect
"""
# ensure that differing case doesn't get interpreted as different repos
# on case-insensitive platforms (eg windows)
location = canonical_path(location, platform_)
super(FileSystemPackageRepository, self).__init__(location, resource_pool)
# load settings optionally defined in a settings.yaml
local_settings = {}
settings_filepath = os.path.join(location, "settings.yaml")
if os.path.exists(settings_filepath):
local_settings.update(load_yaml(settings_filepath))
self.disable_pkg_ignore = disable_pkg_ignore
if disable_memcache is None:
self.disable_memcache = local_settings.get("disable_memcache", False)
else:
self.disable_memcache = disable_memcache
# TODO allow these settings to be overridden in settings.yaml also
global _settings
_settings = config.plugins.package_repository.filesystem
self.register_resource(FileSystemPackageFamilyResource)
self.register_resource(FileSystemPackageResource)
self.register_resource(FileSystemVariantResource)
self.register_resource(FileSystemCombinedPackageFamilyResource)
self.register_resource(FileSystemCombinedPackageResource)
self.register_resource(FileSystemCombinedVariantResource)
self.get_families = lru_cache(maxsize=None)(self._get_families)
self.get_family = lru_cache(maxsize=None)(self._get_family)
self.get_packages = lru_cache(maxsize=None)(self._get_packages)
self.get_variants = lru_cache(maxsize=None)(self._get_variants)
self.get_file = lru_cache(maxsize=None)(self._get_file)
# decorate with memcachemed memoizers unless told otherwise
if not self.disable_memcache:
decorator1 = memcached(
servers=config.memcached_uri if config.cache_listdir else None,
min_compress_len=config.memcached_listdir_min_compress_len,
key=self._get_family_dirs__key,
debug=config.debug_memcache
)
self._get_family_dirs = decorator1(self._get_family_dirs)
decorator2 = memcached(
servers=config.memcached_uri if config.cache_listdir else None,
min_compress_len=config.memcached_listdir_min_compress_len,
key=self._get_version_dirs__key,
debug=config.debug_memcache
)
self._get_version_dirs = decorator2(self._get_version_dirs)
def _uid(self):
t = ["filesystem", self.location]
if os.path.exists(self.location):
st = os.stat(self.location)
t.append(int(st.st_ino))
return tuple(t)
def get_package_family(self, name):
return self.get_family(name)
@pool_memcached_connections
def iter_package_families(self):
for family in self.get_families():
yield family
@pool_memcached_connections
def iter_packages(self, package_family_resource):
for package in self.get_packages(package_family_resource):
yield package
def iter_variants(self, package_resource):
for variant in self.get_variants(package_resource):
yield variant
def get_parent_package_family(self, package_resource):
return package_resource.parent
def get_parent_package(self, variant_resource):
return variant_resource.parent
def get_variant_state_handle(self, variant_resource):
package_resource = variant_resource.parent
return package_resource.state_handle
def get_last_release_time(self, package_family_resource):
return package_family_resource.get_last_release_time()
def get_package_from_uri(self, uri):
"""
Example URIs:
- /svr/packages/mypkg/1.0.0/package.py
- /svr/packages/mypkg/package.py # (unversioned package - rare)
- /svr/packages/mypkg/package.py<1.0.0> # ("combined" package type - rare)
"""
uri = os.path.normcase(uri)
prefix = self.location + os.path.sep
if not is_subdirectory(uri, prefix):
return None
part = uri[len(prefix):] # eg 'mypkg/1.0.0/package.py'
parts = part.split(os.path.sep)
pkg_name = parts[0]
if len(parts) == 2:
if '<' in part:
# "combined" package type, like 'mypkg/package.py<1.0.0>'
pkg_ver_str = parts[1][1:-1]
else:
# 'mypkg/package.py' (unversioned)
pkg_ver_str = ''
elif len(parts) == 3:
# typical case: 'mypkg/1.0.0/package.py'
pkg_ver_str = parts[1]
else:
return None
# find package
pkg_ver = Version(pkg_ver_str)
return self.get_package(pkg_name, pkg_ver)
def get_variant_from_uri(self, uri):
"""
Example URIs:
- /svr/packages/mypkg/1.0.0/package.py[1]
- /svr/packages/mypkg/1.0.0/package.py[] # ("null" variant)
- /svr/packages/mypkg/package.py[1] # (unversioned package - rare)
- /svr/packages/mypkg/package.py<1.0.0>[1] # ("combined" package type - rare)
"""
i = uri.rfind('[')
if i == -1:
return None
package_uri = uri[:i] # eg 'mypkg/1.0.0/package.py'
variant_index_str = uri[i + 1:-1] # the '1' in '[1]'
# find package
pkg = self.get_package_from_uri(package_uri)
if pkg is None:
return None
# find variant in package
if variant_index_str == '':
variant_index = None
else:
try:
variant_index = int(variant_index_str)
except ValueError:
# future proof - we may move to hash-based indices for hashed variants
variant_index = variant_index_str
for variant in pkg.iter_variants():
if variant.index == variant_index:
return variant
return None
def ignore_package(self, pkg_name, pkg_version, allow_missing=False):
# find package, even if already ignored
if not allow_missing:
repo_copy = self._copy(
disable_pkg_ignore=True,
disable_memcache=True
)
if not repo_copy.get_package(pkg_name, pkg_version):
return -1
filename = self.ignore_prefix + str(pkg_version)
fam_path = os.path.join(self.location, pkg_name)
filepath = os.path.join(fam_path, filename)
# do nothing if already ignored
if os.path.exists(filepath):
return 0
# create .ignore{ver} file
try:
os.makedirs(fam_path)
except OSError: # already exists
pass
with open(filepath, 'w'):
pass
self._on_changed(pkg_name)
return 1
def unignore_package(self, pkg_name, pkg_version):
# find and remove .ignore{ver} file if it exists
ignore_file_was_removed = False
filename = self.ignore_prefix + str(pkg_version)
filepath = os.path.join(self.location, pkg_name, filename)
if os.path.exists(filepath):
os.remove(filepath)
ignore_file_was_removed = True
if self.get_package(pkg_name, pkg_version):
if ignore_file_was_removed:
self._on_changed(pkg_name)
return 1
else:
return 0
else:
return -1
def remove_package(self, pkg_name, pkg_version):
# ignore it first, so a partially deleted pkg is not visible
i = self.ignore_package(pkg_name, pkg_version)
if i == -1:
return False
# check for combined-style package, this is not supported
repo_copy = self._copy(
disable_pkg_ignore=True,
disable_memcache=True
)
pkg = repo_copy.get_package(pkg_name, pkg_version)
assert pkg
if isinstance(pkg, FileSystemCombinedPackageResource):
raise NotImplementedError(
"Package removal not supported in combined-style packages")
# delete the payload
pkg_dir = os.path.join(self.location, pkg_name, str(pkg_version))
shutil.rmtree(pkg_dir)
# unignore (just so the .ignore{ver} file is removed)
self.unignore_package(pkg_name, pkg_version)
return True
def remove_package_family(self, pkg_name, force=False):
# get a non-cached copy and see if fam exists
repo_copy = self._copy(
disable_pkg_ignore=True,
disable_memcache=True
)
fam = repo_copy.get_package_family(pkg_name)
if fam is None:
return False
# check that the pkg fam is empty
if not force:
empty = True
for _ in repo_copy.iter_packages(fam):
empty = False
break
if not empty:
raise PackageRepositoryError(
"Cannot remove non-empty package family %r" % pkg_name
)
# delete the fam dir
fam_dir = os.path.join(self.location, pkg_name)
shutil.rmtree(fam_dir)
self._on_changed(pkg_name)
return True
def remove_ignored_since(self, days, dry_run=False, verbose=False):
now = int(time.time())
num_removed = 0
def _info(msg, *nargs):
if verbose:
print_info(msg, *nargs)
for fam in self._get_families():
fam_path = os.path.join(self.location, fam.name)
if not os.path.isdir(fam_path):
continue # might be a combined-style package
for name in os.listdir(fam_path):
if not name.startswith(self.ignore_prefix):
continue
# get age of .ignore{ver} file
filepath = os.path.join(fam_path, name)
st = os.stat(filepath)
age_secs = now - int(st.st_ctime)
age_days = age_secs / (3600 * 24)
if age_days < days:
continue
# extract pkg version from .ignore filename
ver_str = name[len(self.ignore_prefix):]
# remove the package
if dry_run:
_info("Would remove %s-%s from %s", fam.name, ver_str, self)
num_removed += 1
elif self.remove_package(fam.name, Version(ver_str)):
num_removed += 1
_info("Removed %s-%s from %s", fam.name, ver_str, self)
return num_removed
def get_resource_from_handle(self, resource_handle, verify_repo=True):
if verify_repo:
repository_type = resource_handle.variables.get("repository_type")
location = resource_handle.variables.get("location")
if repository_type != self.name():
raise ResourceError("repository_type mismatch - requested %r, "
"repository_type is %r"
% (repository_type, self.name()))
# It appears that sometimes, the handle location can differ to the
# repo location even though they are the same path (different
# mounts). We account for that here.
#
# https://github.com/AcademySoftwareFoundation/rez/pull/957
#
if location != self.location:
location = canonical_path(location, platform_)
if location != self.location:
raise ResourceError("location mismatch - requested %r, "
"repository location is %r "
% (location, self.location))
resource = self.pool.get_resource_from_handle(resource_handle)
resource._repository = self
return resource
@cached_property
def file_lock_dir(self):
dirname = _settings.file_lock_dir
if not dirname:
return None
# sanity check
if os.path.isabs(dirname) or os.path.basename(dirname) != dirname:
raise ConfigurationError(
"filesystem package repository setting 'file_lock_dir' must be "
"a single relative directory such as '.lock'")
# fall back to location path if lock dir doesn't exist.
path = os.path.join(self.location, dirname)
if not os.path.exists(path):
return None
return dirname
def pre_variant_install(self, variant_resource):
if not variant_resource.version:
return
# create 'building' tagfile, this makes sure that a resolve doesn't
# pick up this package if it doesn't yet have a package.py created.
path = self.location
family_path = os.path.join(path, variant_resource.name)
if not os.path.isdir(family_path):
os.makedirs(family_path)
filename = self.building_prefix + str(variant_resource.version)
filepath = os.path.join(family_path, filename)
with open(filepath, 'w'): # create empty file
pass
def on_variant_install_cancelled(self, variant_resource):
"""
TODO:
Currently this will not delete a newly created package version
directory. The reason is because behaviour with multiple rez procs
installing variants of the same package in parallel is not well
tested and hasn't been fully designed for yet. Currently, if this
did delete the version directory, it could delete it while another
proc is performing a successful variant install into the same dir.
Note though that this does do useful work, if the cancelled variant
was getting installed into an existing package. In this case, the
.building file is deleted, because the existing package.py is valid.
Work has to be done to change the way that new variant dirs and the
.building file are created, so that we can safely delete cancelled
variant dirs in the presence of multiple rez procs.
See #810
"""
family_path = os.path.join(self.location, variant_resource.name)
self._delete_stale_build_tagfiles(family_path)
def install_variant(self, variant_resource, dry_run=False, overrides=None):
overrides = overrides or {}
# Name and version overrides are a special case - they change the
# destination variant to be created/replaced.
#
variant_name = variant_resource.name
variant_version = variant_resource.version
if "name" in overrides:
variant_name = overrides["name"]
if variant_name is self.remove:
raise PackageRepositoryError(
"Cannot remove package attribute 'name'")
if "version" in overrides:
ver = overrides["version"]
if ver is self.remove:
raise PackageRepositoryError(
"Cannot remove package attribute 'version'")
if isinstance(ver, str):
ver = Version(ver)
overrides = overrides.copy()
overrides["version"] = ver
variant_version = ver
# cannot install over one's self, just return existing variant
if variant_resource._repository is self and \
variant_name == variant_resource.name and \
variant_version == variant_resource.version:
return variant_resource
# create repo path on disk if it doesn't exist
path = self.location
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise PackageRepositoryError(
"Package repository path %r could not be created: %s: %s"
% (path, e.__class__.__name__, e)
)
# install the variant
def _create_variant():
return self._create_variant(
variant_resource,
dry_run=dry_run,
overrides=overrides
)
if dry_run:
variant = _create_variant()
else:
with self._lock_package(variant_name, variant_version):
variant = _create_variant()
return variant
def _copy(self, **kwargs):
"""
Make a copy of the repo that does not share resources with this one.
"""
pool = ResourcePool(cache_size=None)
repo_copy = self.__class__(self.location, pool, **kwargs)
return repo_copy
@contextmanager
def _lock_package(self, package_name, package_version=None):
from rez.vendor.lockfile import NotLocked
if _settings.file_lock_type == 'default':
from rez.vendor.lockfile import LockFile
elif _settings.file_lock_type == 'mkdir':
from rez.vendor.lockfile.mkdirlockfile import MkdirLockFile as LockFile
elif _settings.file_lock_type == 'link':
from rez.vendor.lockfile.linklockfile import LinkLockFile as LockFile
elif _settings.file_lock_type == 'symlink':
from rez.vendor.lockfile.symlinklockfile import SymlinkLockFile as LockFile
path = self.location
if self.file_lock_dir:
path = os.path.join(path, self.file_lock_dir)
if not os.path.exists(path):
raise PackageRepositoryError(
"Lockfile directory %s does not exist - please create and try "
"again" % path)
filename = ".lock.%s" % package_name
if package_version:
filename += "-%s" % str(package_version)
lock_file = os.path.join(path, filename)
lock = LockFile(lock_file)
try:
lock.acquire(timeout=_settings.file_lock_timeout)
yield
finally: