-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy path__init__.py
More file actions
1618 lines (1338 loc) · 57.2 KB
/
__init__.py
File metadata and controls
1618 lines (1338 loc) · 57.2 KB
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
from __future__ import annotations
import abc
import asyncio
import datetime
import enum
import os
import textwrap
from collections.abc import Callable
from dataclasses import dataclass
from dataclasses import field
from pathlib import Path
from typing import Literal
from typing import overload
import jinja2
from bci_build.container_attributes import Arch
from bci_build.container_attributes import BuildType
from bci_build.container_attributes import ImageType
from bci_build.container_attributes import NetworkPort
from bci_build.container_attributes import PackageType
from bci_build.container_attributes import ReleaseStage
from bci_build.container_attributes import SupportLevel
from bci_build.containercrate import ContainerCrate
from bci_build.os_version import ALL_OS_LTSS_VERSIONS
from bci_build.os_version import RELEASED_OS_VERSIONS
from bci_build.os_version import OsVersion
from bci_build.registry import ApplicationCollectionRegistry
from bci_build.registry import Registry
from bci_build.registry import publish_registry
from bci_build.service import Service
from bci_build.templates import DOCKERFILE_TEMPLATE
from bci_build.templates import INFOHEADER_TEMPLATE
from bci_build.templates import KIWI_TEMPLATE
from bci_build.templates import SERVICE_TEMPLATE
from bci_build.util import write_to_file
_BASH_SET: str = "set -euo pipefail"
#: a ``RUN`` command with a common set of bash flags applied to prevent errors
#: from not being noticed
DOCKERFILE_RUN: str = f"RUN {_BASH_SET};"
#: Remove various log files. While it is possible to just ``rm -rf /var/log/*``,
#: that would also remove some package owned directories (not %ghost)
LOG_CLEAN: str = "rm -rf {/target,}/var/log/{alternatives.log,lastlog,tallylog,zypper.log,zypp/history,YaST2}"
#: The string to use as a placeholder for the build source services to put in the release number
_RELEASE_PLACEHOLDER = "%RELEASE%"
@dataclass
class Package:
"""Representation of a package in a kiwi build, for Dockerfile based builds the
:py:attr:`~Package.pkg_type`.
"""
#: The name of the package
name: str
#: The package type. This parameter is only applicable for kiwi builds and
#: defines into which ``<packages>`` element this package is inserted.
pkg_type: PackageType = PackageType.IMAGE
def __str__(self) -> str:
return self.name
@enum.unique
class ParseVersion(enum.StrEnum):
MAJOR = enum.auto()
MINOR = enum.auto()
PATCH = enum.auto()
PATCH_UPDATE = enum.auto()
OFFSET = enum.auto()
@dataclass
class Replacement:
"""Represents a replacement via the `obs-service-replace_using_package_version
<https://github.com/openSUSE/obs-service-replace_using_package_version>`_.
"""
#: regex to be replaced in :py:attr:`~bci_build.package.Replacement.file_name`, :file:`Dockerfile` or :file:`$pkg_name.kiwi`
regex_in_build_description: str
#: package name to be queried for the version
package_name: str
#: override file name, if unset use :file:`Dockerfile` or :file:`$pkg_name.kiwi`
file_name: str | None = None
#: specify how the version should be formatted, see
#: `<https://github.com/openSUSE/obs-service-replace_using_package_version#usage>`_
#: for further details
parse_version: None | ParseVersion = None
def __post_init__(self) -> None:
"""Barf if someone tries to replace variables in README, as those
changes will be only performed in the buildroot, but not in the actual
source package.
"""
if "%%" not in self.regex_in_build_description:
raise ValueError("regex_in_build_description must be in the form %%foo%%")
if self.file_name and "readme" in self.file_name.lower():
raise ValueError(f"Cannot replace variables in {self.file_name}!")
def to_service(self, default_file_name: str) -> Service:
"""Convert this replacement into a
:py:class:`~bci__build.service.Service`.
"""
return Service(
name="replace_using_package_version",
param=[
("file", self.file_name or default_file_name),
("regex", self.regex_in_build_description),
("package", self.package_name),
]
+ ([("parse-version", self.parse_version)] if self.parse_version else []),
)
def _build_tag_prefix(os_version: OsVersion) -> str:
if os_version == OsVersion.TUMBLEWEED:
return "opensuse/bci"
if os_version == OsVersion.SP3:
return "suse/ltss/sle15.3"
if os_version == OsVersion.SP4:
return "suse/ltss/sle15.4"
return "bci"
@dataclass
class BaseContainerImage(abc.ABC):
"""Base class for all Base Containers."""
#: Name of this image. It is used to generate the build tags, i.e. it
#: defines under which name this image is published.
name: str
#: The SLE service pack to which this package belongs
os_version: OsVersion
#: Human readable name that will be inserted into the image title and description
pretty_name: str
#: Optional a package_name, used for creating the package name on OBS or IBS in
# ``devel:BCI:SLE-15-SP$ver`` (on OBS) or ``SUSE:SLE-15-SP$ver:Update:BCI`` (on IBS)
package_name: str | None = None
#: The container from which the build stage is running. On SLE15, this defaults to
#: ``suse/sle15:15.$SP`` for Application Containers and ``bci/bci-base:15.$SP``
#: for all other images. On openSUSE, ``opensuse/tumbleweed:latest`` is used
#: when an empty string is used.
#:
#: When from image is ``None``, then this image will not be based on
#: **anything**, i.e. the ``FROM`` line is missing in the ``Dockerfile``.
from_image: str | None = ""
#: The container that is used to install this image into. If this is not set, then
#: only a single stage build is produced, otherwise a multistage build
from_target_image: str | None = None
#: Architectures of this image.
#:
#: If supplied, then this image will be restricted to only build on the
#: supplied architectures. By default, there is no restriction
exclusive_arch: list[Arch] | None = None
#: Determines whether this image will have the ``latest`` tag.
is_latest: bool = False
#: Determines whether only one version of this image will be published
#: under the same registry path.
is_singleton_image: bool = False
#: An optional entrypoint for the image, it is omitted if empty or ``None``
#: If you provide a string, then it will be included in the container build
#: recipe as is, i.e. it will be called via a shell as
#: :command:`sh -c "MY_CMD"`.
#: If your entrypoint must not be called through a shell, then pass the
#: binary and its parameters as a list
entrypoint: list[str] | None = None
# The user to use for entrypoint service
entrypoint_user: str | None = ""
#: An optional CMD for the image, it is omitted if empty or ``None``
cmd: list[str] | None = None
#: An optional list of volumes, it is omitted if empty or ``None``
volumes: list[str] | None = None
#: An optional list of port exposes, it is omitted if empty or ``None``.
exposes_ports: list[NetworkPort] | None = None
#: Extra environment variables to be set in the container
env: dict[str, str | int] | dict[str, str] | dict[str, int] = field(
default_factory=dict
)
#: build flavors to produce for this container variant
build_flavor: str | None = None
#: create that this container is part of
crate: ContainerCrate = None
#: Add any replacements via `obs-service-replace_using_package_version
#: <https://github.com/openSUSE/obs-service-replace_using_package_version>`_
#: that are used in this image into this list.
#: See also :py:class:`~Replacement`
replacements_via_service: list[Replacement] = field(default_factory=list)
#: Additional labels that should be added to the image. These are added as labels
# within the "labelprefix" section.
extra_labels: dict[str, str] = field(default_factory=dict)
#: Packages to be installed inside the container image
package_list: list[str] | list[Package] = field(default_factory=list)
#: This string is appended to the automatically generated dockerfile and can
#: contain arbitrary instructions valid for a :file:`Dockerfile`.
#:
#: .. note::
#: Setting both this property and :py:attr:`~BaseContainerImage.config_sh_script`
#: is not possible and will result in an error.
custom_end: str = ""
#: This string is appended to the the build stage in a multistage build and can
#: contain arbitrary instructions valid for a :file:`Dockerfile`.
build_stage_custom_end: str | None = None
#: This string defines which build counter identifier should be used for this
#: container. can be an arbitrary string is used to derive the checkin-counter.
#: Defaults to the main package for packages with a flavor.
buildcounter_synctag: str | None = None
#: A script that is put into :file:`config.sh` if a kiwi image is
#: created. If a :file:`Dockerfile` based build is used then this script is
#: prependend with a :py:const:`~bci_build.package.DOCKERFILE_RUN` and added
#: at the end of the ``Dockerfile``. It must thus fit on a single line if
#: you want to be able to build from a kiwi and :file:`Dockerfile` at the
#: same time!
config_sh_script: str = ""
#: The interpreter of the :file:`config.sh` script that is executed by kiwi
#: during the image build.
#: It defaults to :file:`/bin/bash` and has no effect for :file:`Dockerfile`
#: based builds.
#: *Warning:* Using a different interpreter than :file:`/bin/bash` could
#: lead to unpredictable results as kiwi's internal functions are written
#: for bash and not for a different shell.
config_sh_interpreter: str = "/bin/bash"
#: The oci image author annotation for this image, defaults to SUSE/openSUSE
oci_authors: str | None = None
#: Additional files that belong into this container-package.
#: The key is the filename, the values are the file contents.
extra_files: dict[str, str | bytes] | dict[str, bytes] | dict[str, str] = field(
default_factory=dict
)
#: Additional names under which this image should be published alongside
#: :py:attr:`~BaseContainerImage.name`.
#: These names are only inserted into the
#: :py:attr:`~BaseContainerImage.build_tags`
additional_names: list[str] = field(default_factory=list)
#: By default the containers get the labelprefix
#: ``{label_prefix}.bci.{self.name}``. If this value is not an empty string,
#: then it is used instead of the name after ``com.suse.bci.``.
custom_labelprefix_end: str = ""
#: Provide a custom description instead of the automatically generated one
custom_description: str = ""
#: Define whether this container image is built using docker or kiwi.
#: If not set, then the build type will default to docker from SP4 onwards.
build_recipe_type: BuildType | None = None
#: Define packages that should be ignored by kiwi in the creation of the
#: final container image even if dependencies would otherwise pull them in.
kiwi_ignore_packages: list[str] | None = None
#: A license string to be placed in a comment at the top of the Dockerfile
#: or kiwi build description file.
license: str = "MIT"
#: The support level for this image, defaults to :py:attr:`SupportLevel.TECHPREVIEW`
support_level: SupportLevel = SupportLevel.TECHPREVIEW
#: The support level end date
supported_until: datetime.date | None = None
#: flag whether to not install recommended packages in the call to
#: :command:`zypper` in :file:`Dockerfile`
no_recommends: bool = True
#: URL to the logo of this container image.
#: This value is added to the ``io.artifacthub.package.logo-url`` label if
#: present
logo_url: str = ""
#: Optional build_release setting that will be inserted as the
#: ``#!BuildRelease`` magic comment for the build service to ensure that
#: the release suffix of a container tag is sequentially increasing (for
#: webui sorting)
_min_release_counter: int | None = None
#: The registry implementation for which this container is being built.
_publish_registry: Registry | None = None
@property
def publish_registry(self) -> Registry:
assert self._publish_registry
return self._publish_registry
def __post_init__(self) -> None:
self.pretty_name = self.pretty_name.strip()
if not self.package_name:
self.package_name = f"{self.name}-image"
if not self.package_list:
raise ValueError(f"No packages were added to {self.pretty_name}.")
if self.exclusive_arch and Arch.LOCAL in self.exclusive_arch:
raise ValueError(f"{Arch.LOCAL} must not appear in {self.exclusive_arch=}")
if self.config_sh_script and self.custom_end:
raise ValueError(
"Cannot specify both a custom_end and a config.sh script! Use just config_sh_script."
)
if self.build_recipe_type is None:
self.build_recipe_type = (
BuildType.KIWI if self.os_version == OsVersion.SP3 else BuildType.DOCKER
)
if not self._publish_registry:
self._publish_registry = publish_registry(self.os_version)
# AppCollection preferences
if isinstance(self._publish_registry, ApplicationCollectionRegistry):
# Limit to aarch64 and x86_64
if not self.exclusive_arch:
self.exclusive_arch = [Arch.AARCH64, Arch.X86_64]
# Override maintainer listing from base container by setting an empty value
self.oci_authors = ""
elif not self.oci_authors and not self.os_version.is_tumbleweed:
self.oci_authors = "https://github.com/SUSE/bci/discussions"
# limit to tech preview for beta releases
if (
self.release_stage == ReleaseStage.BETA
and self.support_level == SupportLevel.L3
):
self.support_level = SupportLevel.TECHPREVIEW
# set buildcounter to the package name if not set
if not self.buildcounter_synctag and self.package_name and self.build_flavor:
self.buildcounter_synctag = self.package_name
@abc.abstractmethod
def prepare_template(self) -> None:
"""Hook to do delayed expensive work prior template rendering"""
pass
@property
@abc.abstractmethod
def uid(self) -> str:
"""unique identifier of this image, either its name or ``$name-$tag_version``."""
pass
@property
@abc.abstractmethod
def oci_version(self) -> str:
"""The "main" version label of this image.
It is added as the ``org.opencontainers.image.version`` label to the
container image.
"""
pass
@property
def build_name(self) -> str | None:
if self.build_tags:
# build_tags[0] is with -RELEASE suffix, build_tags[1] without
assert _RELEASE_PLACEHOLDER in self.build_tags[0]
assert _RELEASE_PLACEHOLDER not in self.build_tags[1]
build_name: str = self.build_tags[1]
if self.is_singleton_image:
build_name = build_name.partition(":")[0]
return build_name.replace("/", ":").replace(":", "-")
return None
@property
def build_version(self) -> str | None:
"""Define the BuildVersion that is used for determining which container build
is newer than the other in the build service."""
# KIWI used to require an at least 3 component version X.Y.Z. For SLE, we set
# X.Y to MAJOR.MINOR and set Z to 0 for OsContainers. Derived
# containers inhert the base build_version X.Y and append a suffix .Z.ZZ
# It is important that the behavior for OsContainers is identical
# between KIWI and Dockerfile builds so that we can switch between these
# types.
if self.os_version.is_tumbleweed:
if isinstance(self, OsContainer):
return "%OS_VERSION_ID_SP%.0.0"
# TODO: also set it for non-kiwi type (historically we haven't done so)
if self.build_recipe_type == BuildType.KIWI:
return f"{str(datetime.datetime.now().year)}.0"
elif self.os_version.is_sle15:
if isinstance(self, OsContainer):
return f"15.{int(self.os_version.value)}.0"
return f"15.{int(self.os_version.value)}"
elif self.os_version.is_sl16:
if isinstance(self, OsContainer):
return f"{str(self.os_version.value)}.0"
return str(self.os_version.value)
return None
@property
def kiwi_version(self) -> str | None:
"""Return a BuildVersion that is compatible with the requirements that KIWI imposes.
https://osinside.github.io/kiwi/image_description/elements.html#preferences-version
It a version strictly in the format X.Y.Z.
"""
build_ver: str | None = self.build_version
if build_ver:
return ".".join(build_ver.split(".")[:3])
return None
@property
def build_release(self) -> str | None:
if self.os_version not in (OsVersion.SP6,):
return None
return (
str(self._min_release_counter)
if self._min_release_counter is not None
else None
)
@property
def eula(self) -> str:
"""EULA covering this image. can be ``sle-eula`` or ``sle-bci``."""
if self.os_version.is_ltss or isinstance(
self._publish_registry, ApplicationCollectionRegistry
):
return "sle-eula"
return "sle-bci"
@property
def lifecycle_url(self) -> str:
if self.os_version.is_tumbleweed:
return "https://en.opensuse.org/Lifetime#openSUSE_BCI"
if self.os_version.is_sle15:
return "https://www.suse.com/lifecycle#suse-linux-enterprise-server-15"
return "https://www.suse.com/lifecycle"
@property
def release_stage(self) -> ReleaseStage:
"""This container images' release stage.
It is :py:attr:`~ReleaseStage.RELEASED` if the container images'
operating system version is in the list
:py:const:`~bci_build.package.RELEASED_OS_VERSIONS`. Otherwise it
is :py:attr:`~ReleaseStage.BETA`.
"""
if self.os_version in RELEASED_OS_VERSIONS:
return ReleaseStage.RELEASED
return ReleaseStage.BETA
@property
def url(self) -> str:
"""The default url that is put into the
``org.opencontainers.image.url`` label
"""
return self.publish_registry.url(container=self)
@property
def base_image_registry(self) -> str:
"""The registry where the base image is available on."""
return publish_registry(self.os_version).registry
@property
def registry(self) -> str:
"""The registry where the image is available on."""
return self.publish_registry.registry
@property
def dockerfile_custom_end(self) -> str:
"""This part is appended at the end of the :file:`Dockerfile`. It is either
generated from :py:attr:`BaseContainerImage.custom_end` or by prepending
``RUN`` in front of :py:attr:`BaseContainerImage.config_sh_script`. The
later implies that the script in that variable fits on a single line or
newlines are escaped, e.g. via `ansi escapes
<https://stackoverflow.com/a/33439625>`_.
"""
if self.custom_end:
return self.custom_end
if self.config_sh_script:
return f"{DOCKERFILE_RUN} {self.config_sh_script}"
return ""
@property
def registry_prefix(self) -> str:
return _build_tag_prefix(self.os_version)
@staticmethod
def _cmd_entrypoint_docker(
prefix: Literal["CMD", "ENTRYPOINT"], value: list[str] | None
) -> str | None:
if not value:
return None
if isinstance(value, list):
return "\n" + prefix + " " + str(value).replace("'", '"')
assert False, f"Unexpected type for {prefix}: {type(value)}"
@property
def entrypoint_docker(self) -> str | None:
"""The entrypoint line in a :file:`Dockerfile`."""
return self._cmd_entrypoint_docker("ENTRYPOINT", self.entrypoint)
@property
def cmd_docker(self) -> str | None:
return self._cmd_entrypoint_docker("CMD", self.cmd)
@staticmethod
def _cmd_entrypoint_kiwi(
prefix: Literal["subcommand", "entrypoint"],
value: list[str] | None,
) -> str | None:
if not value:
return None
if len(value) == 1:
val = value if isinstance(value, str) else value[0]
return f'\n <{prefix} execute="{val}"/>'
else:
return (
f"""\n <{prefix} execute=\"{value[0]}\">
"""
+ "\n".join(f' <argument name="{arg}"/>' for arg in value[1:])
+ f"""
</{prefix}>
"""
)
@property
def entrypoint_kiwi(self) -> str | None:
return self._cmd_entrypoint_kiwi("entrypoint", self.entrypoint)
@property
def cmd_kiwi(self) -> str | None:
return self._cmd_entrypoint_kiwi("subcommand", self.cmd)
@property
def config_sh(self) -> str:
"""The full :file:`config.sh` script required for kiwi builds."""
if not self.config_sh_script and self.custom_end:
raise ValueError(
"This image cannot be build as a kiwi image, it has a `custom_end` set."
)
return f"""#!{self.config_sh_interpreter}
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: (c) 2022-{datetime.datetime.now().date().strftime("%Y")} SUSE LLC
{_BASH_SET}
test -f /.kconfig && . /.kconfig
test -f /.profile && . /.profile
echo "Configure image: [$kiwi_iname]..."
#============================================
# Import repositories' keys if rpm is present
#--------------------------------------------
if command -v rpm > /dev/null; then
suseImportBuildKey
fi
{self.config_sh_script}
#=======================================
# Clean up after zypper if it is present
#---------------------------------------
if command -v zypper > /dev/null; then
zypper -n clean
fi
{LOG_CLEAN}
exit 0
"""
@property
def _from_image(self) -> str | None:
if self.from_image is None:
return None
if self.from_image:
return self.from_image
if self.os_version == OsVersion.TUMBLEWEED:
return "opensuse/tumbleweed:latest"
if self.os_version == OsVersion.SLE16_0:
return f"{_build_tag_prefix(self.os_version)}/bci-base:{self.os_version}"
if self.os_version in ALL_OS_LTSS_VERSIONS:
return f"{_build_tag_prefix(self.os_version)}/sle15:15.{self.os_version}"
if not self.from_target_image and self.os_version in RELEASED_OS_VERSIONS:
return f"{self.base_image_registry}/bci/bci-base:15.{self.os_version}"
if (
not isinstance(self._publish_registry, ApplicationCollectionRegistry)
and self.image_type == ImageType.APPLICATION
):
return f"suse/sle15:15.{self.os_version}"
return f"bci/bci-base:15.{self.os_version}"
@property
def dockerfile_from_target_ref(self) -> str:
"""Provide the reference for the target image if multistage build is used, empty string otherwise."""
if not self.from_target_image:
return ""
if self.from_target_image == "scratch":
return self.from_target_image
# build against the released container on SLE for proper base.digest/name generation
return (
self.from_target_image
if (
self.os_version.is_tumbleweed
or self.from_target_image.startswith(self.base_image_registry)
or self.os_version not in RELEASED_OS_VERSIONS
)
else f"{self.base_image_registry}/{self.from_target_image}"
)
@property
def is_base_container_annotation_available(self) -> bool:
"""return True if the obs-service-kiwi_metainfo_helper can provide base.name/digest annotations."""
_from_image = self._from_image
return bool(
_from_image
and self.os_version in RELEASED_OS_VERSIONS
and (
self.from_target_image
or _from_image.startswith(self.base_image_registry)
)
and not self.os_version.is_tumbleweed
and not self.os_version.is_sl16 # waiting for ibs#345975
)
@property
def dockerfile_from_line(self) -> str:
if self._from_image is None:
return ""
if self.from_target_image:
return f"FROM {self.dockerfile_from_target_ref} AS target\nFROM {self._from_image} AS builder"
return f"FROM {self._from_image}"
@property
def kiwi_derived_from_entry(self) -> str:
if self._from_image is None:
return ""
# Adjust for the special format that OBS expects to reference
# external images
if self.is_base_container_annotation_available:
repo: str = self._from_image.replace("registry.suse.com/", "").replace(
":", "#"
)
return f' derived_from="obsrepositories:/{repo}"'
return f' derived_from="obsrepositories:/{self._from_image.replace(":", "#")}"'
@property
def packages(self) -> str:
"""The list of packages joined so that it can be appended to a
:command:`zypper in`.
"""
packages_to_install: list[str] = []
for pkg in self.package_list:
if isinstance(pkg, Package):
if pkg.pkg_type == PackageType.DELETE:
continue
if pkg.pkg_type != PackageType.IMAGE:
raise ValueError(
f"Cannot add a package of type {pkg.pkg_type} into a Dockerfile based build."
)
packages_to_install.append(str(pkg))
return " ".join(packages_to_install)
@property
def packages_to_delete(self) -> str:
"""The list of packages joined that can be passed to zypper -n rm after an install`."""
packages_to_delete: list[str] = [
str(pkg)
for pkg in self.package_list
if (isinstance(pkg, Package) and pkg.pkg_type == PackageType.DELETE)
]
return " ".join(packages_to_delete)
@overload
def _kiwi_volumes_expose(
self,
main_element: Literal["volumes"],
entry_element: Literal["volume name"],
entries: list[str] | None,
) -> str: ...
@overload
def _kiwi_volumes_expose(
self,
main_element: Literal["expose"],
entry_element: Literal["port number"],
entries: list[NetworkPort] | None,
) -> str: ...
def _kiwi_volumes_expose(
self,
main_element: Literal["volumes", "expose"],
entry_element: Literal["volume name", "port number"],
entries: list[NetworkPort] | list[str] | None,
) -> str:
if not entries:
return ""
res = f"""
<{main_element}>
"""
for entry in entries:
res += f""" <{entry_element}="{entry}" />
"""
res += f""" </{main_element}>"""
return res
@property
def volumes_kiwi(self) -> str:
"""The volumes for this image as xml elements that are inserted into
a container.
"""
return self._kiwi_volumes_expose("volumes", "volume name", self.volumes)
@property
def exposes_kiwi(self) -> str:
"""The EXPOSES for this image as kiwi xml elements."""
return self._kiwi_volumes_expose("expose", "port number", self.exposes_ports)
@overload
def _dockerfile_volume_expose(
self,
instruction: Literal["EXPOSE"],
entries: list[NetworkPort] | None,
) -> str: ...
@overload
def _dockerfile_volume_expose(
self,
instruction: Literal["VOLUME"],
entries: list[str] | None,
) -> str: ...
def _dockerfile_volume_expose(
self,
instruction: Literal["EXPOSE", "VOLUME"],
entries: list[NetworkPort] | list[str] | None,
):
if not entries:
return ""
return "\n" + f"{instruction} " + " ".join(str(e) for e in entries)
@property
def volume_dockerfile(self) -> str:
return self._dockerfile_volume_expose("VOLUME", self.volumes)
@property
def expose_dockerfile(self) -> str:
return self._dockerfile_volume_expose("EXPOSE", self.exposes_ports)
@property
def kiwi_packages(self) -> str:
"""The package list as xml elements that are inserted into a kiwi build
description file.
"""
def create_pkg_filter_func(
pkg_type: PackageType,
) -> Callable[[str | Package], bool]:
def pkg_filter_func(p: str | Package) -> bool:
if isinstance(p, str):
return pkg_type == PackageType.IMAGE
return p.pkg_type == pkg_type
return pkg_filter_func
def pkg_listing_func(pkg: Package) -> str:
return f'<package name="{pkg}"/>'
PKG_TYPES = (
PackageType.DELETE,
PackageType.BOOTSTRAP,
PackageType.IMAGE,
PackageType.UNINSTALL,
)
delete_packages, bootstrap_packages, image_packages, uninstall_packages = (
list(filter(create_pkg_filter_func(pkg_type), self.package_list))
for pkg_type in PKG_TYPES
)
res = ""
for pkg_list, pkg_type in zip(
(delete_packages, bootstrap_packages, image_packages, uninstall_packages),
PKG_TYPES,
):
if pkg_list:
res += (
f""" <packages type="{pkg_type}">
"""
+ "\n ".join(pkg_listing_func(pkg) for pkg in pkg_list)
+ """
</packages>
"""
)
return res
@property
def env_lines(self) -> str:
"""Part of the :file:`Dockerfile` that sets every environment variable defined
in :py:attr:`~BaseContainerImage.env`.
"""
return (
""
if not self.env
else "\n" + "\n".join(f'ENV {k}="{v}"' for k, v in self.env.items())
)
@property
def kiwi_env_entry(self) -> str:
"""Environment variable settings for a kiwi build recipe."""
if not self.env:
return ""
return (
"""\n <environment>
"""
+ """
""".join(f'<env name="{k}" value="{v}"/>' for k, v in self.env.items())
+ """
</environment>
"""
)
@property
@abc.abstractmethod
def image_type(self) -> ImageType:
"""Define the value of the ``com.suse.image-type`` label."""
pass
@property
@abc.abstractmethod
def build_tags(self) -> list[str]:
"""All build tags that will be added to this image. Note that build tags are
full paths on the registry and not just a tag.
"""
pass
@property
@abc.abstractmethod
def image_ref_name(self) -> str:
"""The immutable reference for this target under which this image can be pulled. It is used
to set the ``org.opencontainers.image.ref.name`` OCI annotation and defaults to
``{self.build_tags[0]}``.
"""
pass
@property
@abc.abstractmethod
def reference(self) -> str:
"""The primary URL via which this image can be pulled. It is used to set the
``org.opensuse.reference`` label and defaults to
``{self.registry}/{self.image_ref_name}``.
"""
pass
@property
@abc.abstractmethod
def pretty_reference(self) -> str:
"""Returns the human readable registry URL to this image. It is intended
to be used in the image documentation.
This url needn't point to an exact version-release but can include just
the major os version or the latest tag.
"""
@property
def description(self) -> str:
"""The description of this image which is inserted into the
``org.opencontainers.image.description`` label.
If :py:attr:`BaseContainerImage.custom_description` is set, then that
value is used. Custom descriptions can use str.format() substitution to
expand the custom description with the following options:
- ``{pretty_name}``: the value of the pretty_name property
- ``{based_on_container}``: the standard "based on the $distro Base Container Image" suffix that descriptions have
- ``{podman_only}``: "This container is only supported with podman."
- ``{privileged_only}``: "This container is only supported in privileged mode."
Otherwise it reuses
:py:attr:`BaseContainerImage.pretty_name` to generate a description.
"""
description_formatters = {
"pretty_name": self.pretty_name,
"based_on_container": (
f"based on the {self.os_version.distribution_base_name} Base Container Image"
),
"podman_only": "This container is only supported with podman.",
"privileged_only": "This container is only supported in privileged mode.",
}
description = "{pretty_name} container {based_on_container}."
if self.custom_description:
description = self.custom_description
return description.format(**description_formatters)
@property
def title(self) -> str:
"""The image title that is inserted into the ``org.opencontainers.image.title``
label.
It is generated from :py:attr:`BaseContainerImage.pretty_name` as
follows: ``"{distribution_base_name} BCI {self.pretty_name}"``, where
``distribution_base_name`` is taken from
:py:attr:`~OsVersion.distribution_base_name`.
"""
return f"{self.os_version.distribution_base_name} BCI {self.pretty_name}"
@property
def readme_name(self) -> str:
return f"README.{self.build_flavor}.md" if self.build_flavor else "README.md"
@property
def readme_path(self) -> str:
return f"{self.package_name}/{self.readme_name}"
@property
def readme_url(self) -> str:
return f"%SOURCEURL_WITH({self.readme_name})%"
@property
def readme(self) -> str:
if "README.md" in self.extra_files:
if isinstance(self.extra_files["README.md"], bytes):
return self.extra_files["README.md"].decode("utf-8")
return str(self.extra_files["README.md"])
# default template if no custom README.md.j2 template is provided in the package folder
readme_template = textwrap.dedent(f"""
# The {self.title} container image
{{% include 'badges.j2' %}}
{self.description}
{{% include 'licensing_and_eula.j2' %}}
""").strip()
readme_template_fname = Path(__file__).parent / self.name / "README.md.j2"
if readme_template_fname.exists():
readme_template = readme_template_fname.read_text()
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(Path(__file__).parent / "templates"),
autoescape=jinja2.select_autoescape(["md"]),
)
return jinja2_env.from_string(readme_template).render(image=self)
@property
def extra_label_lines(self) -> str:
"""Lines for a :file:`Dockerfile` to set the additional labels defined in
:py:attr:`BaseContainerImage.extra_labels`.