diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..a894e29e --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.ipynb linguist-detectable=false diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 57070739..db952e8e 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -47,7 +47,7 @@ jobs: - name: Run poetry build run: poetry build - name: Create new documentation - run: poetry run pdoc --html -o docs src/codeflare_sdk && pushd docs && rm -rf cluster job utils && mv codeflare_sdk/* . && rm -rf codeflare_sdk && popd + run: poetry run pdoc --html -o docs src/codeflare_sdk && pushd docs && rm -rf cluster job utils && mv codeflare_sdk/* . && rm -rf codeflare_sdk && popd && find docs -type f -name "*.html" -exec bash -c "echo '' >> {}" \; - name: Set Pypi token run: poetry config pypi-token.pypi ${{ secrets.PYPI_TOKEN }} - name: Publish new release to Pypi repository diff --git a/.gitignore b/.gitignore index e4af971d..fbb31b2b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,7 @@ __pycache__/ Pipfile Pipfile.lock poetry.lock +.venv* +build/ +tls-cluster-namespace +quicktest.yaml diff --git a/CodeFlareSDK_Design_Doc.md b/CodeFlareSDK_Design_Doc.md new file mode 100644 index 00000000..0274f65d --- /dev/null +++ b/CodeFlareSDK_Design_Doc.md @@ -0,0 +1,113 @@ +# CodeFlare SDK Design Doc + +## Context and Scope + +The primary purpose for the CodeFlare SDK is to provide a pythonic interaction layer between a user and the CodeFlare Stack (a set of services that enable advanced queuing, resource management and distributed compute on Kubernetes). + +The reason that this SDK is needed is due to the fact that many of the benefits associated with the CodeFlare stack are aimed at making the work of data scientists simpler and more efficient. However, since all parts of the CodeFlare stack are separate Kubernetes services, there needs to be something that unifies the interactions between the user and these separate services. Furthermore, we do not expect the average user to be experienced working with Kubernetes infrastructure, and want to provide them with a Python native way of interacting with these services. + +The SDK should support any operation that a user would need to do in order to successfully submit machine learning training jobs to their kubernetes cluster. + +## Goals + +* Serve as an interaction layer between a data scientist and the CodeFlare Stack (MCAD, InstaScale, KubeRay) +* Abstract away user’s infrastructure concerns; Specifically, dealing with Kubernetes resources, consoles, or CLI’s (kubectl). +* Provide users the ability to programmatically request, monitor, and stop the kubernetes resources associated with the CodeFlare stack. + +## Non-Goals + +* We do not want to re-implement any existing SDK’s or clients for Ray, MCAD, or any other service. + +## Architecture and Design + +The CodeFlare SDK is a python package that allows a user to programmatically define, create, monitor, and shutdown framework clusters (RayClusters for now) as well as define, submit, monitor and cancel distributed training jobs for machine learning models on an authenticated Kubernetes cluster that has the CodeFlare Stack installed. + +In order to achieve this we need the capacity to: + +* Generate valid AppWrapper yaml files based on user provided parameters +* Get, list, watch, create, update, patch, and delete AppWrapper custom resources on a kubernetes cluster +* Get, list, watch, create, update, patch, and delete RayCluster custom resources on a kubernetes cluster. +* Expose a secure route to the Ray Dashboard endpoint. +* Define, submit, monitor and cancel Jobs submitted via TorchX. TorchX jobs must support both Ray and MCAD-Kubernetes scheduler backends. +* Provide means of authenticating to a Kubernetes cluster + +![](/assets/images/sdk-diagram.png) + +### Framework Clusters: + +In order to create these framework clusters, we will start with a [template AppWrapper yaml file](/src/codeflare_sdk/templates/base-template.yaml) with reasonable defaults that will generate a valid RayCluster via MCAD. + +Users can customize their AppWrapper by passing their desired parameters to `ClusterConfig()` and applying that configuration when initializing a `Cluster()` object. When a `Cluster()` is initialized, it will update the AppWrapper template with the user’s specified requirements, and save it to the current working directory. + +Our aim is to simplify the process of generating valid AppWrappers for RayClusters, so we will strive to find the appropriate balance between ease of use and exposing all possible AppWrapper parameters. And we will find this balance through user feedback. + +With a valid AppWrapper, we will use the Kubernetes python client to apply the AppWrapper to our Kubernetes cluster via a call to `cluster.up()` + +We will also use the Kubernetes python client to get information about both the RayCluster and AppWrapper custom resources to monitor the status of our Framework Cluster via `cluster.status()` and `cluster.details()`. + +The RayCluster deployed on your Kubernetes cluster can be interacted with in two ways: Either through an interactive session via `ray.init()` or through the submission of batch jobs. + +Finally we will use the Kubernetes python client to delete the AppWrapper via `cluster.down()` + +### Training Jobs: + +For the submission of Jobs we will rely on the [TorchX](https://pytorch.org/torchx/latest/) job launcher to handle orchestrating the distribution of our model training jobs across the available resources on our cluster. We will support two distributed backend schedulers: Ray and Kubernetes-MCAD. TorchX is designed to be used primarily as a CLI, so we will wrap a limited subset of its functionality into our SDK so that it can be used as part of a python script. + +Users can define their jobs with `DDPJobDefinition()` providing parameters for the script they want to run as part of the job, the resources required for the job, additional args specific to the script being run and scheduler being used. + +Once a job is defined it can be submitted to the Kubernetes cluster to be run via `job.submit()`. If `job.submit()` is left empty the SDK will assume the Kubernetes-MCAD scheduler is being used. If a RayCluster is specified like, `job.submit(cluster)`, then the SDK will assume that the Ray scheduler is being used and submit the job to that RayCluster. + +After the job is submitted, a user can monitor its progress via `job.status()` and `job.logs()` to retrieve the status and logs output by the job. At any point the user can also call `job.cancel()` to stop the job. + +### Authentication: + +Since we are dealing with controlling and accessing different resources on a Kubernetes cluster, the user will need to have certain permissions on that cluster granted to them by their cluster administrator. + +The SDK itself will not enforce any authentication, however, it will provide simple interfaces to allow users to authenticate themselves to their Kubernetes cluster. By default, if a user is already authenticated with a `~/.kube/config` file, that authentication will automatically be picked up by the SDK and no additional authentication is required. + +Users can authorize themselves by calling `TokenAuthentication()` and providing their access token and server address. This will populate the Kubernetes python configuration of the ApiClient object and allow users to be properly authenticated to the cluster. Users are also able to toggle whether or not they want to skip tls verification. + +Alternatively users can provide their own custom kubeconfig file with `KubeConfigFileAuthentication()` and pass it the correct path. + +In either case, users can log out and clear the authentication inputs with `.logout()` + +## Alternatives Considered + +* Ray API Server + * Has no notion of MCAD. Does not support any other backends beside Ray. (However, this may change in the near future) +* Ray Python Client + * Has no notion of MCAD. Does not support any other backends besides Ray +* Existing CodeFlare CLI + * Is not pythonic. +* Nothing (let users define their own AppWrappers manually) + * Antithetical to the purpose of the SDK. + +## Security Considerations + + +We will rely on the Kubernetes cluster’s default security, where users cannot perform any operations on a cluster if they are not authenticated correctly. + +## Testing and Validation + +* Testing plan and strategies + + * Unit testing for all SDK functionality + * Integration testing of SDK interactions with OpenShift and Kubernetes + * System tests of SDK as part of the entire CodeFlare stack for main scenarios +* Unit testing, integration testing, and system testing approaches + * Unit testing will occur with every PR. + * For system testing we can leverage [current e2e](https://github.com/project-codeflare/codeflare-operator/tree/main/test/e2e) tests from the operator repo. +* Validation criteria and expected outcomes + * Minimum of 95% code coverage at all times. + * Expect all unit tests to pass before a PR is merged. + * Expect all integration and system tests to pass before a new release. + +## Deployment and Rollout + +* Deployment strategy and considerations + * The SDK is part of the wider project CodeFlare ecosystem, and serves as the primary interaction layer between the user and the rest of the CodeFlare stack. Therefore, deployment and release strategies cannot occur in isolation, but must take into consideration the current state of the other pieces of the CodeFlare stack (MCAD, KubeRay, Instascale) + +* Versioning and release management + * Releases are performed automatically via a github action. + * The SDK can have minor releases for urgent bug fixes. + * The SDK will normally have a new release alongside the rest of the CodeFlare stack with the same version number. diff --git a/assets/images/sdk-diagram.png b/assets/images/sdk-diagram.png new file mode 100644 index 00000000..adf2a7e1 Binary files /dev/null and b/assets/images/sdk-diagram.png differ diff --git a/coverage.svg b/coverage.svg index ee07d4c2..c1490035 100644 --- a/coverage.svg +++ b/coverage.svg @@ -9,13 +9,13 @@ - + coverage coverage - 96% - 96% + 90% + 90% diff --git a/custom-nb-image/imagestream.yaml b/custom-nb-image/imagestream.yaml index e44c2f09..bd17076f 100644 --- a/custom-nb-image/imagestream.yaml +++ b/custom-nb-image/imagestream.yaml @@ -21,7 +21,7 @@ metadata: annotations: opendatahub.io/notebook-image-name: "CodeFlare Notebook" - opendatahub.io/notebook-image-desc: "Custom Jupyter notebook image with CodeFlare SDK, Python 3.8, Ray 2.1.0 and PyTorch 1.12.1" + opendatahub.io/notebook-image-desc: "Custom Jupyter notebook image with CodeFlare SDK, Python 3.8, Ray 2.5.0 and PyTorch 1.12.1" spec: lookupPolicy: local: true diff --git a/custom-nb-image/requirements.txt b/custom-nb-image/requirements.txt index 17822fab..35b5d559 100644 --- a/custom-nb-image/requirements.txt +++ b/custom-nb-image/requirements.txt @@ -157,7 +157,7 @@ python-json-logger==2.0.4; python_version >= '3.5' pytz==2022.2.1 pyyaml==6.0; python_version >= '3.6' pyzmq==24.0.1; python_version >= '3.6' -ray[default]==2.1.0 +ray[default]==2.5.0 requests-oauthlib==1.3.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' requests==2.28.1; python_version >= '3.7' and python_version < '4' rsa==4.9; python_version >= '3.6' diff --git a/demo-notebooks/batch-job/batch_mnist_ray.ipynb b/demo-notebooks/batch-job/batch_mnist_ray.ipynb index 88b05070..b725bfc5 100644 --- a/demo-notebooks/batch-job/batch_mnist_ray.ipynb +++ b/demo-notebooks/batch-job/batch_mnist_ray.ipynb @@ -63,6 +63,7 @@ " min_memory=16,\n", " max_memory=16,\n", " gpu=4,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", " instascale=True, # Can be set to false if scaling not needed\n", " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"] # Can be removed if above is false\n", "))" @@ -88,7 +89,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "657ebdfb", "metadata": {}, @@ -222,7 +222,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "b3a55fe4", "metadata": {}, @@ -5224,7 +5223,7 @@ ], "metadata": { "kernelspec": { - "display_name": "sdktest", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, diff --git a/demo-notebooks/guided-demos/0_basic_ray.ipynb b/demo-notebooks/guided-demos/0_basic_ray.ipynb index 7daf4b88..338f5730 100644 --- a/demo-notebooks/guided-demos/0_basic_ray.ipynb +++ b/demo-notebooks/guided-demos/0_basic_ray.ipynb @@ -1,7 +1,6 @@ { "cells": [ { - "attachments": {}, "cell_type": "markdown", "id": "8d4a42f6", "metadata": {}, @@ -65,6 +64,7 @@ " max_cpus=1,\n", " min_memory=4,\n", " max_memory=4,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", " gpu=0,\n", " instascale=False\n", "))" @@ -90,7 +90,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "657ebdfb", "metadata": {}, @@ -129,7 +128,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "b3a55fe4", "metadata": {}, @@ -178,7 +176,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -192,7 +190,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.8.13" }, "vscode": { "interpreter": { diff --git a/demo-notebooks/guided-demos/1_basic_instascale.ipynb b/demo-notebooks/guided-demos/1_basic_instascale.ipynb index 8bb86e12..cc5c8224 100644 --- a/demo-notebooks/guided-demos/1_basic_instascale.ipynb +++ b/demo-notebooks/guided-demos/1_basic_instascale.ipynb @@ -1,7 +1,6 @@ { "cells": [ { - "attachments": {}, "cell_type": "markdown", "id": "9865ee8c", "metadata": {}, @@ -38,7 +37,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "bc27f84c", "metadata": {}, @@ -64,13 +62,13 @@ " min_memory=8,\n", " max_memory=8,\n", " gpu=1,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", " instascale=True, # InstaScale now enabled, will scale OCP cluster to guarantee resource request\n", " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"] # Head, worker AWS machine types desired\n", "))" ] }, { - "attachments": {}, "cell_type": "markdown", "id": "12eef53c", "metadata": {}, @@ -91,7 +89,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "6abfe904", "metadata": {}, @@ -130,7 +127,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "c883caea", "metadata": {}, @@ -151,7 +147,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -165,7 +161,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.8.13" }, "vscode": { "interpreter": { diff --git a/demo-notebooks/guided-demos/2_basic_jobs.ipynb b/demo-notebooks/guided-demos/2_basic_jobs.ipynb index 37560b17..3fe46a8a 100644 --- a/demo-notebooks/guided-demos/2_basic_jobs.ipynb +++ b/demo-notebooks/guided-demos/2_basic_jobs.ipynb @@ -1,7 +1,6 @@ { "cells": [ { - "attachments": {}, "cell_type": "markdown", "id": "464af595", "metadata": {}, @@ -38,7 +37,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "bc27f84c", "metadata": {}, @@ -64,6 +62,7 @@ " min_memory=4,\n", " max_memory=4,\n", " gpu=0,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", " instascale=False\n", "))" ] @@ -91,7 +90,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "33663f47", "metadata": {}, @@ -110,7 +108,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "83d77b74", "metadata": {}, @@ -134,7 +131,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "5b9ae53a", "metadata": {}, @@ -163,7 +159,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "5af8cd32", "metadata": {}, @@ -182,7 +177,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "31096641", "metadata": {}, @@ -211,7 +205,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "0837e43b", "metadata": {}, @@ -240,7 +233,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "aebf376a", "metadata": {}, @@ -271,7 +263,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -285,7 +277,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.8.13" }, "vscode": { "interpreter": { diff --git a/demo-notebooks/guided-demos/3_basic_interactive.ipynb b/demo-notebooks/guided-demos/3_basic_interactive.ipynb index 4a1b0f6f..9ffed0c7 100644 --- a/demo-notebooks/guided-demos/3_basic_interactive.ipynb +++ b/demo-notebooks/guided-demos/3_basic_interactive.ipynb @@ -62,6 +62,7 @@ " min_memory=8,\n", " max_memory=8,\n", " gpu=1,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", " instascale=True,\n", " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"]\n", " \n", @@ -138,7 +139,7 @@ "ray.shutdown()\n", "# establish connection to ray cluster\n", "\n", - "#install additionall libraries that will be required for model training\n", + "#install additional libraries that will be required for model training\n", "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\", \"pyarrow<7.0.0\", \"accelerate\"]}\n", "\n", "ray.init(address=f'{ray_cluster_uri}', runtime_env=runtime_env)\n", @@ -275,7 +276,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -289,7 +290,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.8.13" }, "vscode": { "interpreter": { diff --git a/demo-notebooks/guided-demos/4_gpt.ipynb b/demo-notebooks/guided-demos/4_gpt.ipynb index 0132bd4a..e489c9bc 100644 --- a/demo-notebooks/guided-demos/4_gpt.ipynb +++ b/demo-notebooks/guided-demos/4_gpt.ipynb @@ -45,6 +45,7 @@ " min_memory=8,\n", " max_memory=8,\n", " gpu=1,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", " instascale=True,\n", " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"],\n", "))" diff --git a/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb b/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb index df4c3a94..ebcb52a6 100644 --- a/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb +++ b/demo-notebooks/guided-demos/notebook-ex-outputs/3_basic_interactive.ipynb @@ -230,7 +230,7 @@ "ray.shutdown()\n", "# establish connection to ray cluster\n", "\n", - "#install additionall libraries that will be required for model training\n", + "#install additional libraries that will be required for model training\n", "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\", \"pyarrow<7.0.0\", \"accelerate\"]}\n", "\n", "ray.init(address=f'{ray_cluster_uri}', runtime_env=runtime_env)\n", diff --git a/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb new file mode 100644 index 00000000..b3040676 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/0_basic_ray.ipynb @@ -0,0 +1,202 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8d4a42f6", + "metadata": {}, + "source": [ + "In this first notebook, we will go through the basics of using the SDK to:\n", + " - Spin up a Ray cluster with our desired resources\n", + " - View the status and specs of our Ray cluster\n", + " - Take down the Ray cluster when finished" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "Here, we want to define our cluster by specifying the resources we require for our batch workload. Below, we define our cluster object (which generates a corresponding AppWrapper)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='raytest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=1,\n", + " max_cpus=1,\n", + " min_memory=4,\n", + " max_memory=4,\n", + " num_gpus=0,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\", #current default\n", + " instascale=False\n", + "))" + ] + }, + { + "cell_type": "markdown", + "id": "12eef53c", + "metadata": {}, + "source": [ + "Next, we want to bring our cluster up, so we call the `up()` function below to submit our cluster AppWrapper yaml onto the MCAD queue, and begin the process of obtaining our resource cluster." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()" + ] + }, + { + "cell_type": "markdown", + "id": "657ebdfb", + "metadata": {}, + "source": [ + "Now, we want to check on the status of our resource cluster, and wait until it is finally ready for use." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c1b4311-2e61-44c9-8225-87c2db11363d", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a99d5aff", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df71c1ed", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.status()" + ] + }, + { + "cell_type": "markdown", + "id": "b3a55fe4", + "metadata": {}, + "source": [ + "Let's quickly verify that the specs of the cluster are as expected." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7fd45bc5-03c0-4ae5-9ec5-dd1c30f1a084", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Finally, we bring our resource cluster down and release/terminate the associated resources, bringing everything back to the way it was before our cluster was brought up." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb b/demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb new file mode 100644 index 00000000..8f8a6ed7 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/1_basic_instascale.ipynb @@ -0,0 +1,172 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "9865ee8c", + "metadata": {}, + "source": [ + "In this second notebook, we will go over the basics of using InstaScale to scale up/down necessary resources that are not currently available on your OpenShift Cluster (in cloud environments)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "This time, we are working in a cloud environment, and our OpenShift cluster does not have the resources needed for our desired workloads. We will use InstaScale to dynamically scale-up guaranteed resources based on our request (that will also automatically scale-down when we are finished working):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='instascaletest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=2,\n", + " max_cpus=2,\n", + " min_memory=8,\n", + " max_memory=8,\n", + " num_gpus=1,\n", + " instascale=True, # InstaScale now enabled, will scale OCP cluster to guarantee resource request\n", + " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"] # Head, worker AWS machine types desired\n", + "))" + ] + }, + { + "cell_type": "markdown", + "id": "12eef53c", + "metadata": {}, + "source": [ + "Same as last time, we will bring the cluster up, wait for it to be ready, and confirm that the specs are as-requested:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()\n", + "cluster.wait_ready()" + ] + }, + { + "cell_type": "markdown", + "id": "6abfe904", + "metadata": {}, + "source": [ + "While the resources are being scaled, we can also go into the console and take a look at the InstaScale logs, as well as the new machines/nodes spinning up.\n", + "\n", + "Once the cluster is ready, we can confirm the specs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7fd45bc5-03c0-4ae5-9ec5-dd1c30f1a084", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Finally, we bring our resource cluster down and release/terminate the associated resources, bringing everything back to the way it was before our cluster was brought up." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "markdown", + "id": "c883caea", + "metadata": {}, + "source": [ + "Once again, we can look at the machines/nodes and see that everything has been successfully scaled down!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb b/demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb new file mode 100644 index 00000000..eb924715 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/2_basic_jobs.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "464af595", + "metadata": {}, + "source": [ + "In this third notebook, we will go over the basics of submitting jobs via the SDK, either to a Ray cluster or directly to MCAD." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "Let's start by running through the same cluster setup as before:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='jobtest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=1,\n", + " max_cpus=1,\n", + " min_memory=4,\n", + " max_memory=4,\n", + " num_gpus=0,\n", + " instascale=False\n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()\n", + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df71c1ed", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "33663f47", + "metadata": {}, + "source": [ + "This time, however, we are going to use the CodeFlare SDK to submit batch jobs via TorchX, either to the Ray cluster we have just brought up, or directly to MCAD." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c7b4f232", + "metadata": {}, + "outputs": [], + "source": [ + "from codeflare_sdk.job.jobs import DDPJobDefinition" + ] + }, + { + "cell_type": "markdown", + "id": "83d77b74", + "metadata": {}, + "source": [ + "First, let's begin by submitting to Ray, training a basic NN on the MNIST dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8c2c5138", + "metadata": {}, + "outputs": [], + "source": [ + "jobdef = DDPJobDefinition(\n", + " name=\"mnisttest\",\n", + " script=\"mnist.py\",\n", + " scheduler_args={\"requirements\": \"requirements.txt\"}\n", + ")\n", + "job = jobdef.submit(cluster)" + ] + }, + { + "cell_type": "markdown", + "id": "5b9ae53a", + "metadata": {}, + "source": [ + "Now we can take a look at the status of our submitted job, as well as the logs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e36c3d9", + "metadata": {}, + "outputs": [], + "source": [ + "job.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "834cfb5c", + "metadata": {}, + "outputs": [], + "source": [ + "job.logs()" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Once complete, we can bring our Ray cluster down and clean up:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "markdown", + "id": "31096641", + "metadata": {}, + "source": [ + "Now, an alternative option for job submission is to submit directly to MCAD, which will schedule pods to run the job with requested resources:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "496139cc", + "metadata": {}, + "outputs": [], + "source": [ + "jobdef = DDPJobDefinition(\n", + " name=\"mnistjob\",\n", + " script=\"mnist.py\",\n", + " scheduler_args={\"namespace\": \"default\"},\n", + " j=\"1x1\",\n", + " gpu=0,\n", + " cpu=1,\n", + " memMB=8000,\n", + " image=\"quay.io/project-codeflare/mnist-job-test:v0.0.1\"\n", + ")\n", + "job = jobdef.submit()" + ] + }, + { + "cell_type": "markdown", + "id": "0837e43b", + "metadata": {}, + "source": [ + "Once again, we can look at job status and logs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d18d42c", + "metadata": {}, + "outputs": [], + "source": [ + "job.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "36d7ea97", + "metadata": {}, + "outputs": [], + "source": [ + "job.logs()" + ] + }, + { + "cell_type": "markdown", + "id": "aebf376a", + "metadata": {}, + "source": [ + "This time, once the pods complete, we can clean them up alongside any other associated resources. The following command can also be used to delete jobs early for both Ray and MCAD submission:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ebbb0674", + "metadata": {}, + "outputs": [], + "source": [ + "job.cancel()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb b/demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb new file mode 100644 index 00000000..73eff977 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/3_basic_interactive.ipynb @@ -0,0 +1,301 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "bbc21043", + "metadata": {}, + "source": [ + "In this fourth and final notebook, we will go over how to leverage the SDK to directly work interactively with a Ray cluster during development." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b55bc3ea-4ce3-49bf-bb1f-e209de8ca47a", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "614daa0c", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "markdown", + "id": "bc27f84c", + "metadata": {}, + "source": [ + "Once again, let's start by running through the same cluster setup as before:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f4bc870-091f-4e11-9642-cba145710159", + "metadata": {}, + "outputs": [], + "source": [ + "# Create and configure our cluster object (and appwrapper)\n", + "cluster = Cluster(ClusterConfiguration(\n", + " name='interactivetest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=2,\n", + " max_cpus=2,\n", + " min_memory=8,\n", + " max_memory=8,\n", + " num_gpus=1,\n", + " instascale=True,\n", + " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"]\n", + " \n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0884bbc-c224-4ca0-98a0-02dfa09c2200", + "metadata": {}, + "outputs": [], + "source": [ + "# Bring up the cluster\n", + "cluster.up()\n", + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df71c1ed", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "markdown", + "id": "33663f47", + "metadata": {}, + "source": [ + "This time we will demonstrate another potential method of use: working with the Ray cluster interactively.\n", + "\n", + "Using the SDK, we can get both the Ray cluster URI and dashboard URI:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c1719bca", + "metadata": {}, + "outputs": [], + "source": [ + "ray_dashboard_uri = cluster.cluster_dashboard_uri()\n", + "ray_cluster_uri = cluster.cluster_uri()\n", + "print(ray_dashboard_uri)\n", + "print(ray_cluster_uri)" + ] + }, + { + "cell_type": "markdown", + "id": "2a2aca6a", + "metadata": {}, + "source": [ + "Now we can connect directly to our Ray cluster via the Ray python client:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "300146dc", + "metadata": {}, + "outputs": [], + "source": [ + "#before proceeding make sure the cluster exists and the uri is not empty\n", + "assert ray_cluster_uri, \"Ray cluster needs to be started and set before proceeding\"\n", + "\n", + "import ray\n", + "from ray.air.config import ScalingConfig\n", + "\n", + "# reset the ray context in case there's already one. \n", + "ray.shutdown()\n", + "# establish connection to ray cluster\n", + "\n", + "#install additional libraries that will be required for model training\n", + "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\", \"pyarrow<7.0.0\", \"accelerate\"]}\n", + "\n", + "ray.init(address=f'{ray_cluster_uri}', runtime_env=runtime_env)\n", + "\n", + "print(\"Ray cluster is up and running: \", ray.is_initialized())" + ] + }, + { + "cell_type": "markdown", + "id": "9711030b", + "metadata": {}, + "source": [ + "Now that we are connected (and have passed in some package requirements), let's try writing some training code for a DistilBERT transformer model via HuggingFace (using IMDB dataset):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1b36e0d9", + "metadata": {}, + "outputs": [], + "source": [ + "@ray.remote\n", + "def train_fn():\n", + " from datasets import load_dataset\n", + " import transformers\n", + " from transformers import AutoTokenizer, TrainingArguments\n", + " from transformers import AutoModelForSequenceClassification\n", + " import numpy as np\n", + " from datasets import load_metric\n", + " import ray\n", + " from ray import tune\n", + " from ray.train.huggingface import HuggingFaceTrainer\n", + "\n", + " dataset = load_dataset(\"imdb\")\n", + " tokenizer = AutoTokenizer.from_pretrained(\"distilbert-base-uncased\")\n", + "\n", + " def tokenize_function(examples):\n", + " return tokenizer(examples[\"text\"], padding=\"max_length\", truncation=True)\n", + "\n", + " tokenized_datasets = dataset.map(tokenize_function, batched=True)\n", + "\n", + " #using a fraction of dataset but you can run with the full dataset\n", + " small_train_dataset = tokenized_datasets[\"train\"].shuffle(seed=42).select(range(100))\n", + " small_eval_dataset = tokenized_datasets[\"test\"].shuffle(seed=42).select(range(100))\n", + "\n", + " print(f\"len of train {small_train_dataset} and test {small_eval_dataset}\")\n", + "\n", + " ray_train_ds = ray.data.from_huggingface(small_train_dataset)\n", + " ray_evaluation_ds = ray.data.from_huggingface(small_eval_dataset)\n", + "\n", + " def compute_metrics(eval_pred):\n", + " metric = load_metric(\"accuracy\")\n", + " logits, labels = eval_pred\n", + " predictions = np.argmax(logits, axis=-1)\n", + " return metric.compute(predictions=predictions, references=labels)\n", + "\n", + " def trainer_init_per_worker(train_dataset, eval_dataset, **config):\n", + " model = AutoModelForSequenceClassification.from_pretrained(\"distilbert-base-uncased\", num_labels=2)\n", + "\n", + " training_args = TrainingArguments(\"/tmp/hf_imdb/test\", eval_steps=1, disable_tqdm=True, \n", + " num_train_epochs=1, skip_memory_metrics=True,\n", + " learning_rate=2e-5,\n", + " per_device_train_batch_size=16,\n", + " per_device_eval_batch_size=16, \n", + " weight_decay=0.01,)\n", + " return transformers.Trainer(\n", + " model=model,\n", + " args=training_args,\n", + " train_dataset=train_dataset,\n", + " eval_dataset=eval_dataset,\n", + " compute_metrics=compute_metrics\n", + " )\n", + "\n", + " scaling_config = ScalingConfig(num_workers=2, use_gpu=True) #num workers is the number of gpus\n", + "\n", + " # we are using the ray native HuggingFaceTrainer, but you can swap out to use non ray Huggingface Trainer. Both have the same method signature. \n", + " # the ray native HFTrainer has built in support for scaling to multiple GPUs\n", + " trainer = HuggingFaceTrainer(\n", + " trainer_init_per_worker=trainer_init_per_worker,\n", + " scaling_config=scaling_config,\n", + " datasets={\"train\": ray_train_ds, \"evaluation\": ray_evaluation_ds},\n", + " )\n", + " result = trainer.fit()" + ] + }, + { + "cell_type": "markdown", + "id": "d4d8fd65", + "metadata": {}, + "source": [ + "Once we want to test our code out, we can run the training function we defined above remotely on our Ray cluster:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5901d958", + "metadata": {}, + "outputs": [], + "source": [ + "#call the above cell as a remote ray function\n", + "ray.get(train_fn.remote())" + ] + }, + { + "cell_type": "markdown", + "id": "5af8cd32", + "metadata": {}, + "source": [ + "Once complete, we can bring our Ray cluster down and clean up:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f36db0f-31f6-4373-9503-dc3c1c4c3f57", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d41b90e", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.13" + }, + "vscode": { + "interpreter": { + "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb b/demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb new file mode 100644 index 00000000..919f8f0a --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/4_gpt.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "b6c05b69-4ce8-45ef-82d3-bacb2491bee8", + "metadata": {}, + "outputs": [], + "source": [ + "# Import pieces from codeflare-sdk\n", + "from codeflare_sdk.cluster.cluster import Cluster, ClusterConfiguration\n", + "from codeflare_sdk.cluster.auth import TokenAuthentication" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "32f99bbd-9903-4d38-a4f2-223dec684ae2", + "metadata": {}, + "outputs": [], + "source": [ + "# Create authentication object for oc user permissions\n", + "auth = TokenAuthentication(\n", + " token = \"XXXXX\",\n", + " server = \"XXXXX\",\n", + " skip_tls=False\n", + ")\n", + "auth.login()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f32119a-c4ee-4163-b103-d9ca3bddbdb5", + "metadata": {}, + "outputs": [], + "source": [ + "cluster = Cluster(ClusterConfiguration(\n", + " name='gptfttest',\n", + " namespace='default',\n", + " num_workers=2,\n", + " min_cpus=2,\n", + " max_cpus=2,\n", + " min_memory=8,\n", + " max_memory=8,\n", + " num_gpus=1,\n", + " instascale=True,\n", + " machine_types=[\"m5.xlarge\", \"g4dn.xlarge\"],\n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "107c8277-3b3b-4238-a786-a391a662fd7c", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.up()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "730f66ce-adaa-4709-b9cf-22417847e059", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.wait_ready()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48fac218-2f22-428b-9228-137a4bb0e666", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.details()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ed5bd75-4230-4c7c-a9e2-0f247890e62a", + "metadata": {}, + "outputs": [], + "source": [ + "from codeflare_sdk.job.jobs import DDPJobDefinition" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "611d203a-35aa-4357-a748-1d01b022fcdb", + "metadata": {}, + "outputs": [], + "source": [ + "arg_list = [\n", + " \"--model_name_or_path\", \"gpt2\",\n", + " \"--dataset_name\", \"wikitext\",\n", + " \"--dataset_config_name\", \"wikitext-2-raw-v1\",\n", + " \"--per_device_train_batch_size\", \"2\",\n", + " \"--per_device_eval_batch_size\", \"2\",\n", + " \"--do_train\",\n", + " \"--do_eval\",\n", + " \"--output_dir\", \"/tmp/test-clm\",\n", + " \"--overwrite_output_dir\"\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8ac7c34f-e227-44c2-a4b1-a57c853ac3a7", + "metadata": {}, + "outputs": [], + "source": [ + "jobdef = DDPJobDefinition(\n", + " name=\"gpttest\",\n", + " script=\"gpt_og.py\",\n", + " script_args=arg_list,\n", + " scheduler_args={\"requirements\": \"requirements_gpt.txt\"}\n", + ")\n", + "job = jobdef.submit(cluster)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1680d287-de46-45f8-b95a-02ba3c83912c", + "metadata": {}, + "outputs": [], + "source": [ + "job.status()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d25d6198-9941-47e8-857f-9811830cc854", + "metadata": {}, + "outputs": [], + "source": [ + "job.logs()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "beb1a6b9-d9b3-49b7-b036-09f1d3569b59", + "metadata": {}, + "outputs": [], + "source": [ + "cluster.down()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8398d977-db24-46d0-a7d2-b4e9197808d7", + "metadata": {}, + "outputs": [], + "source": [ + "auth.logout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/demo-notebooks/guided-demos/preview_nbs/gpt_og.py b/demo-notebooks/guided-demos/preview_nbs/gpt_og.py new file mode 100644 index 00000000..d69e41fc --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/gpt_og.py @@ -0,0 +1,728 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. All rights reserved. +# +# Licensed 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. +""" +Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset. + +Here is the full list of checkpoints on the hub that can be fine-tuned by this script: +https://huggingface.co/models?filter=text-generation +""" +# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments. + +import subprocess + +subprocess.run(["pip", "uninstall", "protobuf"]) +subprocess.run( + [ + "pip", + "install", + "--upgrade", + "--target=/home/ray/workspace", + "-r", + "requirements.txt", + ] +) + +import logging +import math +import os +import sys +from dataclasses import dataclass, field +from itertools import chain +from typing import Optional + +import datasets +import evaluate +import torch +from datasets import load_dataset + +import transformers +from transformers import ( + CONFIG_MAPPING, + MODEL_FOR_CAUSAL_LM_MAPPING, + AutoConfig, + AutoModelForCausalLM, + AutoTokenizer, + HfArgumentParser, + Trainer, + TrainingArguments, + default_data_collator, + is_torch_tpu_available, + set_seed, +) +from transformers.testing_utils import CaptureLogger +from transformers.trainer_utils import get_last_checkpoint +from transformers.utils import check_min_version, send_example_telemetry +from transformers.utils.versions import require_version + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +# check_min_version("4.29.0.dev0") + +require_version( + "datasets>=1.8.0", + "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt", +) + +logger = logging.getLogger(__name__) + + +MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. + """ + + model_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch." + ) + }, + ) + model_type: Optional[str] = field( + default=None, + metadata={ + "help": "If training from scratch, pass a model type from the list: " + + ", ".join(MODEL_TYPES) + }, + ) + config_overrides: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override some existing default config settings when a model is trained from scratch. Example: " + "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" + ) + }, + ) + config_name: Optional[str] = field( + default=None, + metadata={ + "help": "Pretrained config name or path if not the same as model_name" + }, + ) + tokenizer_name: Optional[str] = field( + default=None, + metadata={ + "help": "Pretrained tokenizer name or path if not the same as model_name" + }, + ) + cache_dir: Optional[str] = field( + default=None, + metadata={ + "help": "Where do you want to store the pretrained models downloaded from huggingface.co" + }, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={ + "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not." + }, + ) + model_revision: str = field( + default="main", + metadata={ + "help": "The specific model version to use (can be a branch name, tag name or commit id)." + }, + ) + use_auth_token: bool = field( + default=False, + metadata={ + "help": ( + "Will use the token generated when running `huggingface-cli login` (necessary to use this script " + "with private models)." + ) + }, + ) + torch_dtype: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " + "dtype will be automatically derived from the model's weights." + ), + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + low_cpu_mem_usage: bool = field( + default=False, + metadata={ + "help": ( + "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded." + "set True will benefit LLM loading time and RAM consumption." + ) + }, + ) + + def __post_init__(self): + if self.config_overrides is not None and ( + self.config_name is not None or self.model_name_or_path is not None + ): + raise ValueError( + "--config_overrides can't be used in combination with --config_name or --model_name_or_path" + ) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + dataset_name: Optional[str] = field( + default=None, + metadata={"help": "The name of the dataset to use (via the datasets library)."}, + ) + dataset_config_name: Optional[str] = field( + default=None, + metadata={ + "help": "The configuration name of the dataset to use (via the datasets library)." + }, + ) + train_file: Optional[str] = field( + default=None, metadata={"help": "The input training data file (a text file)."} + ) + validation_file: Optional[str] = field( + default=None, + metadata={ + "help": "An optional input evaluation data file to evaluate the perplexity on (a text file)." + }, + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_eval_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of evaluation examples to this " + "value if set." + ) + }, + ) + streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"}) + block_size: Optional[int] = field( + default=None, + metadata={ + "help": ( + "Optional input sequence length after tokenization. " + "The training dataset will be truncated in block of this size for training. " + "Default to the model max input length for single sentence inputs (take into account special tokens)." + ) + }, + ) + overwrite_cache: bool = field( + default=False, + metadata={"help": "Overwrite the cached training and evaluation sets"}, + ) + validation_split_percentage: Optional[int] = field( + default=5, + metadata={ + "help": "The percentage of the train set used as validation set in case there's no validation split" + }, + ) + preprocessing_num_workers: Optional[int] = field( + default=None, + metadata={"help": "The number of processes to use for the preprocessing."}, + ) + keep_linebreaks: bool = field( + default=True, + metadata={"help": "Whether to keep line breaks when using TXT files or not."}, + ) + + def __post_init__(self): + if self.streaming: + require_version( + "datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`" + ) + + if ( + self.dataset_name is None + and self.train_file is None + and self.validation_file is None + ): + raise ValueError( + "Need either a dataset name or a training/validation file." + ) + else: + if self.train_file is not None: + extension = self.train_file.split(".")[-1] + assert extension in [ + "csv", + "json", + "txt", + ], "`train_file` should be a csv, a json or a txt file." + if self.validation_file is not None: + extension = self.validation_file.split(".")[-1] + assert extension in [ + "csv", + "json", + "txt", + ], "`validation_file` should be a csv, a json or a txt file." + + +def main(): + # See all possible arguments in src/transformers/training_args.py + # or by passing the --help flag to this script. + # We now keep distinct sets of args, for a cleaner separation of concerns. + + parser = HfArgumentParser( + (ModelArguments, DataTrainingArguments, TrainingArguments) + ) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file( + json_file=os.path.abspath(sys.argv[1]) + ) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The + # information sent is the one passed as arguments along with your Python/PyTorch versions. + send_example_telemetry("run_clm", model_args, data_args) + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + + if training_args.should_log: + # The default of training_args.log_level is passive, so we set log level at info here to have that default. + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + datasets.utils.logging.set_verbosity(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Training/evaluation parameters {training_args}") + + # Detecting last checkpoint. + last_checkpoint = None + if ( + os.path.isdir(training_args.output_dir) + and training_args.do_train + and not training_args.overwrite_output_dir + ): + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif ( + last_checkpoint is not None and training_args.resume_from_checkpoint is None + ): + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + # Set seed before initializing model. + set_seed(training_args.seed) + + # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called + # 'text' is found. You can easily tweak this behavior (see below). + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if data_args.dataset_name is not None: + # Downloading and loading a dataset from the hub. + raw_datasets = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + streaming=data_args.streaming, + ) + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + streaming=data_args.streaming, + ) + raw_datasets["train"] = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + streaming=data_args.streaming, + ) + else: + data_files = {} + dataset_args = {} + if data_args.train_file is not None: + data_files["train"] = data_args.train_file + if data_args.validation_file is not None: + data_files["validation"] = data_args.validation_file + extension = ( + data_args.train_file.split(".")[-1] + if data_args.train_file is not None + else data_args.validation_file.split(".")[-1] + ) + if extension == "txt": + extension = "text" + dataset_args["keep_linebreaks"] = data_args.keep_linebreaks + raw_datasets = load_dataset( + extension, + data_files=data_files, + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + **dataset_args, + ) + # If no validation data is there, validation_split_percentage will be used to divide the dataset. + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + extension, + data_files=data_files, + split=f"train[:{data_args.validation_split_percentage}%]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + **dataset_args, + ) + raw_datasets["train"] = load_dataset( + extension, + data_files=data_files, + split=f"train[{data_args.validation_split_percentage}%:]", + cache_dir=model_args.cache_dir, + use_auth_token=True if model_args.use_auth_token else None, + **dataset_args, + ) + + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at + # https://huggingface.co/docs/datasets/loading_datasets.html. + + # Load pretrained model and tokenizer + # + # Distributed training: + # The .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + + config_kwargs = { + "cache_dir": model_args.cache_dir, + "revision": model_args.model_revision, + "use_auth_token": True if model_args.use_auth_token else None, + } + if model_args.config_name: + config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) + elif model_args.model_name_or_path: + config = AutoConfig.from_pretrained( + model_args.model_name_or_path, **config_kwargs + ) + else: + config = CONFIG_MAPPING[model_args.model_type]() + logger.warning("You are instantiating a new config instance from scratch.") + if model_args.config_overrides is not None: + logger.info(f"Overriding config: {model_args.config_overrides}") + config.update_from_string(model_args.config_overrides) + logger.info(f"New config: {config}") + + tokenizer_kwargs = { + "cache_dir": model_args.cache_dir, + "use_fast": model_args.use_fast_tokenizer, + "revision": model_args.model_revision, + "use_auth_token": True if model_args.use_auth_token else None, + } + if model_args.tokenizer_name: + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name, **tokenizer_kwargs + ) + elif model_args.model_name_or_path: + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, **tokenizer_kwargs + ) + else: + raise ValueError( + "You are instantiating a new tokenizer from scratch. This is not supported by this script." + "You can do it from another script, save it, and load it from here, using --tokenizer_name." + ) + + if model_args.model_name_or_path: + torch_dtype = ( + model_args.torch_dtype + if model_args.torch_dtype in ["auto", None] + else getattr(torch, model_args.torch_dtype) + ) + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + use_auth_token=True if model_args.use_auth_token else None, + torch_dtype=torch_dtype, + low_cpu_mem_usage=model_args.low_cpu_mem_usage, + ) + else: + model = AutoModelForCausalLM.from_config(config) + n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) + logger.info( + f"Training new model from scratch - Total size={n_params/2**20:.2f}M params" + ) + + # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch + # on a small vocab and want a smaller embedding size, remove this test. + embedding_size = model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + model.resize_token_embeddings(len(tokenizer)) + + # Preprocessing the datasets. + # First we tokenize all the texts. + if training_args.do_train: + column_names = list(raw_datasets["train"].features) + else: + column_names = list(raw_datasets["validation"].features) + text_column_name = "text" if "text" in column_names else column_names[0] + + # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function + tok_logger = transformers.utils.logging.get_logger( + "transformers.tokenization_utils_base" + ) + + def tokenize_function(examples): + with CaptureLogger(tok_logger) as cl: + output = tokenizer(examples[text_column_name]) + # clm input could be much much longer than block_size + if "Token indices sequence length is longer than the" in cl.out: + tok_logger.warning( + "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits" + " before being passed to the model." + ) + return output + + with training_args.main_process_first(desc="dataset map tokenization"): + if not data_args.streaming: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + else: + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + remove_columns=column_names, + ) + + if data_args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > 1024: + logger.warning( + "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" + " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" + " override this default with `--block_size xxx`." + ) + block_size = 1024 + else: + if data_args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model" + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(data_args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can + # customize this part to your needs. + if total_length >= block_size: + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + result["labels"] = result["input_ids"].copy() + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + # + # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: + # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map + + with training_args.main_process_first(desc="grouping texts together"): + if not data_args.streaming: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=data_args.preprocessing_num_workers, + load_from_cache_file=not data_args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + else: + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + ) + + if training_args.do_train: + if "train" not in tokenized_datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = lm_datasets["train"] + if data_args.max_train_samples is not None: + max_train_samples = min(len(train_dataset), data_args.max_train_samples) + train_dataset = train_dataset.select(range(max_train_samples)) + + if training_args.do_eval: + if "validation" not in tokenized_datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = lm_datasets["validation"] + if data_args.max_eval_samples is not None: + max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) + eval_dataset = eval_dataset.select(range(max_eval_samples)) + + def preprocess_logits_for_metrics(logits, labels): + if isinstance(logits, tuple): + # Depending on the model and config, logits may contain extra tensors, + # like past_key_values, but logits always come first + logits = logits[0] + return logits.argmax(dim=-1) + + metric = evaluate.load("accuracy") + + def compute_metrics(eval_preds): + preds, labels = eval_preds + # preds have the same shape as the labels, after the argmax(-1) has been calculated + # by preprocess_logits_for_metrics but we need to shift the labels + labels = labels[:, 1:].reshape(-1) + preds = preds[:, :-1].reshape(-1) + return metric.compute(predictions=preds, references=labels) + + # Initialize our Trainer + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + tokenizer=tokenizer, + # Data collator will default to DataCollatorWithPadding, so we change it. + data_collator=default_data_collator, + compute_metrics=compute_metrics + if training_args.do_eval and not is_torch_tpu_available() + else None, + preprocess_logits_for_metrics=preprocess_logits_for_metrics + if training_args.do_eval and not is_torch_tpu_available() + else None, + ) + + # Training + if training_args.do_train: + checkpoint = None + if training_args.resume_from_checkpoint is not None: + checkpoint = training_args.resume_from_checkpoint + elif last_checkpoint is not None: + checkpoint = last_checkpoint + train_result = trainer.train(resume_from_checkpoint=checkpoint) + trainer.save_model() # Saves the tokenizer too for easy upload + + metrics = train_result.metrics + + max_train_samples = ( + data_args.max_train_samples + if data_args.max_train_samples is not None + else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + # Evaluation + if training_args.do_eval: + logger.info("*** Evaluate ***") + + metrics = trainer.evaluate() + + max_eval_samples = ( + data_args.max_eval_samples + if data_args.max_eval_samples is not None + else len(eval_dataset) + ) + metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) + try: + perplexity = math.exp(metrics["eval_loss"]) + except OverflowError: + perplexity = float("inf") + metrics["perplexity"] = perplexity + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + kwargs = { + "finetuned_from": model_args.model_name_or_path, + "tasks": "text-generation", + } + if data_args.dataset_name is not None: + kwargs["dataset_tags"] = data_args.dataset_name + if data_args.dataset_config_name is not None: + kwargs["dataset_args"] = data_args.dataset_config_name + kwargs[ + "dataset" + ] = f"{data_args.dataset_name} {data_args.dataset_config_name}" + else: + kwargs["dataset"] = data_args.dataset_name + + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/demo-notebooks/guided-demos/preview_nbs/mnist.py b/demo-notebooks/guided-demos/preview_nbs/mnist.py new file mode 100644 index 00000000..6eb663dc --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/mnist.py @@ -0,0 +1,160 @@ +# Copyright 2022 IBM, Red Hat +# +# Licensed 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. + +# In[] +import os + +import torch +from pytorch_lightning import LightningModule, Trainer +from pytorch_lightning.callbacks.progress import TQDMProgressBar +from pytorch_lightning.loggers import CSVLogger +from torch import nn +from torch.nn import functional as F +from torch.utils.data import DataLoader, random_split +from torchmetrics import Accuracy +from torchvision import transforms +from torchvision.datasets import MNIST + +PATH_DATASETS = os.environ.get("PATH_DATASETS", ".") +BATCH_SIZE = 256 if torch.cuda.is_available() else 64 +# %% + +print("prior to running the trainer") +print("MASTER_ADDR: is ", os.getenv("MASTER_ADDR")) +print("MASTER_PORT: is ", os.getenv("MASTER_PORT")) + + +class LitMNIST(LightningModule): + def __init__(self, data_dir=PATH_DATASETS, hidden_size=64, learning_rate=2e-4): + super().__init__() + + # Set our init args as class attributes + self.data_dir = data_dir + self.hidden_size = hidden_size + self.learning_rate = learning_rate + + # Hardcode some dataset specific attributes + self.num_classes = 10 + self.dims = (1, 28, 28) + channels, width, height = self.dims + self.transform = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize((0.1307,), (0.3081,)), + ] + ) + + # Define PyTorch model + self.model = nn.Sequential( + nn.Flatten(), + nn.Linear(channels * width * height, hidden_size), + nn.ReLU(), + nn.Dropout(0.1), + nn.Linear(hidden_size, hidden_size), + nn.ReLU(), + nn.Dropout(0.1), + nn.Linear(hidden_size, self.num_classes), + ) + + self.val_accuracy = Accuracy() + self.test_accuracy = Accuracy() + + def forward(self, x): + x = self.model(x) + return F.log_softmax(x, dim=1) + + def training_step(self, batch, batch_idx): + x, y = batch + logits = self(x) + loss = F.nll_loss(logits, y) + return loss + + def validation_step(self, batch, batch_idx): + x, y = batch + logits = self(x) + loss = F.nll_loss(logits, y) + preds = torch.argmax(logits, dim=1) + self.val_accuracy.update(preds, y) + + # Calling self.log will surface up scalars for you in TensorBoard + self.log("val_loss", loss, prog_bar=True) + self.log("val_acc", self.val_accuracy, prog_bar=True) + + def test_step(self, batch, batch_idx): + x, y = batch + logits = self(x) + loss = F.nll_loss(logits, y) + preds = torch.argmax(logits, dim=1) + self.test_accuracy.update(preds, y) + + # Calling self.log will surface up scalars for you in TensorBoard + self.log("test_loss", loss, prog_bar=True) + self.log("test_acc", self.test_accuracy, prog_bar=True) + + def configure_optimizers(self): + optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate) + return optimizer + + #################### + # DATA RELATED HOOKS + #################### + + def prepare_data(self): + # download + print("Downloading MNIST dataset...") + MNIST(self.data_dir, train=True, download=True) + MNIST(self.data_dir, train=False, download=True) + + def setup(self, stage=None): + # Assign train/val datasets for use in dataloaders + if stage == "fit" or stage is None: + mnist_full = MNIST(self.data_dir, train=True, transform=self.transform) + self.mnist_train, self.mnist_val = random_split(mnist_full, [55000, 5000]) + + # Assign test dataset for use in dataloader(s) + if stage == "test" or stage is None: + self.mnist_test = MNIST( + self.data_dir, train=False, transform=self.transform + ) + + def train_dataloader(self): + return DataLoader(self.mnist_train, batch_size=BATCH_SIZE) + + def val_dataloader(self): + return DataLoader(self.mnist_val, batch_size=BATCH_SIZE) + + def test_dataloader(self): + return DataLoader(self.mnist_test, batch_size=BATCH_SIZE) + + +# Init DataLoader from MNIST Dataset + +model = LitMNIST() + +print("GROUP: ", int(os.environ.get("GROUP_WORLD_SIZE", 1))) +print("LOCAL: ", int(os.environ.get("LOCAL_WORLD_SIZE", 1))) + +# Initialize a trainer +trainer = Trainer( + accelerator="auto", + # devices=1 if torch.cuda.is_available() else None, # limiting got iPython runs + max_epochs=5, + callbacks=[TQDMProgressBar(refresh_rate=20)], + num_nodes=int(os.environ.get("GROUP_WORLD_SIZE", 1)), + devices=int(os.environ.get("LOCAL_WORLD_SIZE", 1)), + strategy="ddp", +) + +# Train the model ⚡ +trainer.fit(model) diff --git a/demo-notebooks/guided-demos/preview_nbs/requirements.txt b/demo-notebooks/guided-demos/preview_nbs/requirements.txt new file mode 100644 index 00000000..7266b064 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/requirements.txt @@ -0,0 +1,4 @@ +pytorch_lightning==1.5.10 +ray_lightning +torchmetrics==0.9.1 +torchvision==0.12.0 diff --git a/demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt b/demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt new file mode 100644 index 00000000..bd6c4f52 --- /dev/null +++ b/demo-notebooks/guided-demos/preview_nbs/requirements_gpt.txt @@ -0,0 +1,8 @@ +accelerate >= 0.12.0 +torch >= 1.3 +datasets >= 1.8.0 +sentencepiece != 0.1.92 +evaluate +scikit-learn +transformers==4.28.1 +protobuf<=3.20.1,>=3.8.0 diff --git a/demo-notebooks/interactive/hf_interactive.ipynb b/demo-notebooks/interactive/hf_interactive.ipynb index ed774821..e80df90d 100644 --- a/demo-notebooks/interactive/hf_interactive.ipynb +++ b/demo-notebooks/interactive/hf_interactive.ipynb @@ -86,7 +86,17 @@ ], "source": [ "# Create our cluster and submit appwrapper\n", - "cluster = Cluster(ClusterConfiguration(name='hfgputest', min_worker=1, max_worker=1, min_cpus=8, max_cpus=8, min_memory=16, max_memory=16, gpu=4, instascale=True, machine_types=[\"m5.xlarge\", \"p3.8xlarge\"]))" + "cluster = Cluster(ClusterConfiguration(name='hfgputest', \n", + " namespace=\"default\",\n", + " min_worker=1, \n", + " max_worker=1, \n", + " min_cpus=8, \n", + " max_cpus=8, \n", + " min_memory=16, \n", + " max_memory=16, \n", + " gpu=4,\n", + " image=\"quay.io/project-codeflare/ray:2.5.0-py38-cu116\",\n", + " instascale=True, machine_types=[\"m5.xlarge\", \"p3.8xlarge\"]))" ] }, { @@ -108,7 +118,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "657ebdfb", "metadata": {}, @@ -189,7 +198,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "477ac246", "metadata": {}, @@ -308,8 +316,8 @@ "ray.shutdown()\n", "# establish connection to ray cluster\n", "\n", - "#install additionall libraries that will be required for this training\n", - "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\"]}\n", + "#install additional libraries that will be required for this training\n", + "runtime_env = {\"pip\": [\"transformers\", \"datasets\", \"evaluate\", \"pyarrow<7.0.0\", \"accelerate\"]}\n", "\n", "ray.init(address=f'{ray_cluster_uri}', runtime_env=runtime_env)\n", "\n", @@ -1443,7 +1451,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3.9.7 64-bit", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -1457,7 +1465,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.8.13" }, "vscode": { "interpreter": { diff --git a/demo-notebooks/interactive/local_interactive.ipynb b/demo-notebooks/interactive/local_interactive.ipynb index 88a6ccd5..d70c00df 100644 --- a/demo-notebooks/interactive/local_interactive.ipynb +++ b/demo-notebooks/interactive/local_interactive.ipynb @@ -32,20 +32,12 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "id": "4364ac2e-dd10-4d30-ba66-12708daefb3f", "metadata": { "tags": [] }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Written to: hfgputest-1.yaml\n" - ] - } - ], + "outputs": [], "source": [ "# Create our cluster and submit appwrapper\n", "namespace = \"default\"\n", @@ -89,7 +81,6 @@ ] }, { - "attachments": {}, "cell_type": "markdown", "id": "12eef53c", "metadata": {}, @@ -99,38 +90,21 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "id": "cf1b749e-2335-42c2-b673-26768ec9895d", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "rayclient-hfgputest-1-default.apps.tedbig412.cp.fyre.ibm.com\n" - ] - } - ], + "outputs": [], "source": [ - "import openshift as oc\n", "from codeflare_sdk.utils import generate_cert\n", "\n", "if local_interactive:\n", " generate_cert.generate_tls_cert(cluster_name, namespace)\n", - " generate_cert.export_env(cluster_name, namespace)\n", - "\n", - "with oc.project(namespace):\n", - " routes=oc.selector(\"route\").objects()\n", - " rayclient_url=\"\"\n", - " for r in routes:\n", - " if \"rayclient\" in r.name():\n", - " rayclient_url=r.model.spec.host\n", - "print(rayclient_url)" + " generate_cert.export_env(cluster_name, namespace)" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 6, "id": "9483bb98-33b3-4beb-9b15-163d7e76c1d7", "metadata": { "scrolled": true, @@ -141,15 +115,15 @@ "name": "stderr", "output_type": "stream", "text": [ - "2023-05-31 14:12:37,816\tINFO client_builder.py:251 -- Passing the following kwargs to ray.init() on the server: logging_level\n", - "2023-05-31 14:12:37,820\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.IDLE\n", - "2023-05-31 14:12:38,034\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.CONNECTING\n", - "2023-05-31 14:12:38,246\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.READY\n", - "2023-05-31 14:12:38,290\tDEBUG worker.py:807 -- Pinging server.\n", - "2023-05-31 14:12:40,521\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000001000000\n", - "2023-05-31 14:12:40,523\tDEBUG worker.py:564 -- Scheduling task get_dashboard_url 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n", - "2023-05-31 14:12:40,535\tDEBUG worker.py:640 -- Retaining c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n", - "2023-05-31 14:12:41,379\tDEBUG worker.py:636 -- Releasing c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n" + "2023-06-27 19:14:16,088\tINFO client_builder.py:251 -- Passing the following kwargs to ray.init() on the server: logging_level\n", + "2023-06-27 19:14:16,100\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.IDLE\n", + "2023-06-27 19:14:16,308\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.CONNECTING\n", + "2023-06-27 19:14:16,434\tDEBUG worker.py:378 -- client gRPC channel state change: ChannelConnectivity.READY\n", + "2023-06-27 19:14:16,436\tDEBUG worker.py:807 -- Pinging server.\n", + "2023-06-27 19:14:18,634\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000001000000\n", + "2023-06-27 19:14:18,635\tDEBUG worker.py:564 -- Scheduling task get_dashboard_url 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n", + "2023-06-27 19:14:18,645\tDEBUG worker.py:640 -- Retaining c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n", + "2023-06-27 19:14:19,454\tDEBUG worker.py:636 -- Releasing c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000\n" ] }, { @@ -190,7 +164,7 @@ " \n", " \n", " Dashboard:\n", - " http://10.254.12.141:8265\n", + " http://10.254.20.41:8265\n", "\n", "\n", " \n", @@ -198,10 +172,10 @@ "\n" ], "text/plain": [ - "ClientContext(dashboard_url='10.254.12.141:8265', python_version='3.8.13', ray_version='2.1.0', ray_commit='23f34d948dae8de9b168667ab27e6cf940b3ae85', protocol_version='2022-10-05', _num_clients=1, _context_to_restore=)" + "ClientContext(dashboard_url='10.254.20.41:8265', python_version='3.8.13', ray_version='2.1.0', ray_commit='23f34d948dae8de9b168667ab27e6cf940b3ae85', protocol_version='2022-10-05', _num_clients=1, _context_to_restore=)" ] }, - "execution_count": 12, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } @@ -210,12 +184,12 @@ "import ray\n", "\n", "ray.shutdown()\n", - "ray.init(address=f\"ray://{rayclient_url}\", logging_level=\"DEBUG\")" + "ray.init(address=cluster.local_client_url(), logging_level=\"DEBUG\")" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 7, "id": "3436eb4a-217c-4109-a3c3-309fda7e2442", "metadata": {}, "outputs": [], @@ -239,7 +213,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 8, "id": "5cca1874-2be3-4631-ae48-9adfa45e3af3", "metadata": { "scrolled": true, @@ -250,8 +224,8 @@ "name": "stderr", "output_type": "stream", "text": [ - "2023-05-31 14:13:29,868\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000002000000\n", - "2023-05-31 14:13:29,870\tDEBUG worker.py:564 -- Scheduling task heavy_calculation 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00'\n" + "2023-06-27 19:14:28,222\tDEBUG worker.py:640 -- Retaining 00ffffffffffffffffffffffffffffffffffffff0100000002000000\n", + "2023-06-27 19:14:28,222\tDEBUG worker.py:564 -- Scheduling task heavy_calculation 0 b'\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00'\n" ] } ], @@ -261,7 +235,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 9, "id": "01172c29-e8bf-41ef-8db5-eccb07906111", "metadata": {}, "outputs": [ @@ -269,8 +243,8 @@ "name": "stderr", "output_type": "stream", "text": [ - "2023-05-31 14:13:32,643\tDEBUG worker.py:640 -- Retaining 16310a0f0a45af5cffffffffffffffffffffffff0100000001000000\n", - "2023-05-31 14:13:34,677\tDEBUG worker.py:439 -- Internal retry for get [ClientObjectRef(16310a0f0a45af5cffffffffffffffffffffffff0100000001000000)]\n" + "2023-06-27 19:14:29,202\tDEBUG worker.py:640 -- Retaining 16310a0f0a45af5cffffffffffffffffffffffff0100000001000000\n", + "2023-06-27 19:14:31,224\tDEBUG worker.py:439 -- Internal retry for get [ClientObjectRef(16310a0f0a45af5cffffffffffffffffffffffff0100000001000000)]\n" ] }, { @@ -279,7 +253,7 @@ "1789.4644387076714" ] }, - "execution_count": 15, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -290,7 +264,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 10, "id": "9e79b547-a457-4232-b77d-19147067b972", "metadata": {}, "outputs": [ @@ -298,10 +272,10 @@ "name": "stderr", "output_type": "stream", "text": [ - "2023-05-31 14:13:37,659\tDEBUG dataclient.py:287 -- Got unawaited response connection_cleanup {\n", + "2023-06-27 19:14:33,161\tDEBUG dataclient.py:287 -- Got unawaited response connection_cleanup {\n", "}\n", "\n", - "2023-05-31 14:13:38,681\tDEBUG dataclient.py:278 -- Shutting down data channel.\n" + "2023-06-27 19:14:34,460\tDEBUG dataclient.py:278 -- Shutting down data channel.\n" ] } ], @@ -312,7 +286,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 11, "id": "2c198f1f-68bf-43ff-a148-02b5cb000ff2", "metadata": {}, "outputs": [], diff --git a/docs/cluster/auth.html b/docs/cluster/auth.html index 15b563f9..dbec66ac 100644 --- a/docs/cluster/auth.html +++ b/docs/cluster/auth.html @@ -53,8 +53,12 @@

Module codeflare_sdk.cluster.auth

""" import abc -import openshift as oc -from openshift import OpenShiftPythonException +from kubernetes import client, config + +global api_client +api_client = None +global config_path +config_path = None class Authentication(metaclass=abc.ABCMeta): @@ -76,83 +80,134 @@

Module codeflare_sdk.cluster.auth

pass +class KubeConfiguration(metaclass=abc.ABCMeta): + """ + An abstract class that defines the method for loading a user defined config file using the `load_kube_config()` function + """ + + def load_kube_config(self): + """ + Method for setting your Kubernetes configuration to a certain file + """ + pass + + def logout(self): + """ + Method for logging out of the remote cluster + """ + pass + + class TokenAuthentication(Authentication): """ - `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift + `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to a Kubernetes cluster when the user has an API token and the API server address. """ - def __init__(self, token: str = None, server: str = None, skip_tls: bool = False): + def __init__( + self, + token: str, + server: str, + skip_tls: bool = False, + ca_cert_path: str = None, + ): """ Initialize a TokenAuthentication object that requires a value for `token`, the API Token - and `server`, the API server address for authenticating to an OpenShift cluster. + and `server`, the API server address for authenticating to a Kubernetes cluster. """ self.token = token self.server = server self.skip_tls = skip_tls + self.ca_cert_path = ca_cert_path def login(self) -> str: """ - This function is used to login to an OpenShift cluster using the user's API token and API server address. - Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls` - to `True`. + This function is used to log in to a Kubernetes cluster using the user's API token and API server address. + Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls` + to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`. """ - args = [f"--token={self.token}", f"--server={self.server}"] - if self.skip_tls: - args.append("--insecure-skip-tls-verify") + global config_path + global api_client try: - response = oc.invoke("login", args) - except OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "The server uses a certificate signed by unknown authority" in error_msg: - return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication" - elif "invalid" in error_msg: - raise PermissionError(error_msg) + configuration = client.Configuration() + configuration.api_key_prefix["authorization"] = "Bearer" + configuration.host = self.server + configuration.api_key["authorization"] = self.token + if self.skip_tls == False and self.ca_cert_path == None: + configuration.verify_ssl = True + elif self.skip_tls == False: + configuration.ssl_ca_cert = self.ca_cert_path else: - return error_msg - return response.out() + configuration.verify_ssl = False + api_client = client.ApiClient(configuration) + client.AuthenticationApi(api_client).get_api_group() + config_path = None + return "Logged into %s" % self.server + except client.ApiException: # pragma: no cover + api_client = None + print("Authentication Error please provide the correct token + server") def logout(self) -> str: """ - This function is used to logout of an OpenShift cluster. + This function is used to logout of a Kubernetes cluster. """ - args = [f"--token={self.token}", f"--server={self.server}"] - response = oc.invoke("logout", args) - return response.out() + global config_path + config_path = None + global api_client + api_client = None + return "Successfully logged out of %s" % self.server -class PasswordUserAuthentication(Authentication): +class KubeConfigFileAuthentication(KubeConfiguration): """ - `PasswordUserAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift - cluster when the user has a username and password. + A class that defines the necessary methods for passing a user's own Kubernetes config file. + Specifically this class defines the `load_kube_config()` and `config_check()` functions. """ - def __init__( - self, - username: str = None, - password: str = None, - ): - """ - Initialize a PasswordUserAuthentication object that requires a value for `username` - and `password` for authenticating to an OpenShift cluster. - """ - self.username = username - self.password = password + def __init__(self, kube_config_path: str = None): + self.kube_config_path = kube_config_path - def login(self) -> str: + def load_kube_config(self): """ - This function is used to login to an OpenShift cluster using the user's `username` and `password`. + Function for loading a user's own predefined Kubernetes config file. """ - response = oc.login(self.username, self.password) - return response.out() + global config_path + global api_client + try: + if self.kube_config_path == None: + return "Please specify a config file path" + config_path = self.kube_config_path + api_client = None + config.load_kube_config(config_path) + response = "Loaded user config file at path %s" % self.kube_config_path + except config.ConfigException: # pragma: no cover + config_path = None + raise Exception("Please specify a config file path") + return response - def logout(self) -> str: - """ - This function is used to logout of an OpenShift cluster. - """ - response = oc.invoke("logout") - return response.out() + +def config_check() -> str: + """ + Function for loading the config file at the default config location ~/.kube/config if the user has not + specified their own config file or has logged in with their token and server. + """ + global config_path + global api_client + if config_path == None and api_client == None: + config.load_kube_config() + if config_path != None and api_client == None: + return config_path + + +def api_config_handler() -> str: + """ + This function is used to load the api client if the user has logged in + """ + if api_client != None and config_path == None: + return api_client + else: + return None
@@ -160,6 +215,51 @@

Module codeflare_sdk.cluster.auth

+

Functions

+
+
+def api_config_handler() ‑> str +
+
+

This function is used to load the api client if the user has logged in

+
+ +Expand source code + +
def api_config_handler() -> str:
+    """
+    This function is used to load the api client if the user has logged in
+    """
+    if api_client != None and config_path == None:
+        return api_client
+    else:
+        return None
+
+
+
+def config_check() ‑> str +
+
+

Function for loading the config file at the default config location ~/.kube/config if the user has not +specified their own config file or has logged in with their token and server.

+
+ +Expand source code + +
def config_check() -> str:
+    """
+    Function for loading the config file at the default config location ~/.kube/config if the user has not
+    specified their own config file or has logged in with their token and server.
+    """
+    global config_path
+    global api_client
+    if config_path == None and api_client == None:
+        config.load_kube_config()
+    if config_path != None and api_client == None:
+        return config_path
+
+
+

Classes

@@ -194,7 +294,6 @@

Classes

Subclasses

Methods

@@ -233,150 +332,226 @@

Methods

-
-class PasswordUserAuthentication -(username: str = None, password: str = None) +
+class KubeConfigFileAuthentication +(kube_config_path: str = None)
-

PasswordUserAuthentication is a subclass of Authentication. It can be used to authenticate to an OpenShift -cluster when the user has a username and password.

-

Initialize a PasswordUserAuthentication object that requires a value for username -and password for authenticating to an OpenShift cluster.

+

A class that defines the necessary methods for passing a user's own Kubernetes config file. +Specifically this class defines the load_kube_config() and config_check() functions.

Expand source code -
class PasswordUserAuthentication(Authentication):
+
class KubeConfigFileAuthentication(KubeConfiguration):
     """
-    `PasswordUserAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift
-    cluster when the user has a username and password.
+    A class that defines the necessary methods for passing a user's own Kubernetes config file.
+    Specifically this class defines the `load_kube_config()` and `config_check()` functions.
     """
 
-    def __init__(
-        self,
-        username: str = None,
-        password: str = None,
-    ):
+    def __init__(self, kube_config_path: str = None):
+        self.kube_config_path = kube_config_path
+
+    def load_kube_config(self):
         """
-        Initialize a PasswordUserAuthentication object that requires a value for `username`
-        and `password` for authenticating to an OpenShift cluster.
+        Function for loading a user's own predefined Kubernetes config file.
         """
-        self.username = username
-        self.password = password
+        global config_path
+        global api_client
+        try:
+            if self.kube_config_path == None:
+                return "Please specify a config file path"
+            config_path = self.kube_config_path
+            api_client = None
+            config.load_kube_config(config_path)
+            response = "Loaded user config file at path %s" % self.kube_config_path
+        except config.ConfigException:  # pragma: no cover
+            config_path = None
+            raise Exception("Please specify a config file path")
+        return response
+
+

Ancestors

+ +

Methods

+
+
+def load_kube_config(self) +
+
+

Function for loading a user's own predefined Kubernetes config file.

+
+ +Expand source code + +
def load_kube_config(self):
+    """
+    Function for loading a user's own predefined Kubernetes config file.
+    """
+    global config_path
+    global api_client
+    try:
+        if self.kube_config_path == None:
+            return "Please specify a config file path"
+        config_path = self.kube_config_path
+        api_client = None
+        config.load_kube_config(config_path)
+        response = "Loaded user config file at path %s" % self.kube_config_path
+    except config.ConfigException:  # pragma: no cover
+        config_path = None
+        raise Exception("Please specify a config file path")
+    return response
+
+
+
+

Inherited members

+ +
+
+class KubeConfiguration +
+
+

An abstract class that defines the method for loading a user defined config file using the load_kube_config() function

+
+ +Expand source code + +
class KubeConfiguration(metaclass=abc.ABCMeta):
+    """
+    An abstract class that defines the method for loading a user defined config file using the `load_kube_config()` function
+    """
 
-    def login(self) -> str:
+    def load_kube_config(self):
         """
-        This function is used to login to an OpenShift cluster using the user's `username` and `password`.
+        Method for setting your Kubernetes configuration to a certain file
         """
-        response = oc.login(self.username, self.password)
-        return response.out()
+        pass
 
-    def logout(self) -> str:
+    def logout(self):
         """
-        This function is used to logout of an OpenShift cluster.
+        Method for logging out of the remote cluster
         """
-        response = oc.invoke("logout")
-        return response.out()
+ pass
-

Ancestors

+

Subclasses

Methods

-
-def login(self) ‑> str +
+def load_kube_config(self)
-

This function is used to login to an OpenShift cluster using the user's username and password.

+

Method for setting your Kubernetes configuration to a certain file

Expand source code -
def login(self) -> str:
+
def load_kube_config(self):
     """
-    This function is used to login to an OpenShift cluster using the user's `username` and `password`.
+    Method for setting your Kubernetes configuration to a certain file
     """
-    response = oc.login(self.username, self.password)
-    return response.out()
+ pass
-
-def logout(self) ‑> str +
+def logout(self)
-

This function is used to logout of an OpenShift cluster.

+

Method for logging out of the remote cluster

Expand source code -
def logout(self) -> str:
+
def logout(self):
     """
-    This function is used to logout of an OpenShift cluster.
+    Method for logging out of the remote cluster
     """
-    response = oc.invoke("logout")
-    return response.out()
+ pass
class TokenAuthentication -(token: str = None, server: str = None, skip_tls: bool = False) +(token: str, server: str, skip_tls: bool = False, ca_cert_path: str = None)
-

TokenAuthentication is a subclass of Authentication. It can be used to authenticate to an OpenShift +

TokenAuthentication is a subclass of Authentication. It can be used to authenticate to a Kubernetes cluster when the user has an API token and the API server address.

Initialize a TokenAuthentication object that requires a value for token, the API Token -and server, the API server address for authenticating to an OpenShift cluster.

+and server, the API server address for authenticating to a Kubernetes cluster.

Expand source code
class TokenAuthentication(Authentication):
     """
-    `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift
+    `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to a Kubernetes
     cluster when the user has an API token and the API server address.
     """
 
-    def __init__(self, token: str = None, server: str = None, skip_tls: bool = False):
+    def __init__(
+        self,
+        token: str,
+        server: str,
+        skip_tls: bool = False,
+        ca_cert_path: str = None,
+    ):
         """
         Initialize a TokenAuthentication object that requires a value for `token`, the API Token
-        and `server`, the API server address for authenticating to an OpenShift cluster.
+        and `server`, the API server address for authenticating to a Kubernetes cluster.
         """
 
         self.token = token
         self.server = server
         self.skip_tls = skip_tls
+        self.ca_cert_path = ca_cert_path
 
     def login(self) -> str:
         """
-        This function is used to login to an OpenShift cluster using the user's API token and API server address.
-        Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls`
-        to `True`.
+        This function is used to log in to a Kubernetes cluster using the user's API token and API server address.
+        Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls`
+        to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`.
         """
-        args = [f"--token={self.token}", f"--server={self.server}"]
-        if self.skip_tls:
-            args.append("--insecure-skip-tls-verify")
+        global config_path
+        global api_client
         try:
-            response = oc.invoke("login", args)
-        except OpenShiftPythonException as osp:  # pragma: no cover
-            error_msg = osp.result.err()
-            if "The server uses a certificate signed by unknown authority" in error_msg:
-                return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication"
-            elif "invalid" in error_msg:
-                raise PermissionError(error_msg)
+            configuration = client.Configuration()
+            configuration.api_key_prefix["authorization"] = "Bearer"
+            configuration.host = self.server
+            configuration.api_key["authorization"] = self.token
+            if self.skip_tls == False and self.ca_cert_path == None:
+                configuration.verify_ssl = True
+            elif self.skip_tls == False:
+                configuration.ssl_ca_cert = self.ca_cert_path
             else:
-                return error_msg
-        return response.out()
+                configuration.verify_ssl = False
+            api_client = client.ApiClient(configuration)
+            client.AuthenticationApi(api_client).get_api_group()
+            config_path = None
+            return "Logged into %s" % self.server
+        except client.ApiException:  # pragma: no cover
+            api_client = None
+            print("Authentication Error please provide the correct token + server")
 
     def logout(self) -> str:
         """
-        This function is used to logout of an OpenShift cluster.
+        This function is used to logout of a Kubernetes cluster.
         """
-        args = [f"--token={self.token}", f"--server={self.server}"]
-        response = oc.invoke("logout", args)
-        return response.out()
+ global config_path + config_path = None + global api_client + api_client = None + return "Successfully logged out of %s" % self.server

Ancestors

    @@ -388,51 +563,59 @@

    Methods

    def login(self) ‑> str
    -

    This function is used to login to an OpenShift cluster using the user's API token and API server address. -Depending on the cluster, a user can choose to login in with "–insecure-skip-tls-verify by setting skip_tls` -to True.

    +

    This function is used to log in to a Kubernetes cluster using the user's API token and API server address. +Depending on the cluster, a user can choose to login in with --insecure-skip-tls-verify by setting skip_tls +to True or --certificate-authority by setting skip_tls to False and providing a path to a ca bundle with ca_cert_path.

    Expand source code
    def login(self) -> str:
         """
    -    This function is used to login to an OpenShift cluster using the user's API token and API server address.
    -    Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls`
    -    to `True`.
    +    This function is used to log in to a Kubernetes cluster using the user's API token and API server address.
    +    Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls`
    +    to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`.
         """
    -    args = [f"--token={self.token}", f"--server={self.server}"]
    -    if self.skip_tls:
    -        args.append("--insecure-skip-tls-verify")
    +    global config_path
    +    global api_client
         try:
    -        response = oc.invoke("login", args)
    -    except OpenShiftPythonException as osp:  # pragma: no cover
    -        error_msg = osp.result.err()
    -        if "The server uses a certificate signed by unknown authority" in error_msg:
    -            return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication"
    -        elif "invalid" in error_msg:
    -            raise PermissionError(error_msg)
    +        configuration = client.Configuration()
    +        configuration.api_key_prefix["authorization"] = "Bearer"
    +        configuration.host = self.server
    +        configuration.api_key["authorization"] = self.token
    +        if self.skip_tls == False and self.ca_cert_path == None:
    +            configuration.verify_ssl = True
    +        elif self.skip_tls == False:
    +            configuration.ssl_ca_cert = self.ca_cert_path
             else:
    -            return error_msg
    -    return response.out()
    + configuration.verify_ssl = False + api_client = client.ApiClient(configuration) + client.AuthenticationApi(api_client).get_api_group() + config_path = None + return "Logged into %s" % self.server + except client.ApiException: # pragma: no cover + api_client = None + print("Authentication Error please provide the correct token + server")
    def logout(self) ‑> str
    -

    This function is used to logout of an OpenShift cluster.

    +

    This function is used to logout of a Kubernetes cluster.

    Expand source code
    def logout(self) -> str:
         """
    -    This function is used to logout of an OpenShift cluster.
    +    This function is used to logout of a Kubernetes cluster.
         """
    -    args = [f"--token={self.token}", f"--server={self.server}"]
    -    response = oc.invoke("logout", args)
    -    return response.out()
    + global config_path + config_path = None + global api_client + api_client = None + return "Successfully logged out of %s" % self.server
    @@ -451,6 +634,12 @@

    Index

  • codeflare_sdk.cluster
+
  • Functions

    + +
  • Classes

    • @@ -461,10 +650,16 @@

      PasswordUserAuthentication

      +

      KubeConfigFileAuthentication

      + +
    • +
    • +

      KubeConfiguration

    • @@ -483,4 +678,4 @@

      pdoc 0.10.0.

      - \ No newline at end of file + diff --git a/docs/cluster/awload.html b/docs/cluster/awload.html index 7abc120a..d2afb7ea 100644 --- a/docs/cluster/awload.html +++ b/docs/cluster/awload.html @@ -51,9 +51,12 @@

      Module codeflare_sdk.cluster.awload

      from os.path import isfile import errno import os -import openshift as oc import yaml +from kubernetes import client, config +from ..utils.kube_api_helpers import _kube_api_error_handling +from .auth import config_check, api_config_handler + class AWManager: """ @@ -71,10 +74,10 @@

      Module codeflare_sdk.cluster.awload

      self.filename = filename try: with open(self.filename) as f: - awyaml = yaml.load(f, Loader=yaml.FullLoader) - assert awyaml["kind"] == "AppWrapper" - self.name = awyaml["metadata"]["name"] - self.namespace = awyaml["metadata"]["namespace"] + self.awyaml = yaml.load(f, Loader=yaml.FullLoader) + assert self.awyaml["kind"] == "AppWrapper" + self.name = self.awyaml["metadata"]["name"] + self.namespace = self.awyaml["metadata"]["namespace"] except: raise ValueError( f"{filename } is not a correctly formatted AppWrapper yaml" @@ -86,19 +89,17 @@

      Module codeflare_sdk.cluster.awload

      Attempts to create the AppWrapper custom resource using the yaml file """ try: - with oc.project(self.namespace): - oc.invoke("create", ["-f", self.filename]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg or "Forbidden" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "AlreadyExists" in error_msg: - raise FileExistsError( - f"An AppWrapper of the name {self.name} already exists in namespace {self.namespace}" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + body=self.awyaml, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = True print(f"AppWrapper {self.filename} submitted!") @@ -113,25 +114,17 @@

      Module codeflare_sdk.cluster.awload

      return try: - with oc.project(self.namespace): - oc.invoke("delete", ["AppWrapper", self.name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "not found" in error_msg: - self.submitted = False - print("AppWrapper not found, was deleted in another manner") - return - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + name=self.name, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = False print(f"AppWrapper {self.name} removed!")
      @@ -175,10 +168,10 @@

      Classes

      self.filename = filename try: with open(self.filename) as f: - awyaml = yaml.load(f, Loader=yaml.FullLoader) - assert awyaml["kind"] == "AppWrapper" - self.name = awyaml["metadata"]["name"] - self.namespace = awyaml["metadata"]["namespace"] + self.awyaml = yaml.load(f, Loader=yaml.FullLoader) + assert self.awyaml["kind"] == "AppWrapper" + self.name = self.awyaml["metadata"]["name"] + self.namespace = self.awyaml["metadata"]["namespace"] except: raise ValueError( f"{filename } is not a correctly formatted AppWrapper yaml" @@ -190,19 +183,17 @@

      Classes

      Attempts to create the AppWrapper custom resource using the yaml file """ try: - with oc.project(self.namespace): - oc.invoke("create", ["-f", self.filename]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg or "Forbidden" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "AlreadyExists" in error_msg: - raise FileExistsError( - f"An AppWrapper of the name {self.name} already exists in namespace {self.namespace}" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + body=self.awyaml, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = True print(f"AppWrapper {self.filename} submitted!") @@ -217,25 +208,17 @@

      Classes

      return try: - with oc.project(self.namespace): - oc.invoke("delete", ["AppWrapper", self.name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "not found" in error_msg: - self.submitted = False - print("AppWrapper not found, was deleted in another manner") - return - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + name=self.name, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = False print(f"AppWrapper {self.name} removed!") @@ -262,25 +245,17 @@

      Methods

      return try: - with oc.project(self.namespace): - oc.invoke("delete", ["AppWrapper", self.name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "not found" in error_msg: - self.submitted = False - print("AppWrapper not found, was deleted in another manner") - return - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + name=self.name, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = False print(f"AppWrapper {self.name} removed!") @@ -300,19 +275,17 @@

      Methods

      Attempts to create the AppWrapper custom resource using the yaml file """ try: - with oc.project(self.namespace): - oc.invoke("create", ["-f", self.filename]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg or "Forbidden" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "AlreadyExists" in error_msg: - raise FileExistsError( - f"An AppWrapper of the name {self.name} already exists in namespace {self.namespace}" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + body=self.awyaml, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = True print(f"AppWrapper {self.filename} submitted!") @@ -352,4 +325,4 @@

      pdoc 0.10.0.

      - \ No newline at end of file + diff --git a/docs/cluster/cluster.html b/docs/cluster/cluster.html index 83b2ef5f..e8205b42 100644 --- a/docs/cluster/cluster.html +++ b/docs/cluster/cluster.html @@ -50,15 +50,15 @@

      Module codeflare_sdk.cluster.cluster

      cluster setup queue, a list of all existing clusters, and the user's working namespace. """ -from os import stat from time import sleep from typing import List, Optional, Tuple, Dict -import openshift as oc from ray.job_submission import JobSubmissionClient +from .auth import config_check, api_config_handler from ..utils import pretty_print from ..utils.generate_yaml import generate_appwrapper +from ..utils.kube_api_helpers import _kube_api_error_handling from .config import ClusterConfiguration from .model import ( AppWrapper, @@ -67,6 +67,9 @@

      Module codeflare_sdk.cluster.cluster

      RayCluster, RayClusterStatus, ) +from kubernetes import client, config +import yaml +import os class Cluster: @@ -97,8 +100,10 @@

      Module codeflare_sdk.cluster.cluster

      """ if self.config.namespace is None: - self.config.namespace = oc.get_project_name() - if type(self.config.namespace) is not str: + self.config.namespace = get_current_namespace() + if self.config.namespace is None: + print("Please specify with namespace=<your_current_namespace>") + elif type(self.config.namespace) is not str: raise TypeError( f"Namespace {self.config.namespace} is of type {type(self.config.namespace)}. Check your Kubernetes Authentication." ) @@ -109,8 +114,8 @@

      Module codeflare_sdk.cluster.cluster

      max_cpu = self.config.max_cpus min_memory = self.config.min_memory max_memory = self.config.max_memory - gpu = self.config.gpu - workers = self.config.max_worker + gpu = self.config.num_gpus + workers = self.config.num_workers template = self.config.template image = self.config.image instascale = self.config.instascale @@ -144,15 +149,19 @@

      Module codeflare_sdk.cluster.cluster

      """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("apply", ["-f", self.app_wrapper_yaml]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + with open(self.app_wrapper_yaml) as f: + aw = yaml.load(f, Loader=yaml.FullLoader) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + body=aw, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) def down(self): """ @@ -161,23 +170,17 @@

      Module codeflare_sdk.cluster.cluster

      """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("delete", ["AppWrapper", self.app_wrapper_name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you run auth.login()/cluster.up() yet?" - ) - elif "not found" in error_msg: - print("Cluster not found, have you run cluster.up() yet?") - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + name=self.app_wrapper_name, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) def status( self, print_to_console: bool = True @@ -205,9 +208,15 @@

      Module codeflare_sdk.cluster.cluster

      ready = False status = CodeFlareClusterStatus.FAILED # should deleted be separate return status, ready # exit early, no need to check ray status - elif appwrapper.status in [AppWrapperStatus.PENDING]: + elif appwrapper.status in [ + AppWrapperStatus.PENDING, + AppWrapperStatus.QUEUEING, + ]: ready = False - status = CodeFlareClusterStatus.QUEUED + if appwrapper.status == AppWrapperStatus.PENDING: + status = CodeFlareClusterStatus.QUEUED + else: + status = CodeFlareClusterStatus.QUEUEING if print_to_console: pretty_print.print_app_wrappers_status([appwrapper]) return ( @@ -230,7 +239,7 @@

      Module codeflare_sdk.cluster.cluster

      if print_to_console: # overriding the number of gpus with requested - cluster.worker_gpu = self.config.gpu + cluster.worker_gpu = self.config.num_gpus pretty_print.print_cluster_status(cluster) elif print_to_console: if status == CodeFlareClusterStatus.UNKNOWN: @@ -279,16 +288,21 @@

      Module codeflare_sdk.cluster.cluster

      Returns a string containing the cluster's dashboard URI. """ try: - with oc.project(self.config.namespace): - route = oc.invoke( - "get", ["route", "-o", "jsonpath='{$.items[*].spec.host}'"] - ) - route = route.out().split(" ") - route = [x for x in route if f"ray-dashboard-{self.config.name}" in x] - route = route[0].strip().strip("'") - return f"http://{route}" - except: - return "Dashboard route not available yet, have you run cluster.up()?" + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + routes = api_instance.list_namespaced_custom_object( + group="route.openshift.io", + version="v1", + namespace=self.config.namespace, + plural="routes", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for route in routes["items"]: + if route["metadata"]["name"] == f"ray-dashboard-{self.config.name}": + return f"http://{route['spec']['host']}" + return "Dashboard route not available yet, have you run cluster.up()?" def list_jobs(self) -> List: """ @@ -328,6 +342,55 @@

      Module codeflare_sdk.cluster.cluster

      to_return["requirements"] = requirements return to_return + def from_k8_cluster_object(rc): + machine_types = ( + rc["metadata"]["labels"]["orderedinstance"].split("_") + if "orderedinstance" in rc["metadata"]["labels"] + else [] + ) + local_interactive = ( + "volumeMounts" + in rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0] + ) + cluster_config = ClusterConfiguration( + name=rc["metadata"]["name"], + namespace=rc["metadata"]["namespace"], + machine_types=machine_types, + num_workers=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], + min_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["requests"]["cpu"], + max_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["cpu"], + min_memory=int( + rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ + "resources" + ]["requests"]["memory"][:-1] + ), + max_memory=int( + rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ + "resources" + ]["limits"]["memory"][:-1] + ), + num_gpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["nvidia.com/gpu"], + instascale=True if machine_types else False, + image=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][ + 0 + ]["image"], + local_interactive=local_interactive, + ) + return Cluster(cluster_config) + + def local_client_url(self): + if self.config.local_interactive == True: + ingress_domain = _get_ingress_domain() + return f"ray://rayclient-{self.config.name}-{self.config.namespace}.{ingress_domain}" + else: + return "None" + def list_all_clusters(namespace: str, print_to_console: bool = True): """ @@ -352,78 +415,120 @@

      Module codeflare_sdk.cluster.cluster

      return app_wrappers +def get_current_namespace(): # pragma: no cover + if api_config_handler() != None: + if os.path.isfile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"): + try: + file = open( + "/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r" + ) + active_context = file.readline().strip("\n") + return active_context + except Exception as e: + print("Unable to find current namespace") + return None + else: + print("Unable to find current namespace") + return None + else: + try: + _, active_context = config.list_kube_config_contexts(config_check()) + except Exception as e: + return _kube_api_error_handling(e) + try: + return active_context["context"]["namespace"] + except KeyError: + return None + + +def get_cluster(cluster_name: str, namespace: str = "default"): + try: + config.load_kube_config() + api_instance = client.CustomObjectsApi() + rcs = api_instance.list_namespaced_custom_object( + group="ray.io", + version="v1alpha1", + namespace=namespace, + plural="rayclusters", + ) + except Exception as e: + return _kube_api_error_handling(e) + + for rc in rcs["items"]: + if rc["metadata"]["name"] == cluster_name: + return Cluster.from_k8_cluster_object(rc) + raise FileNotFoundError( + f"Cluster {cluster_name} is not found in {namespace} namespace" + ) + + # private methods +def _get_ingress_domain(): + try: + config.load_kube_config() + api_client = client.CustomObjectsApi(api_config_handler()) + ingress = api_client.get_cluster_custom_object( + "config.openshift.io", "v1", "ingresses", "cluster" + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + return ingress["spec"]["domain"] def _app_wrapper_status(name, namespace="default") -> Optional[AppWrapper]: - cluster = None try: - with oc.project(namespace), oc.timeout(10 * 60): - cluster = oc.selector(f"appwrapper/{name}").object() - except oc.OpenShiftPythonException as osp: # pragma: no cover - msg = osp.msg - if "Expected a single object, but selected 0" in msg: - return cluster - error_msg = osp.result.err() - if not ( - 'the server doesn\'t have a resource type "appwrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise osp - - if cluster: - return _map_to_app_wrapper(cluster) - - return cluster + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + aws = api_instance.list_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for aw in aws["items"]: + if aw["metadata"]["name"] == name: + return _map_to_app_wrapper(aw) + return None def _ray_cluster_status(name, namespace="default") -> Optional[RayCluster]: - cluster = None try: - with oc.project(namespace), oc.timeout(10 * 60): - cluster = oc.selector(f"rayclusters/{name}").object() - except oc.OpenShiftPythonException as osp: # pragma: no cover - msg = osp.msg - if "Expected a single object, but selected 0" in msg: - return cluster - error_msg = osp.result.err() - if not ( - 'the server doesn\'t have a resource type "rayclusters"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise osp - - if cluster: - return _map_to_ray_cluster(cluster) - - return cluster + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + rcs = api_instance.list_namespaced_custom_object( + group="ray.io", + version="v1alpha1", + namespace=namespace, + plural="rayclusters", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for rc in rcs["items"]: + if rc["metadata"]["name"] == name: + return _map_to_ray_cluster(rc) + return None def _get_ray_clusters(namespace="default") -> List[RayCluster]: list_of_clusters = [] try: - with oc.project(namespace), oc.timeout(10 * 60): - ray_clusters = oc.selector("rayclusters").objects() - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "rayclusters"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + rcs = api_instance.list_namespaced_custom_object( + group="ray.io", + version="v1alpha1", + namespace=namespace, + plural="rayclusters", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) - for cluster in ray_clusters: - list_of_clusters.append(_map_to_ray_cluster(cluster)) + for rc in rcs["items"]: + list_of_clusters.append(_map_to_ray_cluster(rc)) return list_of_clusters @@ -433,23 +538,18 @@

      Module codeflare_sdk.cluster.cluster

      list_of_app_wrappers = [] try: - with oc.project(namespace), oc.timeout(10 * 60): - app_wrappers = oc.selector("appwrappers").objects() - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "appwrappers"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + aws = api_instance.list_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) - for item in app_wrappers: + for item in aws["items"]: app_wrapper = _map_to_app_wrapper(item) if filter and app_wrapper.status in filter: list_of_app_wrappers.append(app_wrapper) @@ -459,48 +559,58 @@

      Module codeflare_sdk.cluster.cluster

      return list_of_app_wrappers -def _map_to_ray_cluster(cluster) -> Optional[RayCluster]: - cluster_model = cluster.model - if type(cluster_model.status.state) == oc.model.MissingModel: - status = RayClusterStatus.UNKNOWN +def _map_to_ray_cluster(rc) -> Optional[RayCluster]: + if "state" in rc["status"]: + status = RayClusterStatus(rc["status"]["state"].lower()) else: - status = RayClusterStatus(cluster_model.status.state.lower()) + status = RayClusterStatus.UNKNOWN - with oc.project(cluster.namespace()), oc.timeout(10 * 60): - route = ( - oc.selector(f"route/ray-dashboard-{cluster.name()}") - .object() - .model.spec.host - ) + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + routes = api_instance.list_namespaced_custom_object( + group="route.openshift.io", + version="v1", + namespace=rc["metadata"]["namespace"], + plural="routes", + ) + ray_route = None + for route in routes["items"]: + if route["metadata"]["name"] == f"ray-dashboard-{rc['metadata']['name']}": + ray_route = route["spec"]["host"] return RayCluster( - name=cluster.name(), + name=rc["metadata"]["name"], status=status, # for now we are not using autoscaling so same replicas is fine - min_workers=cluster_model.spec.workerGroupSpecs[0].replicas, - max_workers=cluster_model.spec.workerGroupSpecs[0].replicas, - worker_mem_max=cluster_model.spec.workerGroupSpecs[0] - .template.spec.containers[0] - .resources.limits.memory, - worker_mem_min=cluster_model.spec.workerGroupSpecs[0] - .template.spec.containers[0] - .resources.requests.memory, - worker_cpu=cluster_model.spec.workerGroupSpecs[0] - .template.spec.containers[0] - .resources.limits.cpu, + workers=rc["spec"]["workerGroupSpecs"][0]["replicas"], + worker_mem_max=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["memory"], + worker_mem_min=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["requests"]["memory"], + worker_cpu=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][ + 0 + ]["resources"]["limits"]["cpu"], worker_gpu=0, # hard to detect currently how many gpus, can override it with what the user asked for - namespace=cluster.namespace(), - dashboard=route, + namespace=rc["metadata"]["namespace"], + dashboard=ray_route, ) -def _map_to_app_wrapper(cluster) -> AppWrapper: - cluster_model = cluster.model +def _map_to_app_wrapper(aw) -> AppWrapper: + if "status" in aw and "canrun" in aw["status"]: + return AppWrapper( + name=aw["metadata"]["name"], + status=AppWrapperStatus(aw["status"]["state"].lower()), + can_run=aw["status"]["canrun"], + job_state=aw["status"]["queuejobstate"], + ) return AppWrapper( - name=cluster.name(), - status=AppWrapperStatus(cluster_model.status.state.lower()), - can_run=cluster_model.status.canrun, - job_state=cluster_model.status.queuejobstate, + name=aw["metadata"]["name"], + status=AppWrapperStatus("queueing"), + can_run=False, + job_state="Still adding to queue", ) @@ -508,12 +618,11 @@

      Module codeflare_sdk.cluster.cluster

      ray = RayCluster( name=cluster.config.name, status=cluster.status(print_to_console=False)[0], - min_workers=cluster.config.min_worker, - max_workers=cluster.config.max_worker, + workers=cluster.config.num_workers, worker_mem_min=cluster.config.min_memory, worker_mem_max=cluster.config.max_memory, worker_cpu=cluster.config.min_cpus, - worker_gpu=cluster.config.gpu, + worker_gpu=cluster.config.num_gpus, namespace=cluster.config.namespace, dashboard=cluster.cluster_dashboard_uri(), ) @@ -529,6 +638,71 @@

      Module codeflare_sdk.cluster.cluster

      Functions

      +
      +def get_cluster(cluster_name: str, namespace: str = 'default') +
      +
      +
      +
      + +Expand source code + +
      def get_cluster(cluster_name: str, namespace: str = "default"):
      +    try:
      +        config.load_kube_config()
      +        api_instance = client.CustomObjectsApi()
      +        rcs = api_instance.list_namespaced_custom_object(
      +            group="ray.io",
      +            version="v1alpha1",
      +            namespace=namespace,
      +            plural="rayclusters",
      +        )
      +    except Exception as e:
      +        return _kube_api_error_handling(e)
      +
      +    for rc in rcs["items"]:
      +        if rc["metadata"]["name"] == cluster_name:
      +            return Cluster.from_k8_cluster_object(rc)
      +    raise FileNotFoundError(
      +        f"Cluster {cluster_name} is not found in {namespace} namespace"
      +    )
      +
      +
      +
      +def get_current_namespace() +
      +
      +
      +
      + +Expand source code + +
      def get_current_namespace():  # pragma: no cover
      +    if api_config_handler() != None:
      +        if os.path.isfile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"):
      +            try:
      +                file = open(
      +                    "/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r"
      +                )
      +                active_context = file.readline().strip("\n")
      +                return active_context
      +            except Exception as e:
      +                print("Unable to find current namespace")
      +                return None
      +        else:
      +            print("Unable to find current namespace")
      +            return None
      +    else:
      +        try:
      +            _, active_context = config.list_kube_config_contexts(config_check())
      +        except Exception as e:
      +            return _kube_api_error_handling(e)
      +        try:
      +            return active_context["context"]["namespace"]
      +        except KeyError:
      +            return None
      +
      +
      def list_all_clusters(namespace: str, print_to_console: bool = True)
      @@ -620,8 +794,10 @@

      Classes

      """ if self.config.namespace is None: - self.config.namespace = oc.get_project_name() - if type(self.config.namespace) is not str: + self.config.namespace = get_current_namespace() + if self.config.namespace is None: + print("Please specify with namespace=<your_current_namespace>") + elif type(self.config.namespace) is not str: raise TypeError( f"Namespace {self.config.namespace} is of type {type(self.config.namespace)}. Check your Kubernetes Authentication." ) @@ -632,8 +808,8 @@

      Classes

      max_cpu = self.config.max_cpus min_memory = self.config.min_memory max_memory = self.config.max_memory - gpu = self.config.gpu - workers = self.config.max_worker + gpu = self.config.num_gpus + workers = self.config.num_workers template = self.config.template image = self.config.image instascale = self.config.instascale @@ -667,15 +843,19 @@

      Classes

      """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("apply", ["-f", self.app_wrapper_yaml]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + with open(self.app_wrapper_yaml) as f: + aw = yaml.load(f, Loader=yaml.FullLoader) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + body=aw, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) def down(self): """ @@ -684,23 +864,17 @@

      Classes

      """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("delete", ["AppWrapper", self.app_wrapper_name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you run auth.login()/cluster.up() yet?" - ) - elif "not found" in error_msg: - print("Cluster not found, have you run cluster.up() yet?") - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + name=self.app_wrapper_name, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) def status( self, print_to_console: bool = True @@ -728,9 +902,15 @@

      Classes

      ready = False status = CodeFlareClusterStatus.FAILED # should deleted be separate return status, ready # exit early, no need to check ray status - elif appwrapper.status in [AppWrapperStatus.PENDING]: + elif appwrapper.status in [ + AppWrapperStatus.PENDING, + AppWrapperStatus.QUEUEING, + ]: ready = False - status = CodeFlareClusterStatus.QUEUED + if appwrapper.status == AppWrapperStatus.PENDING: + status = CodeFlareClusterStatus.QUEUED + else: + status = CodeFlareClusterStatus.QUEUEING if print_to_console: pretty_print.print_app_wrappers_status([appwrapper]) return ( @@ -753,7 +933,7 @@

      Classes

      if print_to_console: # overriding the number of gpus with requested - cluster.worker_gpu = self.config.gpu + cluster.worker_gpu = self.config.num_gpus pretty_print.print_cluster_status(cluster) elif print_to_console: if status == CodeFlareClusterStatus.UNKNOWN: @@ -802,16 +982,21 @@

      Classes

      Returns a string containing the cluster's dashboard URI. """ try: - with oc.project(self.config.namespace): - route = oc.invoke( - "get", ["route", "-o", "jsonpath='{$.items[*].spec.host}'"] - ) - route = route.out().split(" ") - route = [x for x in route if f"ray-dashboard-{self.config.name}" in x] - route = route[0].strip().strip("'") - return f"http://{route}" - except: - return "Dashboard route not available yet, have you run cluster.up()?" + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + routes = api_instance.list_namespaced_custom_object( + group="route.openshift.io", + version="v1", + namespace=self.config.namespace, + plural="routes", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for route in routes["items"]: + if route["metadata"]["name"] == f"ray-dashboard-{self.config.name}": + return f"http://{route['spec']['host']}" + return "Dashboard route not available yet, have you run cluster.up()?" def list_jobs(self) -> List: """ @@ -849,7 +1034,56 @@

      Classes

      to_return["working_dir"] = working_dir if requirements: to_return["requirements"] = requirements - return to_return
      + return to_return + + def from_k8_cluster_object(rc): + machine_types = ( + rc["metadata"]["labels"]["orderedinstance"].split("_") + if "orderedinstance" in rc["metadata"]["labels"] + else [] + ) + local_interactive = ( + "volumeMounts" + in rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0] + ) + cluster_config = ClusterConfiguration( + name=rc["metadata"]["name"], + namespace=rc["metadata"]["namespace"], + machine_types=machine_types, + num_workers=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], + min_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["requests"]["cpu"], + max_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["cpu"], + min_memory=int( + rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ + "resources" + ]["requests"]["memory"][:-1] + ), + max_memory=int( + rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ + "resources" + ]["limits"]["memory"][:-1] + ), + num_gpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["nvidia.com/gpu"], + instascale=True if machine_types else False, + image=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][ + 0 + ]["image"], + local_interactive=local_interactive, + ) + return Cluster(cluster_config) + + def local_client_url(self): + if self.config.local_interactive == True: + ingress_domain = _get_ingress_domain() + return f"ray://rayclient-{self.config.name}-{self.config.namespace}.{ingress_domain}" + else: + return "None"

      Class variables

      @@ -874,16 +1108,21 @@

      Methods

      Returns a string containing the cluster's dashboard URI. """ try: - with oc.project(self.config.namespace): - route = oc.invoke( - "get", ["route", "-o", "jsonpath='{$.items[*].spec.host}'"] - ) - route = route.out().split(" ") - route = [x for x in route if f"ray-dashboard-{self.config.name}" in x] - route = route[0].strip().strip("'") - return f"http://{route}" - except: - return "Dashboard route not available yet, have you run cluster.up()?" + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + routes = api_instance.list_namespaced_custom_object( + group="route.openshift.io", + version="v1", + namespace=self.config.namespace, + plural="routes", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for route in routes["items"]: + if route["metadata"]["name"] == f"ray-dashboard-{self.config.name}": + return f"http://{route['spec']['host']}" + return "Dashboard route not available yet, have you run cluster.up()?"

  • @@ -919,8 +1158,10 @@

    Methods

    """ if self.config.namespace is None: - self.config.namespace = oc.get_project_name() - if type(self.config.namespace) is not str: + self.config.namespace = get_current_namespace() + if self.config.namespace is None: + print("Please specify with namespace=<your_current_namespace>") + elif type(self.config.namespace) is not str: raise TypeError( f"Namespace {self.config.namespace} is of type {type(self.config.namespace)}. Check your Kubernetes Authentication." ) @@ -931,8 +1172,8 @@

    Methods

    max_cpu = self.config.max_cpus min_memory = self.config.min_memory max_memory = self.config.max_memory - gpu = self.config.gpu - workers = self.config.max_worker + gpu = self.config.num_gpus + workers = self.config.num_workers template = self.config.template image = self.config.image instascale = self.config.instascale @@ -992,23 +1233,69 @@

    Methods

    """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("delete", ["AppWrapper", self.app_wrapper_name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you run auth.login()/cluster.up() yet?" - ) - elif "not found" in error_msg: - print("Cluster not found, have you run cluster.up() yet?") - else: - raise osp
    + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + name=self.app_wrapper_name, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + +
    +def from_k8_cluster_object(rc) +
    +
    +
    +
    + +Expand source code + +
    def from_k8_cluster_object(rc):
    +    machine_types = (
    +        rc["metadata"]["labels"]["orderedinstance"].split("_")
    +        if "orderedinstance" in rc["metadata"]["labels"]
    +        else []
    +    )
    +    local_interactive = (
    +        "volumeMounts"
    +        in rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0]
    +    )
    +    cluster_config = ClusterConfiguration(
    +        name=rc["metadata"]["name"],
    +        namespace=rc["metadata"]["namespace"],
    +        machine_types=machine_types,
    +        num_workers=rc["spec"]["workerGroupSpecs"][0]["minReplicas"],
    +        min_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][
    +            "containers"
    +        ][0]["resources"]["requests"]["cpu"],
    +        max_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][
    +            "containers"
    +        ][0]["resources"]["limits"]["cpu"],
    +        min_memory=int(
    +            rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][
    +                "resources"
    +            ]["requests"]["memory"][:-1]
    +        ),
    +        max_memory=int(
    +            rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][
    +                "resources"
    +            ]["limits"]["memory"][:-1]
    +        ),
    +        num_gpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][
    +            "containers"
    +        ][0]["resources"]["limits"]["nvidia.com/gpu"],
    +        instascale=True if machine_types else False,
    +        image=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][
    +            0
    +        ]["image"],
    +        local_interactive=local_interactive,
    +    )
    +    return Cluster(cluster_config)
    @@ -1065,6 +1352,23 @@

    Methods

    return client.list_jobs()
    +
    +def local_client_url(self) +
    +
    +
    +
    + +Expand source code + +
    def local_client_url(self):
    +    if self.config.local_interactive == True:
    +        ingress_domain = _get_ingress_domain()
    +        return f"ray://rayclient-{self.config.name}-{self.config.namespace}.{ingress_domain}"
    +    else:
    +        return "None"
    +
    +
    def status(self, print_to_console: bool = True) ‑> Tuple[CodeFlareClusterStatus, bool]
    @@ -1101,9 +1405,15 @@

    Methods

    ready = False status = CodeFlareClusterStatus.FAILED # should deleted be separate return status, ready # exit early, no need to check ray status - elif appwrapper.status in [AppWrapperStatus.PENDING]: + elif appwrapper.status in [ + AppWrapperStatus.PENDING, + AppWrapperStatus.QUEUEING, + ]: ready = False - status = CodeFlareClusterStatus.QUEUED + if appwrapper.status == AppWrapperStatus.PENDING: + status = CodeFlareClusterStatus.QUEUED + else: + status = CodeFlareClusterStatus.QUEUEING if print_to_console: pretty_print.print_app_wrappers_status([appwrapper]) return ( @@ -1126,7 +1436,7 @@

    Methods

    if print_to_console: # overriding the number of gpus with requested - cluster.worker_gpu = self.config.gpu + cluster.worker_gpu = self.config.num_gpus pretty_print.print_cluster_status(cluster) elif print_to_console: if status == CodeFlareClusterStatus.UNKNOWN: @@ -1178,15 +1488,19 @@

    Methods

    """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("apply", ["-f", self.app_wrapper_yaml]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + with open(self.app_wrapper_yaml) as f: + aw = yaml.load(f, Loader=yaml.FullLoader) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + body=aw, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e)
    @@ -1240,6 +1554,8 @@

    Index

  • Functions

    @@ -1254,9 +1570,11 @@

    create_app_wrapper

  • details
  • down
  • +
  • from_k8_cluster_object
  • job_logs
  • job_status
  • list_jobs
  • +
  • local_client_url
  • status
  • torchx_config
  • torchx_scheduler
  • @@ -1273,4 +1591,4 @@

    pdoc 0.10.0.

    - \ No newline at end of file + diff --git a/docs/cluster/config.html b/docs/cluster/config.html index 98015567..168d252b 100644 --- a/docs/cluster/config.html +++ b/docs/cluster/config.html @@ -51,9 +51,7 @@

    Module codeflare_sdk.cluster.config

    """ from dataclasses import dataclass, field -from .auth import Authentication import pathlib -import openshift dir = pathlib.Path(__file__).parent.parent.resolve() @@ -71,15 +69,14 @@

    Module codeflare_sdk.cluster.config

    machine_types: list = field(default_factory=list) # ["m4.xlarge", "g4dn.xlarge"] min_cpus: int = 1 max_cpus: int = 1 - min_worker: int = 1 - max_worker: int = 1 + num_workers: int = 1 min_memory: int = 2 max_memory: int = 2 - gpu: int = 0 + num_gpus: int = 0 template: str = f"{dir}/templates/base-template.yaml" instascale: bool = False envs: dict = field(default_factory=dict) - image: str = "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" + image: str = "quay.io/project-codeflare/ray:2.5.0-py38-cu116" local_interactive: bool = False image_pull_secrets: list = field(default_factory=list)
    @@ -95,7 +92,7 @@

    Classes

    class ClusterConfiguration -(name: str, namespace: str = None, head_info: list = <factory>, machine_types: list = <factory>, min_cpus: int = 1, max_cpus: int = 1, min_worker: int = 1, max_worker: int = 1, min_memory: int = 2, max_memory: int = 2, gpu: int = 0, template: str = '/home/runner/work/codeflare-sdk/codeflare-sdk/src/codeflare_sdk/templates/base-template.yaml', instascale: bool = False, envs: dict = <factory>, image: str = 'ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103', local_interactive: bool = False, image_pull_secrets: list = <factory>) +(name: str, namespace: str = None, head_info: list = <factory>, machine_types: list = <factory>, min_cpus: int = 1, max_cpus: int = 1, num_workers: int = 1, min_memory: int = 2, max_memory: int = 2, num_gpus: int = 0, template: str = '/home/runner/work/codeflare-sdk/codeflare-sdk/src/codeflare_sdk/templates/base-template.yaml', instascale: bool = False, envs: dict = <factory>, image: str = 'quay.io/project-codeflare/ray:2.5.0-py38-cu116', local_interactive: bool = False, image_pull_secrets: list = <factory>)

    This dataclass is used to specify resource requirements and other details, and @@ -116,15 +113,14 @@

    Classes

    machine_types: list = field(default_factory=list) # ["m4.xlarge", "g4dn.xlarge"] min_cpus: int = 1 max_cpus: int = 1 - min_worker: int = 1 - max_worker: int = 1 + num_workers: int = 1 min_memory: int = 2 max_memory: int = 2 - gpu: int = 0 + num_gpus: int = 0 template: str = f"{dir}/templates/base-template.yaml" instascale: bool = False envs: dict = field(default_factory=dict) - image: str = "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" + image: str = "quay.io/project-codeflare/ray:2.5.0-py38-cu116" local_interactive: bool = False image_pull_secrets: list = field(default_factory=list)
    @@ -134,10 +130,6 @@

    Class variables

    -
    var gpu : int
    -
    -
    -
    var head_info : list
    @@ -170,27 +162,27 @@

    Class variables

    -
    var max_worker : int
    +
    var min_cpus : int
    -
    var min_cpus : int
    +
    var min_memory : int
    -
    var min_memory : int
    +
    var name : str
    -
    var min_worker : int
    +
    var namespace : str
    -
    var name : str
    +
    var num_gpus : int
    -
    var namespace : str
    +
    var num_workers : int
    @@ -220,7 +212,6 @@

    Index

    ClusterConfiguration

    @@ -247,4 +238,4 @@

    pdoc 0.10.0.

    - \ No newline at end of file + diff --git a/docs/cluster/index.html b/docs/cluster/index.html index 77d4de97..a6027e6f 100644 --- a/docs/cluster/index.html +++ b/docs/cluster/index.html @@ -88,4 +88,4 @@

    Index

    Generated by pdoc 0.10.0.

    - \ No newline at end of file + diff --git a/docs/cluster/model.html b/docs/cluster/model.html index 2a461555..7d911255 100644 --- a/docs/cluster/model.html +++ b/docs/cluster/model.html @@ -72,6 +72,7 @@

    Module codeflare_sdk.cluster.model

    Defines the possible reportable states of an AppWrapper. """ + QUEUEING = "queueing" PENDING = "pending" RUNNING = "running" FAILED = "failed" @@ -88,8 +89,9 @@

    Module codeflare_sdk.cluster.model

    READY = 1 STARTING = 2 QUEUED = 3 - FAILED = 4 - UNKNOWN = 5 + QUEUEING = 4 + FAILED = 5 + UNKNOWN = 6 @dataclass @@ -100,8 +102,7 @@

    Module codeflare_sdk.cluster.model

    name: str status: RayClusterStatus - min_workers: int - max_workers: int + workers: int worker_mem_min: str worker_mem_max: str worker_cpu: int @@ -186,6 +187,7 @@

    Class variables

    Defines the possible reportable states of an AppWrapper. """ + QUEUEING = "queueing" PENDING = "pending" RUNNING = "running" FAILED = "failed" @@ -215,6 +217,10 @@

    Class variables

    +
    var QUEUEING
    +
    +
    +
    var RUNNING
    @@ -243,8 +249,9 @@

    Class variables

    READY = 1 STARTING = 2 QUEUED = 3 - FAILED = 4 - UNKNOWN = 5
    + QUEUEING = 4 + FAILED = 5 + UNKNOWN = 6

    Ancestors

      @@ -260,6 +267,10 @@

      Class variables

      +
      var QUEUEING
      +
      +
      +
      var READY
      @@ -276,7 +287,7 @@

      Class variables

      class RayCluster -(name: str, status: RayClusterStatus, min_workers: int, max_workers: int, worker_mem_min: str, worker_mem_max: str, worker_cpu: int, worker_gpu: int, namespace: str, dashboard: str) +(name: str, status: RayClusterStatus, workers: int, worker_mem_min: str, worker_mem_max: str, worker_cpu: int, worker_gpu: int, namespace: str, dashboard: str)

      For storing information about a Ray cluster.

      @@ -291,8 +302,7 @@

      Class variables

      name: str status: RayClusterStatus - min_workers: int - max_workers: int + workers: int worker_mem_min: str worker_mem_max: str worker_cpu: int @@ -306,14 +316,6 @@

      Class variables

      -
      var max_workers : int
      -
      -
      -
      -
      var min_workers : int
      -
      -
      -
      var name : str
      @@ -342,6 +344,10 @@

      Class variables

      +
      var workers : int
      +
      +
      +

    @@ -421,15 +427,17 @@

    DELETED
  • FAILED
  • PENDING
  • +
  • QUEUEING
  • RUNNING
  • RUNNING_HOLD_COMPLETION
  • CodeFlareClusterStatus

    -
      +
      • FAILED
      • QUEUED
      • +
      • QUEUEING
      • READY
      • STARTING
      • UNKNOWN
      • @@ -439,8 +447,6 @@

        RayCluster

      • @@ -468,4 +475,4 @@

        pdoc 0.10.0.

        - \ No newline at end of file + diff --git a/docs/index.html b/docs/index.html index eca42a64..bd408f76 100644 --- a/docs/index.html +++ b/docs/index.html @@ -67,4 +67,4 @@

        Index

        Generated by pdoc 0.10.0.

        - \ No newline at end of file + diff --git a/docs/job/index.html b/docs/job/index.html index 335c2b57..2360deec 100644 --- a/docs/job/index.html +++ b/docs/job/index.html @@ -62,4 +62,4 @@

        Index

        Generated by pdoc 0.10.0.

        - \ No newline at end of file + diff --git a/docs/job/jobs.html b/docs/job/jobs.html index 08099daa..96ea4744 100644 --- a/docs/job/jobs.html +++ b/docs/job/jobs.html @@ -45,13 +45,13 @@

        Module codeflare_sdk.job.jobs

        from typing import TYPE_CHECKING, Optional, Dict, List from pathlib import Path -import openshift as oc from torchx.components.dist import ddp from torchx.runner import get_runner from torchx.specs import AppHandle, parse_app_handle, AppDryRunInfo if TYPE_CHECKING: from ..cluster.cluster import Cluster +from ..cluster.cluster import get_current_namespace all_jobs: List["Job"] = [] torchx_runner = get_runner() @@ -119,7 +119,7 @@

        Module codeflare_sdk.job.jobs

        self.workspace = workspace def _dry_run(self, cluster: "Cluster"): - j = f"{cluster.config.max_worker}x{max(cluster.config.gpu, 1)}" # # of proc. = # of gpus + j = f"{cluster.config.num_workers}x{max(cluster.config.num_gpus, 1)}" # # of proc. = # of gpus return torchx_runner.dryrun( app=ddp( *self.script_args, @@ -128,7 +128,7 @@

        Module codeflare_sdk.job.jobs

        name=self.name, h=self.h, cpu=self.cpu if self.cpu is not None else cluster.config.max_cpus, - gpu=self.gpu if self.gpu is not None else cluster.config.gpu, + gpu=self.gpu if self.gpu is not None else cluster.config.num_gpus, memMB=self.memMB if self.memMB is not None else cluster.config.max_memory * 1024, @@ -152,7 +152,7 @@

        Module codeflare_sdk.job.jobs

        def _dry_run_no_cluster(self): if self.scheduler_args is not None: if self.scheduler_args.get("namespace") is None: - self.scheduler_args["namespace"] = oc.get_project_name() + self.scheduler_args["namespace"] = get_current_namespace() return torchx_runner.dryrun( app=ddp( *self.script_args, @@ -359,7 +359,7 @@

        Methods

        self.workspace = workspace def _dry_run(self, cluster: "Cluster"): - j = f"{cluster.config.max_worker}x{max(cluster.config.gpu, 1)}" # # of proc. = # of gpus + j = f"{cluster.config.num_workers}x{max(cluster.config.num_gpus, 1)}" # # of proc. = # of gpus return torchx_runner.dryrun( app=ddp( *self.script_args, @@ -368,7 +368,7 @@

        Methods

        name=self.name, h=self.h, cpu=self.cpu if self.cpu is not None else cluster.config.max_cpus, - gpu=self.gpu if self.gpu is not None else cluster.config.gpu, + gpu=self.gpu if self.gpu is not None else cluster.config.num_gpus, memMB=self.memMB if self.memMB is not None else cluster.config.max_memory * 1024, @@ -392,7 +392,7 @@

        Methods

        def _dry_run_no_cluster(self): if self.scheduler_args is not None: if self.scheduler_args.get("namespace") is None: - self.scheduler_args["namespace"] = oc.get_project_name() + self.scheduler_args["namespace"] = get_current_namespace() return torchx_runner.dryrun( app=ddp( *self.script_args, @@ -593,4 +593,4 @@

        pdoc 0.10.0.

        - \ No newline at end of file + diff --git a/docs/utils/generate_cert.html b/docs/utils/generate_cert.html index 5f1fa18a..b41846f9 100644 --- a/docs/utils/generate_cert.html +++ b/docs/utils/generate_cert.html @@ -47,6 +47,7 @@

        Module codeflare_sdk.utils.generate_cert

        from cryptography import x509 from cryptography.x509.oid import NameOID import datetime +from ..cluster.auth import config_check, api_config_handler from kubernetes import client, config @@ -110,8 +111,8 @@

        Module codeflare_sdk.utils.generate_cert

        # Similar to: # oc get secret ca-secret-<cluster-name> -o template='{{index .data "ca.key"}}' # oc get secret ca-secret-<cluster-name> -o template='{{index .data "ca.crt"}}'|base64 -d > ${TLSDIR}/ca.crt - config.load_kube_config() - v1 = client.CoreV1Api() + config_check() + v1 = client.CoreV1Api(api_config_handler()) secret = v1.read_namespaced_secret(f"ca-secret-{cluster_name}", namespace).data ca_cert = secret.get("ca.crt") ca_key = secret.get("ca.key") @@ -291,8 +292,8 @@

        Functions

        # Similar to: # oc get secret ca-secret-<cluster-name> -o template='{{index .data "ca.key"}}' # oc get secret ca-secret-<cluster-name> -o template='{{index .data "ca.crt"}}'|base64 -d > ${TLSDIR}/ca.crt - config.load_kube_config() - v1 = client.CoreV1Api() + config_check() + v1 = client.CoreV1Api(api_config_handler()) secret = v1.read_namespaced_secret(f"ca-secret-{cluster_name}", namespace).data ca_cert = secret.get("ca.crt") ca_key = secret.get("ca.key") @@ -392,4 +393,4 @@

        Index

        Generated by pdoc 0.10.0.

        - \ No newline at end of file + diff --git a/docs/utils/generate_yaml.html b/docs/utils/generate_yaml.html index 9dc44b42..f8e6dcb9 100644 --- a/docs/utils/generate_yaml.html +++ b/docs/utils/generate_yaml.html @@ -52,7 +52,9 @@

        Module codeflare_sdk.utils.generate_yaml

        import sys import argparse import uuid -import openshift as oc +from kubernetes import client, config +from .kube_api_helpers import _kube_api_error_handling +from ..cluster.auth import api_config_handler def read_template(template): @@ -279,12 +281,16 @@

        Module codeflare_sdk.utils.generate_yaml

        ][0].get("command")[2] command = command.replace("deployment-name", cluster_name) - - server_name = ( - oc.whoami("--show-server").split(":")[1].split("//")[1].replace("api", "apps") - ) - - command = command.replace("server-name", server_name) + try: + config.load_kube_config() + api_client = client.CustomObjectsApi(api_config_handler()) + ingress = api_client.get_cluster_custom_object( + "config.openshift.io", "v1", "ingresses", "cluster" + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + domain = ingress["spec"]["domain"] + command = command.replace("server-name", domain) item["generictemplate"]["spec"]["headGroupSpec"]["template"]["spec"][ "initContainers" @@ -292,26 +298,61 @@

        Module codeflare_sdk.utils.generate_yaml

        def disable_raycluster_tls(resources): - del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][ - "template" - ]["spec"]["volumes"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][ - "template" - ]["spec"]["containers"][0]["volumeMounts"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][ - "template" - ]["spec"]["initContainers"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][ - "template" - ]["spec"]["volumes"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][ - "template" - ]["spec"]["containers"][0]["volumeMounts"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][ - "template" - ]["spec"]["initContainers"][1] - del resources["GenericItems"][3] # rayclient route - del resources["GenericItems"][2] # ca-secret + generic_template_spec = resources["GenericItems"][0]["generictemplate"]["spec"] + + if "volumes" in generic_template_spec["headGroupSpec"]["template"]["spec"]: + del generic_template_spec["headGroupSpec"]["template"]["spec"]["volumes"] + + if ( + "volumeMounts" + in generic_template_spec["headGroupSpec"]["template"]["spec"]["containers"][0] + ): + del generic_template_spec["headGroupSpec"]["template"]["spec"]["containers"][0][ + "volumeMounts" + ] + + if "initContainers" in generic_template_spec["headGroupSpec"]["template"]["spec"]: + del generic_template_spec["headGroupSpec"]["template"]["spec"]["initContainers"] + + if "volumes" in generic_template_spec["workerGroupSpecs"][0]["template"]["spec"]: + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"]["volumes"] + + if ( + "volumeMounts" + in generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0] + ): + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["volumeMounts"] + + for i in range( + len( + generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ] + ) + ): + if ( + generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ][i]["name"] + == "create-cert" + ): + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ][i] + + updated_items = [] + for i in resources["GenericItems"][:]: + if "rayclient-deployment-name" in i["generictemplate"]["metadata"]["name"]: + continue + if "ca-secret-deployment-name" in i["generictemplate"]["metadata"]["name"]: + continue + updated_items.append(i) + + resources["GenericItems"] = updated_items def write_user_appwrapper(user_yaml, output_file_name): @@ -368,135 +409,7 @@

        Module codeflare_sdk.utils.generate_yaml

        disable_raycluster_tls(resources["resources"]) outfile = appwrapper_name + ".yaml" write_user_appwrapper(user_yaml, outfile) - return outfile - - -def main(): # pragma: no cover - parser = argparse.ArgumentParser(description="Generate user AppWrapper") - parser.add_argument( - "--name", - required=False, - default="", - help="User selected name for AppWrapper and Ray Cluster (auto-generated if not provided)", - ) - parser.add_argument( - "--min-cpu", - type=int, - required=True, - help="min number of CPU(s) in a worker required for running job", - ) - parser.add_argument( - "--max-cpu", - type=int, - required=True, - help="max number of CPU(s) in a worker required for running job", - ) - parser.add_argument( - "--min-memory", - type=int, - required=True, - help="min RAM required in a worker for running job, in GB", - ) - parser.add_argument( - "--max-memory", - type=int, - required=True, - help="max RAM required in a worker for running job, in GB", - ) - parser.add_argument( - "--gpu", - type=int, - required=True, - help="GPU(s) required in a worker for running job", - ) - parser.add_argument( - "--workers", - type=int, - required=True, - help="How many workers are required in the cluster", - ) - parser.add_argument( - "--template", required=True, help="Template AppWrapper yaml file" - ) - parser.add_argument( - "--image", - required=False, - default="rayproject/ray:latest", - help="Ray image to be used (defaults to rayproject/ray:latest)", - ) - parser.add_argument( - "--instascale", - default=False, - required=False, - action="store_true", - help="Indicates that instascale is installed on the cluster", - ) - parser.add_argument( - "--instance-types", - type=str, - nargs="+", - default=[], - required=False, - help="Head,worker instance types (space separated)", - ) - parser.add_argument( - "--namespace", - required=False, - default="default", - help="Set the kubernetes namespace you want to deploy your cluster to. Default. If left blank, uses the 'default' namespace", - ) - parser.add_argument( - "--local-interactive", - required=False, - default=False, - help="Enable local interactive mode", - ) - parser.add_argument( - "--image-pull-secrets", - required=False, - default=[], - help="Set image pull secrets for private registries", - ) - - args = parser.parse_args() - name = args.name - min_cpu = args.min_cpu - max_cpu = args.max_cpu - min_memory = args.min_memory - max_memory = args.max_memory - gpu = args.gpu - workers = args.workers - template = args.template - image = args.image - instascale = args.instascale - instance_types = args.instance_types - namespace = args.namespace - local_interactive = args.local_interactive - env = {} - image_pull_secrets = args.image_pull_secrets - - outfile = generate_appwrapper( - name, - namespace, - min_cpu, - max_cpu, - min_memory, - max_memory, - gpu, - workers, - template, - image, - instascale, - instance_types, - local_interactive, - env, - image_pull_secrets, - ) - return outfile - - -if __name__ == "__main__": # pragma: no cover - main()
        + return outfile

  • @@ -516,26 +429,61 @@

    Functions

    Expand source code
    def disable_raycluster_tls(resources):
    -    del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][
    -        "template"
    -    ]["spec"]["volumes"]
    -    del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][
    -        "template"
    -    ]["spec"]["containers"][0]["volumeMounts"]
    -    del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][
    -        "template"
    -    ]["spec"]["initContainers"]
    -    del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][
    -        "template"
    -    ]["spec"]["volumes"]
    -    del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][
    -        "template"
    -    ]["spec"]["containers"][0]["volumeMounts"]
    -    del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][
    -        "template"
    -    ]["spec"]["initContainers"][1]
    -    del resources["GenericItems"][3]  # rayclient route
    -    del resources["GenericItems"][2]  # ca-secret
    + generic_template_spec = resources["GenericItems"][0]["generictemplate"]["spec"] + + if "volumes" in generic_template_spec["headGroupSpec"]["template"]["spec"]: + del generic_template_spec["headGroupSpec"]["template"]["spec"]["volumes"] + + if ( + "volumeMounts" + in generic_template_spec["headGroupSpec"]["template"]["spec"]["containers"][0] + ): + del generic_template_spec["headGroupSpec"]["template"]["spec"]["containers"][0][ + "volumeMounts" + ] + + if "initContainers" in generic_template_spec["headGroupSpec"]["template"]["spec"]: + del generic_template_spec["headGroupSpec"]["template"]["spec"]["initContainers"] + + if "volumes" in generic_template_spec["workerGroupSpecs"][0]["template"]["spec"]: + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"]["volumes"] + + if ( + "volumeMounts" + in generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0] + ): + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["volumeMounts"] + + for i in range( + len( + generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ] + ) + ): + if ( + generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ][i]["name"] + == "create-cert" + ): + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ][i] + + updated_items = [] + for i in resources["GenericItems"][:]: + if "rayclient-deployment-name" in i["generictemplate"]["metadata"]["name"]: + continue + if "ca-secret-deployment-name" in i["generictemplate"]["metadata"]["name"]: + continue + updated_items.append(i) + + resources["GenericItems"] = updated_items
    @@ -573,12 +521,16 @@

    Functions

    ][0].get("command")[2] command = command.replace("deployment-name", cluster_name) - - server_name = ( - oc.whoami("--show-server").split(":")[1].split("//")[1].replace("api", "apps") - ) - - command = command.replace("server-name", server_name) + try: + config.load_kube_config() + api_client = client.CustomObjectsApi(api_config_handler()) + ingress = api_client.get_cluster_custom_object( + "config.openshift.io", "v1", "ingresses", "cluster" + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + domain = ingress["spec"]["domain"] + command = command.replace("server-name", domain) item["generictemplate"]["spec"]["headGroupSpec"]["template"]["spec"][ "initContainers" @@ -664,139 +616,6 @@

    Functions

    return outfile
    -
    -def main() -
    -
    -
    -
    - -Expand source code - -
    def main():  # pragma: no cover
    -    parser = argparse.ArgumentParser(description="Generate user AppWrapper")
    -    parser.add_argument(
    -        "--name",
    -        required=False,
    -        default="",
    -        help="User selected name for AppWrapper and Ray Cluster (auto-generated if not provided)",
    -    )
    -    parser.add_argument(
    -        "--min-cpu",
    -        type=int,
    -        required=True,
    -        help="min number of CPU(s) in a worker required for running job",
    -    )
    -    parser.add_argument(
    -        "--max-cpu",
    -        type=int,
    -        required=True,
    -        help="max number of CPU(s) in a worker required for running job",
    -    )
    -    parser.add_argument(
    -        "--min-memory",
    -        type=int,
    -        required=True,
    -        help="min RAM required in a worker for running job, in GB",
    -    )
    -    parser.add_argument(
    -        "--max-memory",
    -        type=int,
    -        required=True,
    -        help="max RAM required in a worker for running job, in GB",
    -    )
    -    parser.add_argument(
    -        "--gpu",
    -        type=int,
    -        required=True,
    -        help="GPU(s) required in a worker for running job",
    -    )
    -    parser.add_argument(
    -        "--workers",
    -        type=int,
    -        required=True,
    -        help="How many workers are required in the cluster",
    -    )
    -    parser.add_argument(
    -        "--template", required=True, help="Template AppWrapper yaml file"
    -    )
    -    parser.add_argument(
    -        "--image",
    -        required=False,
    -        default="rayproject/ray:latest",
    -        help="Ray image to be used (defaults to rayproject/ray:latest)",
    -    )
    -    parser.add_argument(
    -        "--instascale",
    -        default=False,
    -        required=False,
    -        action="store_true",
    -        help="Indicates that instascale is installed on the cluster",
    -    )
    -    parser.add_argument(
    -        "--instance-types",
    -        type=str,
    -        nargs="+",
    -        default=[],
    -        required=False,
    -        help="Head,worker instance types (space separated)",
    -    )
    -    parser.add_argument(
    -        "--namespace",
    -        required=False,
    -        default="default",
    -        help="Set the kubernetes namespace you want to deploy your cluster to. Default. If left blank, uses the 'default' namespace",
    -    )
    -    parser.add_argument(
    -        "--local-interactive",
    -        required=False,
    -        default=False,
    -        help="Enable local interactive mode",
    -    )
    -    parser.add_argument(
    -        "--image-pull-secrets",
    -        required=False,
    -        default=[],
    -        help="Set image pull secrets for private registries",
    -    )
    -
    -    args = parser.parse_args()
    -    name = args.name
    -    min_cpu = args.min_cpu
    -    max_cpu = args.max_cpu
    -    min_memory = args.min_memory
    -    max_memory = args.max_memory
    -    gpu = args.gpu
    -    workers = args.workers
    -    template = args.template
    -    image = args.image
    -    instascale = args.instascale
    -    instance_types = args.instance_types
    -    namespace = args.namespace
    -    local_interactive = args.local_interactive
    -    env = {}
    -    image_pull_secrets = args.image_pull_secrets
    -
    -    outfile = generate_appwrapper(
    -        name,
    -        namespace,
    -        min_cpu,
    -        max_cpu,
    -        min_memory,
    -        max_memory,
    -        gpu,
    -        workers,
    -        template,
    -        image,
    -        instascale,
    -        instance_types,
    -        local_interactive,
    -        env,
    -        image_pull_secrets,
    -    )
    -    return outfile
    -
    -
    def read_template(template)
    @@ -1138,7 +957,6 @@

    Index

  • enable_local_interactive
  • gen_names
  • generate_appwrapper
  • -
  • main
  • read_template
  • update_affinity
  • update_ca_secret
  • @@ -1162,4 +980,4 @@

    Index

    Generated by pdoc 0.10.0.

    - \ No newline at end of file + diff --git a/docs/utils/index.html b/docs/utils/index.html index bfbc5d7b..1eb081d2 100644 --- a/docs/utils/index.html +++ b/docs/utils/index.html @@ -35,6 +35,11 @@

    Sub-modules

    This sub-module exists primarily to be used internally by the Cluster object (in the cluster sub-module) for AppWrapper generation.

    +
    codeflare_sdk.utils.kube_api_helpers
    +
    +

    This sub-module exists primarily to be used internally for any Kubernetes +API error handling or wrapping.

    +
    codeflare_sdk.utils.pretty_print

    This sub-module exists primarily to be used internally by the Cluster object @@ -64,6 +69,7 @@

    Index

    @@ -74,4 +80,4 @@

    Index

    Generated by pdoc 0.10.0.

    - \ No newline at end of file + diff --git a/docs/utils/kube_api_helpers.html b/docs/utils/kube_api_helpers.html new file mode 100644 index 00000000..4c2ecb78 --- /dev/null +++ b/docs/utils/kube_api_helpers.html @@ -0,0 +1,105 @@ + + + + + + +codeflare_sdk.utils.kube_api_helpers API documentation + + + + + + + + + + + +
    +
    +
    +

    Module codeflare_sdk.utils.kube_api_helpers

    +
    +
    +

    This sub-module exists primarily to be used internally for any Kubernetes +API error handling or wrapping.

    +
    + +Expand source code + +
    # Copyright 2022 IBM, Red Hat
    +#
    +# Licensed 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.
    +
    +"""
    +This sub-module exists primarily to be used internally for any Kubernetes
    +API error handling or wrapping.
    +"""
    +
    +import executing
    +from kubernetes import client, config
    +
    +
    +# private methods
    +def _kube_api_error_handling(e: Exception):  # pragma: no cover
    +    perm_msg = (
    +        "Action not permitted, have you put in correct/up-to-date auth credentials?"
    +    )
    +    nf_msg = "No instances found, nothing to be done."
    +    exists_msg = "Resource with this name already exists."
    +    if type(e) == config.ConfigException:
    +        raise PermissionError(perm_msg)
    +    if type(e) == executing.executing.NotOneValueFound:
    +        print(nf_msg)
    +        return
    +    if type(e) == client.ApiException:
    +        if e.reason == "Not Found":
    +            print(nf_msg)
    +            return
    +        elif e.reason == "Unauthorized" or e.reason == "Forbidden":
    +            raise PermissionError(perm_msg)
    +        elif e.reason == "Conflict":
    +            raise FileExistsError(exists_msg)
    +    raise e
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    + + + diff --git a/docs/utils/pretty_print.html b/docs/utils/pretty_print.html index d6f64b3a..5ff38db1 100644 --- a/docs/utils/pretty_print.html +++ b/docs/utils/pretty_print.html @@ -146,8 +146,7 @@

    Module codeflare_sdk.utils.pretty_print

    ) name = cluster.name dashboard = cluster.dashboard - mincount = str(cluster.min_workers) - maxcount = str(cluster.max_workers) + workers = str(cluster.workers) memory = str(cluster.worker_mem_min) + "~" + str(cluster.worker_mem_max) cpu = str(cluster.worker_cpu) gpu = str(cluster.worker_gpu) @@ -173,10 +172,9 @@

    Module codeflare_sdk.utils.pretty_print

    #'table1' to display the worker counts table1 = Table(box=None) table1.add_row() - table1.add_column("Min", style="cyan", no_wrap=True) - table1.add_column("Max", style="magenta") + table1.add_column("# Workers", style="magenta") table1.add_row() - table1.add_row(mincount, maxcount) + table1.add_row(workers) table1.add_row() #'table2' to display the worker resources @@ -334,8 +332,7 @@

    Functions

    ) name = cluster.name dashboard = cluster.dashboard - mincount = str(cluster.min_workers) - maxcount = str(cluster.max_workers) + workers = str(cluster.workers) memory = str(cluster.worker_mem_min) + "~" + str(cluster.worker_mem_max) cpu = str(cluster.worker_cpu) gpu = str(cluster.worker_gpu) @@ -361,10 +358,9 @@

    Functions

    #'table1' to display the worker counts table1 = Table(box=None) table1.add_row() - table1.add_column("Min", style="cyan", no_wrap=True) - table1.add_column("Max", style="magenta") + table1.add_column("# Workers", style="magenta") table1.add_row() - table1.add_row(mincount, maxcount) + table1.add_row(workers) table1.add_row() #'table2' to display the worker resources @@ -450,4 +446,4 @@

    Index

    Generated by pdoc 0.10.0.

    - \ No newline at end of file + diff --git a/pyproject.toml b/pyproject.toml index 79b90cb3..6f8393ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,13 +23,20 @@ keywords = ['codeflare', 'python', 'sdk', 'client', 'batch', 'scale'] python = "^3.7" openshift-client = "1.0.18" rich = "^12.5" -ray = {version = "2.1.0", extras = ["default"]} +ray = {version = "2.5.0", extras = ["default"]} kubernetes = ">= 25.3.0, < 27" codeflare-torchx = "0.6.0.dev0" cryptography = "40.0.2" +executing = "1.2.0" +pydantic = "< 2" [tool.poetry.group.docs] optional = true [tool.poetry.group.docs.dependencies] pdoc3 = "0.10.0" + +[tool.poetry.group.test.dependencies] +pytest = "7.4.0" +coverage = "7.2.7" +pytest-mock = "3.11.1" diff --git a/requirements.txt b/requirements.txt index e529bc39..2a48812a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,8 @@ openshift-client==1.0.18 rich==12.5.1 -ray[default]==2.1.0 +ray[default]==2.5.0 kubernetes>=25.3.0,<27 codeflare-torchx==0.6.0.dev0 +pydantic<2 # 2.0+ broke ray[default] see detail: https://github.com/ray-project/ray/pull/37000 +cryptography==40.0.2 +executing==1.2.0 diff --git a/src/codeflare_sdk/cluster/auth.py b/src/codeflare_sdk/cluster/auth.py index 33ad8cf7..85db3d61 100644 --- a/src/codeflare_sdk/cluster/auth.py +++ b/src/codeflare_sdk/cluster/auth.py @@ -20,8 +20,12 @@ """ import abc -import openshift as oc -from openshift import OpenShiftPythonException +from kubernetes import client, config + +global api_client +api_client = None +global config_path +config_path = None class Authentication(metaclass=abc.ABCMeta): @@ -43,80 +47,131 @@ def logout(self): pass +class KubeConfiguration(metaclass=abc.ABCMeta): + """ + An abstract class that defines the method for loading a user defined config file using the `load_kube_config()` function + """ + + def load_kube_config(self): + """ + Method for setting your Kubernetes configuration to a certain file + """ + pass + + def logout(self): + """ + Method for logging out of the remote cluster + """ + pass + + class TokenAuthentication(Authentication): """ - `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift + `TokenAuthentication` is a subclass of `Authentication`. It can be used to authenticate to a Kubernetes cluster when the user has an API token and the API server address. """ - def __init__(self, token: str = None, server: str = None, skip_tls: bool = False): + def __init__( + self, + token: str, + server: str, + skip_tls: bool = False, + ca_cert_path: str = None, + ): """ Initialize a TokenAuthentication object that requires a value for `token`, the API Token - and `server`, the API server address for authenticating to an OpenShift cluster. + and `server`, the API server address for authenticating to a Kubernetes cluster. """ self.token = token self.server = server self.skip_tls = skip_tls + self.ca_cert_path = ca_cert_path def login(self) -> str: """ - This function is used to login to an OpenShift cluster using the user's API token and API server address. - Depending on the cluster, a user can choose to login in with "--insecure-skip-tls-verify` by setting `skip_tls` - to `True`. + This function is used to log in to a Kubernetes cluster using the user's API token and API server address. + Depending on the cluster, a user can choose to login in with `--insecure-skip-tls-verify` by setting `skip_tls` + to `True` or `--certificate-authority` by setting `skip_tls` to False and providing a path to a ca bundle with `ca_cert_path`. """ - args = [f"--token={self.token}", f"--server={self.server}"] - if self.skip_tls: - args.append("--insecure-skip-tls-verify") + global config_path + global api_client try: - response = oc.invoke("login", args) - except OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "The server uses a certificate signed by unknown authority" in error_msg: - return "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication" - elif "invalid" in error_msg: - raise PermissionError(error_msg) + configuration = client.Configuration() + configuration.api_key_prefix["authorization"] = "Bearer" + configuration.host = self.server + configuration.api_key["authorization"] = self.token + if self.skip_tls == False and self.ca_cert_path == None: + configuration.verify_ssl = True + elif self.skip_tls == False: + configuration.ssl_ca_cert = self.ca_cert_path else: - return error_msg - return response.out() + configuration.verify_ssl = False + api_client = client.ApiClient(configuration) + client.AuthenticationApi(api_client).get_api_group() + config_path = None + return "Logged into %s" % self.server + except client.ApiException: # pragma: no cover + api_client = None + print("Authentication Error please provide the correct token + server") def logout(self) -> str: """ - This function is used to logout of an OpenShift cluster. + This function is used to logout of a Kubernetes cluster. """ - args = [f"--token={self.token}", f"--server={self.server}"] - response = oc.invoke("logout", args) - return response.out() + global config_path + config_path = None + global api_client + api_client = None + return "Successfully logged out of %s" % self.server -class PasswordUserAuthentication(Authentication): +class KubeConfigFileAuthentication(KubeConfiguration): """ - `PasswordUserAuthentication` is a subclass of `Authentication`. It can be used to authenticate to an OpenShift - cluster when the user has a username and password. + A class that defines the necessary methods for passing a user's own Kubernetes config file. + Specifically this class defines the `load_kube_config()` and `config_check()` functions. """ - def __init__( - self, - username: str = None, - password: str = None, - ): - """ - Initialize a PasswordUserAuthentication object that requires a value for `username` - and `password` for authenticating to an OpenShift cluster. - """ - self.username = username - self.password = password + def __init__(self, kube_config_path: str = None): + self.kube_config_path = kube_config_path - def login(self) -> str: + def load_kube_config(self): """ - This function is used to login to an OpenShift cluster using the user's `username` and `password`. + Function for loading a user's own predefined Kubernetes config file. """ - response = oc.login(self.username, self.password) - return response.out() + global config_path + global api_client + try: + if self.kube_config_path == None: + return "Please specify a config file path" + config_path = self.kube_config_path + api_client = None + config.load_kube_config(config_path) + response = "Loaded user config file at path %s" % self.kube_config_path + except config.ConfigException: # pragma: no cover + config_path = None + raise Exception("Please specify a config file path") + return response + + +def config_check() -> str: + """ + Function for loading the config file at the default config location ~/.kube/config if the user has not + specified their own config file or has logged in with their token and server. + """ + global config_path + global api_client + if config_path == None and api_client == None: + config.load_kube_config() + if config_path != None and api_client == None: + return config_path - def logout(self) -> str: - """ - This function is used to logout of an OpenShift cluster. - """ - response = oc.invoke("logout") - return response.out() + +def api_config_handler() -> str: + """ + This function is used to load the api client if the user has logged in + """ + if api_client != None and config_path == None: + return api_client + else: + return None diff --git a/src/codeflare_sdk/cluster/awload.py b/src/codeflare_sdk/cluster/awload.py index 5621d673..12544eba 100644 --- a/src/codeflare_sdk/cluster/awload.py +++ b/src/codeflare_sdk/cluster/awload.py @@ -20,9 +20,12 @@ from os.path import isfile import errno import os -import openshift as oc import yaml +from kubernetes import client, config +from ..utils.kube_api_helpers import _kube_api_error_handling +from .auth import config_check, api_config_handler + class AWManager: """ @@ -40,10 +43,10 @@ def __init__(self, filename: str) -> None: self.filename = filename try: with open(self.filename) as f: - awyaml = yaml.load(f, Loader=yaml.FullLoader) - assert awyaml["kind"] == "AppWrapper" - self.name = awyaml["metadata"]["name"] - self.namespace = awyaml["metadata"]["namespace"] + self.awyaml = yaml.load(f, Loader=yaml.FullLoader) + assert self.awyaml["kind"] == "AppWrapper" + self.name = self.awyaml["metadata"]["name"] + self.namespace = self.awyaml["metadata"]["namespace"] except: raise ValueError( f"{filename } is not a correctly formatted AppWrapper yaml" @@ -55,19 +58,17 @@ def submit(self) -> None: Attempts to create the AppWrapper custom resource using the yaml file """ try: - with oc.project(self.namespace): - oc.invoke("create", ["-f", self.filename]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg or "Forbidden" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "AlreadyExists" in error_msg: - raise FileExistsError( - f"An AppWrapper of the name {self.name} already exists in namespace {self.namespace}" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + body=self.awyaml, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = True print(f"AppWrapper {self.filename} submitted!") @@ -82,25 +83,17 @@ def remove(self) -> None: return try: - with oc.project(self.namespace): - oc.invoke("delete", ["AppWrapper", self.name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - elif "not found" in error_msg: - self.submitted = False - print("AppWrapper not found, was deleted in another manner") - return - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=self.namespace, + plural="appwrappers", + name=self.name, + ) + except Exception as e: + return _kube_api_error_handling(e) self.submitted = False print(f"AppWrapper {self.name} removed!") diff --git a/src/codeflare_sdk/cluster/cluster.py b/src/codeflare_sdk/cluster/cluster.py index c09e981b..d698331e 100644 --- a/src/codeflare_sdk/cluster/cluster.py +++ b/src/codeflare_sdk/cluster/cluster.py @@ -18,15 +18,15 @@ cluster setup queue, a list of all existing clusters, and the user's working namespace. """ -from os import stat from time import sleep from typing import List, Optional, Tuple, Dict -import openshift as oc from ray.job_submission import JobSubmissionClient +from .auth import config_check, api_config_handler from ..utils import pretty_print from ..utils.generate_yaml import generate_appwrapper +from ..utils.kube_api_helpers import _kube_api_error_handling from .config import ClusterConfiguration from .model import ( AppWrapper, @@ -35,6 +35,9 @@ RayCluster, RayClusterStatus, ) +from kubernetes import client, config +import yaml +import os class Cluster: @@ -65,8 +68,10 @@ def create_app_wrapper(self): """ if self.config.namespace is None: - self.config.namespace = oc.get_project_name() - if type(self.config.namespace) is not str: + self.config.namespace = get_current_namespace() + if self.config.namespace is None: + print("Please specify with namespace=") + elif type(self.config.namespace) is not str: raise TypeError( f"Namespace {self.config.namespace} is of type {type(self.config.namespace)}. Check your Kubernetes Authentication." ) @@ -77,8 +82,8 @@ def create_app_wrapper(self): max_cpu = self.config.max_cpus min_memory = self.config.min_memory max_memory = self.config.max_memory - gpu = self.config.gpu - workers = self.config.max_worker + gpu = self.config.num_gpus + workers = self.config.num_workers template = self.config.template image = self.config.image instascale = self.config.instascale @@ -112,15 +117,19 @@ def up(self): """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("apply", ["-f", self.app_wrapper_yaml]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if "Unauthorized" in error_msg: - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + with open(self.app_wrapper_yaml) as f: + aw = yaml.load(f, Loader=yaml.FullLoader) + api_instance.create_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + body=aw, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) def down(self): """ @@ -129,23 +138,17 @@ def down(self): """ namespace = self.config.namespace try: - with oc.project(namespace): - oc.invoke("delete", ["AppWrapper", self.app_wrapper_name]) - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "AppWrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you run auth.login()/cluster.up() yet?" - ) - elif "not found" in error_msg: - print("Cluster not found, have you run cluster.up() yet?") - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + api_instance.delete_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + name=self.app_wrapper_name, + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) def status( self, print_to_console: bool = True @@ -173,9 +176,15 @@ def status( ready = False status = CodeFlareClusterStatus.FAILED # should deleted be separate return status, ready # exit early, no need to check ray status - elif appwrapper.status in [AppWrapperStatus.PENDING]: + elif appwrapper.status in [ + AppWrapperStatus.PENDING, + AppWrapperStatus.QUEUEING, + ]: ready = False - status = CodeFlareClusterStatus.QUEUED + if appwrapper.status == AppWrapperStatus.PENDING: + status = CodeFlareClusterStatus.QUEUED + else: + status = CodeFlareClusterStatus.QUEUEING if print_to_console: pretty_print.print_app_wrappers_status([appwrapper]) return ( @@ -198,7 +207,7 @@ def status( if print_to_console: # overriding the number of gpus with requested - cluster.worker_gpu = self.config.gpu + cluster.worker_gpu = self.config.num_gpus pretty_print.print_cluster_status(cluster) elif print_to_console: if status == CodeFlareClusterStatus.UNKNOWN: @@ -247,16 +256,21 @@ def cluster_dashboard_uri(self) -> str: Returns a string containing the cluster's dashboard URI. """ try: - with oc.project(self.config.namespace): - route = oc.invoke( - "get", ["route", "-o", "jsonpath='{$.items[*].spec.host}'"] - ) - route = route.out().split(" ") - route = [x for x in route if f"ray-dashboard-{self.config.name}" in x] - route = route[0].strip().strip("'") - return f"http://{route}" - except: - return "Dashboard route not available yet, have you run cluster.up()?" + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + routes = api_instance.list_namespaced_custom_object( + group="route.openshift.io", + version="v1", + namespace=self.config.namespace, + plural="routes", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for route in routes["items"]: + if route["metadata"]["name"] == f"ray-dashboard-{self.config.name}": + return f"http://{route['spec']['host']}" + return "Dashboard route not available yet, have you run cluster.up()?" def list_jobs(self) -> List: """ @@ -296,6 +310,55 @@ def torchx_config( to_return["requirements"] = requirements return to_return + def from_k8_cluster_object(rc): + machine_types = ( + rc["metadata"]["labels"]["orderedinstance"].split("_") + if "orderedinstance" in rc["metadata"]["labels"] + else [] + ) + local_interactive = ( + "volumeMounts" + in rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0] + ) + cluster_config = ClusterConfiguration( + name=rc["metadata"]["name"], + namespace=rc["metadata"]["namespace"], + machine_types=machine_types, + num_workers=rc["spec"]["workerGroupSpecs"][0]["minReplicas"], + min_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["requests"]["cpu"], + max_cpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["cpu"], + min_memory=int( + rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ + "resources" + ]["requests"]["memory"][:-1] + ), + max_memory=int( + rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][0][ + "resources" + ]["limits"]["memory"][:-1] + ), + num_gpus=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["nvidia.com/gpu"], + instascale=True if machine_types else False, + image=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][ + 0 + ]["image"], + local_interactive=local_interactive, + ) + return Cluster(cluster_config) + + def local_client_url(self): + if self.config.local_interactive == True: + ingress_domain = _get_ingress_domain() + return f"ray://rayclient-{self.config.name}-{self.config.namespace}.{ingress_domain}" + else: + return "None" + def list_all_clusters(namespace: str, print_to_console: bool = True): """ @@ -320,78 +383,120 @@ def list_all_queued(namespace: str, print_to_console: bool = True): return app_wrappers +def get_current_namespace(): # pragma: no cover + if api_config_handler() != None: + if os.path.isfile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"): + try: + file = open( + "/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r" + ) + active_context = file.readline().strip("\n") + return active_context + except Exception as e: + print("Unable to find current namespace") + return None + else: + print("Unable to find current namespace") + return None + else: + try: + _, active_context = config.list_kube_config_contexts(config_check()) + except Exception as e: + return _kube_api_error_handling(e) + try: + return active_context["context"]["namespace"] + except KeyError: + return None + + +def get_cluster(cluster_name: str, namespace: str = "default"): + try: + config.load_kube_config() + api_instance = client.CustomObjectsApi() + rcs = api_instance.list_namespaced_custom_object( + group="ray.io", + version="v1alpha1", + namespace=namespace, + plural="rayclusters", + ) + except Exception as e: + return _kube_api_error_handling(e) + + for rc in rcs["items"]: + if rc["metadata"]["name"] == cluster_name: + return Cluster.from_k8_cluster_object(rc) + raise FileNotFoundError( + f"Cluster {cluster_name} is not found in {namespace} namespace" + ) + + # private methods +def _get_ingress_domain(): + try: + config.load_kube_config() + api_client = client.CustomObjectsApi(api_config_handler()) + ingress = api_client.get_cluster_custom_object( + "config.openshift.io", "v1", "ingresses", "cluster" + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + return ingress["spec"]["domain"] def _app_wrapper_status(name, namespace="default") -> Optional[AppWrapper]: - cluster = None try: - with oc.project(namespace), oc.timeout(10 * 60): - cluster = oc.selector(f"appwrapper/{name}").object() - except oc.OpenShiftPythonException as osp: # pragma: no cover - msg = osp.msg - if "Expected a single object, but selected 0" in msg: - return cluster - error_msg = osp.result.err() - if not ( - 'the server doesn\'t have a resource type "appwrapper"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise osp - - if cluster: - return _map_to_app_wrapper(cluster) - - return cluster + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + aws = api_instance.list_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for aw in aws["items"]: + if aw["metadata"]["name"] == name: + return _map_to_app_wrapper(aw) + return None def _ray_cluster_status(name, namespace="default") -> Optional[RayCluster]: - cluster = None try: - with oc.project(namespace), oc.timeout(10 * 60): - cluster = oc.selector(f"rayclusters/{name}").object() - except oc.OpenShiftPythonException as osp: # pragma: no cover - msg = osp.msg - if "Expected a single object, but selected 0" in msg: - return cluster - error_msg = osp.result.err() - if not ( - 'the server doesn\'t have a resource type "rayclusters"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise osp - - if cluster: - return _map_to_ray_cluster(cluster) - - return cluster + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + rcs = api_instance.list_namespaced_custom_object( + group="ray.io", + version="v1alpha1", + namespace=namespace, + plural="rayclusters", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + + for rc in rcs["items"]: + if rc["metadata"]["name"] == name: + return _map_to_ray_cluster(rc) + return None def _get_ray_clusters(namespace="default") -> List[RayCluster]: list_of_clusters = [] try: - with oc.project(namespace), oc.timeout(10 * 60): - ray_clusters = oc.selector("rayclusters").objects() - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "rayclusters"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + rcs = api_instance.list_namespaced_custom_object( + group="ray.io", + version="v1alpha1", + namespace=namespace, + plural="rayclusters", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) - for cluster in ray_clusters: - list_of_clusters.append(_map_to_ray_cluster(cluster)) + for rc in rcs["items"]: + list_of_clusters.append(_map_to_ray_cluster(rc)) return list_of_clusters @@ -401,23 +506,18 @@ def _get_app_wrappers( list_of_app_wrappers = [] try: - with oc.project(namespace), oc.timeout(10 * 60): - app_wrappers = oc.selector("appwrappers").objects() - except oc.OpenShiftPythonException as osp: # pragma: no cover - error_msg = osp.result.err() - if ( - 'the server doesn\'t have a resource type "appwrappers"' in error_msg - or "forbidden" in error_msg - or "Unauthorized" in error_msg - or "Missing or incomplete configuration" in error_msg - ): - raise PermissionError( - "Action not permitted, have you put in correct/up-to-date auth credentials?" - ) - else: - raise osp + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + aws = api_instance.list_namespaced_custom_object( + group="mcad.ibm.com", + version="v1beta1", + namespace=namespace, + plural="appwrappers", + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) - for item in app_wrappers: + for item in aws["items"]: app_wrapper = _map_to_app_wrapper(item) if filter and app_wrapper.status in filter: list_of_app_wrappers.append(app_wrapper) @@ -427,48 +527,58 @@ def _get_app_wrappers( return list_of_app_wrappers -def _map_to_ray_cluster(cluster) -> Optional[RayCluster]: - cluster_model = cluster.model - if type(cluster_model.status.state) == oc.model.MissingModel: - status = RayClusterStatus.UNKNOWN +def _map_to_ray_cluster(rc) -> Optional[RayCluster]: + if "state" in rc["status"]: + status = RayClusterStatus(rc["status"]["state"].lower()) else: - status = RayClusterStatus(cluster_model.status.state.lower()) + status = RayClusterStatus.UNKNOWN - with oc.project(cluster.namespace()), oc.timeout(10 * 60): - route = ( - oc.selector(f"route/ray-dashboard-{cluster.name()}") - .object() - .model.spec.host - ) + config_check() + api_instance = client.CustomObjectsApi(api_config_handler()) + routes = api_instance.list_namespaced_custom_object( + group="route.openshift.io", + version="v1", + namespace=rc["metadata"]["namespace"], + plural="routes", + ) + ray_route = None + for route in routes["items"]: + if route["metadata"]["name"] == f"ray-dashboard-{rc['metadata']['name']}": + ray_route = route["spec"]["host"] return RayCluster( - name=cluster.name(), + name=rc["metadata"]["name"], status=status, # for now we are not using autoscaling so same replicas is fine - min_workers=cluster_model.spec.workerGroupSpecs[0].replicas, - max_workers=cluster_model.spec.workerGroupSpecs[0].replicas, - worker_mem_max=cluster_model.spec.workerGroupSpecs[0] - .template.spec.containers[0] - .resources.limits.memory, - worker_mem_min=cluster_model.spec.workerGroupSpecs[0] - .template.spec.containers[0] - .resources.requests.memory, - worker_cpu=cluster_model.spec.workerGroupSpecs[0] - .template.spec.containers[0] - .resources.limits.cpu, + workers=rc["spec"]["workerGroupSpecs"][0]["replicas"], + worker_mem_max=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["limits"]["memory"], + worker_mem_min=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["resources"]["requests"]["memory"], + worker_cpu=rc["spec"]["workerGroupSpecs"][0]["template"]["spec"]["containers"][ + 0 + ]["resources"]["limits"]["cpu"], worker_gpu=0, # hard to detect currently how many gpus, can override it with what the user asked for - namespace=cluster.namespace(), - dashboard=route, + namespace=rc["metadata"]["namespace"], + dashboard=ray_route, ) -def _map_to_app_wrapper(cluster) -> AppWrapper: - cluster_model = cluster.model +def _map_to_app_wrapper(aw) -> AppWrapper: + if "status" in aw and "canrun" in aw["status"]: + return AppWrapper( + name=aw["metadata"]["name"], + status=AppWrapperStatus(aw["status"]["state"].lower()), + can_run=aw["status"]["canrun"], + job_state=aw["status"]["queuejobstate"], + ) return AppWrapper( - name=cluster.name(), - status=AppWrapperStatus(cluster_model.status.state.lower()), - can_run=cluster_model.status.canrun, - job_state=cluster_model.status.queuejobstate, + name=aw["metadata"]["name"], + status=AppWrapperStatus("queueing"), + can_run=False, + job_state="Still adding to queue", ) @@ -476,12 +586,11 @@ def _copy_to_ray(cluster: Cluster) -> RayCluster: ray = RayCluster( name=cluster.config.name, status=cluster.status(print_to_console=False)[0], - min_workers=cluster.config.min_worker, - max_workers=cluster.config.max_worker, + workers=cluster.config.num_workers, worker_mem_min=cluster.config.min_memory, worker_mem_max=cluster.config.max_memory, worker_cpu=cluster.config.min_cpus, - worker_gpu=cluster.config.gpu, + worker_gpu=cluster.config.num_gpus, namespace=cluster.config.namespace, dashboard=cluster.cluster_dashboard_uri(), ) diff --git a/src/codeflare_sdk/cluster/config.py b/src/codeflare_sdk/cluster/config.py index a00d128a..aed3674e 100644 --- a/src/codeflare_sdk/cluster/config.py +++ b/src/codeflare_sdk/cluster/config.py @@ -19,9 +19,7 @@ """ from dataclasses import dataclass, field -from .auth import Authentication import pathlib -import openshift dir = pathlib.Path(__file__).parent.parent.resolve() @@ -39,14 +37,13 @@ class ClusterConfiguration: machine_types: list = field(default_factory=list) # ["m4.xlarge", "g4dn.xlarge"] min_cpus: int = 1 max_cpus: int = 1 - min_worker: int = 1 - max_worker: int = 1 + num_workers: int = 1 min_memory: int = 2 max_memory: int = 2 - gpu: int = 0 + num_gpus: int = 0 template: str = f"{dir}/templates/base-template.yaml" instascale: bool = False envs: dict = field(default_factory=dict) - image: str = "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" + image: str = "quay.io/project-codeflare/ray:2.5.0-py38-cu116" local_interactive: bool = False image_pull_secrets: list = field(default_factory=list) diff --git a/src/codeflare_sdk/cluster/model.py b/src/codeflare_sdk/cluster/model.py index 9f034da9..639cc734 100644 --- a/src/codeflare_sdk/cluster/model.py +++ b/src/codeflare_sdk/cluster/model.py @@ -39,6 +39,7 @@ class AppWrapperStatus(Enum): Defines the possible reportable states of an AppWrapper. """ + QUEUEING = "queueing" PENDING = "pending" RUNNING = "running" FAILED = "failed" @@ -55,8 +56,9 @@ class CodeFlareClusterStatus(Enum): READY = 1 STARTING = 2 QUEUED = 3 - FAILED = 4 - UNKNOWN = 5 + QUEUEING = 4 + FAILED = 5 + UNKNOWN = 6 @dataclass @@ -67,8 +69,7 @@ class RayCluster: name: str status: RayClusterStatus - min_workers: int - max_workers: int + workers: int worker_mem_min: str worker_mem_max: str worker_cpu: int diff --git a/src/codeflare_sdk/job/jobs.py b/src/codeflare_sdk/job/jobs.py index 6b5ce0a5..b9bb9cdc 100644 --- a/src/codeflare_sdk/job/jobs.py +++ b/src/codeflare_sdk/job/jobs.py @@ -17,13 +17,13 @@ from typing import TYPE_CHECKING, Optional, Dict, List from pathlib import Path -import openshift as oc from torchx.components.dist import ddp from torchx.runner import get_runner from torchx.specs import AppHandle, parse_app_handle, AppDryRunInfo if TYPE_CHECKING: from ..cluster.cluster import Cluster +from ..cluster.cluster import get_current_namespace all_jobs: List["Job"] = [] torchx_runner = get_runner() @@ -91,7 +91,7 @@ def __init__( self.workspace = workspace def _dry_run(self, cluster: "Cluster"): - j = f"{cluster.config.max_worker}x{max(cluster.config.gpu, 1)}" # # of proc. = # of gpus + j = f"{cluster.config.num_workers}x{max(cluster.config.num_gpus, 1)}" # # of proc. = # of gpus return torchx_runner.dryrun( app=ddp( *self.script_args, @@ -100,7 +100,7 @@ def _dry_run(self, cluster: "Cluster"): name=self.name, h=self.h, cpu=self.cpu if self.cpu is not None else cluster.config.max_cpus, - gpu=self.gpu if self.gpu is not None else cluster.config.gpu, + gpu=self.gpu if self.gpu is not None else cluster.config.num_gpus, memMB=self.memMB if self.memMB is not None else cluster.config.max_memory * 1024, @@ -124,7 +124,7 @@ def _missing_spec(self, spec: str): def _dry_run_no_cluster(self): if self.scheduler_args is not None: if self.scheduler_args.get("namespace") is None: - self.scheduler_args["namespace"] = oc.get_project_name() + self.scheduler_args["namespace"] = get_current_namespace() return torchx_runner.dryrun( app=ddp( *self.script_args, diff --git a/src/codeflare_sdk/utils/generate_cert.py b/src/codeflare_sdk/utils/generate_cert.py index 2d73621b..04b04d3e 100644 --- a/src/codeflare_sdk/utils/generate_cert.py +++ b/src/codeflare_sdk/utils/generate_cert.py @@ -19,6 +19,7 @@ from cryptography import x509 from cryptography.x509.oid import NameOID import datetime +from ..cluster.auth import config_check, api_config_handler from kubernetes import client, config @@ -82,8 +83,8 @@ def generate_tls_cert(cluster_name, namespace, days=30): # Similar to: # oc get secret ca-secret- -o template='{{index .data "ca.key"}}' # oc get secret ca-secret- -o template='{{index .data "ca.crt"}}'|base64 -d > ${TLSDIR}/ca.crt - config.load_kube_config() - v1 = client.CoreV1Api() + config_check() + v1 = client.CoreV1Api(api_config_handler()) secret = v1.read_namespaced_secret(f"ca-secret-{cluster_name}", namespace).data ca_cert = secret.get("ca.crt") ca_key = secret.get("ca.key") diff --git a/src/codeflare_sdk/utils/generate_yaml.py b/src/codeflare_sdk/utils/generate_yaml.py index 9538a1e8..9c5804cd 100755 --- a/src/codeflare_sdk/utils/generate_yaml.py +++ b/src/codeflare_sdk/utils/generate_yaml.py @@ -21,7 +21,9 @@ import sys import argparse import uuid -import openshift as oc +from kubernetes import client, config +from .kube_api_helpers import _kube_api_error_handling +from ..cluster.auth import api_config_handler def read_template(template): @@ -248,12 +250,16 @@ def enable_local_interactive(resources, cluster_name, namespace): ][0].get("command")[2] command = command.replace("deployment-name", cluster_name) - - server_name = ( - oc.whoami("--show-server").split(":")[1].split("//")[1].replace("api", "apps") - ) - - command = command.replace("server-name", server_name) + try: + config.load_kube_config() + api_client = client.CustomObjectsApi(api_config_handler()) + ingress = api_client.get_cluster_custom_object( + "config.openshift.io", "v1", "ingresses", "cluster" + ) + except Exception as e: # pragma: no cover + return _kube_api_error_handling(e) + domain = ingress["spec"]["domain"] + command = command.replace("server-name", domain) item["generictemplate"]["spec"]["headGroupSpec"]["template"]["spec"][ "initContainers" @@ -261,26 +267,61 @@ def enable_local_interactive(resources, cluster_name, namespace): def disable_raycluster_tls(resources): - del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][ - "template" - ]["spec"]["volumes"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][ - "template" - ]["spec"]["containers"][0]["volumeMounts"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["headGroupSpec"][ - "template" - ]["spec"]["initContainers"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][ - "template" - ]["spec"]["volumes"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][ - "template" - ]["spec"]["containers"][0]["volumeMounts"] - del resources["GenericItems"][0]["generictemplate"]["spec"]["workerGroupSpecs"][0][ - "template" - ]["spec"]["initContainers"][1] - del resources["GenericItems"][3] # rayclient route - del resources["GenericItems"][2] # ca-secret + generic_template_spec = resources["GenericItems"][0]["generictemplate"]["spec"] + + if "volumes" in generic_template_spec["headGroupSpec"]["template"]["spec"]: + del generic_template_spec["headGroupSpec"]["template"]["spec"]["volumes"] + + if ( + "volumeMounts" + in generic_template_spec["headGroupSpec"]["template"]["spec"]["containers"][0] + ): + del generic_template_spec["headGroupSpec"]["template"]["spec"]["containers"][0][ + "volumeMounts" + ] + + if "initContainers" in generic_template_spec["headGroupSpec"]["template"]["spec"]: + del generic_template_spec["headGroupSpec"]["template"]["spec"]["initContainers"] + + if "volumes" in generic_template_spec["workerGroupSpecs"][0]["template"]["spec"]: + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"]["volumes"] + + if ( + "volumeMounts" + in generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0] + ): + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "containers" + ][0]["volumeMounts"] + + for i in range( + len( + generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ] + ) + ): + if ( + generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ][i]["name"] + == "create-cert" + ): + del generic_template_spec["workerGroupSpecs"][0]["template"]["spec"][ + "initContainers" + ][i] + + updated_items = [] + for i in resources["GenericItems"][:]: + if "rayclient-deployment-name" in i["generictemplate"]["metadata"]["name"]: + continue + if "ca-secret-deployment-name" in i["generictemplate"]["metadata"]["name"]: + continue + updated_items.append(i) + + resources["GenericItems"] = updated_items def write_user_appwrapper(user_yaml, output_file_name): @@ -338,131 +379,3 @@ def generate_appwrapper( outfile = appwrapper_name + ".yaml" write_user_appwrapper(user_yaml, outfile) return outfile - - -def main(): # pragma: no cover - parser = argparse.ArgumentParser(description="Generate user AppWrapper") - parser.add_argument( - "--name", - required=False, - default="", - help="User selected name for AppWrapper and Ray Cluster (auto-generated if not provided)", - ) - parser.add_argument( - "--min-cpu", - type=int, - required=True, - help="min number of CPU(s) in a worker required for running job", - ) - parser.add_argument( - "--max-cpu", - type=int, - required=True, - help="max number of CPU(s) in a worker required for running job", - ) - parser.add_argument( - "--min-memory", - type=int, - required=True, - help="min RAM required in a worker for running job, in GB", - ) - parser.add_argument( - "--max-memory", - type=int, - required=True, - help="max RAM required in a worker for running job, in GB", - ) - parser.add_argument( - "--gpu", - type=int, - required=True, - help="GPU(s) required in a worker for running job", - ) - parser.add_argument( - "--workers", - type=int, - required=True, - help="How many workers are required in the cluster", - ) - parser.add_argument( - "--template", required=True, help="Template AppWrapper yaml file" - ) - parser.add_argument( - "--image", - required=False, - default="rayproject/ray:latest", - help="Ray image to be used (defaults to rayproject/ray:latest)", - ) - parser.add_argument( - "--instascale", - default=False, - required=False, - action="store_true", - help="Indicates that instascale is installed on the cluster", - ) - parser.add_argument( - "--instance-types", - type=str, - nargs="+", - default=[], - required=False, - help="Head,worker instance types (space separated)", - ) - parser.add_argument( - "--namespace", - required=False, - default="default", - help="Set the kubernetes namespace you want to deploy your cluster to. Default. If left blank, uses the 'default' namespace", - ) - parser.add_argument( - "--local-interactive", - required=False, - default=False, - help="Enable local interactive mode", - ) - parser.add_argument( - "--image-pull-secrets", - required=False, - default=[], - help="Set image pull secrets for private registries", - ) - - args = parser.parse_args() - name = args.name - min_cpu = args.min_cpu - max_cpu = args.max_cpu - min_memory = args.min_memory - max_memory = args.max_memory - gpu = args.gpu - workers = args.workers - template = args.template - image = args.image - instascale = args.instascale - instance_types = args.instance_types - namespace = args.namespace - local_interactive = args.local_interactive - env = {} - image_pull_secrets = args.image_pull_secrets - - outfile = generate_appwrapper( - name, - namespace, - min_cpu, - max_cpu, - min_memory, - max_memory, - gpu, - workers, - template, - image, - instascale, - instance_types, - local_interactive, - env, - image_pull_secrets, - ) - return outfile - - -if __name__ == "__main__": # pragma: no cover - main() diff --git a/src/codeflare_sdk/utils/kube_api_helpers.py b/src/codeflare_sdk/utils/kube_api_helpers.py new file mode 100644 index 00000000..58358a05 --- /dev/null +++ b/src/codeflare_sdk/utils/kube_api_helpers.py @@ -0,0 +1,44 @@ +# Copyright 2022 IBM, Red Hat +# +# Licensed 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. + +""" +This sub-module exists primarily to be used internally for any Kubernetes +API error handling or wrapping. +""" + +import executing +from kubernetes import client, config + + +# private methods +def _kube_api_error_handling(e: Exception): # pragma: no cover + perm_msg = ( + "Action not permitted, have you put in correct/up-to-date auth credentials?" + ) + nf_msg = "No instances found, nothing to be done." + exists_msg = "Resource with this name already exists." + if type(e) == config.ConfigException: + raise PermissionError(perm_msg) + if type(e) == executing.executing.NotOneValueFound: + print(nf_msg) + return + if type(e) == client.ApiException: + if e.reason == "Not Found": + print(nf_msg) + return + elif e.reason == "Unauthorized" or e.reason == "Forbidden": + raise PermissionError(perm_msg) + elif e.reason == "Conflict": + raise FileExistsError(exists_msg) + raise e diff --git a/src/codeflare_sdk/utils/pretty_print.py b/src/codeflare_sdk/utils/pretty_print.py index 0fd17e61..ca371182 100644 --- a/src/codeflare_sdk/utils/pretty_print.py +++ b/src/codeflare_sdk/utils/pretty_print.py @@ -115,8 +115,7 @@ def print_clusters(clusters: List[RayCluster]): ) name = cluster.name dashboard = cluster.dashboard - mincount = str(cluster.min_workers) - maxcount = str(cluster.max_workers) + workers = str(cluster.workers) memory = str(cluster.worker_mem_min) + "~" + str(cluster.worker_mem_max) cpu = str(cluster.worker_cpu) gpu = str(cluster.worker_gpu) @@ -142,10 +141,9 @@ def print_clusters(clusters: List[RayCluster]): #'table1' to display the worker counts table1 = Table(box=None) table1.add_row() - table1.add_column("Min", style="cyan", no_wrap=True) - table1.add_column("Max", style="magenta") + table1.add_column("# Workers", style="magenta") table1.add_row() - table1.add_row(mincount, maxcount) + table1.add_row(workers) table1.add_row() #'table2' to display the worker resources diff --git a/target_users.md b/target_users.md new file mode 100644 index 00000000..8f6ef41a --- /dev/null +++ b/target_users.md @@ -0,0 +1,31 @@ +# CodeFlare Stack Target Users + +[Cluster Admin](#cluster-administrator) + +[Data Scientist I](#data-scientist-i) + +[Data Scientist II](#data-scientist-ii) + + + +## Cluster Administrator + +* Quota Management +* Gang-Scheduling for Distributed Compute +* Job/Infrastructure Queuing + +I want to enable a team of data scientists to have self-serve, but limited, access to a shared pool of distributed compute resources such as GPUs for large scale machine learning model training jobs. If the existing pool of resources is insufficient, I want my cluster to scale up (to a defined quota) to meet my users’ needs and scale back down automatically when their jobs have completed. I want these features to be made available through simple installation of generic modules via a user-friendly interface. I also want the ability to monitor current queue of pending tasks, the utilization of active resources, and the progress of all current jobs visualized in a simple dashboard. + +## Data Scientist I + +* Training Mid-Size Models (less than 1,000 nodes) +* Fine-Tuning Existing Models +* Distributed Compute Framework + +I need temporary access to a reasonably large set of GPU enabled nodes on my team’s shared cluster for short term experimentation, parallelizing my existing ML workflow, or fine-tuning existing large scale models. I’d prefer to work from a notebook environment with access to a python sdk that I can use to request the creation of Framework Clusters that I can distribute my workloads across. In addition to interactive experimentation work, I also want the ability to “fire-and-forget” longer running ML jobs onto temporarily deployed Framework Clusters with the ability to monitor these jobs while they are running and access to all of their artifacts once complete. I also want to see where my jobs are in the current queue and the progress of all my current jobs visualized in a simple dashboard. + +## Data Scientist II +* Training Foundation Models (1,000+ nodes) +* Distributed Compute Framework + +I need temporary (but long term) access to a massive amount of GPU enabled infrastructure to train a foundation model. I want to be able to “fire-and-forget” my ML Job into this environment. Due to the size and cost associated with this job, it has already been well tested and validated, so access to jupyter notebooks is unnecessary. I would prefer to write my job as a bash script leveraging a CLI, or as a python script leveraging an SDK. I need the ability to monitor the job while it is running, as well as access to all of its artifacts once complete. I also want to see where my jobs are in the current queue and the progress of all my current jobs visualized in a simple dashboard. diff --git a/tests/test-case-bad.yaml b/tests/test-case-bad.yaml index 1d273ca6..5518cb48 100644 --- a/tests/test-case-bad.yaml +++ b/tests/test-case-bad.yaml @@ -73,7 +73,7 @@ spec: valueFrom: fieldRef: fieldPath: status.podIP - image: ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103 + image: quay.io/project-codeflare/ray:2.5.0-py38-cu116 imagePullPolicy: Always lifecycle: preStop: @@ -130,7 +130,7 @@ spec: valueFrom: fieldRef: fieldPath: status.podIP - image: ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103 + image: quay.io/project-codeflare/ray:2.5.0-py38-cu116 lifecycle: preStop: exec: diff --git a/tests/test-case-cmd.yaml b/tests/test-case-cmd.yaml deleted file mode 100644 index ea235ec9..00000000 --- a/tests/test-case-cmd.yaml +++ /dev/null @@ -1,173 +0,0 @@ -apiVersion: mcad.ibm.com/v1beta1 -kind: AppWrapper -metadata: - name: unit-cmd-cluster - namespace: default -spec: - priority: 9 - resources: - GenericItems: - - custompodresources: - - limits: - cpu: 2 - memory: 8G - nvidia.com/gpu: 0 - replicas: 1 - requests: - cpu: 2 - memory: 8G - nvidia.com/gpu: 0 - - limits: - cpu: 1 - memory: 2G - nvidia.com/gpu: 1 - replicas: 2 - requests: - cpu: 1 - memory: 2G - nvidia.com/gpu: 1 - generictemplate: - apiVersion: ray.io/v1alpha1 - kind: RayCluster - metadata: - labels: - appwrapper.mcad.ibm.com: unit-cmd-cluster - controller-tools.k8s.io: '1.0' - name: unit-cmd-cluster - namespace: default - spec: - autoscalerOptions: - idleTimeoutSeconds: 60 - imagePullPolicy: Always - resources: - limits: - cpu: 500m - memory: 512Mi - requests: - cpu: 500m - memory: 512Mi - upscalingMode: Default - enableInTreeAutoscaling: false - headGroupSpec: - rayStartParams: - block: 'true' - dashboard-host: 0.0.0.0 - num-gpus: '0' - serviceType: ClusterIP - template: - spec: - containers: - - env: - - name: MY_POD_IP - valueFrom: - fieldRef: - fieldPath: status.podIP - - name: RAY_USE_TLS - value: '0' - - name: RAY_TLS_SERVER_CERT - value: /home/ray/workspace/tls/server.crt - - name: RAY_TLS_SERVER_KEY - value: /home/ray/workspace/tls/server.key - - name: RAY_TLS_CA_CERT - value: /home/ray/workspace/tls/ca.crt - image: rayproject/ray:latest - imagePullPolicy: Always - lifecycle: - preStop: - exec: - command: - - /bin/sh - - -c - - ray stop - name: ray-head - ports: - - containerPort: 6379 - name: gcs - - containerPort: 8265 - name: dashboard - - containerPort: 10001 - name: client - resources: - limits: - cpu: 2 - memory: 8G - nvidia.com/gpu: 0 - requests: - cpu: 2 - memory: 8G - nvidia.com/gpu: 0 - imagePullSecrets: [] - rayVersion: 2.1.0 - workerGroupSpecs: - - groupName: small-group-unit-cmd-cluster - maxReplicas: 2 - minReplicas: 2 - rayStartParams: - block: 'true' - num-gpus: '1' - replicas: 2 - template: - metadata: - annotations: - key: value - labels: - key: value - spec: - containers: - - env: - - name: MY_POD_IP - valueFrom: - fieldRef: - fieldPath: status.podIP - - name: RAY_USE_TLS - value: '0' - - name: RAY_TLS_SERVER_CERT - value: /home/ray/workspace/tls/server.crt - - name: RAY_TLS_SERVER_KEY - value: /home/ray/workspace/tls/server.key - - name: RAY_TLS_CA_CERT - value: /home/ray/workspace/tls/ca.crt - image: rayproject/ray:latest - lifecycle: - preStop: - exec: - command: - - /bin/sh - - -c - - ray stop - name: machine-learning - resources: - limits: - cpu: 1 - memory: 2G - nvidia.com/gpu: 1 - requests: - cpu: 1 - memory: 2G - nvidia.com/gpu: 1 - imagePullSecrets: [] - initContainers: - - command: - - sh - - -c - - until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; - do echo waiting for myservice; sleep 2; done - image: busybox:1.28 - name: init-myservice - replicas: 1 - - generictemplate: - apiVersion: route.openshift.io/v1 - kind: Route - metadata: - labels: - odh-ray-cluster-service: unit-cmd-cluster-head-svc - name: ray-dashboard-unit-cmd-cluster - namespace: default - spec: - port: - targetPort: dashboard - to: - kind: Service - name: unit-cmd-cluster-head-svc - replica: 1 - Items: [] diff --git a/tests/test-case.yaml b/tests/test-case.yaml index da605869..167bb61b 100644 --- a/tests/test-case.yaml +++ b/tests/test-case.yaml @@ -81,7 +81,7 @@ spec: value: /home/ray/workspace/tls/server.key - name: RAY_TLS_CA_CERT value: /home/ray/workspace/tls/ca.crt - image: ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103 + image: quay.io/project-codeflare/ray:2.5.0-py38-cu116 imagePullPolicy: Always lifecycle: preStop: @@ -148,7 +148,7 @@ spec: value: /home/ray/workspace/tls/server.key - name: RAY_TLS_CA_CERT value: /home/ray/workspace/tls/ca.crt - image: ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103 + image: quay.io/project-codeflare/ray:2.5.0-py38-cu116 lifecycle: preStop: exec: diff --git a/tests/unit_test.py b/tests/unit_test.py index d6e6c6ef..ac126016 100644 --- a/tests/unit_test.py +++ b/tests/unit_test.py @@ -21,7 +21,7 @@ parent = Path(__file__).resolve().parents[1] sys.path.append(str(parent) + "/src") -from kubernetes import client +from kubernetes import client, config from codeflare_sdk.cluster.awload import AWManager from codeflare_sdk.cluster.cluster import ( Cluster, @@ -29,11 +29,14 @@ list_all_clusters, list_all_queued, _copy_to_ray, + get_cluster, + _app_wrapper_status, + _ray_cluster_status, ) from codeflare_sdk.cluster.auth import ( TokenAuthentication, - PasswordUserAuthentication, Authentication, + KubeConfigFileAuthentication, ) from codeflare_sdk.utils.pretty_print import ( print_no_resources_found, @@ -62,7 +65,6 @@ ) import openshift -from openshift import OpenShiftPythonException from openshift.selector import Selector import ray from torchx.specs import AppDryRunInfo, AppDef @@ -70,6 +72,7 @@ from torchx.schedulers.ray_scheduler import RayJob from torchx.schedulers.kubernetes_mcad_scheduler import KubernetesMCADJob import pytest +import yaml # For mocking openshift client results @@ -85,120 +88,79 @@ def att_side_effect(self): return self.high_level_operation -def att_side_effect_tls(self): - if "--insecure-skip-tls-verify" in self.high_level_operation[1]: - return self.high_level_operation - else: - raise OpenShiftPythonException( - "The server uses a certificate signed by unknown authority" - ) - - def test_token_auth_creation(): try: - token_auth = TokenAuthentication() - assert token_auth.token == None - assert token_auth.server == None - assert token_auth.skip_tls == False - - token_auth = TokenAuthentication("token") - assert token_auth.token == "token" - assert token_auth.server == None - assert token_auth.skip_tls == False - - token_auth = TokenAuthentication("token", "server") + token_auth = TokenAuthentication(token="token", server="server") assert token_auth.token == "token" assert token_auth.server == "server" assert token_auth.skip_tls == False + assert token_auth.ca_cert_path == None - token_auth = TokenAuthentication("token", server="server") + token_auth = TokenAuthentication(token="token", server="server", skip_tls=True) assert token_auth.token == "token" assert token_auth.server == "server" - assert token_auth.skip_tls == False + assert token_auth.skip_tls == True + assert token_auth.ca_cert_path == None - token_auth = TokenAuthentication(token="token", server="server") + token_auth = TokenAuthentication(token="token", server="server", skip_tls=False) assert token_auth.token == "token" assert token_auth.server == "server" assert token_auth.skip_tls == False + assert token_auth.ca_cert_path == None - token_auth = TokenAuthentication(token="token", server="server", skip_tls=True) + token_auth = TokenAuthentication( + token="token", server="server", skip_tls=False, ca_cert_path="path/to/cert" + ) assert token_auth.token == "token" assert token_auth.server == "server" - assert token_auth.skip_tls == True + assert token_auth.skip_tls == False + assert token_auth.ca_cert_path == "path/to/cert" except Exception: assert 0 == 1 def test_token_auth_login_logout(mocker): - mocker.patch("openshift.invoke", side_effect=arg_side_effect) - mock_res = mocker.patch.object(openshift.Result, "out") - mock_res.side_effect = lambda: att_side_effect(fake_res) + mocker.patch.object(client, "ApiClient") - token_auth = TokenAuthentication(token="testtoken", server="testserver:6443") - assert token_auth.login() == ( - "login", - ["--token=testtoken", "--server=testserver:6443"], - ) - assert token_auth.logout() == ( - "logout", - ["--token=testtoken", "--server=testserver:6443"], + token_auth = TokenAuthentication( + token="testtoken", server="testserver:6443", skip_tls=False, ca_cert_path=None ) + assert token_auth.login() == ("Logged into testserver:6443") + assert token_auth.logout() == ("Successfully logged out of testserver:6443") def test_token_auth_login_tls(mocker): - mocker.patch("openshift.invoke", side_effect=arg_side_effect) - mock_res = mocker.patch.object(openshift.Result, "out") - mock_res.side_effect = lambda: att_side_effect_tls(fake_res) - - # FIXME - Pytest mocker not allowing caught exception - # token_auth = TokenAuthentication(token="testtoken", server="testserver") - # assert token_auth.login() == "Error: certificate auth failure, please set `skip_tls=True` in TokenAuthentication" + mocker.patch.object(client, "ApiClient") token_auth = TokenAuthentication( - token="testtoken", server="testserver:6443", skip_tls=True + token="testtoken", server="testserver:6443", skip_tls=True, ca_cert_path=None ) - assert token_auth.login() == ( - "login", - ["--token=testtoken", "--server=testserver:6443", "--insecure-skip-tls-verify"], + assert token_auth.login() == ("Logged into testserver:6443") + token_auth = TokenAuthentication( + token="testtoken", server="testserver:6443", skip_tls=False, ca_cert_path=None ) + assert token_auth.login() == ("Logged into testserver:6443") + token_auth = TokenAuthentication( + token="testtoken", + server="testserver:6443", + skip_tls=False, + ca_cert_path="path/to/cert", + ) + assert token_auth.login() == ("Logged into testserver:6443") -def test_passwd_auth_creation(): - try: - passwd_auth = PasswordUserAuthentication() - assert passwd_auth.username == None - assert passwd_auth.password == None - - passwd_auth = PasswordUserAuthentication("user") - assert passwd_auth.username == "user" - assert passwd_auth.password == None - - passwd_auth = PasswordUserAuthentication("user", "passwd") - assert passwd_auth.username == "user" - assert passwd_auth.password == "passwd" - - passwd_auth = PasswordUserAuthentication("user", password="passwd") - assert passwd_auth.username == "user" - assert passwd_auth.password == "passwd" - - passwd_auth = PasswordUserAuthentication(username="user", password="passwd") - assert passwd_auth.username == "user" - assert passwd_auth.password == "passwd" - - except Exception: - assert 0 == 1 - - -def test_passwd_auth_login_logout(mocker): - mocker.patch("openshift.invoke", side_effect=arg_side_effect) - mocker.patch("openshift.login", side_effect=arg_side_effect) - mock_res = mocker.patch.object(openshift.Result, "out") - mock_res.side_effect = lambda: att_side_effect(fake_res) +def test_load_kube_config(mocker): + mocker.patch.object(config, "load_kube_config") + kube_config_auth = KubeConfigFileAuthentication( + kube_config_path="/path/to/your/config" + ) + response = kube_config_auth.load_kube_config() - token_auth = PasswordUserAuthentication(username="user", password="passwd") - assert token_auth.login() == ("user", "passwd") - assert token_auth.logout() == ("logout",) + assert ( + response + == "Loaded user config file at path %s" % kube_config_auth.kube_config_path + ) def test_auth_coverage(): @@ -211,27 +173,23 @@ def test_config_creation(): config = ClusterConfiguration( name="unit-test-cluster", namespace="ns", - min_worker=1, - max_worker=2, + num_workers=2, min_cpus=3, max_cpus=4, min_memory=5, max_memory=6, - gpu=7, + num_gpus=7, instascale=True, machine_types=["cpu.small", "gpu.large"], image_pull_secrets=["unit-test-pull-secret"], ) assert config.name == "unit-test-cluster" and config.namespace == "ns" - assert config.min_worker == 1 and config.max_worker == 2 + assert config.num_workers == 2 assert config.min_cpus == 3 and config.max_cpus == 4 assert config.min_memory == 5 and config.max_memory == 6 - assert config.gpu == 7 - assert ( - config.image - == "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" - ) + assert config.num_gpus == 7 + assert config.image == "quay.io/project-codeflare/ray:2.5.0-py38-cu116" assert config.template == f"{parent}/src/codeflare_sdk/templates/base-template.yaml" assert config.instascale assert config.machine_types == ["cpu.small", "gpu.large"] @@ -251,7 +209,7 @@ def test_cluster_creation(): def test_default_cluster_creation(mocker): mocker.patch( - "openshift.get_project_name", + "codeflare_sdk.cluster.cluster.get_current_namespace", return_value="opendatahub", ) default_config = ClusterConfiguration( @@ -266,38 +224,103 @@ def test_default_cluster_creation(mocker): return cluster -def arg_check_apply_effect(*args): - assert args[0] == "apply" - assert args[1] == ["-f", "unit-test-cluster.yaml"] +def arg_check_apply_effect(group, version, namespace, plural, body, *args): + assert group == "mcad.ibm.com" + assert version == "v1beta1" + assert namespace == "ns" + assert plural == "appwrappers" + with open("unit-test-cluster.yaml") as f: + aw = yaml.load(f, Loader=yaml.FullLoader) + assert body == aw + assert args == tuple() -def arg_check_del_effect(*args): - assert args[0] == "delete" - assert args[1] == ["AppWrapper", "unit-test-cluster"] +def arg_check_del_effect(group, version, namespace, plural, name, *args): + assert group == "mcad.ibm.com" + assert version == "v1beta1" + assert namespace == "ns" + assert plural == "appwrappers" + assert name == "unit-test-cluster" + assert args == tuple() def test_cluster_up_down(mocker): + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") mocker.patch( - "codeflare_sdk.cluster.auth.TokenAuthentication.login", return_value="ignore" + "kubernetes.client.CustomObjectsApi.create_namespaced_custom_object", + side_effect=arg_check_apply_effect, ) mocker.patch( - "codeflare_sdk.cluster.auth.TokenAuthentication.logout", return_value="ignore" + "kubernetes.client.CustomObjectsApi.delete_namespaced_custom_object", + side_effect=arg_check_del_effect, ) - mocker.patch("openshift.invoke", side_effect=arg_check_apply_effect) cluster = test_cluster_creation() cluster.up() - mocker.patch("openshift.invoke", side_effect=arg_check_del_effect) cluster.down() -def out_route(self): - return "ray-dashboard-raycluster-autoscaler-ns.apps.cluster.awsroute.org ray-dashboard-unit-test-cluster-ns.apps.cluster.awsroute.org" +def aw_status_fields(group, version, namespace, plural, *args): + assert group == "mcad.ibm.com" + assert version == "v1beta1" + assert namespace == "test-ns" + assert plural == "appwrappers" + assert args == tuple() + return {"items": []} + + +def test_aw_status(mocker): + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=aw_status_fields, + ) + aw = _app_wrapper_status("test-aw", "test-ns") + assert aw == None + + +def rc_status_fields(group, version, namespace, plural, *args): + assert group == "ray.io" + assert version == "v1alpha1" + assert namespace == "test-ns" + assert plural == "rayclusters" + assert args == tuple() + return {"items": []} + + +def test_rc_status(mocker): + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=rc_status_fields, + ) + rc = _ray_cluster_status("test-rc", "test-ns") + assert rc == None + + +def uri_retreival(group, version, namespace, plural, *args): + assert group == "route.openshift.io" + assert version == "v1" + assert namespace == "ns" + assert plural == "routes" + assert args == tuple() + return { + "items": [ + { + "metadata": {"name": "ray-dashboard-unit-test-cluster"}, + "spec": { + "host": "ray-dashboard-unit-test-cluster-ns.apps.cluster.awsroute.org" + }, + } + ] + } def test_cluster_uris(mocker): - mocker.patch("openshift.invoke", return_value=fake_res) - mock_res = mocker.patch.object(openshift.Result, "out") - mock_res.side_effect = lambda: out_route(fake_res) + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=uri_retreival, + ) cluster = test_cluster_creation() assert cluster.cluster_uri() == "ray://unit-test-cluster-head-svc.ns.svc:10001" @@ -312,14 +335,40 @@ def test_cluster_uris(mocker): ) +def test_local_client_url(mocker): + mocker.patch( + "kubernetes.client.CustomObjectsApi.get_cluster_custom_object", + return_value={"spec": {"domain": ""}}, + ) + mocker.patch( + "codeflare_sdk.cluster.cluster._get_ingress_domain", + return_value="apps.cluster.awsroute.org", + ) + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.create_app_wrapper", + return_value="unit-test-cluster-localinter.yaml", + ) + + cluster_config = ClusterConfiguration( + name="unit-test-cluster-localinter", namespace="ns", local_interactive=True + ) + cluster = Cluster(cluster_config) + assert ( + cluster.local_client_url() + == "ray://rayclient-unit-test-cluster-localinter-ns.apps.cluster.awsroute.org" + ) + + def ray_addr(self, *args): return self._address def test_ray_job_wrapping(mocker): - mocker.patch("openshift.invoke", return_value=fake_res) - mock_res = mocker.patch.object(openshift.Result, "out") - mock_res.side_effect = lambda: out_route(fake_res) + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=uri_retreival, + ) cluster = test_cluster_creation() mocker.patch( @@ -405,12 +454,11 @@ def test_print_appwrappers(capsys): ) -def test_ray_details(capsys): +def test_ray_details(mocker, capsys): ray1 = RayCluster( name="raytest1", status=RayClusterStatus.READY, - min_workers=1, - max_workers=1, + workers=1, worker_mem_min=2, worker_mem_max=2, worker_cpu=1, @@ -418,6 +466,14 @@ def test_ray_details(capsys): namespace="ns", dashboard="fake-uri", ) + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.status", + return_value=(False, CodeFlareClusterStatus.UNKNOWN), + ) + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.cluster_dashboard_uri", + return_value="", + ) cf = Cluster(ClusterConfiguration(name="raytest2", namespace="ns")) captured = capsys.readouterr() ray2 = _copy_to_ray(cf) @@ -425,8 +481,7 @@ def test_ray_details(capsys): assert details == ray2 assert ray2.name == "raytest2" assert ray1.namespace == ray2.namespace - assert ray1.min_workers == ray2.min_workers - assert ray1.max_workers == ray2.max_workers + assert ray1.workers == ray2.workers assert ray1.worker_mem_min == ray2.worker_mem_min assert ray1.worker_mem_max == ray2.worker_mem_max assert ray1.worker_cpu == ray2.worker_cpu @@ -439,58 +494,58 @@ def test_ray_details(capsys): assert 0 == 1 captured = capsys.readouterr() assert captured.out == ( - " 🚀 CodeFlare Cluster Details 🚀 \n" - " \n" - " ╭──────────────────────────────────────────────────────────────╮ \n" - " │ Name │ \n" - " │ raytest2 Inactive ❌ │ \n" - " │ │ \n" - " │ URI: ray://raytest2-head-svc.ns.svc:10001 │ \n" - " │ │ \n" - " │ Dashboard🔗 │ \n" - " │ │ \n" - " │ Cluster Resources │ \n" - " │ ╭─ Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │ \n" - " │ │ Min Max │ │ Memory CPU GPU │ │ \n" - " │ │ │ │ │ │ \n" - " │ │ 1 1 │ │ 2~2 1 0 │ │ \n" - " │ │ │ │ │ │ \n" - " │ ╰────────────╯ ╰──────────────────────────────────────╯ │ \n" - " ╰──────────────────────────────────────────────────────────────╯ \n" - " 🚀 CodeFlare Cluster Details 🚀 \n" - " \n" - " ╭──────────────────────────────────────────────────────────────╮ \n" - " │ Name │ \n" - " │ raytest1 Active ✅ │ \n" - " │ │ \n" - " │ URI: ray://raytest1-head-svc.ns.svc:10001 │ \n" - " │ │ \n" - " │ Dashboard🔗 │ \n" - " │ │ \n" - " │ Cluster Resources │ \n" - " │ ╭─ Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │ \n" - " │ │ Min Max │ │ Memory CPU GPU │ │ \n" - " │ │ │ │ │ │ \n" - " │ │ 1 1 │ │ 2~2 1 0 │ │ \n" - " │ │ │ │ │ │ \n" - " │ ╰────────────╯ ╰──────────────────────────────────────╯ │ \n" - " ╰──────────────────────────────────────────────────────────────╯ \n" - "╭──────────────────────────────────────────────────────────────╮\n" - "│ Name │\n" - "│ raytest2 Inactive ❌ │\n" - "│ │\n" - "│ URI: ray://raytest2-head-svc.ns.svc:10001 │\n" - "│ │\n" - "│ Dashboard🔗 │\n" - "│ │\n" - "│ Cluster Resources │\n" - "│ ╭─ Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │\n" - "│ │ Min Max │ │ Memory CPU GPU │ │\n" - "│ │ │ │ │ │\n" - "│ │ 1 1 │ │ 2~2 1 0 │ │\n" - "│ │ │ │ │ │\n" - "│ ╰────────────╯ ╰──────────────────────────────────────╯ │\n" - "╰──────────────────────────────────────────────────────────────╯\n" + " 🚀 CodeFlare Cluster Details 🚀 \n" + " \n" + " ╭───────────────────────────────────────────────────────────────╮ \n" + " │ Name │ \n" + " │ raytest2 Inactive ❌ │ \n" + " │ │ \n" + " │ URI: ray://raytest2-head-svc.ns.svc:10001 │ \n" + " │ │ \n" + " │ Dashboard🔗 │ \n" + " │ │ \n" + " │ Cluster Resources │ \n" + " │ ╭── Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │ \n" + " │ │ # Workers │ │ Memory CPU GPU │ │ \n" + " │ │ │ │ │ │ \n" + " │ │ 1 │ │ 2~2 1 0 │ │ \n" + " │ │ │ │ │ │ \n" + " │ ╰─────────────╯ ╰──────────────────────────────────────╯ │ \n" + " ╰───────────────────────────────────────────────────────────────╯ \n" + " 🚀 CodeFlare Cluster Details 🚀 \n" + " \n" + " ╭───────────────────────────────────────────────────────────────╮ \n" + " │ Name │ \n" + " │ raytest1 Active ✅ │ \n" + " │ │ \n" + " │ URI: ray://raytest1-head-svc.ns.svc:10001 │ \n" + " │ │ \n" + " │ Dashboard🔗 │ \n" + " │ │ \n" + " │ Cluster Resources │ \n" + " │ ╭── Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │ \n" + " │ │ # Workers │ │ Memory CPU GPU │ │ \n" + " │ │ │ │ │ │ \n" + " │ │ 1 │ │ 2~2 1 0 │ │ \n" + " │ │ │ │ │ │ \n" + " │ ╰─────────────╯ ╰──────────────────────────────────────╯ │ \n" + " ╰───────────────────────────────────────────────────────────────╯ \n" + "╭───────────────────────────────────────────────────────────────╮\n" + "│ Name │\n" + "│ raytest2 Inactive ❌ │\n" + "│ │\n" + "│ URI: ray://raytest2-head-svc.ns.svc:10001 │\n" + "│ │\n" + "│ Dashboard🔗 │\n" + "│ │\n" + "│ Cluster Resources │\n" + "│ ╭── Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │\n" + "│ │ # Workers │ │ Memory CPU GPU │ │\n" + "│ │ │ │ │ │\n" + "│ │ 1 │ │ 2~2 1 0 │ │\n" + "│ │ │ │ │ │\n" + "│ ╰─────────────╯ ╰──────────────────────────────────────╯ │\n" + "╰───────────────────────────────────────────────────────────────╯\n" " 🚀 CodeFlare Cluster Status 🚀 \n" " \n" " ╭──────────────────────────────────────────────────────────╮ \n" @@ -522,223 +577,151 @@ def act_side_effect_list(self): return [self] -def get_selector(*args): - selector = Selector({"operation": "selector", "status": 0, "actions": []}) - return selector - - -def get_obj_none(): - return [] - - -def get_ray_obj(cls=None): - api_obj = openshift.apiobject.APIObject( - { - "apiVersion": "ray.io/v1alpha1", - "kind": "RayCluster", - "metadata": { - "creationTimestamp": "2023-02-22T16:26:07Z", - "generation": 1, - "labels": { - "appwrapper.mcad.ibm.com": "quicktest", - "controller-tools.k8s.io": "1.0", - "resourceName": "quicktest", - }, - "managedFields": [ - { - "apiVersion": "ray.io/v1alpha1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:metadata": { - "f:labels": { - ".": {}, - "f:appwrapper.mcad.ibm.com": {}, - "f:controller-tools.k8s.io": {}, - "f:resourceName": {}, - }, - "f:ownerReferences": { - ".": {}, - 'k:{"uid":"6334fc1b-471e-4876-8e7b-0b2277679235"}': {}, - }, - }, - "f:spec": { - ".": {}, - "f:autoscalerOptions": { - ".": {}, - "f:idleTimeoutSeconds": {}, - "f:imagePullPolicy": {}, - "f:resources": { +def get_obj_none(group, version, namespace, plural): + return {"items": []} + + +def get_ray_obj(group, version, namespace, plural, cls=None): + api_obj = { + "items": [ + { + "apiVersion": "ray.io/v1alpha1", + "kind": "RayCluster", + "metadata": { + "creationTimestamp": "2023-02-22T16:26:07Z", + "generation": 1, + "labels": { + "appwrapper.mcad.ibm.com": "quicktest", + "controller-tools.k8s.io": "1.0", + "resourceName": "quicktest", + "orderedinstance": "m4.xlarge_g4dn.xlarge", + }, + "managedFields": [ + { + "apiVersion": "ray.io/v1alpha1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:labels": { ".": {}, - "f:limits": { - ".": {}, - "f:cpu": {}, - "f:memory": {}, - }, - "f:requests": { - ".": {}, - "f:cpu": {}, - "f:memory": {}, - }, + "f:appwrapper.mcad.ibm.com": {}, + "f:controller-tools.k8s.io": {}, + "f:resourceName": {}, + }, + "f:ownerReferences": { + ".": {}, + 'k:{"uid":"6334fc1b-471e-4876-8e7b-0b2277679235"}': {}, }, - "f:upscalingMode": {}, }, - "f:enableInTreeAutoscaling": {}, - "f:headGroupSpec": { + "f:spec": { ".": {}, - "f:rayStartParams": { + "f:autoscalerOptions": { ".": {}, - "f:block": {}, - "f:dashboard-host": {}, - "f:num-gpus": {}, + "f:idleTimeoutSeconds": {}, + "f:imagePullPolicy": {}, + "f:resources": { + ".": {}, + "f:limits": { + ".": {}, + "f:cpu": {}, + "f:memory": {}, + }, + "f:requests": { + ".": {}, + "f:cpu": {}, + "f:memory": {}, + }, + }, + "f:upscalingMode": {}, }, - "f:serviceType": {}, - "f:template": { + "f:enableInTreeAutoscaling": {}, + "f:headGroupSpec": { ".": {}, - "f:spec": {".": {}, "f:containers": {}}, + "f:rayStartParams": { + ".": {}, + "f:block": {}, + "f:dashboard-host": {}, + "f:num-gpus": {}, + }, + "f:serviceType": {}, + "f:template": { + ".": {}, + "f:spec": {".": {}, "f:containers": {}}, + }, }, + "f:rayVersion": {}, + "f:workerGroupSpecs": {}, }, - "f:rayVersion": {}, - "f:workerGroupSpecs": {}, }, + "manager": "mcad-controller", + "operation": "Update", + "time": "2023-02-22T16:26:07Z", }, - "manager": "mcad-controller", - "operation": "Update", - "time": "2023-02-22T16:26:07Z", - }, - { - "apiVersion": "ray.io/v1alpha1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:status": { - ".": {}, - "f:availableWorkerReplicas": {}, - "f:desiredWorkerReplicas": {}, - "f:endpoints": { + { + "apiVersion": "ray.io/v1alpha1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { ".": {}, - "f:client": {}, - "f:dashboard": {}, - "f:gcs": {}, - }, - "f:lastUpdateTime": {}, - "f:maxWorkerReplicas": {}, - "f:minWorkerReplicas": {}, - "f:state": {}, - } - }, - "manager": "manager", - "operation": "Update", - "subresource": "status", - "time": "2023-02-22T16:26:16Z", - }, - ], - "name": "quicktest", - "namespace": "ns", - "ownerReferences": [ - { - "apiVersion": "mcad.ibm.com/v1beta1", - "blockOwnerDeletion": True, - "controller": True, - "kind": "AppWrapper", - "name": "quicktest", - "uid": "6334fc1b-471e-4876-8e7b-0b2277679235", - } - ], - "resourceVersion": "9482407", - "uid": "44d45d1f-26c8-43e7-841f-831dbd8c1285", - }, - "spec": { - "autoscalerOptions": { - "idleTimeoutSeconds": 60, - "imagePullPolicy": "Always", - "resources": { - "limits": {"cpu": "500m", "memory": "512Mi"}, - "requests": {"cpu": "500m", "memory": "512Mi"}, - }, - "upscalingMode": "Default", - }, - "enableInTreeAutoscaling": False, - "headGroupSpec": { - "rayStartParams": { - "block": "true", - "dashboard-host": "0.0.0.0", - "num-gpus": "0", - }, - "serviceType": "ClusterIP", - "template": { - "spec": { - "containers": [ - { - "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", - "imagePullPolicy": "Always", - "lifecycle": { - "preStop": { - "exec": { - "command": ["/bin/sh", "-c", "ray stop"] - } - } - }, - "name": "ray-head", - "ports": [ - { - "containerPort": 6379, - "name": "gcs", - "protocol": "TCP", - }, - { - "containerPort": 8265, - "name": "dashboard", - "protocol": "TCP", - }, - { - "containerPort": 10001, - "name": "client", - "protocol": "TCP", - }, - ], - "resources": { - "limits": { - "cpu": 2, - "memory": "8G", - "nvidia.com/gpu": 0, - }, - "requests": { - "cpu": 2, - "memory": "8G", - "nvidia.com/gpu": 0, - }, + "f:availableWorkerReplicas": {}, + "f:desiredWorkerReplicas": {}, + "f:endpoints": { + ".": {}, + "f:client": {}, + "f:dashboard": {}, + "f:gcs": {}, }, + "f:lastUpdateTime": {}, + "f:maxWorkerReplicas": {}, + "f:minWorkerReplicas": {}, + "f:state": {}, } - ] + }, + "manager": "manager", + "operation": "Update", + "subresource": "status", + "time": "2023-02-22T16:26:16Z", + }, + ], + "name": "quicktest", + "namespace": "ns", + "ownerReferences": [ + { + "apiVersion": "mcad.ibm.com/v1beta1", + "blockOwnerDeletion": True, + "controller": True, + "kind": "AppWrapper", + "name": "quicktest", + "uid": "6334fc1b-471e-4876-8e7b-0b2277679235", } - }, + ], + "resourceVersion": "9482407", + "uid": "44d45d1f-26c8-43e7-841f-831dbd8c1285", }, - "rayVersion": "1.12.0", - "workerGroupSpecs": [ - { - "groupName": "small-group-quicktest", - "maxReplicas": 1, - "minReplicas": 1, - "rayStartParams": {"block": "true", "num-gpus": "0"}, - "replicas": 1, + "spec": { + "autoscalerOptions": { + "idleTimeoutSeconds": 60, + "imagePullPolicy": "Always", + "resources": { + "limits": {"cpu": "500m", "memory": "512Mi"}, + "requests": {"cpu": "500m", "memory": "512Mi"}, + }, + "upscalingMode": "Default", + }, + "enableInTreeAutoscaling": False, + "headGroupSpec": { + "rayStartParams": { + "block": "true", + "dashboard-host": "0.0.0.0", + "num-gpus": "0", + }, + "serviceType": "ClusterIP", "template": { - "metadata": { - "annotations": {"key": "value"}, - "labels": {"key": "value"}, - }, "spec": { "containers": [ { - "env": [ - { - "name": "MY_POD_IP", - "valueFrom": { - "fieldRef": { - "fieldPath": "status.podIP" - } - }, - } - ], "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", + "imagePullPolicy": "Always", "lifecycle": { "preStop": { "exec": { @@ -750,262 +733,271 @@ def get_ray_obj(cls=None): } } }, - "name": "machine-learning", + "name": "ray-head", + "ports": [ + { + "containerPort": 6379, + "name": "gcs", + "protocol": "TCP", + }, + { + "containerPort": 8265, + "name": "dashboard", + "protocol": "TCP", + }, + { + "containerPort": 10001, + "name": "client", + "protocol": "TCP", + }, + ], "resources": { "limits": { - "cpu": 1, - "memory": "2G", + "cpu": 2, + "memory": "8G", "nvidia.com/gpu": 0, }, "requests": { - "cpu": 1, - "memory": "2G", + "cpu": 2, + "memory": "8G", "nvidia.com/gpu": 0, }, }, } - ], - "initContainers": [ - { - "command": [ - "sh", - "-c", - "until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done", - ], - "image": "busybox:1.28", - "name": "init-myservice", - } - ], - }, - }, - } - ], - }, - "status": { - "availableWorkerReplicas": 2, - "desiredWorkerReplicas": 1, - "endpoints": {"client": "10001", "dashboard": "8265", "gcs": "6379"}, - "lastUpdateTime": "2023-02-22T16:26:16Z", - "maxWorkerReplicas": 1, - "minWorkerReplicas": 1, - "state": "ready", - }, - } - ) - return [api_obj] - - -def get_aw_obj(): - api_obj1 = openshift.apiobject.APIObject( - { - "apiVersion": "mcad.ibm.com/v1beta1", - "kind": "AppWrapper", - "metadata": { - "annotations": { - "kubectl.kubernetes.io/last-applied-configuration": '{"apiVersion":"mcad.ibm.com/v1beta1","kind":"AppWrapper","metadata":{"annotations":{},"name":"quicktest1","namespace":"ns"},"spec":{"priority":9,"resources":{"GenericItems":[{"custompodresources":[{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}},{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}],"generictemplate":{"apiVersion":"ray.io/v1alpha1","kind":"RayCluster","metadata":{"labels":{"appwrapper.mcad.ibm.com":"quicktest1","controller-tools.k8s.io":"1.0"},"name":"quicktest1","namespace":"ns"},"spec":{"autoscalerOptions":{"idleTimeoutSeconds":60,"imagePullPolicy":"Always","resources":{"limits":{"cpu":"500m","memory":"512Mi"},"requests":{"cpu":"500m","memory":"512Mi"}},"upscalingMode":"Default"},"enableInTreeAutoscaling":false,"headGroupSpec":{"rayStartParams":{"block":"true","dashboard-host":"0.0.0.0","num-gpus":"0"},"serviceType":"ClusterIP","template":{"spec":{"containers":[{"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","imagePullPolicy":"Always","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"ray-head","ports":[{"containerPort":6379,"name":"gcs"},{"containerPort":8265,"name":"dashboard"},{"containerPort":10001,"name":"client"}],"resources":{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}}}]}}},"rayVersion":"1.12.0","workerGroupSpecs":[{"groupName":"small-group-quicktest","maxReplicas":1,"minReplicas":1,"rayStartParams":{"block":"true","num-gpus":"0"},"replicas":1,"template":{"metadata":{"annotations":{"key":"value"},"labels":{"key":"value"}},"spec":{"containers":[{"env":[{"name":"MY_POD_IP","valueFrom":{"fieldRef":{"fieldPath":"status.podIP"}}}],"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"machine-learning","resources":{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}}],"initContainers":[{"command":["sh","-c","until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"],"image":"busybox:1.28","name":"init-myservice"}]}}}]}},"replicas":1},{"generictemplate":{"apiVersion":"route.openshift.io/v1","kind":"Route","metadata":{"labels":{"odh-ray-cluster-service":"quicktest-head-svc"},"name":"ray-dashboard-quicktest","namespace":"default"},"spec":{"port":{"targetPort":"dashboard"},"to":{"kind":"Service","name":"quicktest-head-svc"}}},"replica":1}],"Items":[]}}}\n' - }, - "creationTimestamp": "2023-02-22T16:26:07Z", - "generation": 4, - "managedFields": [ - { - "apiVersion": "mcad.ibm.com/v1beta1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:spec": { - "f:resources": {"f:GenericItems": {}, "f:metadata": {}}, - "f:schedulingSpec": {}, - "f:service": {".": {}, "f:spec": {}}, - }, - "f:status": { - ".": {}, - "f:canrun": {}, - "f:conditions": {}, - "f:controllerfirsttimestamp": {}, - "f:filterignore": {}, - "f:queuejobstate": {}, - "f:sender": {}, - "f:state": {}, - "f:systempriority": {}, - }, + ] + } }, - "manager": "Go-http-client", - "operation": "Update", - "time": "2023-02-22T16:26:07Z", }, - { - "apiVersion": "mcad.ibm.com/v1beta1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:metadata": { - "f:annotations": { - ".": {}, - "f:kubectl.kubernetes.io/last-applied-configuration": {}, - } - }, - "f:spec": { - ".": {}, - "f:priority": {}, - "f:resources": {".": {}, "f:Items": {}}, + "rayVersion": "1.12.0", + "workerGroupSpecs": [ + { + "groupName": "small-group-quicktest", + "maxReplicas": 1, + "minReplicas": 1, + "rayStartParams": {"block": "true", "num-gpus": "0"}, + "replicas": 1, + "template": { + "metadata": { + "annotations": {"key": "value"}, + "labels": {"key": "value"}, + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "MY_POD_IP", + "valueFrom": { + "fieldRef": { + "fieldPath": "status.podIP" + } + }, + } + ], + "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", + "lifecycle": { + "preStop": { + "exec": { + "command": [ + "/bin/sh", + "-c", + "ray stop", + ] + } + } + }, + "name": "machine-learning", + "resources": { + "limits": { + "cpu": 1, + "memory": "2G", + "nvidia.com/gpu": 0, + }, + "requests": { + "cpu": 1, + "memory": "2G", + "nvidia.com/gpu": 0, + }, + }, + } + ], + "initContainers": [ + { + "command": [ + "sh", + "-c", + "until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done", + ], + "image": "busybox:1.28", + "name": "init-myservice", + } + ], + }, }, - }, - "manager": "kubectl-client-side-apply", - "operation": "Update", - "time": "2023-02-22T16:26:07Z", + } + ], + }, + "status": { + "availableWorkerReplicas": 2, + "desiredWorkerReplicas": 1, + "endpoints": { + "client": "10001", + "dashboard": "8265", + "gcs": "6379", }, - ], - "name": "quicktest1", - "namespace": "ns", - "resourceVersion": "9482384", - "uid": "6334fc1b-471e-4876-8e7b-0b2277679235", - }, - "spec": { - "priority": 9, - "resources": { - "GenericItems": [ + "lastUpdateTime": "2023-02-22T16:26:16Z", + "maxWorkerReplicas": 1, + "minWorkerReplicas": 1, + "state": "ready", + }, + } + ] + } + return api_obj + + +def get_aw_obj(group, version, namespace, plural): + api_obj1 = { + "items": [ + { + "apiVersion": "mcad.ibm.com/v1beta1", + "kind": "AppWrapper", + "metadata": { + "annotations": { + "kubectl.kubernetes.io/last-applied-configuration": '{"apiVersion":"mcad.ibm.com/v1beta1","kind":"AppWrapper","metadata":{"annotations":{},"name":"quicktest1","namespace":"ns"},"spec":{"priority":9,"resources":{"GenericItems":[{"custompodresources":[{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}},{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}],"generictemplate":{"apiVersion":"ray.io/v1alpha1","kind":"RayCluster","metadata":{"labels":{"appwrapper.mcad.ibm.com":"quicktest1","controller-tools.k8s.io":"1.0"},"name":"quicktest1","namespace":"ns"},"spec":{"autoscalerOptions":{"idleTimeoutSeconds":60,"imagePullPolicy":"Always","resources":{"limits":{"cpu":"500m","memory":"512Mi"},"requests":{"cpu":"500m","memory":"512Mi"}},"upscalingMode":"Default"},"enableInTreeAutoscaling":false,"headGroupSpec":{"rayStartParams":{"block":"true","dashboard-host":"0.0.0.0","num-gpus":"0"},"serviceType":"ClusterIP","template":{"spec":{"containers":[{"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","imagePullPolicy":"Always","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"ray-head","ports":[{"containerPort":6379,"name":"gcs"},{"containerPort":8265,"name":"dashboard"},{"containerPort":10001,"name":"client"}],"resources":{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}}}]}}},"rayVersion":"1.12.0","workerGroupSpecs":[{"groupName":"small-group-quicktest","maxReplicas":1,"minReplicas":1,"rayStartParams":{"block":"true","num-gpus":"0"},"replicas":1,"template":{"metadata":{"annotations":{"key":"value"},"labels":{"key":"value"}},"spec":{"containers":[{"env":[{"name":"MY_POD_IP","valueFrom":{"fieldRef":{"fieldPath":"status.podIP"}}}],"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"machine-learning","resources":{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}}],"initContainers":[{"command":["sh","-c","until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"],"image":"busybox:1.28","name":"init-myservice"}]}}}]}},"replicas":1},{"generictemplate":{"apiVersion":"route.openshift.io/v1","kind":"Route","metadata":{"labels":{"odh-ray-cluster-service":"quicktest-head-svc"},"name":"ray-dashboard-quicktest","namespace":"default"},"spec":{"port":{"targetPort":"dashboard"},"to":{"kind":"Service","name":"quicktest-head-svc"}}},"replica":1}],"Items":[]}}}\n' + }, + "creationTimestamp": "2023-02-22T16:26:07Z", + "generation": 4, + "managedFields": [ { - "allocated": 0, - "custompodresources": [ - { - "limits": { - "cpu": "2", - "memory": "8G", - "nvidia.com/gpu": "0", - }, - "replicas": 1, - "requests": { - "cpu": "2", - "memory": "8G", - "nvidia.com/gpu": "0", + "apiVersion": "mcad.ibm.com/v1beta1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:spec": { + "f:resources": { + "f:GenericItems": {}, + "f:metadata": {}, }, + "f:schedulingSpec": {}, + "f:service": {".": {}, "f:spec": {}}, }, - { - "limits": { - "cpu": "1", - "memory": "2G", - "nvidia.com/gpu": "0", - }, - "replicas": 1, - "requests": { - "cpu": "1", - "memory": "2G", - "nvidia.com/gpu": "0", - }, + "f:status": { + ".": {}, + "f:canrun": {}, + "f:conditions": {}, + "f:controllerfirsttimestamp": {}, + "f:filterignore": {}, + "f:queuejobstate": {}, + "f:sender": {}, + "f:state": {}, + "f:systempriority": {}, }, - ], - "generictemplate": { - "apiVersion": "ray.io/v1alpha1", - "kind": "RayCluster", - "metadata": { - "labels": { - "appwrapper.mcad.ibm.com": "quicktest1", - "controller-tools.k8s.io": "1.0", - }, - "name": "quicktest1", - "namespace": "ns", + }, + "manager": "Go-http-client", + "operation": "Update", + "time": "2023-02-22T16:26:07Z", + }, + { + "apiVersion": "mcad.ibm.com/v1beta1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {}, + } }, - "spec": { - "autoscalerOptions": { - "idleTimeoutSeconds": 60, - "imagePullPolicy": "Always", - "resources": { - "limits": { - "cpu": "500m", - "memory": "512Mi", - }, - "requests": { - "cpu": "500m", - "memory": "512Mi", - }, + "f:spec": { + ".": {}, + "f:priority": {}, + "f:resources": {".": {}, "f:Items": {}}, + }, + }, + "manager": "kubectl-client-side-apply", + "operation": "Update", + "time": "2023-02-22T16:26:07Z", + }, + ], + "name": "quicktest1", + "namespace": "ns", + "resourceVersion": "9482384", + "uid": "6334fc1b-471e-4876-8e7b-0b2277679235", + }, + "spec": { + "priority": 9, + "resources": { + "GenericItems": [ + { + "allocated": 0, + "custompodresources": [ + { + "limits": { + "cpu": "2", + "memory": "8G", + "nvidia.com/gpu": "0", + }, + "replicas": 1, + "requests": { + "cpu": "2", + "memory": "8G", + "nvidia.com/gpu": "0", }, - "upscalingMode": "Default", }, - "enableInTreeAutoscaling": False, - "headGroupSpec": { - "rayStartParams": { - "block": "true", - "dashboard-host": "0.0.0.0", - "num-gpus": "0", + { + "limits": { + "cpu": "1", + "memory": "2G", + "nvidia.com/gpu": "0", }, - "serviceType": "ClusterIP", - "template": { - "spec": { - "containers": [ - { - "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", - "imagePullPolicy": "Always", - "lifecycle": { - "preStop": { - "exec": { - "command": [ - "/bin/sh", - "-c", - "ray stop", - ] - } - } - }, - "name": "ray-head", - "ports": [ - { - "containerPort": 6379, - "name": "gcs", - }, - { - "containerPort": 8265, - "name": "dashboard", - }, - { - "containerPort": 10001, - "name": "client", - }, - ], - "resources": { - "limits": { - "cpu": 2, - "memory": "8G", - "nvidia.com/gpu": 0, - }, - "requests": { - "cpu": 2, - "memory": "8G", - "nvidia.com/gpu": 0, - }, - }, - } - ] - } + "replicas": 1, + "requests": { + "cpu": "1", + "memory": "2G", + "nvidia.com/gpu": "0", }, }, - "rayVersion": "1.12.0", - "workerGroupSpecs": [ - { - "groupName": "small-group-quicktest", - "maxReplicas": 1, - "minReplicas": 1, + ], + "generictemplate": { + "apiVersion": "ray.io/v1alpha1", + "kind": "RayCluster", + "metadata": { + "labels": { + "appwrapper.mcad.ibm.com": "quicktest1", + "controller-tools.k8s.io": "1.0", + }, + "name": "quicktest1", + "namespace": "ns", + }, + "spec": { + "autoscalerOptions": { + "idleTimeoutSeconds": 60, + "imagePullPolicy": "Always", + "resources": { + "limits": { + "cpu": "500m", + "memory": "512Mi", + }, + "requests": { + "cpu": "500m", + "memory": "512Mi", + }, + }, + "upscalingMode": "Default", + }, + "enableInTreeAutoscaling": False, + "headGroupSpec": { "rayStartParams": { "block": "true", + "dashboard-host": "0.0.0.0", "num-gpus": "0", }, - "replicas": 1, + "serviceType": "ClusterIP", "template": { - "metadata": { - "annotations": {"key": "value"}, - "labels": {"key": "value"}, - }, "spec": { "containers": [ { - "env": [ - { - "name": "MY_POD_IP", - "valueFrom": { - "fieldRef": { - "fieldPath": "status.podIP" - } - }, - } - ], "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", + "imagePullPolicy": "Always", "lifecycle": { "preStop": { "exec": { @@ -1017,317 +1009,318 @@ def get_aw_obj(): } } }, - "name": "machine-learning", + "name": "ray-head", + "ports": [ + { + "containerPort": 6379, + "name": "gcs", + }, + { + "containerPort": 8265, + "name": "dashboard", + }, + { + "containerPort": 10001, + "name": "client", + }, + ], "resources": { "limits": { - "cpu": 1, - "memory": "2G", + "cpu": 2, + "memory": "8G", "nvidia.com/gpu": 0, }, "requests": { - "cpu": 1, - "memory": "2G", + "cpu": 2, + "memory": "8G", "nvidia.com/gpu": 0, }, }, } - ], - "initContainers": [ - { - "command": [ - "sh", - "-c", - "until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done", - ], - "image": "busybox:1.28", - "name": "init-myservice", - } - ], - }, + ] + } }, - } - ], + }, + "rayVersion": "1.12.0", + "workerGroupSpecs": [ + { + "groupName": "small-group-quicktest", + "maxReplicas": 1, + "minReplicas": 1, + "rayStartParams": { + "block": "true", + "num-gpus": "0", + }, + "replicas": 1, + "template": { + "metadata": { + "annotations": {"key": "value"}, + "labels": {"key": "value"}, + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "MY_POD_IP", + "valueFrom": { + "fieldRef": { + "fieldPath": "status.podIP" + } + }, + } + ], + "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", + "lifecycle": { + "preStop": { + "exec": { + "command": [ + "/bin/sh", + "-c", + "ray stop", + ] + } + } + }, + "name": "machine-learning", + "resources": { + "limits": { + "cpu": 1, + "memory": "2G", + "nvidia.com/gpu": 0, + }, + "requests": { + "cpu": 1, + "memory": "2G", + "nvidia.com/gpu": 0, + }, + }, + } + ], + "initContainers": [ + { + "command": [ + "sh", + "-c", + "until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done", + ], + "image": "busybox:1.28", + "name": "init-myservice", + } + ], + }, + }, + } + ], + }, }, + "metadata": {}, + "priority": 0, + "priorityslope": 0, + "replicas": 1, }, - "metadata": {}, - "priority": 0, - "priorityslope": 0, - "replicas": 1, - }, - { - "allocated": 0, - "generictemplate": { - "apiVersion": "route.openshift.io/v1", - "kind": "Route", - "metadata": { - "labels": { - "odh-ray-cluster-service": "quicktest-head-svc" + { + "allocated": 0, + "generictemplate": { + "apiVersion": "route.openshift.io/v1", + "kind": "Route", + "metadata": { + "labels": { + "odh-ray-cluster-service": "quicktest-head-svc" + }, + "name": "ray-dashboard-quicktest", + "namespace": "default", }, - "name": "ray-dashboard-quicktest", - "namespace": "default", - }, - "spec": { - "port": {"targetPort": "dashboard"}, - "to": { - "kind": "Service", - "name": "quicktest-head-svc", + "spec": { + "port": {"targetPort": "dashboard"}, + "to": { + "kind": "Service", + "name": "quicktest-head-svc", + }, }, }, + "metadata": {}, + "priority": 0, + "priorityslope": 0, }, - "metadata": {}, - "priority": 0, - "priorityslope": 0, + ], + "Items": [], + "metadata": {}, + }, + "schedulingSpec": {}, + "service": {"spec": {}}, + }, + "status": { + "canrun": True, + "conditions": [ + { + "lastTransitionMicroTime": "2023-02-22T16:26:07.559447Z", + "lastUpdateMicroTime": "2023-02-22T16:26:07.559447Z", + "status": "True", + "type": "Init", + }, + { + "lastTransitionMicroTime": "2023-02-22T16:26:07.559551Z", + "lastUpdateMicroTime": "2023-02-22T16:26:07.559551Z", + "reason": "AwaitingHeadOfLine", + "status": "True", + "type": "Queueing", + }, + { + "lastTransitionMicroTime": "2023-02-22T16:26:13.220564Z", + "lastUpdateMicroTime": "2023-02-22T16:26:13.220564Z", + "reason": "AppWrapperRunnable", + "status": "True", + "type": "Dispatched", }, ], - "Items": [], - "metadata": {}, + "controllerfirsttimestamp": "2023-02-22T16:26:07.559447Z", + "filterignore": True, + "queuejobstate": "Dispatched", + "sender": "before manageQueueJob - afterEtcdDispatching", + "state": "Running", + "systempriority": 9, }, - "schedulingSpec": {}, - "service": {"spec": {}}, - }, - "status": { - "canrun": True, - "conditions": [ - { - "lastTransitionMicroTime": "2023-02-22T16:26:07.559447Z", - "lastUpdateMicroTime": "2023-02-22T16:26:07.559447Z", - "status": "True", - "type": "Init", - }, - { - "lastTransitionMicroTime": "2023-02-22T16:26:07.559551Z", - "lastUpdateMicroTime": "2023-02-22T16:26:07.559551Z", - "reason": "AwaitingHeadOfLine", - "status": "True", - "type": "Queueing", - }, - { - "lastTransitionMicroTime": "2023-02-22T16:26:13.220564Z", - "lastUpdateMicroTime": "2023-02-22T16:26:13.220564Z", - "reason": "AppWrapperRunnable", - "status": "True", - "type": "Dispatched", - }, - ], - "controllerfirsttimestamp": "2023-02-22T16:26:07.559447Z", - "filterignore": True, - "queuejobstate": "Dispatched", - "sender": "before manageQueueJob - afterEtcdDispatching", - "state": "Running", - "systempriority": 9, }, - } - ) - api_obj2 = openshift.apiobject.APIObject( - { - "apiVersion": "mcad.ibm.com/v1beta1", - "kind": "AppWrapper", - "metadata": { - "annotations": { - "kubectl.kubernetes.io/last-applied-configuration": '{"apiVersion":"mcad.ibm.com/v1beta1","kind":"AppWrapper","metadata":{"annotations":{},"name":"quicktest2","namespace":"ns"},"spec":{"priority":9,"resources":{"GenericItems":[{"custompodresources":[{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}},{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}],"generictemplate":{"apiVersion":"ray.io/v1alpha1","kind":"RayCluster","metadata":{"labels":{"appwrapper.mcad.ibm.com":"quicktest2","controller-tools.k8s.io":"1.0"},"name":"quicktest2","namespace":"ns"},"spec":{"autoscalerOptions":{"idleTimeoutSeconds":60,"imagePullPolicy":"Always","resources":{"limits":{"cpu":"500m","memory":"512Mi"},"requests":{"cpu":"500m","memory":"512Mi"}},"upscalingMode":"Default"},"enableInTreeAutoscaling":false,"headGroupSpec":{"rayStartParams":{"block":"true","dashboard-host":"0.0.0.0","num-gpus":"0"},"serviceType":"ClusterIP","template":{"spec":{"containers":[{"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","imagePullPolicy":"Always","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"ray-head","ports":[{"containerPort":6379,"name":"gcs"},{"containerPort":8265,"name":"dashboard"},{"containerPort":10001,"name":"client"}],"resources":{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}}}]}}},"rayVersion":"1.12.0","workerGroupSpecs":[{"groupName":"small-group-quicktest","maxReplicas":1,"minReplicas":1,"rayStartParams":{"block":"true","num-gpus":"0"},"replicas":1,"template":{"metadata":{"annotations":{"key":"value"},"labels":{"key":"value"}},"spec":{"containers":[{"env":[{"name":"MY_POD_IP","valueFrom":{"fieldRef":{"fieldPath":"status.podIP"}}}],"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"machine-learning","resources":{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}}],"initContainers":[{"command":["sh","-c","until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"],"image":"busybox:1.28","name":"init-myservice"}]}}}]}},"replicas":1},{"generictemplate":{"apiVersion":"route.openshift.io/v1","kind":"Route","metadata":{"labels":{"odh-ray-cluster-service":"quicktest-head-svc"},"name":"ray-dashboard-quicktest","namespace":"default"},"spec":{"port":{"targetPort":"dashboard"},"to":{"kind":"Service","name":"quicktest-head-svc"}}},"replica":1}],"Items":[]}}}\n' - }, - "creationTimestamp": "2023-02-22T16:26:07Z", - "generation": 4, - "managedFields": [ - { - "apiVersion": "mcad.ibm.com/v1beta1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:spec": { - "f:resources": {"f:GenericItems": {}, "f:metadata": {}}, - "f:schedulingSpec": {}, - "f:service": {".": {}, "f:spec": {}}, - }, - "f:status": { - ".": {}, - "f:canrun": {}, - "f:conditions": {}, - "f:controllerfirsttimestamp": {}, - "f:filterignore": {}, - "f:queuejobstate": {}, - "f:sender": {}, - "f:state": {}, - "f:systempriority": {}, - }, - }, - "manager": "Go-http-client", - "operation": "Update", - "time": "2023-02-22T16:26:07Z", + { + "apiVersion": "mcad.ibm.com/v1beta1", + "kind": "AppWrapper", + "metadata": { + "annotations": { + "kubectl.kubernetes.io/last-applied-configuration": '{"apiVersion":"mcad.ibm.com/v1beta1","kind":"AppWrapper","metadata":{"annotations":{},"name":"quicktest2","namespace":"ns"},"spec":{"priority":9,"resources":{"GenericItems":[{"custompodresources":[{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}},{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"replicas":1,"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}],"generictemplate":{"apiVersion":"ray.io/v1alpha1","kind":"RayCluster","metadata":{"labels":{"appwrapper.mcad.ibm.com":"quicktest2","controller-tools.k8s.io":"1.0"},"name":"quicktest2","namespace":"ns"},"spec":{"autoscalerOptions":{"idleTimeoutSeconds":60,"imagePullPolicy":"Always","resources":{"limits":{"cpu":"500m","memory":"512Mi"},"requests":{"cpu":"500m","memory":"512Mi"}},"upscalingMode":"Default"},"enableInTreeAutoscaling":false,"headGroupSpec":{"rayStartParams":{"block":"true","dashboard-host":"0.0.0.0","num-gpus":"0"},"serviceType":"ClusterIP","template":{"spec":{"containers":[{"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","imagePullPolicy":"Always","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"ray-head","ports":[{"containerPort":6379,"name":"gcs"},{"containerPort":8265,"name":"dashboard"},{"containerPort":10001,"name":"client"}],"resources":{"limits":{"cpu":2,"memory":"8G","nvidia.com/gpu":0},"requests":{"cpu":2,"memory":"8G","nvidia.com/gpu":0}}}]}}},"rayVersion":"1.12.0","workerGroupSpecs":[{"groupName":"small-group-quicktest","maxReplicas":1,"minReplicas":1,"rayStartParams":{"block":"true","num-gpus":"0"},"replicas":1,"template":{"metadata":{"annotations":{"key":"value"},"labels":{"key":"value"}},"spec":{"containers":[{"env":[{"name":"MY_POD_IP","valueFrom":{"fieldRef":{"fieldPath":"status.podIP"}}}],"image":"ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103","lifecycle":{"preStop":{"exec":{"command":["/bin/sh","-c","ray stop"]}}},"name":"machine-learning","resources":{"limits":{"cpu":1,"memory":"2G","nvidia.com/gpu":0},"requests":{"cpu":1,"memory":"2G","nvidia.com/gpu":0}}}],"initContainers":[{"command":["sh","-c","until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"],"image":"busybox:1.28","name":"init-myservice"}]}}}]}},"replicas":1},{"generictemplate":{"apiVersion":"route.openshift.io/v1","kind":"Route","metadata":{"labels":{"odh-ray-cluster-service":"quicktest-head-svc"},"name":"ray-dashboard-quicktest","namespace":"default"},"spec":{"port":{"targetPort":"dashboard"},"to":{"kind":"Service","name":"quicktest-head-svc"}}},"replica":1}],"Items":[]}}}\n' }, - { - "apiVersion": "mcad.ibm.com/v1beta1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:metadata": { - "f:annotations": { + "creationTimestamp": "2023-02-22T16:26:07Z", + "generation": 4, + "managedFields": [ + { + "apiVersion": "mcad.ibm.com/v1beta1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:spec": { + "f:resources": { + "f:GenericItems": {}, + "f:metadata": {}, + }, + "f:schedulingSpec": {}, + "f:service": {".": {}, "f:spec": {}}, + }, + "f:status": { ".": {}, - "f:kubectl.kubernetes.io/last-applied-configuration": {}, - } - }, - "f:spec": { - ".": {}, - "f:priority": {}, - "f:resources": {".": {}, "f:Items": {}}, + "f:canrun": {}, + "f:conditions": {}, + "f:controllerfirsttimestamp": {}, + "f:filterignore": {}, + "f:queuejobstate": {}, + "f:sender": {}, + "f:state": {}, + "f:systempriority": {}, + }, }, + "manager": "Go-http-client", + "operation": "Update", + "time": "2023-02-22T16:26:07Z", }, - "manager": "kubectl-client-side-apply", - "operation": "Update", - "time": "2023-02-22T16:26:07Z", - }, - ], - "name": "quicktest2", - "namespace": "ns", - "resourceVersion": "9482384", - "uid": "6334fc1b-471e-4876-8e7b-0b2277679235", - }, - "spec": { - "priority": 9, - "resources": { - "GenericItems": [ { - "allocated": 0, - "custompodresources": [ - { - "limits": { - "cpu": "2", - "memory": "8G", - "nvidia.com/gpu": "0", - }, - "replicas": 1, - "requests": { - "cpu": "2", - "memory": "8G", - "nvidia.com/gpu": "0", - }, - }, - { - "limits": { - "cpu": "1", - "memory": "2G", - "nvidia.com/gpu": "0", - }, - "replicas": 1, - "requests": { - "cpu": "1", - "memory": "2G", - "nvidia.com/gpu": "0", - }, + "apiVersion": "mcad.ibm.com/v1beta1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {}, + } }, - ], - "generictemplate": { - "apiVersion": "ray.io/v1alpha1", - "kind": "RayCluster", - "metadata": { - "labels": { - "appwrapper.mcad.ibm.com": "quicktest2", - "controller-tools.k8s.io": "1.0", - }, - "name": "quicktest2", - "namespace": "ns", + "f:spec": { + ".": {}, + "f:priority": {}, + "f:resources": {".": {}, "f:Items": {}}, }, - "spec": { - "autoscalerOptions": { - "idleTimeoutSeconds": 60, - "imagePullPolicy": "Always", - "resources": { - "limits": { - "cpu": "500m", - "memory": "512Mi", - }, - "requests": { - "cpu": "500m", - "memory": "512Mi", - }, + }, + "manager": "kubectl-client-side-apply", + "operation": "Update", + "time": "2023-02-22T16:26:07Z", + }, + ], + "name": "quicktest2", + "namespace": "ns", + "resourceVersion": "9482384", + "uid": "6334fc1b-471e-4876-8e7b-0b2277679235", + }, + "spec": { + "priority": 9, + "resources": { + "GenericItems": [ + { + "allocated": 0, + "custompodresources": [ + { + "limits": { + "cpu": "2", + "memory": "8G", + "nvidia.com/gpu": "0", + }, + "replicas": 1, + "requests": { + "cpu": "2", + "memory": "8G", + "nvidia.com/gpu": "0", }, - "upscalingMode": "Default", }, - "enableInTreeAutoscaling": False, - "headGroupSpec": { - "rayStartParams": { - "block": "true", - "dashboard-host": "0.0.0.0", - "num-gpus": "0", + { + "limits": { + "cpu": "1", + "memory": "2G", + "nvidia.com/gpu": "0", }, - "serviceType": "ClusterIP", - "template": { - "spec": { - "containers": [ - { - "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", - "imagePullPolicy": "Always", - "lifecycle": { - "preStop": { - "exec": { - "command": [ - "/bin/sh", - "-c", - "ray stop", - ] - } - } - }, - "name": "ray-head", - "ports": [ - { - "containerPort": 6379, - "name": "gcs", - }, - { - "containerPort": 8265, - "name": "dashboard", - }, - { - "containerPort": 10001, - "name": "client", - }, - ], - "resources": { - "limits": { - "cpu": 2, - "memory": "8G", - "nvidia.com/gpu": 0, - }, - "requests": { - "cpu": 2, - "memory": "8G", - "nvidia.com/gpu": 0, - }, - }, - } - ] - } + "replicas": 1, + "requests": { + "cpu": "1", + "memory": "2G", + "nvidia.com/gpu": "0", }, }, - "rayVersion": "1.12.0", - "workerGroupSpecs": [ - { - "groupName": "small-group-quicktest", - "maxReplicas": 1, - "minReplicas": 1, + ], + "generictemplate": { + "apiVersion": "ray.io/v1alpha1", + "kind": "RayCluster", + "metadata": { + "labels": { + "appwrapper.mcad.ibm.com": "quicktest2", + "controller-tools.k8s.io": "1.0", + }, + "name": "quicktest2", + "namespace": "ns", + }, + "spec": { + "autoscalerOptions": { + "idleTimeoutSeconds": 60, + "imagePullPolicy": "Always", + "resources": { + "limits": { + "cpu": "500m", + "memory": "512Mi", + }, + "requests": { + "cpu": "500m", + "memory": "512Mi", + }, + }, + "upscalingMode": "Default", + }, + "enableInTreeAutoscaling": False, + "headGroupSpec": { "rayStartParams": { "block": "true", + "dashboard-host": "0.0.0.0", "num-gpus": "0", }, - "replicas": 1, + "serviceType": "ClusterIP", "template": { - "metadata": { - "annotations": {"key": "value"}, - "labels": {"key": "value"}, - }, "spec": { "containers": [ { - "env": [ - { - "name": "MY_POD_IP", - "valueFrom": { - "fieldRef": { - "fieldPath": "status.podIP" - } - }, - } - ], "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", + "imagePullPolicy": "Always", "lifecycle": { "preStop": { "exec": { @@ -1339,114 +1332,214 @@ def get_aw_obj(): } } }, - "name": "machine-learning", + "name": "ray-head", + "ports": [ + { + "containerPort": 6379, + "name": "gcs", + }, + { + "containerPort": 8265, + "name": "dashboard", + }, + { + "containerPort": 10001, + "name": "client", + }, + ], "resources": { "limits": { - "cpu": 1, - "memory": "2G", + "cpu": 2, + "memory": "8G", "nvidia.com/gpu": 0, }, "requests": { - "cpu": 1, - "memory": "2G", + "cpu": 2, + "memory": "8G", "nvidia.com/gpu": 0, }, }, } - ], - "initContainers": [ - { - "command": [ - "sh", - "-c", - "until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done", - ], - "image": "busybox:1.28", - "name": "init-myservice", - } - ], - }, + ] + } }, - } - ], + }, + "rayVersion": "1.12.0", + "workerGroupSpecs": [ + { + "groupName": "small-group-quicktest", + "maxReplicas": 1, + "minReplicas": 1, + "rayStartParams": { + "block": "true", + "num-gpus": "0", + }, + "replicas": 1, + "template": { + "metadata": { + "annotations": {"key": "value"}, + "labels": {"key": "value"}, + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "MY_POD_IP", + "valueFrom": { + "fieldRef": { + "fieldPath": "status.podIP" + } + }, + } + ], + "image": "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103", + "lifecycle": { + "preStop": { + "exec": { + "command": [ + "/bin/sh", + "-c", + "ray stop", + ] + } + } + }, + "name": "machine-learning", + "resources": { + "limits": { + "cpu": 1, + "memory": "2G", + "nvidia.com/gpu": 0, + }, + "requests": { + "cpu": 1, + "memory": "2G", + "nvidia.com/gpu": 0, + }, + }, + } + ], + "initContainers": [ + { + "command": [ + "sh", + "-c", + "until nslookup $RAY_IP.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done", + ], + "image": "busybox:1.28", + "name": "init-myservice", + } + ], + }, + }, + } + ], + }, }, + "metadata": {}, + "priority": 0, + "priorityslope": 0, + "replicas": 1, }, - "metadata": {}, - "priority": 0, - "priorityslope": 0, - "replicas": 1, - }, - { - "allocated": 0, - "generictemplate": { - "apiVersion": "route.openshift.io/v1", - "kind": "Route", - "metadata": { - "labels": { - "odh-ray-cluster-service": "quicktest-head-svc" + { + "allocated": 0, + "generictemplate": { + "apiVersion": "route.openshift.io/v1", + "kind": "Route", + "metadata": { + "labels": { + "odh-ray-cluster-service": "quicktest-head-svc" + }, + "name": "ray-dashboard-quicktest", + "namespace": "default", }, - "name": "ray-dashboard-quicktest", - "namespace": "default", - }, - "spec": { - "port": {"targetPort": "dashboard"}, - "to": { - "kind": "Service", - "name": "quicktest-head-svc", + "spec": { + "port": {"targetPort": "dashboard"}, + "to": { + "kind": "Service", + "name": "quicktest-head-svc", + }, }, }, + "metadata": {}, + "priority": 0, + "priorityslope": 0, }, - "metadata": {}, - "priority": 0, - "priorityslope": 0, + ], + "Items": [], + "metadata": {}, + }, + "schedulingSpec": {}, + "service": {"spec": {}}, + }, + "status": { + "canrun": True, + "conditions": [ + { + "lastTransitionMicroTime": "2023-02-22T16:26:07.559447Z", + "lastUpdateMicroTime": "2023-02-22T16:26:07.559447Z", + "status": "True", + "type": "Init", + }, + { + "lastTransitionMicroTime": "2023-02-22T16:26:07.559551Z", + "lastUpdateMicroTime": "2023-02-22T16:26:07.559551Z", + "reason": "AwaitingHeadOfLine", + "status": "True", + "type": "Queueing", + }, + { + "lastTransitionMicroTime": "2023-02-22T16:26:13.220564Z", + "lastUpdateMicroTime": "2023-02-22T16:26:13.220564Z", + "reason": "AppWrapperRunnable", + "status": "True", + "type": "Dispatched", }, ], - "Items": [], - "metadata": {}, + "controllerfirsttimestamp": "2023-02-22T16:26:07.559447Z", + "filterignore": True, + "queuejobstate": "Dispatched", + "sender": "before manageQueueJob - afterEtcdDispatching", + "state": "Pending", + "systempriority": 9, }, - "schedulingSpec": {}, - "service": {"spec": {}}, - }, - "status": { - "canrun": True, - "conditions": [ - { - "lastTransitionMicroTime": "2023-02-22T16:26:07.559447Z", - "lastUpdateMicroTime": "2023-02-22T16:26:07.559447Z", - "status": "True", - "type": "Init", - }, - { - "lastTransitionMicroTime": "2023-02-22T16:26:07.559551Z", - "lastUpdateMicroTime": "2023-02-22T16:26:07.559551Z", - "reason": "AwaitingHeadOfLine", - "status": "True", - "type": "Queueing", - }, - { - "lastTransitionMicroTime": "2023-02-22T16:26:13.220564Z", - "lastUpdateMicroTime": "2023-02-22T16:26:13.220564Z", - "reason": "AppWrapperRunnable", - "status": "True", - "type": "Dispatched", - }, - ], - "controllerfirsttimestamp": "2023-02-22T16:26:07.559447Z", - "filterignore": True, - "queuejobstate": "Dispatched", - "sender": "before manageQueueJob - afterEtcdDispatching", - "state": "Pending", - "systempriority": 9, }, - } + ] + } + return api_obj1 + + +def test_get_cluster(mocker): + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=get_ray_obj, ) - return [api_obj1, api_obj2] + cluster = get_cluster("quicktest") + cluster_config = cluster.config + assert cluster_config.name == "quicktest" and cluster_config.namespace == "ns" + assert ( + "m4.xlarge" in cluster_config.machine_types + and "g4dn.xlarge" in cluster_config.machine_types + ) + assert cluster_config.min_cpus == 1 and cluster_config.max_cpus == 1 + assert cluster_config.min_memory == 2 and cluster_config.max_memory == 2 + assert cluster_config.num_gpus == 0 + assert cluster_config.instascale + assert ( + cluster_config.image + == "ghcr.io/foundation-model-stack/base:ray2.1.0-py38-gpu-pytorch1.12.0cu116-20221213-193103" + ) + assert cluster_config.num_workers == 1 def test_list_clusters(mocker, capsys): - mocker.patch("openshift.selector", side_effect=get_selector) - mock_res = mocker.patch.object(Selector, "objects") - mock_res.side_effect = get_obj_none + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=get_obj_none, + ) list_all_clusters("ns") captured = capsys.readouterr() assert captured.out == ( @@ -1454,35 +1547,40 @@ def test_list_clusters(mocker, capsys): "│ No resources found, have you run cluster.up() yet? │\n" "╰──────────────────────────────────────────────────────────────────────────────╯\n" ) - mock_res.side_effect = get_ray_obj + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=get_ray_obj, + ) list_all_clusters("ns") captured = capsys.readouterr() assert captured.out == ( - " 🚀 CodeFlare Cluster Details 🚀 \n" - " \n" - " ╭──────────────────────────────────────────────────────────────╮ \n" - " │ Name │ \n" - " │ quicktest Active ✅ │ \n" - " │ │ \n" - " │ URI: ray://quicktest-head-svc.ns.svc:10001 │ \n" - " │ │ \n" - " │ Dashboard🔗 │ \n" - " │ │ \n" - " │ Cluster Resources │ \n" - " │ ╭─ Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │ \n" - " │ │ Min Max │ │ Memory CPU GPU │ │ \n" - " │ │ │ │ │ │ \n" - " │ │ 1 1 │ │ 2G~2G 1 0 │ │ \n" - " │ │ │ │ │ │ \n" - " │ ╰────────────╯ ╰──────────────────────────────────────╯ │ \n" - " ╰──────────────────────────────────────────────────────────────╯ \n" + " 🚀 CodeFlare Cluster Details 🚀 \n" + " \n" + " ╭───────────────────────────────────────────────────────────────╮ \n" + " │ Name │ \n" + " │ quicktest Active ✅ │ \n" + " │ │ \n" + " │ URI: ray://quicktest-head-svc.ns.svc:10001 │ \n" + " │ │ \n" + " │ Dashboard🔗 │ \n" + " │ │ \n" + " │ Cluster Resources │ \n" + " │ ╭── Workers ──╮ ╭───────── Worker specs(each) ─────────╮ │ \n" + " │ │ # Workers │ │ Memory CPU GPU │ │ \n" + " │ │ │ │ │ │ \n" + " │ │ 1 │ │ 2G~2G 1 0 │ │ \n" + " │ │ │ │ │ │ \n" + " │ ╰─────────────╯ ╰──────────────────────────────────────╯ │ \n" + " ╰───────────────────────────────────────────────────────────────╯ \n" ) def test_list_queue(mocker, capsys): - mocker.patch("openshift.selector", side_effect=get_selector) - mock_res = mocker.patch.object(Selector, "objects") - mock_res.side_effect = get_obj_none + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=get_obj_none, + ) list_all_queued("ns") captured = capsys.readouterr() assert captured.out == ( @@ -1490,7 +1588,10 @@ def test_list_queue(mocker, capsys): "│ No resources found, have you run cluster.up() yet? │\n" "╰──────────────────────────────────────────────────────────────────────────────╯\n" ) - mock_res.side_effect = get_aw_obj + mocker.patch( + "kubernetes.client.CustomObjectsApi.list_namespaced_custom_object", + side_effect=get_aw_obj, + ) list_all_queued("ns") captured = capsys.readouterr() assert captured.out == ( @@ -1510,14 +1611,14 @@ def test_list_queue(mocker, capsys): def test_cluster_status(mocker): + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") fake_aw = AppWrapper( "test", AppWrapperStatus.FAILED, can_run=True, job_state="unused" ) fake_ray = RayCluster( name="test", status=RayClusterStatus.UNKNOWN, - min_workers=1, - max_workers=1, + workers=1, worker_mem_min=2, worker_mem_max=2, worker_cpu=1, @@ -1526,6 +1627,8 @@ def test_cluster_status(mocker): dashboard="fake-uri", ) cf = Cluster(ClusterConfiguration(name="test", namespace="ns")) + mocker.patch("codeflare_sdk.cluster.cluster._app_wrapper_status", return_value=None) + mocker.patch("codeflare_sdk.cluster.cluster._ray_cluster_status", return_value=None) status, ready = cf.status() assert status == CodeFlareClusterStatus.UNKNOWN assert ready == False @@ -1587,6 +1690,9 @@ def test_cluster_status(mocker): def test_wait_ready(mocker, capsys): + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch("codeflare_sdk.cluster.cluster._app_wrapper_status", return_value=None) + mocker.patch("codeflare_sdk.cluster.cluster._ray_cluster_status", return_value=None) cf = Cluster(ClusterConfiguration(name="test", namespace="ns")) try: cf.wait_ready(timeout=5) @@ -1658,12 +1764,17 @@ def test_DDPJobDefinition_creation(): return ddp -def test_DDPJobDefinition_dry_run(): +def test_DDPJobDefinition_dry_run(mocker): """ Test that the dry run method returns the correct type: AppDryRunInfo, that the attributes of the returned object are of the correct type, and that the values from cluster and job definition are correctly passed. """ + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.cluster_dashboard_uri", + return_value="", + ) ddp = test_DDPJobDefinition_creation() cluster = Cluster(test_config_creation()) ddp_job = ddp._dry_run(cluster) @@ -1696,7 +1807,7 @@ def test_DDPJobDefinition_dry_run_no_cluster(mocker): """ mocker.patch( - "openshift.get_project_name", + "codeflare_sdk.job.jobs.get_current_namespace", return_value="opendatahub", ) @@ -1728,11 +1839,15 @@ def test_DDPJobDefinition_dry_run_no_cluster(mocker): assert ddp_job._scheduler == "kubernetes_mcad" -def test_DDPJobDefinition_dry_run_no_resource_args(): +def test_DDPJobDefinition_dry_run_no_resource_args(mocker): """ Test that the dry run correctly gets resources from the cluster object when the job definition does not specify resources. """ + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.cluster_dashboard_uri", + return_value="", + ) cluster = Cluster(test_config_creation()) ddp = DDPJobDefinition( script="test.py", @@ -1749,11 +1864,11 @@ def test_DDPJobDefinition_dry_run_no_resource_args(): ddp_job = ddp._dry_run(cluster) assert ddp_job._app.roles[0].resource.cpu == cluster.config.max_cpus - assert ddp_job._app.roles[0].resource.gpu == cluster.config.gpu + assert ddp_job._app.roles[0].resource.gpu == cluster.config.num_gpus assert ddp_job._app.roles[0].resource.memMB == cluster.config.max_memory * 1024 assert ( parse_j(ddp_job._app.roles[0].args[1]) - == f"{cluster.config.max_worker}x{cluster.config.gpu}" + == f"{cluster.config.num_workers}x{cluster.config.num_gpus}" ) @@ -1765,7 +1880,7 @@ def test_DDPJobDefinition_dry_run_no_cluster_no_resource_args(mocker): """ mocker.patch( - "openshift.get_project_name", + "codeflare_sdk.job.jobs.get_current_namespace", return_value="opendatahub", ) @@ -1817,11 +1932,15 @@ def test_DDPJobDefinition_submit(mocker): Tests that the submit method returns the correct type: DDPJob And that the attributes of the returned object are of the correct type """ + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.cluster_dashboard_uri", + return_value="fake-dashboard-uri", + ) ddp_def = test_DDPJobDefinition_creation() cluster = Cluster(test_config_creation()) mocker.patch( - "openshift.get_project_name", - return_value="opendatahub", + "codeflare_sdk.job.jobs.get_current_namespace", + side_effect="opendatahub", ) mocker.patch( "codeflare_sdk.job.jobs.torchx_runner.schedule", @@ -1844,6 +1963,10 @@ def test_DDPJobDefinition_submit(mocker): def test_DDPJob_creation(mocker): + mocker.patch( + "codeflare_sdk.cluster.cluster.Cluster.cluster_dashboard_uri", + return_value="fake-dashboard-uri", + ) ddp_def = test_DDPJobDefinition_creation() cluster = Cluster(test_config_creation()) mocker.patch( @@ -1870,8 +1993,8 @@ def test_DDPJob_creation_no_cluster(mocker): ddp_def = test_DDPJobDefinition_creation() ddp_def.image = "fake-image" mocker.patch( - "openshift.get_project_name", - return_value="opendatahub", + "codeflare_sdk.job.jobs.get_current_namespace", + side_effect="opendatahub", ) mocker.patch( "codeflare_sdk.job.jobs.torchx_runner.schedule", @@ -1937,9 +2060,9 @@ def parse_j(cmd): else: return None args = substring.split() - max_worker = args[1] + worker = args[1] gpu = args[3] - return f"{max_worker}x{gpu}" + return f"{worker}x{gpu}" def test_AWManager_creation(): @@ -1962,14 +2085,24 @@ def test_AWManager_creation(): ) -def arg_check_aw_create_effect(*args): - assert args[0] == "create" - assert args[1] == ["-f", "test.yaml"] +def arg_check_aw_apply_effect(group, version, namespace, plural, body, *args): + assert group == "mcad.ibm.com" + assert version == "v1beta1" + assert namespace == "ns" + assert plural == "appwrappers" + with open("test.yaml") as f: + aw = yaml.load(f, Loader=yaml.FullLoader) + assert body == aw + assert args == tuple() -def arg_check_aw_delete_effect(*args): - assert args[0] == "delete" - assert args[1] == ["AppWrapper", "test"] +def arg_check_aw_del_effect(group, version, namespace, plural, name, *args): + assert group == "mcad.ibm.com" + assert version == "v1beta1" + assert namespace == "ns" + assert plural == "appwrappers" + assert name == "test" + assert args == tuple() def test_AWManager_submit_remove(mocker, capsys): @@ -1981,10 +2114,17 @@ def test_AWManager_submit_remove(mocker, capsys): == "AppWrapper not submitted by this manager yet, nothing to remove\n" ) assert testaw.submitted == False - mocker.patch("openshift.invoke", side_effect=arg_check_aw_create_effect) + mocker.patch("kubernetes.config.load_kube_config", return_value="ignore") + mocker.patch( + "kubernetes.client.CustomObjectsApi.create_namespaced_custom_object", + side_effect=arg_check_aw_apply_effect, + ) + mocker.patch( + "kubernetes.client.CustomObjectsApi.delete_namespaced_custom_object", + side_effect=arg_check_aw_del_effect, + ) testaw.submit() assert testaw.submitted == True - mocker.patch("openshift.invoke", side_effect=arg_check_aw_delete_effect) testaw.remove() assert testaw.submitted == False @@ -2071,20 +2211,14 @@ def test_export_env(): ) -# Make sure to keep this function and the following function at the end of the file -def test_cmd_line_generation(): - os.system( - f"python3 {parent}/src/codeflare_sdk/utils/generate_yaml.py --name=unit-cmd-cluster --min-cpu=1 --max-cpu=1 --min-memory=2 --max-memory=2 --gpu=1 --workers=2 --template=src/codeflare_sdk/templates/base-template.yaml" - ) - assert filecmp.cmp( - "unit-cmd-cluster.yaml", f"{parent}/tests/test-case-cmd.yaml", shallow=True - ) - os.remove("unit-test-cluster.yaml") - os.remove("unit-test-default-cluster.yaml") - os.remove("unit-cmd-cluster.yaml") - - # Make sure to always keep this function last def test_cleanup(): + os.remove("unit-test-cluster.yaml") + os.remove("unit-test-default-cluster.yaml") os.remove("test.yaml") os.remove("raytest2.yaml") + os.remove("quicktest.yaml") + os.remove("tls-cluster-namespace/ca.crt") + os.remove("tls-cluster-namespace/tls.crt") + os.remove("tls-cluster-namespace/tls.key") + os.rmdir("tls-cluster-namespace")