|
| 1 | +// Copyright 2025 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 | +// http://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 | +// [START functions_billing_stop] |
| 16 | +const {CloudBillingClient} = require('@google-cloud/billing'); |
| 17 | +const functions = require('@google-cloud/functions-framework'); |
| 18 | +const gcpMetadata = require('gcp-metadata'); |
| 19 | + |
| 20 | +const billing = new CloudBillingClient(); |
| 21 | + |
| 22 | +let projectId = process.env.GOOGLE_CLOUD_PROJECT; |
| 23 | + |
| 24 | +// TODO(developer): Since stopping billing is a destructive action |
| 25 | +// for your project, first validate a test budget with a dry run enabled. |
| 26 | +const dryRun = true; |
| 27 | + |
| 28 | +functions.cloudEvent('StopBillingCloudEvent', async cloudEvent => { |
| 29 | + if (projectId === undefined) { |
| 30 | + try { |
| 31 | + projectId = await gcpMetadata.project('project-id'); |
| 32 | + } catch (error) { |
| 33 | + console.error('project-id metadata not found:', error); |
| 34 | + |
| 35 | + console.error( |
| 36 | + 'Project ID could not be found in environment variables ' + |
| 37 | + 'or Cloud Run metadata server. Stopping execution.' |
| 38 | + ); |
| 39 | + return; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + const projectName = `projects/${projectId}`; |
| 44 | + |
| 45 | + // Find more information about the notification format here: |
| 46 | + // https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification-format |
| 47 | + const messageData = cloudEvent.data?.message?.data; |
| 48 | + if (!messageData) { |
| 49 | + console.error('Invalid CloudEvent: missing data.message.data'); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + const eventData = Buffer.from(messageData, 'base64').toString(); |
| 54 | + |
| 55 | + let eventObject; |
| 56 | + try { |
| 57 | + eventObject = JSON.parse(eventData); |
| 58 | + } catch (e) { |
| 59 | + console.error('Error parsing event data:', e); |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + console.log( |
| 64 | + `Project ID: ${projectId} ` + |
| 65 | + `Current cost: ${eventObject.costAmount} ` + |
| 66 | + `Budget: ${eventObject.budgetAmount}` |
| 67 | + ); |
| 68 | + |
| 69 | + if (eventObject.costAmount <= eventObject.budgetAmount) { |
| 70 | + console.log('No action required. Current cost is within budget.'); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + console.log(`Disabling billing for project '${projectName}'...`); |
| 75 | + |
| 76 | + const billingEnabled = await _isBillingEnabled(projectName); |
| 77 | + if (billingEnabled) { |
| 78 | + await _disableBillingForProject(projectName); |
| 79 | + } else { |
| 80 | + console.log('Billing is already disabled.'); |
| 81 | + } |
| 82 | +}); |
| 83 | + |
| 84 | +/** |
| 85 | + * Determine whether billing is enabled for a project |
| 86 | + * @param {string} projectName The name of the project to check |
| 87 | + * @returns {boolean} Whether the project has billing enabled or not |
| 88 | + */ |
| 89 | +const _isBillingEnabled = async projectName => { |
| 90 | + try { |
| 91 | + console.log(`Getting billing info for project '${projectName}'...`); |
| 92 | + const [res] = await billing.getProjectBillingInfo({name: projectName}); |
| 93 | + |
| 94 | + return res.billingEnabled; |
| 95 | + } catch (e) { |
| 96 | + console.error('Error getting billing info:', e); |
| 97 | + console.error( |
| 98 | + 'Unable to determine if billing is enabled on specified project, ' + |
| 99 | + 'assuming billing is enabled' |
| 100 | + ); |
| 101 | + |
| 102 | + return true; |
| 103 | + } |
| 104 | +}; |
| 105 | + |
| 106 | +/** |
| 107 | + * Disable billing for a project by removing its billing account |
| 108 | + * @param {string} projectName The name of the project to disable billing |
| 109 | + * @returns {void} |
| 110 | + */ |
| 111 | +const _disableBillingForProject = async projectName => { |
| 112 | + if (dryRun) { |
| 113 | + console.log( |
| 114 | + '** INFO: Disabling running in info-only mode because "dryRun" is true. ' + |
| 115 | + 'To disable billing, set "dryRun" to false.' |
| 116 | + ); |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + // Find more information about `projects/updateBillingInfo` API method here: |
| 121 | + // https://cloud.google.com/billing/docs/reference/rest/v1/projects/updateBillingInfo |
| 122 | + try { |
| 123 | + // To disable billing set the `billingAccountName` field to empty |
| 124 | + const requestBody = {billingAccountName: ''}; |
| 125 | + |
| 126 | + const [response] = await billing.updateProjectBillingInfo({ |
| 127 | + name: projectName, |
| 128 | + resource: requestBody, |
| 129 | + }); |
| 130 | + |
| 131 | + console.log(`Billing disabled. Response: ${JSON.stringify(response)}`); |
| 132 | + } catch (e) { |
| 133 | + console.error('Failed to disable billing, check permissions.', e); |
| 134 | + } |
| 135 | +}; |
| 136 | +// [END functions_billing_stop] |
0 commit comments