-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
98 lines (85 loc) · 2.68 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const {
google
} = require('googleapis');
const {
GoogleAuth
} = require('google-auth-library');
const PROJECT_ID = 'macgyver-services-production';
const PROJECT_NAME = `projects/${PROJECT_ID}`;
const billing = google.cloudbilling('v1').projects;
exports.stopBilling = async pubsubEvent => {
console.log(pubsubEvent.data);
const pubsubData = JSON.parse(
Buffer.from(pubsubEvent.data, 'base64').toString()
);
console.log(pubsubData);
console.log(pubsubData.costAmount);
console.log(pubsubData.budgetAmount);
if (pubsubData.costAmount <= pubsubData.budgetAmount) {
console.log("No action necessary.");
return `No action necessary. (Current cost: ${pubsubData.costAmount})`;
}
if (!PROJECT_ID) {
console.log("no project specified");
return 'No project specified';
}
_setAuthCredential();
const billingEnabled = await _isBillingEnabled(PROJECT_NAME);
if (billingEnabled) {
console.log("disabling billing");
return _disableBillingForProject(PROJECT_NAME);
} else {
console.log("billing already disabled");
return 'Billing already disabled';
}
};
/**
* @return {Promise} Credentials set globally
*/
const _setAuthCredential = () => {
const client = new GoogleAuth({
scopes: [
'https://www.googleapis.com/auth/cloud-billing',
'https://www.googleapis.com/auth/cloud-platform',
],
});
// Set credential globally for all requests
google.options({
auth: client,
});
};
/**
* Determine whether billing is enabled for a project
* @param {string} projectName Name of project to check if billing is enabled
* @return {bool} Whether project has billing enabled or not
*/
const _isBillingEnabled = async projectName => {
try {
const res = await billing.getBillingInfo({
name: projectName
});
console.log(res);
return res.data.billingEnabled;
} catch (e) {
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 Name of project disable billing on
* @return {string} Text containing response from disabling billing
*/
const _disableBillingForProject = async projectName => {
const res = await billing.updateBillingInfo({
name: projectName,
resource: {
billingAccountName: ''
}, // Disable billing
});
console.log(res);
console.log("Billing Disabled");
return `Billing disabled: ${JSON.stringify(res.data)}`;
};