forked from aszeszo/pkg5
-
Notifications
You must be signed in to change notification settings - Fork 26
/
client.py
executable file
·6158 lines (5347 loc) · 260 KB
/
client.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/python3.5 -Es
#
# 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) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
# Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
#
#
# pkg - package system client utility
#
# The client is going to maintain an on-disk cache of its state, so that
# startup assembly of the graph is reduced.
#
# Client graph is of the entire local catalog. As operations progress, package
# states will change.
#
# Deduction operation allows the compilation of the local component of the
# catalog, only if an authoritative repository can identify critical files.
#
# Environment variables
#
# PKG_IMAGE - root path of target image
# PKG_IMAGE_TYPE [entire, partial, user] - type of image
# XXX or is this in the Image configuration?
from __future__ import print_function
try:
import pkg.no_site_packages
except ImportError:
import sys
if sys.platform == "sunos5":
print("""
The Python environment on this system is damaged and missing a critical core
component (pkg.no_site_packages) and can not be repaired with pkg(1).
To recover this system reboot and select an alternate Boot Environment (BE)
from the boot menu. From the alternate BE mount and run 'pkg fix' on this BE.
""")
sys.exit(1)
try:
import calendar
import collections
import datetime
import errno
import getopt
import gettext
import itertools
import simplejson as json
import locale
import logging
import os
import re
import six
import socket
import sys
import tempfile
import textwrap
import time
import traceback
import pycurl
import atexit
import shutil
import pkg
import pkg.actions as actions
import pkg.client.api as api
import pkg.client.api_errors as api_errors
import pkg.client.bootenv as bootenv
import pkg.client.client_api as client_api
import pkg.client.progress as progress
import pkg.client.linkedimage as li
import pkg.client.publisher as publisher
import pkg.client.transport.transport as transport
import pkg.client.options as options
import pkg.fmri as fmri
import pkg.misc as misc
import pkg.pipeutils as pipeutils
import pkg.portable as portable
import pkg.version as version
if sys.version_info[:2] >= (3, 4):
from importlib import reload
else:
from imp import reload
from pkg.client import global_settings
from pkg.client.api import (IMG_TYPE_ENTIRE, IMG_TYPE_PARTIAL,
IMG_TYPE_USER, RESULT_CANCELED, RESULT_FAILED_BAD_REQUEST,
RESULT_FAILED_CONFIGURATION, RESULT_FAILED_CONSTRAINED,
RESULT_FAILED_LOCKED, RESULT_FAILED_STORAGE, RESULT_NOTHING_TO_DO,
RESULT_SUCCEEDED, RESULT_FAILED_TRANSPORT, RESULT_FAILED_UNKNOWN,
RESULT_FAILED_OUTOFMEMORY)
from pkg.client.debugvalues import DebugValues
from pkg.client.pkgdefs import *
from pkg.misc import EmptyI, msg, emsg, PipeError
from pkg.client.plandesc import (OP_STAGE_PREP, OP_STAGE_EXEC,
OP_STAGE_PLAN)
except KeyboardInterrupt:
import sys
sys.exit(1)
CLIENT_API_VERSION = 83
PKG_CLIENT_NAME = "pkg"
JUST_UNKNOWN = 0
JUST_LEFT = -1
JUST_RIGHT = 1
SYSREPO_HIDDEN_URI = "<system-repository>"
logger = global_settings.logger
pkg_timer = pkg.misc.Timer("pkg client")
valid_special_attrs = ["action.hash", "action.key", "action.name", "action.raw"]
valid_special_prefixes = ["action."]
default_attrs = {}
for atype, aclass in six.iteritems(actions.types):
default_attrs[atype] = [aclass.key_attr]
if atype == "depend":
default_attrs[atype].insert(0, "type")
if atype == "set":
default_attrs[atype].append("value")
_api_inst = None
tmpdirs = []
tmpfiles = []
@atexit.register
def cleanup():
"""To be called at program finish."""
for d in tmpdirs:
shutil.rmtree(d, True)
for f in tmpfiles:
os.unlink(f)
def format_update_error(e):
# This message is displayed to the user whenever an
# ImageFormatUpdateNeeded exception is encountered.
logger.error("\n")
logger.error(str(e))
logger.error(_("To continue, execute 'pkg update-format' as a "
"privileged user and then try again. Please note that updating "
"the format of the image will render it unusable with older "
"versions of the pkg(5) system."))
def error(text, cmd=None):
"""Emit an error message prefixed by the command name """
if not isinstance(text, six.string_types):
# Assume it's an object that can be stringified.
text = str(text)
# If the message starts with whitespace, assume that it should come
# *before* the command-name prefix.
text_nows = text.lstrip()
ws = text[:len(text) - len(text_nows)]
if cmd:
text_nows = "{0}: {1}".format(cmd, text_nows)
pkg_cmd = "pkg "
else:
pkg_cmd = "pkg: "
# This has to be a constant value as we can't reliably get our actual
# program name on all platforms.
logger.error(ws + pkg_cmd + text_nows)
def usage(usage_error=None, cmd=None, retcode=EXIT_BADOPT, full=False,
verbose=False, unknown_cmd=None):
"""Emit a usage message and optionally prefix it with a more
specific error message. Causes program to exit. """
if usage_error:
error(usage_error, cmd=cmd)
basic_usage = {}
adv_usage = {}
priv_usage = {}
basic_cmds = ["refresh", "install", "uninstall", "update",
"apply-hot-fix", "list", "version"]
basic_usage["install"] = _(
"[-nvq] [-C n] [-g path_or_uri ...] [--accept]\n"
" [--licenses] [--no-be-activate] [--no-index] [--no-refresh]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" [--sync-actuators | --sync-actuators-timeout timeout]\n"
" [--reject pkg_fmri_pattern ... ] pkg_fmri_pattern ...")
basic_usage["uninstall"] = _(
"[-nvq] [-C n] [--ignore-missing] [--no-be-activate] [--no-index]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" [--sync-actuators | --sync-actuators-timeout timeout]\n"
" pkg_fmri_pattern ...")
basic_usage["update"] = _(
"[-fnvq] [-C n] [-g path_or_uri ...] [--accept] [--ignore-missing]\n"
" [--licenses] [--no-be-activate] [--no-index] [--no-refresh]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" [--sync-actuators | --sync-actuators-timeout timeout]\n"
" [--reject pkg_fmri_pattern ...] [pkg_fmri_pattern ...]")
basic_usage["apply-hot-fix"] = _(
"[-nvq] [--no-be-activate]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" <path_or_uri> [pkg_fmri_pattern ...]")
basic_usage["list"] = _(
"[-Hafnqsuv] [-g path_or_uri ...] [--no-refresh]\n"
" [pkg_fmri_pattern ...]")
basic_usage["refresh"] = _("[-q] [--full] [publisher ...]")
basic_usage["version"] = ""
advanced_cmds = [
"info",
"contents",
"search",
"",
"verify",
"fix",
"revert",
"",
"mediator",
"set-mediator",
"unset-mediator",
"",
"variant",
"change-variant",
"",
"facet",
"change-facet",
"",
"avoid",
"unavoid",
"",
"freeze",
"unfreeze",
"",
"property",
"set-property",
"add-property-value",
"remove-property-value",
"unset-property",
"",
"publisher",
"set-publisher",
"unset-publisher",
"",
"history",
"purge-history",
"",
"rebuild-index",
"update-format",
"image-create",
"exact-install",
"",
"dehydrate",
"rehydrate"
]
adv_usage["info"] = \
_("[-lqr] [-g path_or_uri ...] [--license] [pkg_fmri_pattern ...]")
adv_usage["contents"] = _(
"[-Hmr] [-a attribute=pattern ...] [-g path_or_uri ...]\n"
" [-o attribute ...] [-s sort_key] [-t action_type ...]\n"
" [pkg_fmri_pattern ...]")
adv_usage["search"] = _(
"[-HIaflpr] [-o attribute ...] [-s repo_uri] query")
adv_usage["verify"] = _("[-Hqv] [-p path]... [--parsable version]\n"
" [--unpackaged] [--unpackaged-only] [pkg_fmri_pattern ...]")
adv_usage["fix"] = _(
"[-Hnvq] [--no-be-activate]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [--accept] [--licenses] [--parsable version] [--unpackaged]\n"
" [pkg_fmri_pattern ...]")
adv_usage["revert"] = _(
"[-nv] [--no-be-activate]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" (--tagged tag-name ... | path-to-file ...)")
adv_usage["image-create"] = _(
"[-FPUfz] [--force] [--full|--partial|--user] [--zone]\n"
" [-k ssl_key] [-c ssl_cert] [--no-refresh]\n"
" [--variant <variant_spec>=<instance> ...]\n"
" [-g uri|--origin=uri ...] [-m uri|--mirror=uri ...]\n"
" [--facet <facet_spec>=(True|False) ...]\n"
" [(-p|--publisher) [<name>=]<repo_uri>] dir")
adv_usage["change-variant"] = _(
"[-nvq] [-C n] [-g path_or_uri ...] [--accept]\n"
" [--licenses] [--no-be-activate] [--no-index] [--no-refresh]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" [--sync-actuators | --sync-actuators-timeout timeout]\n"
" [--reject pkg_fmri_pattern ... ]\n"
" <variant_spec>=<instance> ...")
adv_usage["change-facet"] = _(
"[-nvq] [-C n] [-g path_or_uri ...] [--accept]\n"
" [--licenses] [--no-be-activate] [--no-index] [--no-refresh]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" [--sync-actuators | --sync-actuators-timeout timeout]\n"
" [--reject pkg_fmri_pattern ... ]\n"
" <facet_spec>=[True|False|None] ...")
adv_usage["mediator"] = _("[-aH] [-F format] [<mediator> ...]")
adv_usage["set-mediator"] = _(
"[-nv] [-I <implementation>]\n"
" [-V <version>] [--no-be-activate]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" <mediator> ...")
adv_usage["unset-mediator"] = _("[-nvIV] [--no-be-activate]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" <mediator> ...")
adv_usage["variant"] = _("[-Haiv] [-F format] [<variant_pattern> ...]")
adv_usage["facet"] = ("[-Haim] [-F format] [<facet_pattern> ...]")
adv_usage["avoid"] = _("[pkg_fmri_pattern] ...")
adv_usage["unavoid"] = _("[pkg_fmri_pattern] ...")
adv_usage["freeze"] = _("[-n] [-c reason] [pkg_fmri_pattern] ...")
adv_usage["unfreeze"] = _("[-n] [pkg_name_pattern] ...")
adv_usage["set-property"] = _("propname propvalue")
adv_usage["add-property-value"] = _("propname propvalue")
adv_usage["remove-property-value"] = _("propname propvalue")
adv_usage["unset-property"] = _("propname ...")
adv_usage["property"] = _("[-H] [propname ...]")
adv_usage["set-publisher"] = _("[-Pedv] [-k ssl_key] [-c ssl_cert]\n"
" [-O origin_to_set|--origin_uri=origin_to_set ...]\n"
" [-g origin_to_add|--add-origin=origin_to_add ...]\n"
" [-G origin_to_remove|--remove-origin=origin_to_remove ...]\n"
" [-m mirror_to_add|--add-mirror=mirror_to_add ...]\n"
" [-M mirror_to_remove|--remove-mirror=mirror_to_remove ...]\n"
" [-p repo_uri] [--enable] [--disable] [--no-refresh]\n"
" [-R | -r [-z zonename... | -Z zonename...]]\n"
" [--reset-uuid] [--non-sticky] [--sticky]\n"
" [--search-after=publisher]\n"
" [--search-before=publisher]\n"
" [--search-first]\n"
" [--approve-ca-cert=path_to_CA]\n"
" [--revoke-ca-cert=hash_of_CA_to_revoke]\n"
" [--unset-ca-cert=hash_of_CA_to_unset]\n"
" [--set-property name_of_property=value]\n"
" [--add-property-value name_of_property=value_to_add]\n"
" [--remove-property-value name_of_property=value_to_remove]\n"
" [--unset-property name_of_property_to_delete]\n"
" [--proxy proxy to use]\n"
" [publisher]")
adv_usage["unset-publisher"] = _("publisher ...")
adv_usage["publisher"] = _("[-HPn] [-F format] [publisher ...]")
adv_usage["history"] = _("[-HNl] [-t [time|time-time],...] [-n number] [-o column,...]")
adv_usage["purge-history"] = ""
adv_usage["rebuild-index"] = ""
adv_usage["update-format"] = ""
adv_usage["exact-install"] = _("[-nvq] [-C n] [-g path_or_uri ...] [--accept]\n"
" [--licenses] [--no-be-activate] [--no-index] [--no-refresh]\n"
" [--no-backup-be | --require-backup-be] [--backup-be-name name]\n"
" [--deny-new-be | --require-new-be] [--be-name name]\n"
" [--reject pkg_fmri_pattern ... ] pkg_fmri_pattern ...")
adv_usage["dehydrate"] = _("[-nvq] [-p publisher ...]")
adv_usage["rehydrate"] = _("[-nvq] [-p publisher ...]")
priv_usage["remote"] = _(
"--ctlfd=file_descriptor --progfd=file_descriptor")
priv_usage["list-linked"] = _("-H")
priv_usage["attach-linked"] = _(
"[-fnvq] [-C n] [--accept] [--licenses] [--no-index]\n"
" [--no-refresh] [--no-pkg-updates] [--linked-md-only]\n"
" [--allow-relink]\n"
" [--prop-linked <propname>=<propvalue> ...]\n"
" (-c|-p) <li-name> <dir>")
priv_usage["detach-linked"] = _(
"[-fnvq] [-a|-l <li-name>] [--no-pkg-updates] [--linked-md-only]")
priv_usage["property-linked"] = _("[-H] [-l <li-name>] [propname ...]")
priv_usage["audit-linked"] = _(
"[-H] [-a|-l <li-name>] [--no-parent-sync]")
priv_usage["pubcheck-linked"] = ""
priv_usage["sync-linked"] = _(
"[-nvq] [-C n] [--accept] [--licenses] [--no-index]\n"
" [--no-refresh] [--no-parent-sync] [--no-pkg-updates]\n"
" [--linked-md-only] [-a|-l <name>]")
priv_usage["set-property-linked"] = _(
"[-nvq] [--accept] [--licenses] [--no-index] [--no-refresh]\n"
" [--no-parent-sync] [--no-pkg-updates]\n"
" [--linked-md-only] <propname>=<propvalue> ...")
priv_usage["copy-publishers-from"] = _("<dir>")
def print_cmds(cmd_list, cmd_dic):
for cmd in cmd_list:
if cmd is "":
logger.error("")
else:
if cmd not in cmd_dic:
# this should never happen - callers
# should check for valid subcommands
# before calling usage(..)
raise ValueError(
"Unable to find usage str for "
"{0}".format(cmd))
use_txt = cmd_dic[cmd]
if use_txt is not "":
logger.error(
" pkg {cmd} "
"{use_txt}".format(**locals()))
else:
logger.error(" pkg "
"{0}".format(cmd))
if not full and cmd:
if cmd not in priv_usage:
logger.error(_("Usage:"))
else:
logger.error(_("Private subcommand usage, options "
"subject to change at any time:"))
combined = {}
combined.update(basic_usage)
combined.update(adv_usage)
combined.update(priv_usage)
print_cmds([cmd], combined)
sys.exit(retcode)
elif not full:
# The full list of subcommands isn't desired.
known_words = ["help"]
known_words.extend(basic_cmds)
known_words.extend(w for w in advanced_cmds if w)
candidates = misc.suggest_known_words(unknown_cmd, known_words)
if candidates:
# Suggest correct subcommands if we can.
words = ", ". join(candidates)
logger.error(_("Did you mean:\n {0}\n").format(words))
logger.error(_("For a full list of subcommands, run: pkg help"))
sys.exit(retcode)
if verbose:
# Display a verbose usage message of subcommands.
logger.error(_("""\
Usage:
pkg [options] command [cmd_options] [operands]
"""))
logger.error(_("Basic subcommands:"))
print_cmds(basic_cmds, basic_usage)
logger.error(_("\nAdvanced subcommands:"))
print_cmds(advanced_cmds, adv_usage)
logger.error(_("""
Options:
-R dir
--no-network-cache
--help or -?
Environment:
PKG_IMAGE"""))
else:
# Display the full list of subcommands.
logger.error(_("""\
Usage: pkg [options] command [cmd_options] [operands]"""))
logger.error(_("The following commands are supported:"))
logger.error(_("""
Package Information : list search info contents
Package Transitions : update install uninstall
history exact-install apply-hot-fix
Package Maintenance : verify fix revert
Publishers : publisher set-publisher unset-publisher
Package Configuration: mediator set-mediator unset-mediator
facet change-facet
variant change-variant
Image Constraints : avoid unavoid freeze unfreeze
Image Configuration : refresh rebuild-index purge-history
property set-property add-property-value
unset-property remove-property-value
Miscellaneous : image-create dehydrate rehydrate
For more info, run: pkg help <command>"""))
sys.exit(retcode)
def get_fmri_args(api_inst, pargs, cmd=None):
""" Convenience routine to check that input args are valid fmris. """
res = []
errors = []
for pat, err, pfmri, matcher in api_inst.parse_fmri_patterns(pargs):
if not err:
res.append((pat, err, pfmri, matcher))
continue
if isinstance(err, version.VersionError):
# For version errors, include the pattern so
# that the user understands why it failed.
errors.append("Illegal FMRI '{0}': {1}".format(pat,
err))
else:
# Including the pattern is redundant for other
# exceptions.
errors.append(err)
if errors:
error("\n".join(str(e) for e in errors), cmd=cmd)
return len(errors) == 0, res
def list_inventory(op, api_inst, pargs,
li_parent_sync, list_all, list_installed_newest, list_newest,
list_upgradable, omit_headers, origins, quiet, refresh_catalogs, summary,
verbose):
"""List packages."""
if verbose:
fmt_str = "{0:76} {1}"
elif summary:
fmt_str = "{0:55} {1}"
else:
fmt_str = "{0:49} {1:26} {2}"
state_map = [
[("installed", "i")],
[("frozen", "f")],
[
("obsolete", "o"),
("renamed", "r")
],
]
ppub = api_inst.get_highest_ranked_publisher()
if ppub:
ppub = ppub.prefix
# getting json output.
out_json = client_api._list_inventory(op, api_inst, pargs,
li_parent_sync, list_all, list_installed_newest, list_newest,
list_upgradable, origins, quiet, refresh_catalogs)
errors = None
if "errors" in out_json:
errors = out_json["errors"]
errors = _generate_error_messages(out_json["status"], errors,
selected_type=["catalog_refresh", "catalog_refresh_failed"])
if "data" in out_json:
data = out_json["data"]
for entry in data:
if quiet:
continue
if not omit_headers:
if verbose:
msg(fmt_str.format(
"FMRI", "IFO"))
elif summary:
msg(fmt_str.format(
"NAME (PUBLISHER)",
"SUMMARY"))
else:
msg(fmt_str.format(
"NAME (PUBLISHER)",
"VERSION", "IFO"))
omit_headers = True
status = ""
for sentry in state_map:
for s, v in sentry:
if s in entry["states"]:
st = v
break
else:
st = "-"
status += st
pub, stem, ver = entry["pub"], entry["pkg"], \
entry["version"]
if pub == ppub:
spub = ""
else:
spub = " (" + pub + ")"
# Display full FMRI (without build version) for
# verbose case.
# Use class method instead of creating an object for
# performance reasons.
if verbose:
(release, build_release, branch, ts), \
short_ver = version.Version.split(ver)
pfmri = "pkg://{0}/{1}@{2}:{3}".format(
pub, stem, short_ver, ts)
msg(fmt_str.format(pfmri, status))
continue
# Display short FMRI + summary.
summ = entry["summary"]
pf = stem + spub
if summary:
if summ is None:
summ = ""
msg(fmt_str.format(pf, summ))
continue
# Default case; display short FMRI and version info.
sver = version.Version.split(ver)[-1]
msg(fmt_str.format(pf, sver, status))
# Print errors left.
if errors:
_generate_error_messages(out_json["status"], errors)
return out_json["status"]
def get_tracker():
if global_settings.client_output_parsable_version is not None:
progresstracker = progress.NullProgressTracker()
elif global_settings.client_output_quiet:
progresstracker = progress.QuietProgressTracker()
elif global_settings.client_output_progfd:
# This logic handles linked images: for linked children
# we elide the progress output.
output_file = os.fdopen(global_settings.client_output_progfd,
"w")
child_tracker = progress.LinkedChildProgressTracker(
output_file=output_file)
dot_tracker = progress.DotProgressTracker(
output_file=output_file)
progresstracker = progress.MultiProgressTracker(
[child_tracker, dot_tracker])
else:
try:
progresstracker = progress.FancyUNIXProgressTracker()
except progress.ProgressTrackerException:
progresstracker = progress.CommandLineProgressTracker()
return progresstracker
def accept_plan_licenses(api_inst):
"""Helper function that marks all licenses for the current plan as
accepted if they require acceptance."""
plan = api_inst.describe()
for pfmri, src, dest, accepted, displayed in plan.get_licenses():
if not dest.must_accept:
continue
api_inst.set_plan_license_status(pfmri, dest.license,
accepted=True)
display_plan_options = ["basic", "fmris", "variants/facets", "services",
"actions", "boot-archive"]
def __display_plan(api_inst, verbose, noexecute, op=None):
"""Helper function to display plan to the desired degree.
Verbose can either be a numerical value, or a list of
items to display"""
if isinstance(verbose, int):
disp = ["basic"]
if verbose == 0 and noexecute:
disp.append("release-notes")
if verbose > 0:
disp.extend(["fmris", "mediators", "services",
"variants/facets", "boot-archive",
"release-notes", "editable", "actuators"])
if verbose > 1:
disp.append("actions")
if verbose > 2:
disp.append("solver-errors")
else:
disp = verbose
if DebugValues["plan"] and "solver-errors" not in disp:
disp.append("solver-errors")
plan = api_inst.describe()
if plan.must_display_notes():
disp.append("release-notes")
if api_inst.is_liveroot and not api_inst.is_active_liveroot_be:
# Warn the user since this isn't likely what they wanted.
if plan.new_be:
logger.warning(_("""\
WARNING: The boot environment being modified is not the active one. Changes
made in the active BE will not be reflected on the next boot.
"""))
else:
logger.warning(_("""\
WARNING: The boot environment being modified is not the active one. Changes
made will not be reflected on the next boot.
"""))
a, r, i, c = [], [], [], []
for src, dest in plan.get_changes():
if dest is None:
r.append((src, dest))
elif src is None:
i.append((src, dest))
elif src != dest:
c.append((src, dest))
else:
# Changing or repairing package content (e.g. fix,
# change-facet, etc.)
a.append((dest, dest))
def bool_str(val):
if val:
return _("Yes")
return _("No")
status = []
varcets = plan.get_varcets()
mediators = plan.get_mediators()
if "basic" in disp:
def cond_show(s1, s2, v):
if v:
status.append((s1, s2.format(v)))
cond_show(_("Packages to remove:"), "{0:d}", len(r))
cond_show(_("Packages to install:"), "{0:d}", len(i))
cond_show(_("Packages to update:"), "{0:d}", len(c))
if varcets or mediators:
cond_show(_("Packages to change:"), "{0:d}", len(a))
else:
cond_show(_("Packages to fix:"), "{0:d}", len(a))
cond_show(_("Mediators to change:"), "{0:d}", len(mediators))
cond_show(_("Variants/Facets to change:"), "{0:d}",
len(varcets))
if not plan.new_be:
cond_show(_("Services to change:"), "{0:d}",
len(plan.services))
if verbose:
# Only show space information in verbose mode.
abytes = plan.bytes_added
if abytes:
status.append((_("Estimated space available:"),
misc.bytes_to_str(plan.bytes_avail)))
status.append((
_("Estimated space to be consumed:"),
misc.bytes_to_str(plan.bytes_added)))
# only display BE information if we're operating on the
# liveroot environment (since otherwise we'll never be
# manipulating BEs).
if api_inst.is_liveroot:
status.append((_("Create boot environment:"),
bool_str(plan.new_be)))
if plan.new_be and (verbose or not plan.activate_be):
# Only show activation status if verbose or
# if new BE will not be activated.
status.append((_("Activate boot environment:"),
bool_str(plan.activate_be)))
status.append((_("Create backup boot environment:"),
bool_str(plan.backup_be)))
if "boot-archive" in disp:
status.append((_("Rebuild boot archive:"),
bool_str(plan.update_boot_archive)))
# Right-justify all status strings based on length of longest string.
if status:
rjust_status = max(len(s[0]) for s in status)
rjust_value = max(len(s[1]) for s in status)
for s in status:
logger.info("{0} {1}".format(s[0].rjust(rjust_status),
s[1].rjust(rjust_value)))
need_blank = True
if "mediators" in disp and mediators:
if need_blank:
logger.info("")
logger.info(_("Changed mediators:"))
for x in mediators:
logger.info(" {0}".format(x))
# output has trailing blank
need_blank = False
if "variants/facets" in disp and varcets:
if need_blank:
logger.info("")
need_blank = True
logger.info(_("Changed variants/facets:"))
for x in varcets:
logger.info(" {0}".format(x))
if "solver-errors" in disp:
first = True
for l in plan.get_solver_errors():
if first:
if need_blank:
logger.info("")
need_blank = True
logger.info(_("Solver dependency errors:"))
first = False
logger.info(l)
if "fmris" in disp:
changed = collections.defaultdict(list)
for src, dest in itertools.chain(r, i, c, a):
if src and dest:
if src.publisher != dest.publisher:
pparent = "{0} -> {1}".format(
src.publisher, dest.publisher)
else:
pparent = dest.publisher
pname = dest.pkg_stem
# Only display timestamp if version is same and
# timestamp is not between the two fmris.
sver = src.fmri.version
dver = dest.fmri.version
ssver = sver.get_short_version()
dsver = dver.get_short_version()
include_ts = (ssver == dsver and
sver.timestr != dver.timestr)
if include_ts:
pver = sver.get_version(
include_build=False)
else:
pver = ssver
if src != dest:
if include_ts:
pver += " -> {0}".format(
dver.get_version(
include_build=False))
else:
pver += " -> {0}".format(dsver)
elif dest:
pparent = dest.publisher
pname = dest.pkg_stem
pver = "None -> {0}".format(
dest.fmri.version.get_short_version())
else:
pparent = src.publisher
pname = src.pkg_stem
pver = "{0} -> None".format(
src.fmri.version.get_short_version())
changed[pparent].append((pname, pver))
if changed:
if need_blank:
logger.info("")
need_blank = True
logger.info(_("Changed packages:"))
last_parent = None
for pparent, pname, pver in (
(pparent, pname, pver)
for pparent in sorted(changed)
for pname, pver in changed[pparent]
):
if pparent != last_parent:
logger.info(pparent)
logger.info(" {0}".format(pname))
logger.info(" {0}".format(pver))
last_parent = pparent
if "actuators" in disp:
# print pkg which have been altered due to pkg actuators
# e.g:
#
# Package-triggered Operations:
# TriggerPackage
# update
# PackageA
# PackageB
# uninstall
# PackageC
first = True
for trigger_pkg, act_dict in plan.gen_pkg_actuators():
if first:
first = False
if need_blank:
logger.info("")
need_blank = True
logger.info(
_("Package-triggered Operations:"))
logger.info(trigger_pkg)
for exec_op in sorted(act_dict):
logger.info(" {0}".format(exec_op))
for pkg in sorted(act_dict[exec_op]):
logger.info(
" {0}".format(pkg))
if "services" in disp and not plan.new_be:
last_action = None
for action, smf_fmri in plan.services:
if last_action is None:
if need_blank:
logger.info("")
need_blank = True
logger.info(_("Services:"))
if action != last_action:
logger.info(" {0}:".format(action))
logger.info(" {0}".format(smf_fmri))
last_action = action
# Displaying editable file list is redundant for pkg fix.
if "editable" in disp and op != PKG_OP_FIX:
moved, removed, installed, updated = plan.get_editable_changes()
cfg_change_fmt = " {0}"
cfg_changes = []
first = True
def add_cfg_changes(changes, chg_hdr, chg_fmt=cfg_change_fmt):
first = True
for chg in changes:
if first:
cfg_changes.append(" {0}".format(
chg_hdr))
first = False
cfg_changes.append(chg_fmt.format(*chg))
add_cfg_changes((entry for entry in moved),
_("Move:"), chg_fmt=" {0} -> {1}")
add_cfg_changes(((src,) for (src, dest) in removed),
_("Remove:"))
add_cfg_changes(((dest,) for (src, dest) in installed),
_("Install:"))
add_cfg_changes(((dest,) for (src, dest) in updated),
_("Update:"))
if cfg_changes:
if need_blank:
logger.info("")
need_blank = True
logger.info(_("Editable files to change:"))
for l in cfg_changes:
logger.info(l)
if "actions" in disp:
if need_blank:
logger.info("")
need_blank = True
logger.info(_("Actions:"))
for a in plan.get_actions():
logger.info(" {0}".format(a))
if plan.has_release_notes():
if need_blank:
logger.info("")
need_blank = True
if "release-notes" in disp:
logger.info(_("Release Notes:"))
for a in plan.get_release_notes():
logger.info(" %s", a)
else:
if not plan.new_be and api_inst.is_liveroot and not DebugValues["GenerateNotesFile"]:
logger.info(_("Release notes can be viewed with 'pkg history -n 1 -N'"))
else:
tmp_path = __write_tmp_release_notes(plan)
if tmp_path:
logger.info(_("Release notes can be found in {0} before "
"rebooting.").format(tmp_path))
logger.info(_("After rebooting, use 'pkg history -n 1 -N' to view release notes."))
def __write_tmp_release_notes(plan):
"""try to write release notes out to a file in /tmp and return the name"""