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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
|
# Copyright 2012-2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Image V2 Action Implementations"""
import argparse
from base64 import b64encode
import logging
import os
import sys
from cinderclient import api_versions
from openstack import exceptions as sdk_exceptions
from openstack.image import image_signer
from osc_lib.api import utils as api_utils
from osc_lib.cli import format_columns
from osc_lib.cli import parseractions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from openstackclient.common import pagination
from openstackclient.common import progressbar
from openstackclient.i18n import _
from openstackclient.identity import common as identity_common
if os.name == "nt":
import msvcrt
else:
msvcrt = None
CONTAINER_CHOICES = ["ami", "ari", "aki", "bare", "docker", "ova", "ovf"]
DEFAULT_CONTAINER_FORMAT = 'bare'
DEFAULT_DISK_FORMAT = 'raw'
DISK_CHOICES = [
"ami",
"ari",
"aki",
"vhd",
"vmdk",
"raw",
"qcow2",
"vhdx",
"vdi",
"iso",
"ploop",
]
MEMBER_STATUS_CHOICES = ["accepted", "pending", "rejected", "all"]
LOG = logging.getLogger(__name__)
def _format_image(image, human_readable=False):
"""Format an image to make it more consistent with OSC operations."""
info = {}
properties = {}
# the only fields we're not including is "links", "tags" and the properties
fields_to_show = [
'status',
'name',
'container_format',
'created_at',
'size',
'disk_format',
'updated_at',
'visibility',
'min_disk',
'protected',
'id',
'file',
'checksum',
'owner',
'virtual_size',
'min_ram',
'schema',
]
# TODO(gtema/anybody): actually it should be possible to drop this method,
# since SDK already delivers a proper object
image = image.to_dict(ignore_none=True, original_names=True)
# split out the usual key and the properties which are top-level
for key in image:
if key in fields_to_show:
info[key] = image.get(key)
elif key == 'tags':
continue # handle this later
elif key == 'properties':
# NOTE(gtema): flatten content of properties
properties.update(image.get(key))
elif key != 'location':
properties[key] = image.get(key)
if human_readable:
info['size'] = utils.format_size(image['size'])
# format the tags if they are there
info['tags'] = format_columns.ListColumn(image.get('tags'))
# add properties back into the dictionary as a top-level key
if properties:
info['properties'] = format_columns.DictColumn(properties)
return info
_formatters = {
'tags': format_columns.ListColumn,
}
def _get_member_columns(item):
column_map = {'image_id': 'image_id'}
hidden_columns = ['id', 'location', 'name']
return utils.get_osc_show_columns_for_sdk_resource(
item.to_dict(),
column_map,
hidden_columns,
)
def get_data_from_stdin():
# distinguish cases where:
# (1) stdin is not valid (as in cron jobs):
# openstack ... <&-
# (2) image data is provided through stdin:
# openstack ... < /tmp/file
# (3) no image data provided
# openstack ...
try:
os.fstat(0)
except OSError:
# (1) stdin is not valid
return None
if not sys.stdin.isatty():
# (2) image data is provided through stdin
image = sys.stdin
if hasattr(sys.stdin, 'buffer'):
image = sys.stdin.buffer
if msvcrt:
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
return image
else:
# (3)
return None
def _add_is_protected_args(parser):
protected_group = parser.add_mutually_exclusive_group()
protected_group.add_argument(
"--protected",
action="store_true",
dest="is_protected",
default=None,
help=_("Prevent image from being deleted"),
)
protected_group.add_argument(
"--unprotected",
action="store_false",
dest="is_protected",
default=None,
help=_("Allow image to be deleted (default)"),
)
def _add_visibility_args(parser):
public_group = parser.add_mutually_exclusive_group()
public_group.add_argument(
"--public",
action="store_const",
const="public",
dest="visibility",
help=_("Image is accessible and visible to all users"),
)
public_group.add_argument(
"--private",
action="store_const",
const="private",
dest="visibility",
help=_(
"Image is only accessible by the owner "
"(default until --os-image-api-version 2.5)"
),
)
public_group.add_argument(
"--community",
action="store_const",
const="community",
dest="visibility",
help=_(
"Image is accessible by all users but does not appear in the "
"default image list of any user except the owner "
"(requires --os-image-api-version 2.5 or later)"
),
)
public_group.add_argument(
"--shared",
action="store_const",
const="shared",
dest="visibility",
help=_(
"Image is only accessible by the owner and image members "
"(requires --os-image-api-version 2.5 or later) "
"(default since --os-image-api-version 2.5)"
),
)
class AddProjectToImage(command.ShowOne):
_description = _("Associate project with image")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image to share (name or ID)"),
)
parser.add_argument(
"project",
metavar="<project>",
help=_("Project to associate with image (ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
identity_client = self.app.client_manager.identity
project_id = identity_common.find_project(
identity_client,
parsed_args.project,
parsed_args.project_domain,
).id
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
obj = image_client.add_member(
image=image.id,
member_id=project_id,
)
display_columns, columns = _get_member_columns(obj)
data = utils.get_item_properties(obj, columns, formatters={})
return (display_columns, data)
class CreateImage(command.ShowOne):
_description = _("Create/upload an image")
deadopts = ('size', 'location', 'copy-from', 'checksum', 'store')
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
# TODO(bunting): There are additional arguments that v1 supported
# that v2 either doesn't support or supports weirdly.
# --checksum - could be faked clientside perhaps?
# --location - maybe location add?
# --size - passing image size is actually broken in python-glanceclient
# --copy-from - does not exist in v2
# --store - does not exits in v2
parser.add_argument(
"name",
metavar="<image-name>",
help=_("New image name"),
)
parser.add_argument(
"--id",
metavar="<id>",
help=_("Image ID to reserve"),
)
parser.add_argument(
"--container-format",
default=DEFAULT_CONTAINER_FORMAT,
choices=CONTAINER_CHOICES,
metavar="<container-format>",
help=(
_(
"Image container format. "
"The supported options are: %(option_list)s. "
"The default format is: %(default_opt)s"
)
% {
'option_list': ', '.join(CONTAINER_CHOICES),
'default_opt': DEFAULT_CONTAINER_FORMAT,
}
),
)
parser.add_argument(
"--disk-format",
default=DEFAULT_DISK_FORMAT,
choices=DISK_CHOICES,
metavar="<disk-format>",
help=_(
"Image disk format. The supported options are: %s. "
"The default format is: raw"
)
% ', '.join(DISK_CHOICES),
)
parser.add_argument(
"--min-disk",
metavar="<disk-gb>",
type=int,
help=_("Minimum disk size needed to boot image, in gigabytes"),
)
parser.add_argument(
"--min-ram",
metavar="<ram-mb>",
type=int,
help=_("Minimum RAM size needed to boot image, in megabytes"),
)
source_group = parser.add_mutually_exclusive_group()
source_group.add_argument(
"--file",
dest="filename",
metavar="<file>",
help=_("Upload image from local file"),
)
source_group.add_argument(
"--volume",
metavar="<volume>",
help=_("Create image from a volume"),
)
parser.add_argument(
"--force",
dest='force',
action='store_true',
default=False,
help=_(
"Force image creation if volume is in use "
"(only meaningful with --volume)"
),
)
parser.add_argument(
"--progress",
action="store_true",
default=False,
help=_(
"Show upload progress bar "
"(ignored if passing data via stdin)"
),
)
parser.add_argument(
'--sign-key-path',
metavar="<sign-key-path>",
default=[],
help=_(
"Sign the image using the specified private key. "
"Only use in combination with --sign-cert-id"
),
)
parser.add_argument(
'--sign-cert-id',
metavar="<sign-cert-id>",
default=[],
help=_(
"The specified certificate UUID is a reference to "
"the certificate in the key manager that corresponds "
"to the public key and is used for signature validation. "
"Only use in combination with --sign-key-path"
),
)
_add_is_protected_args(parser)
_add_visibility_args(parser)
parser.add_argument(
"--property",
dest="properties",
metavar="<key=value>",
action=parseractions.KeyValueAction,
help=_(
"Set a property on this image "
"(repeat option to set multiple properties)"
),
)
parser.add_argument(
"--tag",
dest="tags",
metavar="<tag>",
action='append',
help=_(
"Set a tag on this image "
"(repeat option to set multiple tags)"
),
)
parser.add_argument(
"--project",
metavar="<project>",
help=_("Set an alternate project on this image (name or ID)"),
)
parser.add_argument(
"--import",
dest="use_import",
action="store_true",
help=_(
"Force the use of glance image import instead of direct upload"
),
)
identity_common.add_project_domain_option_to_parser(parser)
for deadopt in self.deadopts:
parser.add_argument(
f"--{deadopt}",
metavar=f"<{deadopt}>",
dest=deadopt.replace('-', '_'),
help=argparse.SUPPRESS,
)
return parser
def _take_action_image(self, parsed_args):
identity_client = self.app.client_manager.identity
image_client = self.app.client_manager.image
# Build an attribute dict from the parsed args, only include
# attributes that were actually set on the command line
kwargs = {'allow_duplicates': True}
copy_attrs = (
'name',
'id',
'container_format',
'disk_format',
'min_disk',
'min_ram',
'tags',
'visibility',
)
for attr in copy_attrs:
if attr in parsed_args:
val = getattr(parsed_args, attr, None)
if val:
# Only include a value in kwargs for attributes that
# are actually present on the command line
kwargs[attr] = val
# properties should get flattened into the general kwargs
if getattr(parsed_args, 'properties', None):
for k, v in parsed_args.properties.items():
kwargs[k] = str(v)
# Handle exclusive booleans with care
# Avoid including attributes in kwargs if an option is not
# present on the command line. These exclusive booleans are not
# a single value for the pair of options because the default must be
# to do nothing when no options are present as opposed to always
# setting a default.
if parsed_args.is_protected is not None:
kwargs['is_protected'] = parsed_args.is_protected
if parsed_args.visibility is not None:
kwargs['visibility'] = parsed_args.visibility
if parsed_args.project:
kwargs['owner_id'] = identity_common.find_project(
identity_client,
parsed_args.project,
parsed_args.project_domain,
).id
if parsed_args.use_import:
kwargs['use_import'] = True
# open the file first to ensure any failures are handled before the
# image is created. Get the file name (if it is file, and not stdin)
# for easier further handling.
if parsed_args.filename:
try:
fp = open(parsed_args.filename, 'rb')
except FileNotFoundError:
raise exceptions.CommandError(
f'{parsed_args.filename!r} is not a valid file',
)
else:
fp = get_data_from_stdin()
if fp is not None and parsed_args.volume:
msg = _(
"Uploading data and using container are not allowed at "
"the same time"
)
raise exceptions.CommandError(msg)
if parsed_args.progress and parsed_args.filename:
# NOTE(stephenfin): we only show a progress bar if the user
# requested it *and* we're reading from a file (not stdin)
filesize = os.path.getsize(parsed_args.filename)
if filesize is not None:
kwargs['validate_checksum'] = False
kwargs['data'] = progressbar.VerboseFileWrapper(fp, filesize)
else:
kwargs['data'] = fp
elif parsed_args.filename:
kwargs['filename'] = parsed_args.filename
elif fp:
kwargs['validate_checksum'] = False
kwargs['data'] = fp
# sign an image using a given local private key file
if parsed_args.sign_key_path or parsed_args.sign_cert_id:
if not parsed_args.filename:
msg = _(
"signing an image requires the --file option, "
"passing files via stdin when signing is not "
"supported."
)
raise exceptions.CommandError(msg)
if (
len(parsed_args.sign_key_path) < 1
or len(parsed_args.sign_cert_id) < 1
):
msg = _(
"'sign-key-path' and 'sign-cert-id' must both be "
"specified when attempting to sign an image."
)
raise exceptions.CommandError(msg)
sign_key_path = parsed_args.sign_key_path
sign_cert_id = parsed_args.sign_cert_id
signer = image_signer.ImageSigner()
try:
pw = utils.get_password(
self.app.stdin,
prompt=(
"Please enter private key password, leave "
"empty if none: "
),
confirm=False,
)
if not pw or len(pw) < 1:
pw = None
else:
# load_private_key() requires the password to be
# passed as bytes
pw = pw.encode()
signer.load_private_key(sign_key_path, password=pw)
except Exception:
msg = _(
"Error during sign operation: private key "
"could not be loaded."
)
raise exceptions.CommandError(msg)
signature = signer.generate_signature(fp)
signature_b64 = b64encode(signature)
kwargs['img_signature'] = signature_b64
kwargs['img_signature_certificate_uuid'] = sign_cert_id
kwargs['img_signature_hash_method'] = signer.hash_method
if signer.padding_method:
kwargs['img_signature_key_type'] = signer.padding_method
image = image_client.create_image(**kwargs)
if parsed_args.filename:
fp.close()
# NOTE(pas-ha): create_image returns the image object as it was created
# before the data was uploaded, need a refresh to show the final state
image = image_client.get_image(image)
return _format_image(image)
def _take_action_volume(self, parsed_args):
volume_client = self.app.client_manager.volume
unsupported_opts = {
# 'name', # 'name' is a positional argument and will always exist
'id',
'min_disk',
'min_ram',
'file',
'force',
'progress',
'sign_key_path',
'sign_cert_id',
'properties',
'tags',
'project',
'use_import',
}
for unsupported_opt in unsupported_opts:
if getattr(parsed_args, unsupported_opt, None):
opt_name = unsupported_opt.replace('-', '_')
if unsupported_opt == 'use_import':
opt_name = 'import'
msg = _(
"'--%s' was given, which is not supported when "
"creating an image from a volume. "
"This will be an error in a future version."
)
# TODO(stephenfin): These should be an error in a future
# version
LOG.warning(msg % opt_name)
source_volume = utils.find_resource(
volume_client.volumes,
parsed_args.volume,
)
kwargs = {}
if volume_client.api_version < api_versions.APIVersion('3.1'):
if parsed_args.visibility or parsed_args.is_protected is not None:
msg = _(
'--os-volume-api-version 3.1 or greater is required '
'to support the --public, --private, --community, '
'--shared or --protected option.'
)
raise exceptions.CommandError(msg)
else:
kwargs.update(
visibility=parsed_args.visibility or 'private',
protected=parsed_args.is_protected or False,
)
response, body = volume_client.volumes.upload_to_image(
source_volume.id,
parsed_args.force,
parsed_args.name,
parsed_args.container_format,
parsed_args.disk_format,
**kwargs,
)
info = body['os-volume_upload_image']
try:
info['volume_type'] = info['volume_type']['name']
except TypeError:
info['volume_type'] = None
return info
def take_action(self, parsed_args):
for deadopt in self.deadopts:
if getattr(parsed_args, deadopt.replace('-', '_'), None):
msg = _(
"ERROR: --%s was given, which is an Image v1 option "
"that is no longer supported in Image v2"
)
raise exceptions.CommandError(msg % deadopt)
if parsed_args.volume:
info = self._take_action_volume(parsed_args)
else:
info = self._take_action_image(parsed_args)
return zip(*sorted(info.items()))
class DeleteImage(command.Command):
_description = _("Delete image(s)")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"images",
metavar="<image>",
nargs="+",
help=_("Image(s) to delete (name or ID)"),
)
parser.add_argument(
'--store',
metavar='<STORE>',
# default=None,
dest='store',
help=_('Store to delete image(s) from.'),
)
return parser
def take_action(self, parsed_args):
result = 0
image_client = self.app.client_manager.image
for image in parsed_args.images:
try:
image_obj = image_client.find_image(
image,
ignore_missing=False,
)
image_client.delete_image(
image_obj.id,
store=parsed_args.store,
ignore_missing=False,
)
except sdk_exceptions.ResourceNotFound:
msg = _("Multi Backend support not enabled.")
raise exceptions.CommandError(msg)
except Exception as e:
result += 1
msg = _(
"Failed to delete image with name or "
"ID '%(image)s': %(e)s"
)
LOG.error(msg, {'image': image, 'e': e})
total = len(parsed_args.images)
if result > 0:
msg = _("Failed to delete %(result)s of %(total)s images.") % {
'result': result,
'total': total,
}
raise exceptions.CommandError(msg)
class ListImage(command.Lister):
_description = _("List available images")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
public_group = parser.add_mutually_exclusive_group()
public_group.add_argument(
"--public",
action="store_const",
const="public",
dest="visibility",
help=_("List only public images"),
)
public_group.add_argument(
"--private",
action="store_const",
const="private",
dest="visibility",
help=_("List only private images"),
)
public_group.add_argument(
"--community",
action="store_const",
const="community",
dest="visibility",
help=_(
"List only community images "
"(requires --os-image-api-version 2.5 or later)"
),
)
public_group.add_argument(
"--shared",
action="store_const",
const="shared",
dest="visibility",
help=_(
"List only shared images "
"(requires --os-image-api-version 2.5 or later)"
),
)
public_group.add_argument(
"--all",
action="store_const",
const="all",
dest="visibility",
help=_("List all images"),
)
parser.add_argument(
'--property',
metavar='<key=value>',
action=parseractions.KeyValueAction,
help=_(
'Filter output based on property '
'(repeat option to filter on multiple properties)'
),
)
parser.add_argument(
'--name',
metavar='<name>',
default=None,
help=_("Filter images based on name."),
)
parser.add_argument(
'--status',
metavar='<status>',
default=None,
help=_("Filter images based on status."),
)
parser.add_argument(
'--member-status',
metavar='<member-status>',
default=None,
type=lambda s: s.lower(),
choices=MEMBER_STATUS_CHOICES,
help=(
_(
"Filter images based on member status. "
"The supported options are: %s. "
)
% ', '.join(MEMBER_STATUS_CHOICES)
),
)
parser.add_argument(
'--project',
metavar='<project>',
help=_("Search by project (admin only) (name or ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
parser.add_argument(
'--tag',
metavar='<tag>',
action='append',
default=[],
help=_(
'Filter images based on tag. '
'(repeat option to filter on multiple tags)'
),
)
parser.add_argument(
'--hidden',
action='store_true',
dest='is_hidden',
default=False,
help=_('List hidden images'),
)
parser.add_argument(
'--long',
action='store_true',
default=False,
help=_('List additional fields in output'),
)
# --page-size has never worked, leave here for silent compatibility
# We'll implement limit/marker differently later
# TODO(stephenfin): Remove this in the next major version bump
parser.add_argument(
"--page-size",
metavar="<size>",
help=argparse.SUPPRESS,
)
parser.add_argument(
'--sort',
metavar="<key>[:<direction>]",
default='name:asc',
help=_(
"Sort output by selected keys and directions (asc or desc) "
"(default: name:asc), multiple keys and directions can be "
"specified separated by comma"
),
)
pagination.add_marker_pagination_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
image_client = self.app.client_manager.image
kwargs = {}
if parsed_args.visibility is not None:
kwargs['visibility'] = parsed_args.visibility
if parsed_args.limit:
kwargs['limit'] = parsed_args.limit
if parsed_args.marker:
kwargs['marker'] = image_client.find_image(
parsed_args.marker,
ignore_missing=False,
).id
if parsed_args.name:
kwargs['name'] = parsed_args.name
if parsed_args.status:
kwargs['status'] = parsed_args.status
if parsed_args.member_status:
kwargs['member_status'] = parsed_args.member_status
if parsed_args.tag:
kwargs['tag'] = parsed_args.tag
project_id = None
if parsed_args.project:
project_id = identity_common.find_project(
identity_client,
parsed_args.project,
parsed_args.project_domain,
).id
kwargs['owner'] = project_id
if parsed_args.is_hidden:
kwargs['is_hidden'] = parsed_args.is_hidden
if parsed_args.long:
columns = (
'ID',
'Name',
'Disk Format',
'Container Format',
'Size',
'Checksum',
'Status',
'visibility',
'is_protected',
'owner_id',
'tags',
)
column_headers = (
'ID',
'Name',
'Disk Format',
'Container Format',
'Size',
'Checksum',
'Status',
'Visibility',
'Protected',
'Project',
'Tags',
)
else:
columns = ("ID", "Name", "Status")
column_headers = columns
# List of image data received
if 'limit' in kwargs:
# Disable automatic pagination in SDK
kwargs['paginated'] = False
data = list(image_client.images(**kwargs))
if parsed_args.property:
for attr, value in parsed_args.property.items():
api_utils.simple_filter(
data,
attr=attr,
value=value,
property_field='properties',
)
data = utils.sort_items(data, parsed_args.sort, str)
return (
column_headers,
(
utils.get_item_properties(
s,
columns,
formatters=_formatters,
)
for s in data
),
)
class ListImageProjects(command.Lister):
_description = _("List projects associated with image")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image (name or ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
columns = ("Image ID", "Member ID", "Status")
image_id = image_client.find_image(
parsed_args.image,
ignore_missing=False,
).id
data = image_client.members(image=image_id)
return (
columns,
(
utils.get_item_properties(
s,
columns,
)
for s in data
),
)
class RemoveProjectImage(command.Command):
_description = _("Disassociate project with image")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image to unshare (name or ID)"),
)
parser.add_argument(
"project",
metavar="<project>",
help=_("Project to disassociate with image (name or ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
identity_client = self.app.client_manager.identity
project_id = identity_common.find_project(
identity_client,
parsed_args.project,
parsed_args.project_domain,
).id
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
image_client.remove_member(member=project_id, image=image.id)
class ShowProjectImage(command.ShowOne):
_description = _("Show a particular project associated with image")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image (name or ID)"),
)
parser.add_argument(
"member",
metavar="<project>",
help=_("Project to show (name or ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
obj = image_client.get_member(
image=image.id,
member=parsed_args.member,
)
display_columns, columns = _get_member_columns(obj)
data = utils.get_item_properties(obj, columns, formatters={})
return (display_columns, data)
class SaveImage(command.Command):
_description = _("Save an image locally")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"--file",
metavar="<filename>",
dest="filename",
help=_("Downloaded image save filename (default: stdout)"),
)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image to save (name or ID)"),
)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
output_file = parsed_args.filename
if output_file is None:
output_file = getattr(sys.stdout, "buffer", sys.stdout)
image_client.download_image(image.id, stream=True, output=output_file)
class SetImage(command.Command):
_description = _("Set image properties")
deadopts = ('visibility',)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
# TODO(bunting): There are additional arguments that v1 supported
# --size - does not exist in v2
# --store - does not exist in v2
# --location - maybe location add?
# --copy-from - does not exist in v2
# --file - should be able to upload file
# --volume - not possible with v2 as can't change id
# --force - see `--volume`
# --checksum - maybe could be done client side
# --stdin - could be implemented
parser.add_argument(
"image", metavar="<image>", help=_("Image to modify (name or ID)")
)
parser.add_argument(
"--name", metavar="<name>", help=_("New image name")
)
parser.add_argument(
"--min-disk",
type=int,
metavar="<disk-gb>",
help=_("Minimum disk size needed to boot image, in gigabytes"),
)
parser.add_argument(
"--min-ram",
type=int,
metavar="<ram-mb>",
help=_("Minimum RAM size needed to boot image, in megabytes"),
)
parser.add_argument(
"--container-format",
metavar="<container-format>",
choices=CONTAINER_CHOICES,
help=_("Image container format. The supported options are: %s")
% ', '.join(CONTAINER_CHOICES),
)
parser.add_argument(
"--disk-format",
metavar="<disk-format>",
choices=DISK_CHOICES,
help=_("Image disk format. The supported options are: %s")
% ', '.join(DISK_CHOICES),
)
_add_is_protected_args(parser)
_add_visibility_args(parser)
parser.add_argument(
"--property",
dest="properties",
metavar="<key=value>",
action=parseractions.KeyValueAction,
help=_(
"Set a property on this image "
"(repeat option to set multiple properties)"
),
)
parser.add_argument(
"--tag",
dest="tags",
metavar="<tag>",
default=None,
action='append',
help=_(
"Set a tag on this image "
"(repeat option to set multiple tags)"
),
)
parser.add_argument(
"--architecture",
metavar="<architecture>",
help=_("Operating system architecture"),
)
parser.add_argument(
"--instance-id",
metavar="<instance-id>",
help=_("ID of server instance used to create this image"),
)
parser.add_argument(
"--instance-uuid",
metavar="<instance-id>",
dest="instance_id",
help=argparse.SUPPRESS,
)
parser.add_argument(
"--kernel-id",
metavar="<kernel-id>",
help=_("ID of kernel image used to boot this disk image"),
)
parser.add_argument(
"--os-distro",
metavar="<os-distro>",
help=_("Operating system distribution name"),
)
parser.add_argument(
"--os-version",
metavar="<os-version>",
help=_("Operating system distribution version"),
)
parser.add_argument(
"--ramdisk-id",
metavar="<ramdisk-id>",
help=_("ID of ramdisk image used to boot this disk image"),
)
deactivate_group = parser.add_mutually_exclusive_group()
deactivate_group.add_argument(
"--deactivate",
action="store_true",
help=_("Deactivate the image"),
)
deactivate_group.add_argument(
"--activate",
action="store_true",
help=_("Activate the image"),
)
parser.add_argument(
"--project",
metavar="<project>",
help=_("Set an alternate project on this image (name or ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
for deadopt in self.deadopts:
parser.add_argument(
f"--{deadopt}",
metavar=f"<{deadopt}>",
dest=f"dead_{deadopt.replace('-', '_')}",
help=argparse.SUPPRESS,
)
membership_group = parser.add_mutually_exclusive_group()
membership_group.add_argument(
"--accept",
action="store_const",
const="accepted",
dest="membership",
default=None,
help=_(
"Accept the image membership for either the project indicated "
"by '--project', if provided, or the current user's project"
),
)
membership_group.add_argument(
"--reject",
action="store_const",
const="rejected",
dest="membership",
default=None,
help=_(
"Reject the image membership for either the project indicated "
"by '--project', if provided, or the current user's project"
),
)
membership_group.add_argument(
"--pending",
action="store_const",
const="pending",
dest="membership",
default=None,
help=_("Reset the image membership to 'pending'"),
)
hidden_group = parser.add_mutually_exclusive_group()
hidden_group.add_argument(
"--hidden",
dest="is_hidden",
default=None,
action="store_true",
help=_("Hide the image"),
)
hidden_group.add_argument(
"--unhidden",
dest="is_hidden",
default=None,
action="store_false",
help=_("Unhide the image"),
)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
image_client = self.app.client_manager.image
for deadopt in self.deadopts:
if getattr(parsed_args, f"dead_{deadopt.replace('-', '_')}", None):
raise exceptions.CommandError(
_(
"ERROR: --%s was given, which is an Image v1 option"
" that is no longer supported in Image v2"
)
% deadopt
)
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
project_id = None
if parsed_args.project:
project_id = identity_common.find_project(
identity_client,
parsed_args.project,
parsed_args.project_domain,
).id
# handle activation status changes
activation_status = None
if parsed_args.deactivate or parsed_args.activate:
if parsed_args.deactivate:
image_client.deactivate_image(image.id)
activation_status = "deactivated"
if parsed_args.activate:
image_client.reactivate_image(image.id)
activation_status = "activated"
# handle membership changes
if parsed_args.membership:
# If a specific project is not passed, assume we want to update
# our own membership
if not project_id:
project_id = self.app.client_manager.auth_ref.project_id
image_client.update_member(
image=image.id,
member=project_id,
status=parsed_args.membership,
)
# handle everything else
kwargs = {}
copy_attrs = (
'architecture',
'container_format',
'disk_format',
'file',
'instance_id',
'kernel_id',
'locations',
'min_disk',
'min_ram',
'name',
'os_distro',
'os_version',
'prefix',
'progress',
'ramdisk_id',
'tags',
'visibility',
)
for attr in copy_attrs:
if attr in parsed_args:
val = getattr(parsed_args, attr, None)
if val is not None:
# Only include a value in kwargs for attributes that are
# actually present on the command line
kwargs[attr] = val
# Properties should get flattened into the general kwargs
if getattr(parsed_args, 'properties', None):
for k, v in parsed_args.properties.items():
kwargs[k] = str(v)
# Handle exclusive booleans with care
# Avoid including attributes in kwargs if an option is not
# present on the command line. These exclusive booleans are not
# a single value for the pair of options because the default must be
# to do nothing when no options are present as opposed to always
# setting a default.
if parsed_args.is_protected is not None:
kwargs['is_protected'] = parsed_args.is_protected
if parsed_args.visibility is not None:
kwargs['visibility'] = parsed_args.visibility
if parsed_args.project:
# We already did the project lookup above
kwargs['owner_id'] = project_id
if parsed_args.tags:
# Tags should be extended, but duplicates removed
kwargs['tags'] = list(set(image.tags).union(set(parsed_args.tags)))
if parsed_args.is_hidden is not None:
kwargs['is_hidden'] = parsed_args.is_hidden
try:
image = image_client.update_image(image.id, **kwargs)
except Exception:
if activation_status is not None:
LOG.info(
_("Image %(id)s was %(status)s."),
{'id': image.id, 'status': activation_status},
)
raise
class ShowImage(command.ShowOne):
_description = _("Display image details")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"--human-readable",
default=False,
action='store_true',
help=_("Print image size in a human-friendly format."),
)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image to display (name or ID)"),
)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
info = _format_image(image, parsed_args.human_readable)
return zip(*sorted(info.items()))
class UnsetImage(command.Command):
_description = _("Unset image tags and properties")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"image",
metavar="<image>",
help=_("Image to modify (name or ID)"),
)
parser.add_argument(
"--tag",
dest="tags",
metavar="<tag>",
default=[],
action='append',
help=_(
"Unset a tag on this image "
"(repeat option to unset multiple tags)"
),
)
parser.add_argument(
"--property",
dest="properties",
metavar="<property-key>",
default=[],
action='append',
help=_(
"Unset a property on this image "
"(repeat option to unset multiple properties)"
),
)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
kwargs = {}
tagret = 0
propret = 0
if parsed_args.tags:
for k in parsed_args.tags:
try:
image_client.remove_tag(image.id, k)
except Exception:
LOG.error(
_("tag unset failed, '%s' is a " "nonexistent tag "), k
)
tagret += 1
if parsed_args.properties:
for k in parsed_args.properties:
if k in image:
delattr(image, k)
elif k in image.properties:
# Since image is an "evil" object from SDK POV we need to
# pass modified properties object, so that SDK can figure
# out, what was changed inside
# NOTE: ping gtema to improve that in SDK
new_props = kwargs.get(
'properties', image.get('properties').copy()
)
new_props.pop(k, None)
kwargs['properties'] = new_props
else:
LOG.error(
_(
"property unset failed, '%s' is a "
"nonexistent property "
),
k,
)
propret += 1
# We must give to update a current image for the reference on what
# has changed
image_client.update_image(image, **kwargs)
tagtotal = len(parsed_args.tags)
proptotal = len(parsed_args.properties)
if tagret > 0 and propret > 0:
msg = _(
"Failed to unset %(tagret)s of %(tagtotal)s tags,"
"Failed to unset %(propret)s of %(proptotal)s properties."
) % {
'tagret': tagret,
'tagtotal': tagtotal,
'propret': propret,
'proptotal': proptotal,
}
raise exceptions.CommandError(msg)
elif tagret > 0:
msg = _("Failed to unset %(tagret)s of %(tagtotal)s tags.") % {
'tagret': tagret,
'tagtotal': tagtotal,
}
raise exceptions.CommandError(msg)
elif propret > 0:
msg = _(
"Failed to unset %(propret)s of %(proptotal)s" " properties."
) % {'propret': propret, 'proptotal': proptotal}
raise exceptions.CommandError(msg)
class StageImage(command.Command):
_description = _(
"Upload data for a specific image to staging.\n"
"This requires support for the interoperable image import process, "
"which was first introduced in Image API version 2.6 "
"(Glance 16.0.0 (Queens))"
)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
'--file',
metavar='<file>',
dest='filename',
help=_(
'Local file that contains disk image to be uploaded. '
'Alternatively, images can be passed via stdin.'
),
)
# NOTE(stephenfin): glanceclient had a --size argument but it didn't do
# anything so we have chosen not to port this
parser.add_argument(
'--progress',
action='store_true',
default=False,
help=_(
'Show upload progress bar '
'(ignored if passing data via stdin)'
),
)
parser.add_argument(
'image',
metavar='<image>',
help=_('Image to upload data for (name or ID)'),
)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
image = image_client.find_image(
parsed_args.image,
ignore_missing=False,
)
# open the file first to ensure any failures are handled before the
# image is created. Get the file name (if it is file, and not stdin)
# for easier further handling.
if parsed_args.filename:
try:
fp = open(parsed_args.filename, 'rb')
except FileNotFoundError:
raise exceptions.CommandError(
f'{parsed_args.filename!r} is not a valid file',
)
else:
fp = get_data_from_stdin()
kwargs = {}
if parsed_args.progress and parsed_args.filename:
# NOTE(stephenfin): we only show a progress bar if the user
# requested it *and* we're reading from a file (not stdin)
filesize = os.path.getsize(parsed_args.filename)
if filesize is not None:
kwargs['data'] = progressbar.VerboseFileWrapper(fp, filesize)
else:
kwargs['data'] = fp
elif parsed_args.filename:
kwargs['filename'] = parsed_args.filename
elif fp:
kwargs['data'] = fp
image_client.stage_image(image, **kwargs)
class ImportImage(command.ShowOne):
_description = _(
"Initiate the image import process.\n"
"This requires support for the interoperable image import process, "
"which was first introduced in Image API version 2.6 "
"(Glance 16.0.0 (Queens))"
)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
'image',
metavar='<image>',
help=_('Image to initiate import process for (name or ID)'),
)
parser.add_argument(
'--method',
metavar='<method>',
default='glance-direct',
dest='import_method',
choices=[
'glance-direct',
'web-download',
'glance-download',
'copy-image',
],
help=_(
"Import method used for image import process. "
"Not all deployments will support all methods. "
"The 'glance-direct' method (default) requires images be "
"first staged using the 'image-stage' command."
),
)
parser.add_argument(
'--uri',
metavar='<uri>',
help=_(
"URI to download the external image "
"(only valid with the 'web-download' import method)"
),
)
parser.add_argument(
'--remote-image',
metavar='<REMOTE_IMAGE>',
help=_(
"The image of remote glance (ID only) to be imported "
"(only valid with the 'glance-download' import method)"
),
)
parser.add_argument(
'--remote-region',
metavar='<REMOTE_GLANCE_REGION>',
help=_(
"The remote Glance region to download the image from "
"(only valid with the 'glance-download' import method)"
),
)
parser.add_argument(
'--remote-service-interface',
metavar='<REMOTE_SERVICE_INTERFACE>',
help=_(
"The remote Glance service interface to use when importing "
"images "
"(only valid with the 'glance-download' import method)"
),
)
stores_group = parser.add_mutually_exclusive_group()
stores_group.add_argument(
'--store',
metavar='<STORE>',
dest='stores',
nargs='*',
help=_(
"Backend store to upload image to "
"(specify multiple times to upload to multiple stores) "
"(either '--store' or '--all-stores' required with the "
"'copy-image' import method)"
),
)
stores_group.add_argument(
'--all-stores',
help=_(
"Make image available to all stores "
"(either '--store' or '--all-stores' required with the "
"'copy-image' import method)"
),
)
parser.add_argument(
'--allow-failure',
action='store_true',
dest='allow_failure',
default=True,
help=_(
'When uploading to multiple stores, indicate that the import '
'should be continue should any of the uploads fail. '
'Only usable with --stores or --all-stores'
),
)
parser.add_argument(
'--disallow-failure',
action='store_true',
dest='allow_failure',
default=True,
help=_(
'When uploading to multiple stores, indicate that the import '
'should be reverted should any of the uploads fail. '
'Only usable with --stores or --all-stores'
),
)
parser.add_argument(
'--wait',
action='store_true',
help=_('Wait for operation to complete'),
)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
try:
import_info = image_client.get_import_info()
except sdk_exceptions.ResourceNotFound:
msg = _(
'The Image Import feature is not supported by this deployment'
)
raise exceptions.CommandError(msg)
import_methods = import_info.import_methods['value']
if parsed_args.import_method not in import_methods:
msg = _(
"The '%(method)s' import method is not supported by this "
"deployment. Supported: %(supported)s"
)
raise exceptions.CommandError(
msg
% {
'method': parsed_args.import_method,
'supported': ', '.join(import_methods),
},
)
if parsed_args.import_method == 'web-download':
if not parsed_args.uri:
msg = _(
"The '--uri' option is required when using "
"'--method=web-download'"
)
raise exceptions.CommandError(msg)
else:
if parsed_args.uri:
msg = _(
"The '--uri' option is only supported when using "
"'--method=web-download'"
)
raise exceptions.CommandError(msg)
if parsed_args.import_method == 'glance-download':
if not (parsed_args.remote_region and parsed_args.remote_image):
msg = _(
"The '--remote-region' and '--remote-image' options are "
"required when using '--method=web-download'"
)
raise exceptions.CommandError(msg)
else:
if parsed_args.remote_region:
msg = _(
"The '--remote-region' option is only supported when "
"using '--method=glance-download'"
)
raise exceptions.CommandError(msg)
if parsed_args.remote_image:
msg = _(
"The '--remote-image' option is only supported when using "
"'--method=glance-download'"
)
raise exceptions.CommandError(msg)
if parsed_args.remote_service_interface:
msg = _(
"The '--remote-service-interface' option is only "
"supported when using '--method=glance-download'"
)
raise exceptions.CommandError(msg)
if parsed_args.import_method == 'copy-image':
if not (parsed_args.stores or parsed_args.all_stores):
msg = _(
"The '--stores' or '--all-stores' options are required "
"when using '--method=copy-image'"
)
raise exceptions.CommandError(msg)
image = image_client.find_image(
parsed_args.image, ignore_missing=False
)
if not image.container_format and not image.disk_format:
msg = _(
"The 'container_format' and 'disk_format' properties "
"must be set on an image before it can be imported"
)
raise exceptions.CommandError(msg)
if parsed_args.import_method == 'glance-direct':
if image.status != 'uploading':
msg = _(
"The 'glance-direct' import method can only be used with "
"an image in status 'uploading'"
)
raise exceptions.CommandError(msg)
elif parsed_args.import_method == 'web-download':
if image.status != 'queued':
msg = _(
"The 'web-download' import method can only be used with "
"an image in status 'queued'"
)
raise exceptions.CommandError(msg)
elif parsed_args.import_method == 'copy-image':
if image.status != 'active':
msg = _(
"The 'copy-image' import method can only be used with "
"an image in status 'active'"
)
raise exceptions.CommandError(msg)
image_client.import_image(
image,
method=parsed_args.import_method,
uri=parsed_args.uri,
remote_region=parsed_args.remote_region,
remote_image_id=parsed_args.remote_image,
remote_service_interface=parsed_args.remote_service_interface,
stores=parsed_args.stores,
all_stores=parsed_args.all_stores,
all_stores_must_succeed=not parsed_args.allow_failure,
)
info = _format_image(image)
return zip(*sorted(info.items()))
class StoresInfo(command.Lister):
_description = _(
"Get available backends (only valid with Multi-Backend support)"
)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument(
"--detail",
action='store_true',
default=None,
help=_(
'Shows details of stores (admin only) '
'(requires --os-image-api-version 2.15 or later)'
),
)
return parser
def take_action(self, parsed_args):
image_client = self.app.client_manager.image
try:
columns = ("id", "description", "is_default")
column_headers = ("ID", "Description", "Default")
if parsed_args.detail:
columns += ("properties",)
column_headers += ("Properties",)
data = list(image_client.stores(details=parsed_args.detail))
except sdk_exceptions.ResourceNotFound:
msg = _('Multi Backend support not enabled')
raise exceptions.CommandError(msg)
else:
return (
column_headers,
(
utils.get_item_properties(
store,
columns,
formatters=_formatters,
)
for store in data
),
)
|