areusch commented on code in PR #11329:
URL: https://github.com/apache/tvm/pull/11329#discussion_r876198907


##########
jenkins/Jenkinsfile.j2:
##########
@@ -212,19 +218,21 @@ stage('Lint') {
       )
       skip_ci = should_skip_ci(env.CHANGE_ID)
       skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
-      rebuild_docker_images = sh (
-        returnStatus: true,
-        script: './tests/scripts/git_change_docker.sh',
-        label: 'Check for any docker changes',
-      )
-      if (skip_ci) {
-        // Don't rebuild when skipping CI
-        rebuild_docker_images = false
-      }
-      if (rebuild_docker_images) {
-        // Exit before linting so we can use the newly created Docker images
-        // to run the lint
-        return
+      if (is_first_run) {
+        rebuild_docker_images = sh (

Review Comment:
   should we just factor everything above here into a helper instead of param?



##########
jenkins/Jenkinsfile.j2:
##########
@@ -482,16 +475,29 @@ def cpp_unittest(image) {
   )
 }
 
+def docker_init(image) {
+  if (image.contains("amazon")) {

Review Comment:
   maybe add a comment or change the string to match a longer part of the ecr 
repo name?



##########
tests/scripts/should_rebuild_docker.py:
##########
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3

Review Comment:
   can you add a unit test for this file?



##########
jenkins/Jenkinsfile.j2:
##########
@@ -212,19 +218,21 @@ stage('Lint') {
       )
       skip_ci = should_skip_ci(env.CHANGE_ID)
       skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
-      rebuild_docker_images = sh (
-        returnStatus: true,
-        script: './tests/scripts/git_change_docker.sh',
-        label: 'Check for any docker changes',
-      )
-      if (skip_ci) {
-        // Don't rebuild when skipping CI
-        rebuild_docker_images = false
-      }
-      if (rebuild_docker_images) {
-        // Exit before linting so we can use the newly created Docker images
-        // to run the lint
-        return
+      if (is_first_run) {
+        rebuild_docker_images = sh (

Review Comment:
   should we just factor everything above here into a helper instead of param?



##########
tests/scripts/git_utils.py:
##########
@@ -29,6 +29,18 @@ def compress_query(query: str) -> str:
     return query
 
 
+def get(url: str, headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
+    print("Requesting GET to", url)

Review Comment:
   log.debug?



##########
tests/scripts/should_rebuild_docker.py:
##########
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+# 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.
+import argparse
+import datetime
+from doctest import run_docstring_examples
+import logging
+import subprocess
+
+from typing import Dict, Any, List
+
+
+from git_utils import get
+from cmd_utils import REPO_ROOT, Sh, init_log
+
+
+DOCKER_API_BASE = "https://hub.docker.com/v2/";
+PAGE_SIZE = 25
+
+
+def docker_api(url: str) -> Dict[str, Any]:
+    """
+    Run a paginated fetch from the public Docker Hub API
+    """
+    pagination = f"?page_size={PAGE_SIZE}&page=1"
+    url = DOCKER_API_BASE + url + pagination
+    r, headers = get(url)
+    reset = headers.get("x-ratelimit-reset")
+    if reset is not None:
+        reset = datetime.datetime.fromtimestamp(int(reset))
+        reset = reset.isoformat()
+    logging.info(
+        f"Docker API Rate Limit: {headers.get('x-ratelimit-remaining')} / 
{headers.get('x-ratelimit-limit')} (reset at {reset})"
+    )
+    if "results" not in r:
+        raise RuntimeError(f"Error fetching data, no results found in: {r}")
+    return r
+
+
+def any_docker_changes_since(hash: str) -> bool:
+    """
+    Check the docker/ directory, return True if there have been any code 
changes
+    since the specified hash
+    """
+    sh = Sh(cwd=REPO_ROOT)
+    cmd = f"git diff {hash} -- docker/"
+    proc = sh.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+    stdout = proc.stdout.strip()
+    return stdout != "", stdout
+
+
+def does_commit_exist(hash: str) -> bool:
+    """
+    Returns True if the hash exists in the repo
+    """
+    sh = Sh(cwd=REPO_ROOT)
+    cmd = f"git rev-parse -q {hash}"
+    proc = sh.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
check=False)
+    print(proc.stdout)
+    if proc.returncode == 0:
+        return True
+
+    if "unknown revision or path not in the working tree" in proc.stdout:
+        return False
+
+    raise RuntimeError(f"Unexpected failure when running: {cmd}")
+
+
+def find_hash_for_tag(tag: Dict[str, Any]) -> str:
+    """
+    Split the hash off of a name like <date>-<time>-<hash>
+    """
+    name = tag["name"]
+    name_parts = name.split("-")
+    if len(name_parts) != 3:
+        raise RuntimeError(f"Image {name} is not using new naming scheme")
+    shorthash = name_parts[2]
+    return shorthash
+
+
+def find_commit_in_repo(tags: List[Dict[str, Any]]):
+    """
+    Look through all the docker tags, find the most recent one which references
+    a commit that is present in the repo
+    """
+    for i in range(0, PAGE_SIZE):
+        tag = tags["results"][i]
+        shorthash = find_hash_for_tag(tag)
+        if does_commit_exist(shorthash):
+            return shorthash, tag
+
+    raise RuntimeError(f"No extant hash found in tags:\n{tags}")
+
+
+def main():
+    # Fetch all tlcpack images
+    images = docker_api("repositories/tlcpack")
+
+    # Ignore all non-ci images
+    relevant_images = [image for image in images["results"] if 
image["name"].startswith("ci-")]
+    image_names = [image["name"] for image in relevant_images]
+    # TODO: Delete the ci-wasn and ci_gpu images
+    logging.info(f"Found {len(relevant_images)} images to check: {', 
'.join(image_names)}")
+
+    for image in relevant_images:
+        # Check the tags for the image
+        tags = docker_api(f"repositories/tlcpack/{image['name']}/tags")
+
+        # Find the hash of the most recent tag
+        shorthash, tag = find_commit_in_repo(tags)
+        name = tag["name"]
+        logging.info(f"Looking for docker/ changes since {shorthash}")
+
+        any_docker_changes, diff = any_docker_changes_since(shorthash)
+        if any_docker_changes:
+            logging.info(f"Found docker changes from {shorthash} when checking 
{name}")
+            logging.info(diff)
+            exit(1)
+
+    logging.info("Did not find changes, no rebuild necessary")
+    exit(0)
+
+
+if __name__ == "__main__":
+    init_log()
+    parser = argparse.ArgumentParser(
+        description="Exits 0 if Docker images don't need to be rebuilt, 1 
otherwise"
+    )
+    args = parser.parse_args()
+    # TODO: Just for testing

Review Comment:
   remove



-- 
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