-
Notifications
You must be signed in to change notification settings - Fork 2k
fix(functions): update and fix functions_billing_stop sample
#4085
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 9 commits
24c71f9
5863455
a4712e5
e77736c
2e87396
96a8334
6f98466
c1a36d5
8505f6a
bb58b19
82d6db3
e6ab704
b279adf
3c6c473
5f7f27d
d1cb382
99920e2
ebefd6e
57984ef
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # This file specifies files that are *not* uploaded to Google Cloud Platform | ||
| # using gcloud. It follows the same syntax as .gitignore, with the addition of | ||
| # "#!include" directives (which insert the entries of the given .gitignore-style | ||
| # file at that point). | ||
| # | ||
| # For more information, run: | ||
| # $ gcloud topic gcloudignore | ||
| # | ||
| .gcloudignore | ||
| # If you would like to upload your .git directory, .gitignore file or files | ||
| # from your .gitignore file, remove the corresponding line | ||
| # below: | ||
| .git | ||
| .gitignore | ||
|
|
||
| node_modules | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // 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. | ||
|
|
||
| // [START functions_billing_stop] | ||
| const {CloudBillingClient} = require('@google-cloud/billing'); | ||
| const functions = require('@google-cloud/functions-framework'); | ||
| const gcpMetadata = require('gcp-metadata'); | ||
|
|
||
| const billing = new CloudBillingClient(); | ||
|
|
||
| const projectIdEnv = process.env.GOOGLE_CLOUD_PROJECT; | ||
|
|
||
| functions.cloudEvent('StopBillingCloudEvent', async cloudEvent => { | ||
| // TODO(developer): As stopping billing is a destructive action | ||
| // for your project, change the following constant to `false` | ||
| // after you validate with a test budget. | ||
| const simulateDeactivation = true; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is not something the Python sample does (unless there's a pending change there to match). Also, I would not use the term "simulateDeactivation". Instead I'd use something more forceful like "dry-run". That is a term more associated to actions that don't invoke the processing required. You should also remove any output later that appends "(simulated)" and make it more obvious that it's a dry-run of the function. I can imagine support requests given the seriousness of this sample, and want to make sure it's as obvious as possible what's going on.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please watch my updated sample here: stop_billing.py#L70-L73 I agree with the term About "make it more obvious that it's a dry-run of the function", do you have some reference? I've seen the dry-run for Let's Encrypt, Apache, etc, but I don't know of a case for GCP on a Client Library. I've found for example: https://cloud.google.com/resource-manager/docs/organization-policy/dry-run-policy
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I couldn't find an example in the Node repo. Based on Let's encrypt output, I'm proposing: console.log('** DRY RUN: simulating billing deactivation');
console.log('Billing disabled.');Please let me know if there's a more appropriate syntax or wording for our samples.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think you can change your test, with comment documentation, to check for the dryrun message rather than the live message. You don't want users to see the output of "billing disabled", even with a dryrun message preceeding it. I'd recommend something like: // TODO(developer): As stopping billing is a destructive action
// for your project, this code defaults to not performing the change, unless
// the following variable has been manually changed.
const dryRun = true;
...
const _disableBillingForProject = async (projectName, dryRun) => {
if (dryRun) {
console.log('** This script would disable billing here, but "dryRun" has been set to True. Change "dryRun" to alter this behaviour');
return;
} else { // ⚠️ Important to add here
// rest of code here
};Then update the test to test for the dryrun message, with a comment saying something like "We would never test that this function actually runs, as it breaks CI. So instead, test that the dryrun worked" |
||
|
|
||
| let projectId = projectIdEnv; | ||
|
|
||
| if (projectId === undefined) { | ||
| console.log('Project ID not found in Env variables. Reading metadata...'); | ||
| try { | ||
| projectId = await gcpMetadata.project('project-id'); | ||
|
glasnt marked this conversation as resolved.
|
||
| } catch (error) { | ||
| console.error('project-id metadata not found:', error); | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| const projectName = `projects/${projectId}`; | ||
|
|
||
| // Find more information about the notification format here: | ||
| // https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification-format | ||
| const eventData = Buffer.from( | ||
| cloudEvent.data['message']['data'], | ||
| 'base64' | ||
| ).toString(); | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
|
|
||
| const eventObject = JSON.parse(eventData); | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
|
|
||
| console.log( | ||
| `Project ID: ${projectId} ` + | ||
| `Current cost: ${eventObject.costAmount} ` + | ||
| `Budget: ${eventObject.budgetAmount}` | ||
|
eapl-gemugami marked this conversation as resolved.
|
||
| ); | ||
|
|
||
| if (eventObject.costAmount <= eventObject.budgetAmount) { | ||
| console.log('No action required. Current cost is within budget.'); | ||
| return; | ||
| } | ||
|
|
||
| console.log(`Disabling billing for project '${projectName}'...`); | ||
|
|
||
| const billingEnabled = await _isBillingEnabled(projectName); | ||
| if (billingEnabled) { | ||
| _disableBillingForProject(projectName, simulateDeactivation); | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
| } else { | ||
| console.log('Billing is already disabled.'); | ||
| } | ||
| }); | ||
|
|
||
| /** | ||
| * Determine whether billing is enabled for a project | ||
| * @param {string} projectName The name of the project to check | ||
| * @returns {boolean} Whether the project has billing enabled or not | ||
| */ | ||
| const _isBillingEnabled = async projectName => { | ||
| try { | ||
| console.log(`Getting billing info for project '${projectName}'...`); | ||
| const [res] = await billing.getProjectBillingInfo({name: projectName}); | ||
|
|
||
| return res.billingEnabled; | ||
| } catch (e) { | ||
| console.log('Error getting billing info:', e); | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
| console.log( | ||
| 'Unable to determine if billing is enabled on specified project, ' + | ||
| 'assuming billing is enabled' | ||
| ); | ||
|
|
||
| return true; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Disable billing for a project by removing its billing account | ||
| * @param {string} projectName The name of the project to disable billing | ||
| * @param {boolean} simulateDeactivation | ||
| * If true, it won't actually disable billing. | ||
| * Useful to validate with test budgets. | ||
| * @returns {void} | ||
| */ | ||
| const _disableBillingForProject = async (projectName, simulateDeactivation) => { | ||
| if (simulateDeactivation) { | ||
| console.log('Billing disabled. (Simulated)'); | ||
| return; | ||
| } | ||
|
|
||
| // Find more information about `projects/updateBillingInfo` API method here: | ||
| // https://cloud.google.com/billing/docs/reference/rest/v1/projects/updateBillingInfo | ||
| try { | ||
| // To disable billing set the `billingAccountName` field to empty | ||
| const requestBody = {billingAccountName: ''}; | ||
|
|
||
| const [response] = await billing.updateProjectBillingInfo({ | ||
| name: projectName, | ||
| resource: requestBody, | ||
| }); | ||
|
|
||
| console.log(`Billing disabled: ${JSON.stringify(response)}`); | ||
| } catch (e) { | ||
| console.log('Failed to disable billing, check permissions.', e); | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
| } | ||
| }; | ||
| // [END functions_billing_stop] | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| { | ||
| "name": "cloud-functions-stop-billing", | ||
| "private": "true", | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
| "version": "0.0.1", | ||
| "description": "Disable billing with a budget notification.", | ||
| "main": "index.js", | ||
| "engines": { | ||
| "node": ">=20.0.0" | ||
| }, | ||
| "scripts": { | ||
| "test": "c8 mocha -p -j 2 test/index.test.js --timeout=5000 --exit" | ||
| }, | ||
| "author": "Emmanuel Parada <paradalicea@google.com>", | ||
|
eapl-gemugami marked this conversation as resolved.
Outdated
|
||
| "license": "Apache-2.0", | ||
| "dependencies": { | ||
| "@google-cloud/billing": "^5.1.0", | ||
| "@google-cloud/functions-framework": "^4.0.0", | ||
| "cloudevents": "^10.0.0", | ||
| "gcp-metadata": "^7.0.1" | ||
| }, | ||
| "devDependencies": { | ||
| "c8": "^10.1.3" | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // 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. | ||
|
|
||
| const assert = require('assert'); | ||
| const {CloudEvent} = require('cloudevents'); | ||
| const {getFunction} = require('@google-cloud/functions-framework/testing'); | ||
|
|
||
| require('../index'); | ||
|
|
||
| const getDataWithinBudget = () => { | ||
| return { | ||
| budgetDisplayName: 'BUDGET_NAME', | ||
| costAmount: 5.0, | ||
| costIntervalStart: new Date().toISOString(), | ||
| budgetAmount: 10.0, | ||
| budgetAmountType: 'SPECIFIED_AMOUNT', | ||
| currencyCode: 'USD', | ||
| }; | ||
| }; | ||
|
|
||
| const getDataOverBudget = () => { | ||
| return { | ||
| budgetDisplayName: 'BUDGET_NAME', | ||
| alertThresholdExceeded: 0.9, | ||
| costAmount: 20.0, | ||
| costIntervalStart: new Date().toISOString(), | ||
| budgetAmount: 10.0, | ||
| budgetAmountType: 'SPECIFIED_AMOUNT', | ||
| currencyCode: 'USD', | ||
| }; | ||
| }; | ||
|
|
||
| /** | ||
| * Get a simulated CloudEvent for a Budget notification. | ||
| * Find more examples here: | ||
| * https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications | ||
| * @param {boolean} isOverBudget - Whether or not the budget has been exceeded. | ||
| * @returns {CloudEvent} The simulated CloudEvent. | ||
| */ | ||
| const getCloudEventOverBudgetAlert = isOverBudget => { | ||
| let budgetData; | ||
|
|
||
| if (isOverBudget) { | ||
| budgetData = getDataOverBudget(); | ||
| } else { | ||
| budgetData = getDataWithinBudget(); | ||
| } | ||
|
|
||
| const jsonString = JSON.stringify(budgetData); | ||
| const messageBase64 = Buffer.from(jsonString).toString('base64'); | ||
|
|
||
| const encodedData = { | ||
| message: { | ||
| data: messageBase64, | ||
| }, | ||
| }; | ||
|
|
||
| return new CloudEvent({ | ||
| specversion: '1.0', | ||
| id: 'my-id', | ||
| source: '//pubsub.googleapis.com/projects/PROJECT_NAME/topics/TOPIC_NAME', | ||
| data: encodedData, | ||
| type: 'google.cloud.pubsub.topic.v1.messagePublished', | ||
| datacontenttype: 'application/json', | ||
| time: new Date().toISOString(), | ||
| }); | ||
| }; | ||
|
|
||
| describe('Billing Stop Function', () => { | ||
| let consoleOutput = ''; | ||
| const originalConsoleLog = console.log; | ||
| const originalConsoleError = console.error; | ||
|
|
||
| beforeEach(async () => { | ||
| consoleOutput = ''; | ||
| console.log = message => (consoleOutput += message + '\n'); | ||
| console.error = message => (consoleOutput += 'ERROR: ' + message + '\n'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| console.log = originalConsoleLog; | ||
| console.error = originalConsoleError; | ||
| }); | ||
|
|
||
| it('should receive a notification within budget', async () => { | ||
| const StopBillingCloudEvent = getFunction('StopBillingCloudEvent'); | ||
| const isOverBudget = false; | ||
| await StopBillingCloudEvent(getCloudEventOverBudgetAlert(isOverBudget)); | ||
|
|
||
| assert.ok( | ||
| consoleOutput.includes( | ||
| 'No action required. Current cost is within budget.' | ||
| ) | ||
| ); | ||
| }); | ||
|
|
||
| it('should receive a notification exceeding the budget and simulate stopping billing', async () => { | ||
| const StopBillingCloudEvent = getFunction('StopBillingCloudEvent'); | ||
| const isOverBudget = true; | ||
| await StopBillingCloudEvent(getCloudEventOverBudgetAlert(isOverBudget)); | ||
|
|
||
| assert.ok(consoleOutput.includes('Getting billing info')); | ||
| assert.ok(consoleOutput.includes('Disabling billing for project')); | ||
| assert.ok(consoleOutput.includes('Billing disabled. (Simulated)')); | ||
| }); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.