-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathindex.js
More file actions
165 lines (149 loc) · 4.92 KB
/
Copy pathindex.js
File metadata and controls
165 lines (149 loc) · 4.92 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2018 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_start_instance_pubsub]
// [START functions_stop_instance_pubsub]
const functions = require('@google-cloud/functions-framework');
const {SqlInstancesServiceClient} = require('@google-cloud/sql');
const sqlInstancesClient = new SqlInstancesServiceClient({fallback: true});
// [END functions_stop_instance_pubsub]
/**
* Starts Cloud SQL instances.
*
* Expects a PubSub message with JSON-formatted event data containing
* the label of instances to start.
*
*/
functions.cloudEvent('startInstanceEvent', async cloudEvent => {
try {
const payload = _validatePayload(cloudEvent);
const project = await sqlInstancesClient.getProjectId();
const [labelKey, labelValue] = payload.label.split('=');
const filter = `settings.userLabels.${labelKey}:${labelValue}`;
console.log(
`Attempting to start instances. Project ID resolved to: '${project}'. Filter applied: '${filter}'`
);
// Fetch the response object
const [response] = await sqlInstancesClient.list({
project,
filter,
});
// Extract the array from the 'items' property (default to empty array if undefined)
const instances = response.items || [];
console.log(
`Raw instances array retrieved. Found ${instances.length} matching instances.`
);
if (instances.length === 0) {
console.log(
`No SQL instances found in project '${project}' matching filter '${filter}'.`
);
return;
}
await Promise.all(
instances.map(async instance => {
console.log(`Starting Cloud SQL instance: ${instance.name}`);
const request = {
project,
instance: instance.name,
body: {
settings: {
activationPolicy: 'ALWAYS',
},
},
};
const [operation] = await sqlInstancesClient.patch(request);
console.log(
`Patch operation started for ${instance.name}: ${operation.name}`
);
})
);
} catch (err) {
console.error(err);
throw err;
}
});
// [END functions_start_instance_pubsub]
// [START functions_stop_instance_pubsub]
/**
* Stops Cloud SQL instances.
*
* Expects a PubSub message with JSON-formatted event data containing
* the label of instances to stop.
*
*/
functions.cloudEvent('stopInstanceEvent', async cloudEvent => {
try {
const payload = _validatePayload(cloudEvent);
const project = await sqlInstancesClient.getProjectId();
const [labelKey, labelValue] = payload.label.split('=');
const filter = `settings.userLabels.${labelKey}:${labelValue}`;
console.log(
`Attempting to stop instances. Project ID resolved to: '${project}'. Filter applied: '${filter}'`
);
// Fetch the response object
const [response] = await sqlInstancesClient.list({
project,
filter,
});
// Extract the array from the 'items' property (default to empty array if undefined)
const instances = response.items || [];
console.log(
`Raw instances array retrieved. Found ${instances.length} matching instances.`
);
if (instances.length === 0) {
console.log(`
No SQL instances found in project '${project}' matching filter '${filter}'.`);
return;
}
await Promise.all(
instances.map(async instance => {
console.log(`Stopping Cloud SQL instance: ${instance.name}`);
const request = {
project,
instance: instance.name,
body: {
settings: {
activationPolicy: 'NEVER',
},
},
};
const [operation] = await sqlInstancesClient.patch(request);
console.log(
`Patch operation started for ${instance.name}: ${operation.name}`
);
})
);
} catch (err) {
console.error(err);
throw err;
}
});
// [START functions_start_instance_pubsub]
/**
* Validates that a request payload contains the expected fields.
*/
const _validatePayload = cloudEvent => {
let payload;
try {
const base64Data = cloudEvent.data.message.data;
payload = JSON.parse(Buffer.from(base64Data, 'base64').toString());
} catch (err) {
throw new Error('Invalid CloudEvent / Pub/Sub message: ' + err);
}
if (!payload.label) {
throw new Error("Attribute 'label' missing from payload");
}
return payload;
};
// [END functions_start_instance_pubsub]
// [END functions_stop_instance_pubsub]