cshuo commented on code in PR #20737:
URL: https://github.com/apache/hudi/pull/20737#discussion_r4643250785


##########
hudi-lakehouse/local-dev/scripts/install.py:
##########
@@ -0,0 +1,286 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+"""Local minikube installation; Python standard library only on the host."""
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+HERE = Path(__file__).resolve().parents[1]
+ROOT = HERE.parent
+NS = 'hudi-lakehouse'
+CONNECT_IMAGE = 'hudi-lakehouse-spark-connect:4.1.3-hudi1.2.0'
+GATEWAY_IMAGE = 'hudi-lakehouse-agent-gateway:0.1.0'
+
+
+def run(args, *, capture=False, check=True, **kwargs):
+    return subprocess.run([str(a) for a in args], text=True, check=check,
+                          stdout=subprocess.PIPE if capture else None, 
**kwargs)
+
+
+def image_values(image, policy):
+    if '@' in image or not re.fullmatch(r'[\w./:-]+:[\w.-]+', image) or ':' 
not in image.rsplit('/', 1)[-1]:
+        raise ValueError('Application images require an explicit 
repository:tag: ' + image)
+    repository, tag = image.rsplit(':', 1)
+    return {'repository': repository, 'tag': tag, 'pullPolicy': policy}
+
+
+class Installation:
+    def __init__(self, args):
+        self.args = args
+        self.profile = args.profile
+        self.kube = ['kubectl', '--context', self.profile, '-n', NS]
+        self.mini = ['minikube', '-p', self.profile]
+        self.env = dict(os.environ, HUDI_KUBE_CONTEXT=self.profile)
+
+    def kubectl(self, *args, **kwargs):
+        return run([*self.kube, *args], **kwargs)
+
+    def exec_script(self, deployment, script, *args, check=True):
+        return self.kubectl('exec', '-i', 'deploy/' + deployment, '--', 
'python3', '-', *args,
+                            input=script.read_text(), check=check)
+
+    def assert_gateway_backend(self):
+        # Do not repoint an existing Trino gateway when selecting an old 
profile.
+        result = self.kubectl('get', 'deployment', 'hudi-agent-gateway',
+                              '--ignore-not-found', '-o', 'json', capture=True)
+        if result.stdout.strip():
+            containers = 
json.loads(result.stdout)['spec']['template']['spec']['containers']
+            env = {e['name']: e.get('value') for c in containers for e in 
c.get('env', [])}
+            if env.get('GATEWAY_SQL_BACKEND') != 'spark-connect':
+                raise ValueError('Existing gateway does not use Spark Connect. 
Use a different --profile to preserve it.')
+
+    def images(self):
+        args = self.args
+        if args.build:
+            run([ROOT / 'scripts/build-connect-image.sh'])
+            if args.connect_image != CONNECT_IMAGE:
+                run(['docker', 'tag', CONNECT_IMAGE, args.connect_image])
+            run(['docker', 'build', '-t', args.gateway_image, ROOT.parent / 
'hudi-agent-gateway'])
+        if args.pull_images:
+            print('Using registry application images (IfNotPresent)', 
flush=True)
+            return
+        cached = json.loads(run([*self.mini, 'image', 'ls', '--format=json'], 
capture=True).stdout)
+
+        def normalize(name):
+            return re.sub(r'^(docker.io/)?library/|^docker.io/', '', name)
+
+        def load_image(image, required):
+            entries = [entry for entry in cached if any(normalize(tag) == 
normalize(image)
+                                                        for tag in 
entry.get('repoTags', []))]
+            local = run(['docker', 'image', 'inspect', image], capture=True,
+                        stderr=subprocess.DEVNULL, check=False)
+            if local.returncode == 0:
+                identity = json.loads(local.stdout)[0]['Id'].split(':')[-1]
+                if any(entry['id'].split(':')[-1] == identity for entry in 
entries):
+                    print(f'Reusing unchanged cluster image {image}', 
flush=True)
+                    return
+                print(f'Loading local image {image}', flush=True)
+                run([*self.mini, 'image', 'load', '--daemon', 
'--overwrite=true', image])
+            elif entries:
+                print(f'Reusing cluster image {image}', flush=True)
+            elif required:
+                raise ValueError(f'Image {image} is absent locally and in this 
profile. '
+                                 'Use up --build, or explicit registry images 
with --pull-images. '
+                                 'Default application tags are not published 
releases.')
+
+        for image in (args.connect_image, args.gateway_image):
+            load_image(image, required=True)
+        # Infrastructure can be pulled by Kubernetes if not present locally.
+        for image in (args.minio_image, args.mc_image, args.hms_image):
+            load_image(image, required=False)
+
+    def up(self):
+        args = self.args
+        # Validate files/images before starting any workloads.
+        policy = 'IfNotPresent' if args.pull_images else 'Never'
+        connect = {'image': image_values(args.connect_image, policy)}
+        gateway = {'image': image_values(args.gateway_image, policy)}
+        for path in (args.connect_values, args.gateway_values):
+            if path and not Path(path).is_file():
+                raise ValueError('Values file does not exist: ' + path)
+        status = run([*self.mini, 'status'], capture=True, check=False, 
stderr=subprocess.DEVNULL)
+        if status.returncode:
+            run([*self.mini, 'start', '--driver', args.driver, '--cpus', 
args.cpus,
+                 '--memory', args.memory, '--keep-context'])
+        else:
+            print(f'Reusing running minikube profile {self.profile}', 
flush=True)
+        self.assert_gateway_backend()
+        self.images()
+        with tempfile.TemporaryDirectory(prefix='hudi-minikube-') as directory:
+            temp = Path(directory)
+            for name, values in (('connect', connect), ('gateway', gateway)):
+                # Helm merges the user's file before installer-owned image 
selection.
+                source = getattr(args, name + '_values')
+                files = ['-f', str(Path(source).resolve())] if source else []
+                image_file = temp / (name + '-image.json')
+                image_file.write_text(json.dumps(values))
+                chart = ROOT / 'charts' / ('hudi-spark-connect' if name == 
'connect' else 'hudi-agent-gateway')
+                image_file = temp / (name + '-image.json')

Review Comment:
   I removed the duplicate block. Spark Connect and Gateway now use the same 
loop to write their image values files.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to