forked from googlearchive/compute-getting-started-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgce.py
More file actions
448 lines (353 loc) · 13.1 KB
/
gce.py
File metadata and controls
448 lines (353 loc) · 13.1 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# Copyright 2012 Google Inc. All Rights Reserved.
#
# 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.
"""Google Compute Engine helper class.
Use this class to:
- Start an instance
- List instances
- Delete an instance
"""
import logging
try:
import simplejson as json
except:
import json
import time
import traceback
from apiclient.discovery import build
from apiclient.errors import HttpError
from httplib2 import HttpLib2Error
from oauth2client.client import AccessTokenRefreshError
SETTINGS_FILE = 'settings.json'
DISK_TYPE = 'PERSISTENT'
class Gce(object):
"""Demonstrates some of the image and instance API functionality.
Attributes:
settings: A dictionary of application settings from the settings.json file.
service: An apiclient.discovery.Resource object for Compute Engine.
project_id: The string Compute Engine project ID.
project_url: The string URL of the Compute Engine project.
"""
def __init__(self, auth_http, project_id=None):
"""Initialize the Gce object.
Args:
auth_http: an authorized instance of httplib2.Http.
project_id: the API console project name.
"""
self.settings = json.loads(open(SETTINGS_FILE, 'r').read())
self.service = build(
'compute', self.settings['compute']['api_version'], http=auth_http)
self.gce_url = 'https://www.googleapis.com/compute/%s/projects' % (
self.settings['compute']['api_version'])
self.project_id = None
if not project_id:
self.project_id = self.settings['project']
else:
self.project_id = project_id
self.project_url = '%s/%s' % (self.gce_url, self.project_id)
def start_instance(self,
instance_name,
disk_name,
zone=None,
machine_type=None,
network=None,
service_email=None,
scopes=None,
metadata=None,
startup_script=None,
startup_script_url=None,
blocking=True):
"""Start an instance with the given name and settings.
Args:
instance_name: String name for instance.
disk_name: The string disk name.
zone: The string zone name.
machine_type: The string machine type.
network: The string network.
service_email: The string service email.
scopes: List of string scopes.
metadata: List of metadata dictionaries.
startup_script: The filename of a startup script.
startup_script_url: Url of a startup script.
blocking: Whether the function will wait for the operation to complete.
Returns:
Dictionary response representing the operation.
Raises:
ApiOperationError: Operation contains an error message.
DiskDoesNotExistError: Disk to be used for instance boot does not exist.
ValueError: Either instance_name is None an empty string or disk_name
is None or an empty string.
"""
if not instance_name:
raise ValueError('instance_name required.')
if not disk_name:
raise ValueError('disk_name required.')
# Instance dictionary is sent in the body of the API request.
instance = {}
# Set required instance fields with defaults if not provided.
instance['name'] = instance_name
if not zone:
zone = self.settings['compute']['zone']
if not machine_type:
machine_type = self.settings['compute']['machine_type']
instance['machineType'] = '%s/zones/%s/machineTypes/%s' % (
self.project_url, zone, machine_type)
if not network:
network = self.settings['compute']['network']
instance['networkInterfaces'] = [{
'accessConfigs': [{'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}],
'network': '%s/global/networks/%s' % (self.project_url, network)}]
# Make sure the disk exists, and apply disk to instance resource.
disk_exists = self.get_disk(disk_name)
if not disk_exists:
raise DiskDoesNotExistError(disk_name + ' disk must exist.')
instance['disks'] = [{
'source': '%s/zones/%s/disks/%s' % (self.project_url, zone, disk_name),
'boot': True,
'type': DISK_TYPE
}]
# Set optional fields with provided values.
if service_email and scopes:
instance['serviceAccounts'] = [{'email': service_email, 'scopes': scopes}]
# Set the instance metadata if provided.
instance['metadata'] = {}
instance['metadata']['items'] = []
if metadata:
instance['metadata']['items'].extend(metadata)
# Set the instance startup script if provided.
if startup_script:
startup_script_resource = {
'key': 'startup-script', 'value': open(startup_script, 'r').read()}
instance['metadata']['items'].append(startup_script_resource)
# Set the instance startup script URL if provided.
if startup_script_url:
startup_script_url_resource = {
'key': 'startup-script-url', 'value': startup_script_url}
instance['metadata']['items'].append(startup_script_url_resource)
# Send the request.
request = self.service.instances().insert(
project=self.project_id, zone=zone, body=instance)
response = self._execute_request(request)
if response and blocking:
response = self._blocking_call(response)
if response and 'error' in response:
raise ApiOperationError(response['error']['errors'])
return response
def list_instances(self, zone=None, list_filter=None):
"""Lists project instances.
Args:
zone: The string zone name.
list_filter: String filter for list query.
Returns:
List of instances matching given filter.
"""
if not zone:
zone = self.settings['compute']['zone']
request = None
if list_filter:
request = self.service.instances().list(
project=self.project_id, zone=zone, filter=list_filter)
else:
request = self.service.instances().list(
project=self.project_id, zone=zone)
response = self._execute_request(request)
if response and 'items' in response:
return response['items']
return []
def stop_instance(self,
instance_name,
zone=None,
blocking=True):
"""Stops an instance.
Args:
instance_name: String name for the instance.
zone: The string zone name.
blocking: Whether the function will wait for the operation to complete.
Returns:
Dictionary response representing the operation.
Raises:
ApiOperationError: Operation contains an error message.
ValueError: instance_name is None or an empty string.
"""
if not instance_name:
raise ValueError('instance_name required.')
if not zone:
zone = self.settings['compute']['zone']
# Delete the instance.
request = self.service.instances().delete(
project=self.project_id, zone=zone, instance=instance_name)
response = self._execute_request(request)
if response and blocking:
response = self._blocking_call(response)
if response and 'error' in response:
raise ApiOperationError(response['error']['errors'])
return response
def create_disk(self,
disk_name,
image_project=None,
image=None,
zone=None,
blocking=True):
"""Creates a new persistent disk.
Args:
disk_name: String name for the disk.
image_project: The string name for the project of the image.
image: String name of the image to apply to the disk.
zone: The string zone name.
blocking: Whether the function will wait for the operation to complete.
Returns:
Dictionary response representing the operation.
Raises:
ApiOperationError: Operation contains an error message.
ValueError: disk_name is None or an empty string.
"""
if not disk_name:
raise ValueError('disk_name required.')
# Disk dictionary is sent in the body of the API request.
disk = {}
# Set required disk fields with defaults if not provided.
disk['name'] = disk_name
if not zone:
zone = self.settings['compute']['zone']
if not image_project:
image_project = self.settings['compute']['image_project']
if not image:
image = self.settings['compute']['image']
source_image = '%s/%s/global/images/%s' % (
self.gce_url, image_project, image)
request = self.service.disks().insert(
project=self.project_id,
zone=zone,
sourceImage=source_image,
body=disk)
response = self._execute_request(request)
if response and blocking:
response = self._blocking_call(response)
if response and 'error' in response:
raise ApiOperationError(response['error']['errors'])
return response
def get_disk(self, disk_name, zone=None):
"""Gets the specified disk by name.
Args:
disk_name: The string name of the disk.
zone: The string name of the zone.
Returns:
Dictionary response representing the disk or None if the disk
does not exist.
"""
if not zone:
zone = self.settings['compute']['zone']
request = self.service.disks().get(
project=self.project_id, zone=zone, disk=disk_name)
try:
response = self._execute_request(request)
return response
except ApiError, e:
return
def delete_disk(self, disk_name, zone=None, blocking=True):
"""Deletes a disk.
Args:
disk_name: String name for the disk.
zone: The string zone name.
blocking: Whether the function will wait for the operation to complete.
Returns:
Dictionary response representing the operation.
Raises:
ApiOperationError: Operation contains an error message.
ValueError: disk_name is None or an empty string.
"""
if not disk_name:
raise ValueError('disk_name required.')
if not zone:
zone = self.settings['compute']['zone']
# Delete the disk.
request = self.service.disks().delete(
project=self.project_id, zone=zone, disk=disk_name)
response = self._execute_request(request)
if response and blocking:
response = self._blocking_call(response)
if response and 'error' in response:
raise ApiOperationError(response['error']['errors'])
return response
def _blocking_call(self, response):
"""Blocks until the operation status is done for the given operation.
Args:
response: The response from the API call.
Returns:
Dictionary response representing the operation.
"""
status = response['status']
while status != 'DONE' and response:
operation_id = response['name']
if 'zone' in response:
zone = response['zone'].rsplit('/', 1)[-1]
request = self.service.zoneOperations().get(
project=self.project_id, zone=zone, operation=operation_id)
else:
request = self.service.globalOperations().get(
project=self.project_id, operation=operation_id)
response = self._execute_request(request)
if response:
status = response['status']
logging.info(
'Waiting until operation is DONE. Current status: %s', status)
if status != 'DONE':
time.sleep(3)
return response
def _execute_request(self, request):
"""Helper method to execute API requests.
Args:
request: The API request to execute.
Returns:
Dictionary response representing the operation if successful.
Raises:
ApiError: Error occurred during API call.
"""
try:
response = request.execute()
except AccessTokenRefreshError, e:
logging.error('Access token is invalid.')
raise ApiError(e)
except HttpError, e:
logging.error('Http response was not 2xx.')
raise ApiError(e)
except HttpLib2Error, e:
logging.error('Transport error.')
raise ApiError(e)
except Exception, e:
logging.error('Unexpected error occured.')
traceback.print_stack()
raise ApiError(e)
return response
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class ApiError(Error):
"""Error occurred during API call."""
pass
class ApiOperationError(Error):
"""Raised when an API operation contains an error."""
def __init__(self, error_list):
"""Initialize the Error.
Args:
error_list: the list of errors from the operation.
"""
super(ApiOperationError, self).__init__()
self.error_list = error_list
def __str__(self):
"""String representation of the error."""
return repr(self.error_list)
class DiskDoesNotExistError(Error):
"""Disk to be used for instance boot does not exist."""
pass