-
Notifications
You must be signed in to change notification settings - Fork 24
/
common.py
3913 lines (3193 loc) · 137 KB
/
common.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
#!/usr/bin/python
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright (c) 2011, 2024, Oracle and/or its affiliates.
#
"""
Linked image module classes.
The following classes for manipulating linked images are defined here:
LinkedImage
LinkedImageChild
The following template classes which linked image plugins should inherit from
are also defined here:
LinkedImagePlugin
LinkedImageChildPlugin
"""
# standard python classes
import collections
import copy
import itertools
import operator
import os
import select
import rapidjson as json
# Redefining built-in 'reduce'; pylint: disable=W0622
from functools import reduce
# pkg classes
import pkg.actions
import pkg.altroot as ar
import pkg.catalog
import pkg.client.api_errors as apx
import pkg.client.bootenv as bootenv
import pkg.client.linkedimage
import pkg.client.pkgdefs as pkgdefs
import pkg.client.pkgplan as pkgplan
import pkg.client.pkgremote
import pkg.client.progress as progress
import pkg.facet
import pkg.fmri
import pkg.misc as misc
import pkg.pkgsubprocess
import pkg.version
from pkg.client import global_settings
logger = global_settings.logger
# linked image relationship types (returned by LinkedImage.list_related())
REL_PARENT = "parent"
REL_SELF = "self"
REL_CHILD = "child"
# linked image properties
PROP_CURRENT_PARENT_PATH = "li-current-parent"
PROP_CURRENT_PATH = "li-current-path"
PROP_MODEL = "li-model"
PROP_NAME = "li-name"
PROP_PARENT_PATH = "li-parent"
PROP_PATH = "li-path"
PROP_PATH_TRANSFORM = "li-path-transform"
PROP_RECURSE = "li-recurse"
prop_values = frozenset([
PROP_CURRENT_PARENT_PATH,
PROP_CURRENT_PATH,
PROP_MODEL,
PROP_NAME,
PROP_PARENT_PATH,
PROP_PATH,
PROP_PATH_TRANSFORM,
PROP_RECURSE,
])
# properties that never get saved
temporal_props = frozenset([
PROP_CURRENT_PARENT_PATH,
PROP_CURRENT_PATH,
PROP_PATH_TRANSFORM,
])
# special linked image name values (PROP_NAME)
PV_NAME_NONE = "-"
# linked image model values (PROP_MODEL)
PV_MODEL_PUSH = "push"
PV_MODEL_PULL = "pull"
model_values = frozenset([
PV_MODEL_PUSH,
PV_MODEL_PULL,
])
# files which contain linked image data
__DATA_DIR = "linked"
PATH_PFACETS = os.path.join(__DATA_DIR, "linked_pfacets")
PATH_PPKGS = os.path.join(__DATA_DIR, "linked_ppkgs")
PATH_PROP = os.path.join(__DATA_DIR, "linked_prop")
PATH_PUBS = os.path.join(__DATA_DIR, "linked_ppubs")
#
# we define PATH_TRANSFORM_NONE as a tuple instead of just None because this
# will prevent it from being accidentally serialized to json.
#
PATH_TRANSFORM_NONE = ("/", "/")
LI_RVTuple = collections.namedtuple("LI_RVTuple", "rvt_rv rvt_e rvt_p_dict")
def _li_rvtuple_check(rvtuple):
"""Sanity check a linked image operation return value tuple.
The format of said tuple is:
process return code
LinkedImageException exception (optional)
json dictionary containing planned image changes
"""
# make sure we're using the LI_RVTuple class
assert type(rvtuple) == LI_RVTuple
# decode the tuple
rv, e, p_dict = rvtuple
# rv must be an integer
assert type(rv) == int
# any exception returned must be a LinkedImageException
assert e is None or type(e) == apx.LinkedImageException
# if specified, p_dict must be a dictionary
assert p_dict is None or type(p_dict) is dict
# some child return codes should never be associated with an exception
assert rv not in [pkgdefs.EXIT_OK, pkgdefs.EXIT_NOP] or e is None
# a p_dict can only be returned if the child returned EXIT_OK
assert rv == pkgdefs.EXIT_OK or p_dict is None
# return the value that was passed in
return rvtuple
def _li_rvdict_check(rvdict):
"""Given a linked image return value dictionary, sanity check all the
entries."""
assert type(rvdict) == dict
for k, v in rvdict.items():
assert type(k) == LinkedImageName, \
("Unexpected rvdict key: ", k)
_li_rvtuple_check(v)
# return the value that was passed in
return rvdict
def _li_rvdict_exceptions(rvdict):
"""Given a linked image return value dictionary, return a list of any
exceptions that were encountered while processing children."""
# sanity check rvdict
_li_rvdict_check(rvdict)
# get a list of exceptions
return [
rvtuple.rvt_e
for rvtuple in rvdict.values()
if rvtuple.rvt_e is not None
]
def _li_rvdict_raise_exceptions(rvdict):
"""If an exception was encountered while operating on a linked
child then raise that exception. If multiple exceptions were
encountered while operating on multiple children, then bundle
those exceptions together and raise them."""
# get a list of exceptions
exceptions = _li_rvdict_exceptions(rvdict)
if len(exceptions) == 1:
# one exception encountered
raise exceptions[0]
if exceptions:
# multiple exceptions encountered
raise apx.LinkedImageException(bundle=exceptions)
class LinkedImagePlugin(object):
"""This class is a template that all linked image plugins should
inherit from. Linked image plugins derived from this class are
designed to manage linked aspects of the current image (vs managing
linked aspects of a specific child of the current image).
All the interfaces exported by this class and its descendants are
private to the linked image subsystem and should not be called
directly by any other subsystem."""
# functionality flags
support_attach = False
support_detach = False
# Unused argument; pylint: disable=W0613
def __init__(self, pname, linked):
"""Initialize a linked image plugin.
'pname' is the name of the plugin class derived from this
base class.
'linked' is the LinkedImage object initializing this plugin.
"""
return
def init_root(self, root):
"""Called when the path to the image that we're operating on
is changing. This normally occurs when we clone an image
after we've planned and prepared to do an operation."""
# return value: None
raise NotImplementedError
def guess_path_transform(self, ignore_errors=False):
"""If the linked image plugin is able to detect that we're
operating on an image in an alternate root then return an
transform that can be used to translate between the original
image path and the current one."""
# return value: string or None
raise NotImplementedError
def get_child_list(self, nocache=False, ignore_errors=False):
"""Return a list of the child images and paths associated with
the current image. The paths that are returned should be
absolute paths to the original child image locations."""
# return value: list
raise NotImplementedError
def get_child_props(self, lin):
"""Get the linked image properties associated with the
specified child image."""
# return value: dict
raise NotImplementedError
def attach_child_inmemory(self, props, allow_relink):
"""Attach the specified child image. This operation should
only affect in-memory state of the current image. It should
not update any persistent on-disk linked image state or access
the child image in any way. This routine should assume that
the linked image properties have already been validated."""
# return value: None
raise NotImplementedError
def detach_child_inmemory(self, lin):
"""Detach the specified child image. This operation should
only affect in-memory state of the current image. It should
not update any persistent on-disk linked image state or access
the child image in any way."""
# return value: None
raise NotImplementedError
def sync_children_todisk(self):
"""Sync out the in-memory linked image state of this image to
disk."""
# return value: LI_RVTuple()
raise NotImplementedError
class LinkedImageChildPlugin(object):
"""This class is a template that all linked image child plugins should
inherit from. Linked image child plugins derived from this class are
designed to manage linked aspects of children of the current image.
(vs managing linked aspects of the current image itself).
All the interfaces exported by this class and its descendants are
private to the linked image subsystem and should not be called
directly by any other subsystem."""
def __init__(self, lic): # Unused argument; pylint: disable=W0613
"""Initialize a linked image child plugin.
'lic' is the LinkedImageChild object initializing this plugin.
"""
return
def munge_props(self, props):
"""Called before a parent image saves linked image properties
into a child image. Gives the linked image child plugin a
chance to update the properties that will be saved within the
child image."""
# return value: None
raise NotImplementedError
class LinkedImageName(object):
"""A class for naming child linked images. Linked image names are
used for all child images (and only child images), and they encode two
pieces of information. The name of the plugin used to manage the
image and a linked image name. Linked image names have the following
format "<linked_image_plugin>:<linked_image_name>"""
def __init__(self, name):
assert type(name) == str
self.lin_type = self.lin_name = None
try:
self.lin_type, self.lin_name = name.split(":")
except ValueError:
raise apx.LinkedImageException(lin_malformed=name)
if len(self.lin_type) == 0 or len(self.lin_name) == 0 :
raise apx.LinkedImageException(lin_malformed=name)
if self.lin_type not in pkg.client.linkedimage.p_types:
raise apx.LinkedImageException(lin_malformed=name)
@staticmethod
def getstate(obj, je_state=None):
"""Returns the serialized state of this object in a format
that that can be easily stored using JSON, pickle, etc."""
# Unused argument; pylint: disable=W0613
return str(obj)
@staticmethod
def fromstate(state, jd_state=None):
"""Allocate a new object using previously serialized state
obtained via getstate()."""
# Unused argument; pylint: disable=W0613
return LinkedImageName(state)
def __str__(self):
return "{0}:{1}".format(self.lin_type, self.lin_name)
def __len__(self):
return len(self.__str__())
def __lt__(self, other):
assert type(self) == LinkedImageName
if not other:
return False
if other == PV_NAME_NONE:
return False
assert type(other) == LinkedImageName
if self.lin_type < other.lin_type:
return True
if self.lin_type != other.lin_type:
return False
return self.lin_name < other.lin_name
def __gt__(self, other):
assert type(self) == LinkedImageName
if not other:
return True
if other == PV_NAME_NONE:
return True
assert type(other) == LinkedImageName
if self.lin_type > other.lin_type:
return True
if self.lin_type != other.lin_type:
return False
return self.lin_name > other.lin_name
def __le__(self, other):
return not self > other
def __ge__(self, other):
return not self < other
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
if not isinstance(other, LinkedImageName):
return False
return str(self) == str(other)
def __ne__(self, other):
return not self.__eq__(other)
class LinkedImage(object):
"""A LinkedImage object is used to manage the linked image aspects of
an image. This image could be a child image, a parent image, or both
a parent and child. This object allows for access to linked image
properties and also provides routines that allow operations to be
performed on child images."""
# Properties that a parent image with push children should save locally.
__parent_props = frozenset([
PROP_PATH
])
# Properties that a pull child image should save locally.
__pull_child_props = frozenset([
PROP_NAME,
PROP_PATH,
PROP_MODEL,
PROP_PARENT_PATH,
])
# Properties that a parent image with push children should save in
# those children.
__push_child_props = frozenset([
PROP_NAME,
PROP_PATH,
PROP_MODEL,
PROP_RECURSE,
])
# make sure there is no invalid overlap
assert not (temporal_props & (
__parent_props |
__pull_child_props |
__push_child_props))
def __init__(self, img):
"""Initialize a new LinkedImage object."""
# globals
self.__img = img
# variables reset by self.__update_props()
self.__props = dict()
self.__ppkgs = frozenset()
self.__ppubs = None
self.__pfacets = pkg.facet.Facets()
self.__pimg = None
# variables reset by self.__recursion_init()
self.__lic_ignore = None
self.__lic_dict = {}
# variables reset by self._init_root()
self.__root = None
self.__path_ppkgs = None
self.__path_prop = None
self.__path_ppubs = None
self.__path_pfacets = None
self.__img_insync = True
# initialize with no properties
self.__update_props()
# initialize linked image plugin objects
self.__plugins = dict()
for p in pkg.client.linkedimage.p_types:
self.__plugins[p] = \
pkg.client.linkedimage.p_classes[p](p, self)
# if the image has a path setup, we can load data from it.
if self.__img.imgdir:
self._init_root()
@property
def image(self):
"""Get a pointer to the image object associated with this
linked image object."""
return self.__img
def _init_root(self):
"""Called during object initialization and by
image.py`__set_root() to let us know when we're changing the
root location of the image. (The only time we change the root
path is when changes BEs during operations which clone BEs.
So when this happens most our metadata shouldn't actually
change."""
assert self.__img.root, \
"root = {0}".format(str(self.__img.root))
assert self.__img.imgdir, \
"imgdir = {0}".format(str(self.__img.imgdir))
# Check if this is our first time accessing the current image
# or if we're just re-initializing ourselves.
first_pass = self.__root is None
# figure out the new root image path
root = self.__img.root.rstrip(os.sep) + os.sep
# initialize paths for linked image data files
self.__root = root
imgdir = self.__img.imgdir.rstrip(os.sep) + os.sep
self.__path_ppkgs = os.path.join(imgdir, PATH_PPKGS)
self.__path_prop = os.path.join(imgdir, PATH_PROP)
self.__path_ppubs = os.path.join(imgdir, PATH_PUBS)
self.__path_pfacets = os.path.join(imgdir, PATH_PFACETS)
# if this isn't a reset, then load data from the image
if first_pass:
# the first time around we load non-temporary data (if
# there is any) so that we can audit ourselves and see
# if we're in currently in sync.
self.__load(tmp=False)
if self.ischild():
self.__img_insync = self.__insync()
# now re-load all the data taking into account any
# temporary new data associated with an in-progress
# operation.
self.__load()
# if we're not linked we're done
if not self.__props:
return
# if this is a reset, update temporal properties
if not first_pass:
self.__set_current_path(self.__props, update=True)
# Tell linked image plugins about the updated paths
# Unused variable 'plugin'; pylint: disable=W0612
for plugin, lip in self.__plugins.items():
# pylint: enable=W0612
lip.init_root(root)
# Tell linked image children about the updated paths
for lic in self.__lic_dict.values():
lic.child_init_root()
def __update_props(self, props=None):
"""Internal helper routine used when we want to update any
linked image properties. This routine sanity check the
new properties, updates them, and resets any cached state
that is affected by property values."""
if props is None:
props = dict()
elif props:
self.__verify_props(props)
# all temporal properties must exist
for p in temporal_props:
# PROP_CURRENT_PARENT_PATH can only be set if
# we have PROP_PARENT_PATH.
if p is PROP_CURRENT_PARENT_PATH and \
PROP_PARENT_PATH not in props:
continue
assert p in props, \
"'{0}' not in {1}".format(p, set(props))
# update state
self.__props = props
self.__ppkgs = frozenset()
self.__ppubs = None
self.__pfacets = pkg.facet.Facets()
self.__pimg = None
def __verify_props(self, props):
"""Perform internal consistency checks for a set of linked
image properties. Don't update any state."""
props_set = set(props)
# if we're not a child image ourselves, then we're done
if (props_set - temporal_props) == self.__parent_props:
return props
# make sure PROP_MODEL was specified
if PROP_NAME not in props:
_rterr(path=self.__root,
missing_props=[PROP_NAME])
# validate the linked image name
try:
lin = LinkedImageName(str(props[PROP_NAME]))
except apx.LinkedImageException:
_rterr(path=self.__root,
bad_prop=(PROP_NAME, props[PROP_NAME]))
if lin.lin_type not in self.__plugins:
_rterr(path=self.__root, lin=lin,
bad_lin_type=lin.lin_type)
# make sure PROP_MODEL was specified
if PROP_MODEL not in props:
_rterr(path=self.__root, lin=lin,
missing_props=[PROP_MODEL])
model = props[PROP_MODEL]
if model not in model_values:
_rterr(path=self.__root, lin=lin,
bad_prop=(PROP_MODEL, model))
if model == PV_MODEL_PUSH:
missing = self.__push_child_props - props_set
if missing:
_rterr(path=self.__root, lin=lin,
missing_props=missing)
if model == PV_MODEL_PULL:
missing = self.__pull_child_props - props_set
if missing:
_rterr(path=self.__root, lin=lin,
missing_props=missing)
@staticmethod
def set_path_transform(props, path_transform,
path=None, current_path=None, update=False):
"""Given a new path_transform, update path properties."""
if update:
assert (set(props) & temporal_props), \
"no temporal properties are set: {0}".format(props)
else:
assert not (set(props) & temporal_props), \
"temporal properties already set: {0}".format(props)
# Either 'path' or 'current_path' must be specified.
assert path is None or current_path is None
assert path is not None or current_path is not None
if path is not None:
current_path = path_transform_apply(path,
path_transform)
elif current_path is not None:
path = path_transform_revert(current_path,
path_transform)
props[PROP_PATH] = path
props[PROP_CURRENT_PATH] = current_path
props[PROP_PATH_TRANSFORM] = path_transform
parent_path = props.get(PROP_PARENT_PATH)
if not parent_path:
return
if not path_transform_applicable(parent_path, path_transform):
props[PROP_CURRENT_PARENT_PATH] = parent_path
return
props[PROP_CURRENT_PARENT_PATH] = path_transform_apply(
parent_path, path_transform)
def __set_current_path(self, props, update=False):
"""Given a set of linked image properties, the image paths
stored within those properties may not match the actual image
paths if we're executing within an alternate root environment.
To deal with this situation we create temporal in-memory
properties that represent the current path to the image, and a
transform that allows us to translate between the current path
and the original path."""
current_path = self.__root
path_transform = compute_path_transform(props[PROP_PATH],
current_path)
self.set_path_transform(props, path_transform,
current_path=current_path, update=update)
def __guess_path_transform(self, ignore_errors=False):
"""If we're initializing parent linked image properties for
the first time (or if those properties somehow got deleted)
then we need to know if the parent image that we're currently
operating on is located within an alternate root. One way to
do this is to ask our linked image plugins if they can
determine this (the zones linked image plugin usually can
if the image is a global zone)."""
# ask each plugin if we're operating in an alternate root
p_transforms = []
for plugin, lip in self.__plugins.items():
p_transform = lip.guess_path_transform(
ignore_errors=ignore_errors)
if p_transform is not PATH_TRANSFORM_NONE:
p_transforms.append((plugin, p_transform))
if not p_transforms:
# no transform suggested by plugins
return PATH_TRANSFORM_NONE
# check for conflicting transforms
transforms = list(set([
p_transform
# Unused variable; pylint: disable=W0612
for pname, p_transform in p_transforms
# pylint: enable=W0612
]))
if len(transforms) == 1:
# we have a transform from our plugins
return transforms[0]
# we have conflicting transforms, time to die
_rterr(li=self, multiple_transforms=p_transforms)
def __fabricate_parent_props(self, ignore_errors=False):
"""Fabricate the minimum set of properties required for a
parent image."""
# ask our plugins if we're operating with alternate image paths
path_transform = self.__guess_path_transform(
ignore_errors=ignore_errors)
props = dict()
self.set_path_transform(props, path_transform,
current_path=self.__root)
return props
def __load_ondisk_props(self, tmp=True):
"""Load linked image properties from disk and return them to
the caller. We sanity check the properties, but we don't
update any internal linked image state.
'tmp' determines if we should read/write to the official
linked image metadata files, or if we should access temporary
versions (which have ".<runid>" appended to them."""
path = self.__path_prop
path_tmp = "{0}.{1:d}".format(self.__path_prop,
global_settings.client_runid)
# read the linked image properties from disk
if tmp and path_exists(path_tmp):
path = path_tmp
props = load_data(path)
elif path_exists(path):
props = load_data(path)
else:
return None
# make sure there are no saved temporal properties
assert not set(props) & temporal_props
if PROP_NAME in props:
# convert PROP_NAME into a linked image name obj
name = props[PROP_NAME]
try:
lin = LinkedImageName(name)
props[PROP_NAME] = lin
except apx.LinkedImageException:
_rterr(path=self.__root,
bad_prop=(PROP_NAME, name))
# sanity check our properties
self.__verify_props(props)
return props
def __load_ondisk_pfacets(self, tmp=True):
"""Load linked image inherited facets from disk.
Don't update any internal state.
'tmp' determines if we should read/write to the official
linked image metadata files, or if we should access temporary
versions (which have ".<runid>" appended to them."""
pfacets = misc.EmptyDict
path = "{0}.{1:d}".format(self.__path_pfacets,
global_settings.client_runid)
if tmp and path_exists(path):
pfacets = load_data(path)
else:
path = self.__path_pfacets
pfacets = load_data(path, missing_ok=True)
if pfacets is None:
return None
rv = pkg.facet.Facets()
for k, v in pfacets.items():
# W0212 Access to a protected member
# pylint: disable=W0212
rv._set_inherited(k, v)
return rv
def __load_ondisk_ppkgs(self, tmp=True):
"""Load linked image parent packages from disk.
Don't update any internal state.
'tmp' determines if we should read/write to the official
linked image metadata files, or if we should access temporary
versions (which have ".<runid>" appended to them."""
fmri_strs = None
path = "{0}.{1:d}".format(self.__path_ppkgs,
global_settings.client_runid)
if tmp and path_exists(path):
fmri_strs = load_data(path)
else:
path = self.__path_ppkgs
fmri_strs = load_data(path, missing_ok=True)
if fmri_strs is None:
return None
return frozenset([
pkg.fmri.PkgFmri(str(s))
for s in fmri_strs
])
def __load_ondisk_ppubs(self, tmp=True):
"""Load linked image parent publishers from disk.
Don't update any internal state.
'tmp' determines if we should read/write to the official
linked image metadata files, or if we should access temporary
versions (which have ".<runid>" appended to them."""
ppubs = None
path = "{0}.{1:d}".format(self.__path_ppubs,
global_settings.client_runid)
if tmp and path_exists(path):
ppubs = load_data(path)
else:
path = self.__path_ppubs
ppubs = load_data(path, missing_ok=True)
return ppubs
def __load(self, tmp=True):
"""Load linked image properties and constraints from disk.
Update the linked image internal state with the loaded data."""
#
# Normally, if we're a parent image we'll have linked image
# properties stored on disk. So load those now.
#
# If no properties are loaded, we may still be a parent image
# that is just missing it's metadata. (oops.) We attempt to
# detect this situation by invoking __isparent(), which will
# ask each child if there are any children. This is a best
# effort attempt, so when we do this we ignore any plugin
# runtime errors since we really want Image object
# initialization to succeed. If we don't have any linked
# image metadata, and we're having runtime errors querying for
# children, then we'll allow initialization here, but any
# subsequent operation that tries to access children will fail
# and the caller will have to specify that they want to ignore
# all children to allow the operation to succeed.
#
props = self.__load_ondisk_props(tmp=tmp)
if not props and not self.__isparent(ignore_errors=True):
# we're not linked
return
if not props:
#
# Oops. We're a parent image with no properties
# stored on disk. Rather than throwing an exception
# try to fabricate up some props with reasonably
# guessed values which the user can subsequently
# change and/or fix.
#
props = self.__fabricate_parent_props(
ignore_errors=True)
else:
self.__set_current_path(props)
self.__update_props(props)
if not self.ischild():
return
# load parent packages. if parent package data is missing just
# continue along and hope for the best.
ppkgs = self.__load_ondisk_ppkgs(tmp=tmp)
if ppkgs is not None:
self.__ppkgs = ppkgs
# load inherited facets. if inherited facet data is missing
# just continue along and hope for the best.
pfacets = self.__load_ondisk_pfacets(tmp=tmp)
if pfacets is not None:
self.__pfacets = pfacets
# load parent publisher data. if publisher data is missing
# continue along and we'll just skip the publisher checks,
# it's better than failing and preventing any image updates.
self.__ppubs = self.__load_ondisk_ppubs(tmp=tmp)
@staticmethod
def __validate_prop_recurse(v):
"""Verify property value for PROP_RECURSE."""
if v in [True, False]:
return True
if type(v) == str and v.lower() in ["true", "false"]:
return True
return False
def __validate_attach_props(self, model, props):
"""Validate user supplied linked image attach properties.
Don't update any internal state."""
# make sure that only attach time options have been
# specified, and that they have allowed values.
validate_props = {
PROP_RECURSE: self.__validate_prop_recurse
}
if model == PV_MODEL_PUSH:
allowed_props = self.__push_child_props
else:
assert model == PV_MODEL_PULL
allowed_props = self.__pull_child_props
errs = []
# check each property the user specified.
for k, v in props.items():
# did the user specify an allowable property?
if k not in validate_props:
errs.append(apx.LinkedImageException(
attach_bad_prop=k))
continue
# did the user specify a valid property value?
if not validate_props[k](v):
errs.append(apx.LinkedImageException(
attach_bad_prop_value=(k, v)))
continue
# is this property valid for this type of image?
if k not in allowed_props:
errs.append(apx.LinkedImageException(
attach_bad_prop=k))
continue
if len(errs) == 1:
raise errs[0]
if errs:
raise apx.LinkedImageException(bundle=errs)
def __init_pimg(self, path):
"""Initialize an Image object which can be used to access a
parent image."""
try:
os.stat(path)
except OSError:
raise apx.LinkedImageException(parent_bad_path=path)
try:
pimg = self.__img.alloc(
root=path,
user_provided_dir=True,
cmdpath=self.__img.cmdpath)
except apx.ImageNotFoundException:
raise apx.LinkedImageException(parent_bad_img=path)
return pimg
def nothingtodo(self):
"""If our in-memory linked image state matches the on-disk
linked image state then there's nothing to do. If the state
differs then there is stuff to do since the new state needs
to be saved to disk."""
# check if we're not a linked image.
if not self.isparent() and not self.ischild():
# if any linked image metadata files exist they need
# to be deleted.
paths = [
self.__path_pfacets,
self.__path_ppkgs,
self.__path_ppubs,
self.__path_prop,
]
for path in paths:
if path_exists(path):
return False
return True
# compare in-memory and on-disk properties
li_ondisk_props = self.__load_ondisk_props(tmp=False)
if li_ondisk_props is None:
li_ondisk_props = dict()
li_inmemory_props = rm_dict_ent(self.__props,
temporal_props)
if li_ondisk_props != li_inmemory_props: