summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/okd/plugins/module_utils/openshift_import_image.py
blob: c9953d76151d072c61c72f437765cbc3ccfd4341 (plain)
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
#!/usr/bin/env python

from __future__ import absolute_import, division, print_function

__metaclass__ = type

import copy

from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils.six import string_types

from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
    AnsibleOpenshiftModule,
)

try:
    from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError:
    pass

from ansible_collections.community.okd.plugins.module_utils.openshift_docker_image import (
    parse_docker_image_ref,
)

err_stream_not_found_ref = "NotFound reference"


def follow_imagestream_tag_reference(stream, tag):
    multiple = False

    def _imagestream_has_tag():
        for ref in stream["spec"].get("tags", []):
            if ref["name"] == tag:
                return ref
        return None

    def _imagestream_split_tag(name):
        parts = name.split(":")
        name = parts[0]
        tag = ""
        if len(parts) > 1:
            tag = parts[1]
        if len(tag) == 0:
            tag = "latest"
        return name, tag, len(parts) == 2

    content = []
    err_cross_stream_ref = (
        "tag %s points to an imagestreamtag from another ImageStream" % tag
    )
    while True:
        if tag in content:
            return (
                tag,
                None,
                multiple,
                "tag %s on the image stream is a reference to same tag" % tag,
            )
        content.append(tag)
        tag_ref = _imagestream_has_tag()
        if not tag_ref:
            return None, None, multiple, err_stream_not_found_ref

        if not tag_ref.get("from") or tag_ref["from"]["kind"] != "ImageStreamTag":
            return tag, tag_ref, multiple, None

        if (
            tag_ref["from"]["namespace"] != ""
            and tag_ref["from"]["namespace"] != stream["metadata"]["namespace"]
        ):
            return tag, None, multiple, err_cross_stream_ref

        # The reference needs to be followed with two format patterns:
        # a) sameis:sometag and b) sometag
        if ":" in tag_ref["from"]["name"]:
            name, tagref, result = _imagestream_split_tag(tag_ref["from"]["name"])
            if not result:
                return (
                    tag,
                    None,
                    multiple,
                    "tag %s points to an invalid imagestreamtag" % tag,
                )
            if name != stream["metadata"]["namespace"]:
                # anotheris:sometag - this should not happen.
                return tag, None, multiple, err_cross_stream_ref
            # sameis:sometag - follow the reference as sometag
            tag = tagref
        else:
            tag = tag_ref["from"]["name"]
        multiple = True


