Debian Codegraph @

ansible_collections/community/okd/plugins/module_utils/openshift_registry.py

raw
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, division, print_function
4
5 __metaclass__ = type
6
7 import traceback
8 from urllib.parse import urlparse
9
10 from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
11 AnsibleOpenshiftModule,
12 )
13
14 from ansible_collections.community.okd.plugins.module_utils.openshift_docker_image import (
15 parse_docker_image_ref,
16 )
17
18 try:
19 from requests import request
20 from requests.auth import HTTPBasicAuth
21
22 HAS_REQUESTS_MODULE = True
23 requests_import_exception = None
24 except ImportError as e:
25 HAS_REQUESTS_MODULE = False
26 requests_import_exception = e
27 REQUESTS_MODULE_ERROR = traceback.format_exc()
28
29
30 class OpenShiftRegistry(AnsibleOpenshiftModule):
31 def __init__(self, **kwargs):
32 super(OpenShiftRegistry, self).__init__(**kwargs)
33 self.check = self.params.get("check")
34
35 def list_image_streams(self, namespace=None):
36 kind = "ImageStream"
37 api_version = "image.openshift.io/v1"
38
39 params = dict(kind=kind, api_version=api_version, namespace=namespace)
40 result = self.kubernetes_facts(**params)
41 imagestream = []
42 if len(result["resources"]) > 0:
43 imagestream = result["resources"]
44 return imagestream
45
46 def find_registry_info(self):
47 def _determine_registry(image_stream):
48 public, internal = None, None
49 docker_repo = image_stream["status"].get("publicDockerImageRepository")
50 if docker_repo:
51 ref, err = parse_docker_image_ref(docker_repo, self.module)
52 public = ref["hostname"]
53
54 docker_repo = image_stream["status"].get("dockerImageRepository")
55 if docker_repo:
56 ref, err = parse_docker_image_ref(docker_repo, self.module)
57 internal = ref["hostname"]
58 return internal, public
59
60 # Try to determine registry hosts from Image Stream from 'openshift' namespace
61 for stream in self.list_image_streams(namespace="openshift"):
62 internal, public = _determine_registry(stream)
63 if not public and not internal:
64 self.fail_json(msg="The integrated registry has not been configured")
65 return internal, public
66
67 # Unable to determine registry from 'openshift' namespace, trying with all namespace
68 for stream in self.list_image_streams():
69 internal, public = _determine_registry(stream)
70 if not public and not internal:
71 self.fail_json(msg="The integrated registry has not been configured")
72 return internal, public
73
74 self.fail_json(
75 msg="No Image Streams could be located to retrieve registry info."
76 )
77
78 def execute_module(self):
79 result = {}
80 (
81 result["internal_hostname"],
82 result["public_hostname"],
83 ) = self.find_registry_info()
84
85 if self.check:
86 public_registry = result["public_hostname"]
87 if not public_registry:
88 result["check"] = dict(
89 reached=False, msg="Registry does not have a public hostname."
90 )
91 else:
92 headers = {"Content-Type": "application/json"}
93 params = {"method": "GET", "verify": False}
94 if self.client.configuration.api_key:
95 headers.update(self.client.configuration.api_key)
96 elif (
97 self.client.configuration.username
98 and self.client.configuration.password
99 ):
100 if not HAS_REQUESTS_MODULE:
101 result["check"] = dict(
102 reached=False,
103 msg="The requests python package is missing, try `pip install requests`",
104 error=requests_import_exception,
105 )
106 self.exit_json(**result)
107 params.update(
108 dict(
109 auth=HTTPBasicAuth(
110 self.client.configuration.username,
111 self.client.configuration.password,
112 )
113 )
114 )
115
116 # verify ssl
117 host = urlparse(public_registry)
118 if len(host.scheme) == 0:
119 registry_url = "https://" + public_registry
120
121 if (
122 registry_url.startswith("https://")
123 and self.client.configuration.ssl_ca_cert
124 ):
125 params.update(dict(verify=self.client.configuration.ssl_ca_cert))
126 params.update(dict(headers=headers))
127 last_bad_status, last_bad_reason = None, None
128 for path in ("/", "/healthz"):
129 params.update(dict(url=registry_url + path))
130 response = request(**params)
131 if response.status_code == 200:
132 result["check"] = dict(
133 reached=True,
134 msg="The local client can contact the integrated registry.",
135 )
136 self.exit_json(**result)
137 last_bad_reason = response.reason
138 last_bad_status = response.status_code
139
140 result["check"] = dict(
141 reached=False,
142 msg="Unable to contact the integrated registry using local client. Status=%d, Reason=%s"
143 % (last_bad_status, last_bad_reason),
144 )
145
146 self.exit_json(**result)