|
| 1 | +// Copyright 2020 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +const {GameServerClustersServiceClient} = require('@google-cloud/game-servers'); |
| 16 | +const {RealmsServiceClient} = require('@google-cloud/game-servers'); |
| 17 | + |
| 18 | +const gameServerClusterClient = new GameServerClustersServiceClient(); |
| 19 | +const realmsClient = new RealmsServiceClient(); |
| 20 | + |
| 21 | +/** |
| 22 | + * Utility function for removing unneeded realms from project. |
| 23 | + */ |
| 24 | +module.exports = async () => { |
| 25 | + const projectId = await realmsClient.getProjectId(); |
| 26 | + const location = 'us-central1'; |
| 27 | + |
| 28 | + const request = { |
| 29 | + parent: `projects/${projectId}/locations/${location}`, |
| 30 | + }; |
| 31 | + |
| 32 | + const MAX_REALM_LIFESPAN = 3600000; // One hour (in milliseconds) |
| 33 | + const NOW = new Date(); |
| 34 | + |
| 35 | + const [results] = await realmsClient.listRealms(request); |
| 36 | + for (const realm of results.realms) { |
| 37 | + // Check age of realm. If older than maximum life span, delete. |
| 38 | + const ageOfRealm = new Date(realm.createTime.seconds * 1000); |
| 39 | + if (NOW - ageOfRealm > MAX_REALM_LIFESPAN) { |
| 40 | + // First, delete all clusters associated with this realm. |
| 41 | + const clustersRequest = { |
| 42 | + parent: realm.name, |
| 43 | + }; |
| 44 | + |
| 45 | + const clustersResult = await gameServerClusterClient.listGameServerClusters( |
| 46 | + clustersRequest |
| 47 | + ); |
| 48 | + const [clusters] = clustersResult; |
| 49 | + for (const cluster of clusters.gameServerClusters) { |
| 50 | + const deleteClusterRequest = { |
| 51 | + name: cluster.name, |
| 52 | + }; |
| 53 | + |
| 54 | + const [ |
| 55 | + deleteClusterOperation, |
| 56 | + ] = await gameServerClusterClient.deleteGameServerCluster( |
| 57 | + deleteClusterRequest |
| 58 | + ); |
| 59 | + await deleteClusterOperation.promise(); |
| 60 | + } |
| 61 | + |
| 62 | + // Then delete the realm itself. |
| 63 | + const realmDeleteRequest = { |
| 64 | + name: realm.name, |
| 65 | + }; |
| 66 | + |
| 67 | + const [deleteRealmOperation] = await realmsClient.deleteRealm( |
| 68 | + realmDeleteRequest |
| 69 | + ); |
| 70 | + await deleteRealmOperation.promise(); |
| 71 | + } |
| 72 | + } |
| 73 | +}; |
0 commit comments