class OpenShiftImportImage(AnsibleOpenshiftModule):
    def __init__(self, **kwargs):
        super(OpenShiftImportImage, self).__init__(**kwargs)

        self._rest_client = None
        self.registryhost = self.params.get("registry_url")
        self.changed = False

        ref_policy = self.params.get("reference_policy")
        ref_policy_type = None
        if ref_policy == "source":
            ref_policy_type = "Source"
        elif ref_policy == "local":
            ref_policy_type = "Local"

        self.ref_policy = {"type": ref_policy_type}

        self.validate_certs = self.params.get("validate_registry_certs")
        self.cluster_resources = {}

    def create_image_stream_import(self, stream):
        isi = {
            "apiVersion": "image.openshift.io/v1",
            "kind": "ImageStreamImport",
            "metadata": {
                "name": stream["metadata"]["name"],
                "namespace": stream["metadata"]["namespace"],
                "resourceVersion": stream["metadata"].get("resourceVersion"),
            },
            "spec": {"import": True},
        }

        annotations = stream.get("annotations", {})
        insecure = boolean(
            annotations.get("openshift.io/image.insecureRepository", True)
        )
        if self.validate_certs is not None:
            insecure = not self.validate_certs
        return isi, insecure

    def create_image_stream_import_all(self, stream, source):
        isi, insecure = self.create_image_stream_import(stream)
        isi["spec"]["repository"] = {
            "from": {
                "kind": "DockerImage",
                "name": source,
            },
            "importPolicy": {
                "insecure": insecure,
                "scheduled": self.params.get("scheduled"),
            },
            "referencePolicy": self.ref_policy,
        }
        return isi

    def create_image_stream_import_tags(self, stream, tags):
        isi, streamInsecure = self.create_image_stream_import(stream)
        for k in tags:
            insecure = streamInsecure
            scheduled = self.params.get("scheduled")

            old_tag = None
            for t in stream.get("spec", {}).get("tags", []):
                if t["name"] == k:
                    old_tag = t
                    break

            if old_tag:
                insecure = insecure or old_tag["importPolicy"].get("insecure")
                scheduled = scheduled or old_tag["importPolicy"].get("scheduled")

            images = isi["spec"].get("images", [])
            images.append(
                {
                    "from": {
                        "kind": "DockerImage",
                        "name": tags.get(k),
                    },
                    "to": {"name": k},
                    "importPolicy": {"insecure": insecure, "scheduled": scheduled},
                    "referencePolicy": self.ref_policy,
                }
            )
            isi["spec"]["images"] = images
        return isi

    def create_image_stream(self, ref):
        """
        Create new ImageStream and accompanying ImageStreamImport
        """
        source = self.params.get("source")
        if not source:
            source = ref["source"]

        stream = dict(
            apiVersion="image.openshift.io/v1",
            kind="ImageStream",
            metadata=dict(
                name=ref["name"],
                namespace=self.params.get("namespace"),
            ),
        )
        if self.params.get("all") and not ref["tag"]:
            spec = dict(dockerImageRepository=source)
            isi = self.create_image_stream_import_all(stream, source)
        else:
            spec = dict(
                tags=[
                    {
                        "from": {"kind": "DockerImage", "name": source},
                        "referencePolicy": self.ref_policy,
                    }
                ]
            )
            tags = {ref["tag"]: source}
            isi = self.create_image_stream_import_tags(stream, tags)
        stream.update(dict(spec=spec))
        return stream, isi

    def import_all(self, istream):
        stream = copy.deepcopy(istream)
        # Update ImageStream appropriately
        source = self.params.get("source")
        docker_image_repo = stream["spec"].get("dockerImageRepository")
        if not source:
            if docker_image_repo:
                source = docker_image_repo
            else:
                tags = {}
                for t in stream["spec"].get("tags", []):
                    if t.get("from") and t["from"].get("kind") == "DockerImage":
                        tags[t.get("name")] = t["from"].get("name")
                if tags == {}:
                    msg = (
                        "image stream %s/%s does not have tags pointing to external container images"
                        % (stream["metadata"]["namespace"], stream["metadata"]["name"])
                    )
                    self.fail_json(msg=msg)
                isi = self.create_image_stream_import_tags(stream, tags)
                return stream, isi

        if source != docker_image_repo:
            stream["spec"]["dockerImageRepository"] = source
        isi = self.create_image_stream_import_all(stream, source)
        return stream, isi

    def import_tag(self, stream, tag):
        source = self.params.get("source")

        # Follow any referential tags to the destination
        final_tag, existing, multiple, err = follow_imagestream_tag_reference(
            stream, tag
        )
        if err:
            if err == err_stream_not_found_ref:
                # Create a new tag
                if not source and tag == "latest":
                    source = stream["spec"].get("dockerImageRepository")
                # if the from is still empty this means there's no such tag defined
                # nor we can't create any from .spec.dockerImageRepository
                if not source:
                    msg = (
                        "the tag %s does not exist on the image stream - choose an existing tag to import"
                        % tag
                    )
                    self.fail_json(msg=msg)
                existing = {
                    "from": {
                        "kind": "DockerImage",
                        "name": source,
                    }
                }
            else:
                self.fail_json(msg=err)
        else:
            # Disallow re-importing anything other than DockerImage
            if (
                existing.get("from", {})
                and existing["from"].get("kind") != "DockerImage"
            ):
                msg = "tag {tag} points to existing {kind}/={name}, it cannot be re-imported.".format(
                    tag=tag,
                    kind=existing["from"]["kind"],
                    name=existing["from"]["name"],
                )
            # disallow changing an existing tag
            if not existing.get("from", {}):
                msg = (
                    "tag %s already exists - you cannot change the source using this module."
                    % tag
                )
                self.fail_json(msg=msg)
            if source and source != existing["from"]["name"]:
                if multiple:
                    msg = "the tag {0} points to the tag {1} which points to {2} you cannot change the source using this module".format(
                        tag, final_tag, existing["from"]["name"]
                    )
                else:
                    msg = (
                        "the tag %s points to %s you cannot change the source using this module."
                        % (tag, final_tag)
                    )
                self.fail_json(msg=msg)

            # Set the target item to import
            source = existing["from"].get("name")
            if multiple:
                tag = final_tag

            # Clear the legacy annotation
            tag_to_delete = "openshift.io/image.dockerRepositoryCheck"
            if existing["annotations"] and tag_to_delete in existing["annotations"]:
                del existing["annotations"][tag_to_delete]

            # Reset the generation
            existing["generation"] = 0

        new_stream = copy.deepcopy(stream)
        new_stream["spec"]["tags"] = []
        for t in stream["spec"]["tags"]:
            if t["name"] == tag:
                new_stream["spec"]["tags"].append(existing)
            else:
                new_stream["spec"]["tags"].append(t)

        # Create accompanying ImageStreamImport
        tags = {tag: source}
        isi = self.create_image_stream_import_tags(new_stream, tags)
        return new_stream, isi

    def create_image_import(self, ref):
        kind = "ImageStream"
        api_version = "image.openshift.io/v1"

        # Find existing Image Stream
        params = dict(
            kind=kind,
            api_version=api_version,
            name=ref.get("name"),
            namespace=self.params.get("namespace"),
        )
        result = self.kubernetes_facts(**params)
        if not result["api_found"]:
            msg = 'Failed to find API for resource with apiVersion "{0}" and kind "{1}"'.format(
                api_version, kind
            )
            self.fail_json(msg=msg)
        imagestream = None
        if len(result["resources"]) > 0:
            imagestream = result["resources"][0]

        stream, isi = None, None
        if not imagestream:
            stream, isi = self.create_image_stream(ref)
        elif self.params.get("all") and not ref["tag"]:
            # importing the entire repository
            stream, isi = self.import_all(imagestream)
        else:
            # importing a single tag
            stream, isi = self.import_tag(imagestream, ref["tag"])
        return isi

    def parse_image_reference(self, image_ref):
        result, err = parse_docker_image_ref(image_ref, self.module)
        if result.get("digest"):
            self.fail_json(
                msg="Cannot import by ID, error with definition: %s" % image_ref
            )
        tag = result.get("tag") or None
        if not self.params.get("all") and not tag:
            tag = "latest"
        source = self.params.get("source")
        if not source:
            source = image_ref
        return dict(name=result.get("name"), tag=tag, source=image_ref)

    def execute_module(self):
        names = []
        name = self.params.get("name")
        if isinstance(name, string_types):
            names.append(name)
        elif isinstance(name, list):
            names = name
        else:
            self.fail_json(msg="Parameter name should be provided as list or string.")

        images_refs = [self.parse_image_reference(x) for x in names]
        images_imports = []
        for ref in images_refs:
            isi = self.create_image_import(ref)
            images_imports.append(isi)

        # Create image import
        kind = "ImageStreamImport"
        api_version = "image.openshift.io/v1"
        namespace = self.params.get("namespace")
        try:
            resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
            result = []
            for isi in images_imports:
                if not self.check_mode:
                    isi = resource.create(isi, namespace=namespace).to_dict()
                result.append(isi)
            self.exit_json(changed=True, result=result)
        except DynamicApiError as exc:
            msg = "Failed to create object {kind}/{namespace}/{name} due to: {error}".format(
                kind=kind, namespace=namespace, name=isi["metadata"]["name"], error=exc
            )
            self.fail_json(
                msg=msg,
                error=exc.status,
                status=exc.status,
                reason=exc.reason,
            )
        except Exception as exc:
            msg = "Failed to create object {kind}/{namespace}/{name} due to: {error}".format(
                kind=kind, namespace=namespace, name=isi["metadata"]["name"], error=exc
            )
            self.fail_json(msg=msg)