|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2022 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +# [START gke_create_cluster] |
| 17 | +import argparse |
| 18 | +import sys |
| 19 | +from typing import Dict |
| 20 | + |
| 21 | +import backoff |
| 22 | +from google.cloud import container_v1 |
| 23 | + |
| 24 | + |
| 25 | +def on_success(details: Dict[str, str]) -> None: |
| 26 | + """ |
| 27 | + A handler function to pass into the retry backoff algorithm as the function |
| 28 | + to be executed upon a successful attempt. |
| 29 | +
|
| 30 | + Read the `Event handlers` section of the backoff python module at: |
| 31 | + https://pypi.org/project/backoff/ |
| 32 | + """ |
| 33 | + print("Successfully created cluster after {elapsed:0.1f} seconds".format(**details)) |
| 34 | + |
| 35 | + |
| 36 | +def on_failure(details: Dict[str, str]) -> None: |
| 37 | + """ |
| 38 | + A handler function to pass into the retry backoff algorithm as the function |
| 39 | + to be executed upon a failed attempt. |
| 40 | +
|
| 41 | + Read the `Event handlers` section of the backoff python module at: |
| 42 | + https://pypi.org/project/backoff/ |
| 43 | + """ |
| 44 | + print("Backing off {wait:0.1f} seconds after {tries} tries".format(**details)) |
| 45 | + |
| 46 | + |
| 47 | +@backoff.on_predicate( |
| 48 | + # the backoff algorithm to use. we use exponential backoff here |
| 49 | + backoff.expo, |
| 50 | + # the test function on the return value to determine if a retry is necessary |
| 51 | + lambda x: x != container_v1.Operation.Status.DONE, |
| 52 | + # maximum number of times to retry before giving up |
| 53 | + max_tries=20, |
| 54 | + # function to execute upon a failure and when a retry a scheduled |
| 55 | + on_backoff=on_failure, |
| 56 | + # function to execute upon a successful attempt and no more retries needed |
| 57 | + on_success=on_success, |
| 58 | +) |
| 59 | +def poll_for_op_status( |
| 60 | + client: container_v1.ClusterManagerClient, op_id: str |
| 61 | +) -> container_v1.Operation.Status: |
| 62 | + """ |
| 63 | + This function calls the Operation API in GCP with the given operation id. It |
| 64 | + serves as a simple retry function that fetches the operation and returns |
| 65 | + it's status. |
| 66 | +
|
| 67 | + We use the 'backoff' python module to provide us the implementation of the |
| 68 | + backoff & retry strategy. The function is annotated with the `backoff` |
| 69 | + python module to schedule this function based on a reasonable backoff |
| 70 | + algorithm. |
| 71 | + """ |
| 72 | + |
| 73 | + op = client.get_operation({"name": op_id}) |
| 74 | + return op.status |
| 75 | + |
| 76 | + |
| 77 | +def create_cluster(project_id: str, location: str, cluster_name: str) -> None: |
| 78 | + """Create a new GKE cluster in the given GCP Project and Zone""" |
| 79 | + # Initialize the Cluster management client. |
| 80 | + client = container_v1.ClusterManagerClient() |
| 81 | + # Create a fully qualified location identifier of form `projects/{project_id}/location/{zone}'. |
| 82 | + cluster_location = client.common_location_path(project_id, location) |
| 83 | + cluster_def = { |
| 84 | + "name": cluster_name, |
| 85 | + "initial_node_count": 2, |
| 86 | + "node_config": {"machine_type": "e2-standard-2"}, |
| 87 | + } |
| 88 | + # Create the request object with the location identifier. |
| 89 | + request = {"parent": cluster_location, "cluster": cluster_def} |
| 90 | + create_response = client.create_cluster(request) |
| 91 | + op_identifier = f"{cluster_location}/operations/{create_response.name}" |
| 92 | + # poll for the operation status and schedule a retry until the cluster is created |
| 93 | + poll_for_op_status(client, op_identifier) |
| 94 | + |
| 95 | + |
| 96 | +# [END gke_create_cluster] |
| 97 | + |
| 98 | +if __name__ == "__main__": |
| 99 | + parser = argparse.ArgumentParser( |
| 100 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, |
| 101 | + ) |
| 102 | + parser.add_argument("project_id", help="Google Cloud project ID") |
| 103 | + parser.add_argument("zone", help="GKE Cluster zone") |
| 104 | + parser.add_argument("cluster_name", help="Name to be given to the GKE Cluster") |
| 105 | + args = parser.parse_args() |
| 106 | + |
| 107 | + if len(sys.argv) != 4: |
| 108 | + parser.print_usage() |
| 109 | + sys.exit(1) |
| 110 | + |
| 111 | + create_cluster(args.project_id, args.zone, args.cluster_name) |
0 commit comments