Debian Codegraph @

case_studies/micromanage/service_google.py

raw
1 # Copyright 2015 Google Inc. All rights reserved.
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 import copy
16 import json
17 import dateutil.parser
18 import re
19
20 from oauth2client.client import flow_from_clientsecrets
21 from oauth2client.client import GoogleCredentials
22 from oauth2client.service_account import ServiceAccountCredentials
23 from googleapiclient.discovery import build
24
25 import packer
26 import service
27 import validate
28
29 IMAGE_CACHE = {}
30
31 def google_get_images_json_key(project, key_json):
32 credentials = ServiceAccountCredentials.from_json_keyfile_dict(
33 key_json, scopes=['https://www.googleapis.com/auth/compute'])
34
35 compute = build('compute', 'v1', credentials=credentials)
36 images = compute.images().list(project=project).execute()
37 items = images.get('items', [])
38 return [(i['name'], dateutil.parser.parse(i['creationTimestamp'])) for i in items]
39
40
41 class GooglePackerBuildArtefact(packer.PackerBuildArtefact):
42 def __init__(self, image, environment):
43 super(GooglePackerBuildArtefact, self).__init__(image['cmds'])
44
45 self.machineType = image['machineType']
46 self.source = image['source']
47 self.zone = image['zone']
48 self.project = environment['project']
49 self.sshUser = environment['sshUser']
50 self.serviceAccount = environment['serviceAccount']
51
52 def builderHashCode(self):
53 builder_hash = 0;
54 builder_hash ^= packer.hash_string(self.machineType)
55 builder_hash ^= packer.hash_string(self.source)
56 builder_hash ^= packer.hash_string(self.zone)
57 return builder_hash
58
59 def builder(self):
60 return {
61 'name': self.name(),
62 'image_name': self.name(),
63 'instance_name': self.name(),
64
65 'type': 'googlecompute',
66 'image_description': 'Image built by micromanage',
67 'project_id': self.project,
68 'account_file': json.dumps(self.serviceAccount),
69 'machine_type': self.machineType,
70 'source_image': self.source,
71 'zone': self.zone,
72 'ssh_username': self.sshUser,
73 }
74
75 def needsBuild(self):
76 print 'Checking if image exists: %s/%s' % (self.project, self.name())
77 if self.project in IMAGE_CACHE:
78 existing_image_names = IMAGE_CACHE[self.project]
79 else:
80 existing_image_names = [img[0] for img in google_get_images_json_key(self.project, self.serviceAccount)]
81 IMAGE_CACHE[self.project] = existing_image_names
82 return self.name() not in existing_image_names
83
84 def doBuild(self, dirpath):
85 super(GooglePackerBuildArtefact, self).doBuild(dirpath)
86 if self.project not in IMAGE_CACHE:
87 IMAGE_CACHE[self.project] = []
88 IMAGE_CACHE[self.project] += [self.name()]
89
90 def postBuild(self):
91 pass
92
93
94 class GoogleService(service.Service):
95
96 def validateEnvironment(self, root, path):
97 fields = {'kind', 'project', 'region', 'sshUser', 'serviceAccount'}
98 validate.obj_only(root, path, fields)
99 validate.path_val(root, path + ['project'], 'string')
100 validate.path_val(root, path + ['region'], 'string')
101 validate.path_val(root, path + ['sshUser'], 'string')
102
103 acc = validate.path_val(root, path + ['serviceAccount'], 'object')
104 validate.path_val(root, path + ['serviceAccount', 'client_email'], 'string')
105 validate.path_val(root, path + ['serviceAccount', 'private_key'], 'string')
106 validate.path_val(root, path + ['serviceAccount', 'type'], validate.is_value('service_account'), 'service_account')
107 validate.path_val(root, path + ['serviceAccount', 'client_id'], 'string', '')
108 validate.path_val(root, path + ['serviceAccount', 'private_key_id'], 'string', '')
109 fields = {'client_email', 'private_key', 'type', 'client_id', 'private_key_id'}
110 validate.obj_only(root, path + ['serviceAccount'], fields)
111
112 def validateService(self, root, path):
113 super(GoogleService, self).validateService(root, path)
114 infra_path = path + ['infrastructure']
115 validate.path_val(root, infra_path, 'object', {})
116 inst_path = infra_path + ['google_compute_instance']
117 instances = validate.path_val(root, inst_path, 'object', {})
118 disk_path = infra_path + ['google_compute_disk']
119 disks = validate.path_val(root, disk_path, 'object', {})
120
121 # Validate image configs
122 for inst_name, inst in instances.iteritems():
123 self.validateCmds(root, inst_path + [inst_name, 'cmds'])
124 self.validateCmds(root, inst_path + [inst_name, 'bootCmds'])
125 # Assume instances have a boot disk.
126 validate.path_val(root, inst_path + [inst_name, 'boot_disk'], 'object')
127 boot_disk_path = inst_path + [inst_name, 'boot_disk']
128 boot_disk = validate.path_val(root, boot_disk_path, 'object')
129 image = boot_disk.get('initialize_params', {}).get('image')
130 if isinstance(image, dict):
131 self.validateImage(root, boot_disk_path + ['initialize_params', 'image'])
132 for disk_name, disk in disks.iteritems():
133 image = disk.get('image')
134 if isinstance(image, dict):
135 self.validateImage(root, disk_path + [disk_name, 'image'])
136
137 def validateImage(self, root, path):
138 super(GoogleService, self).validateImage(root, path)
139 validate.path_val(root, path + ['machineType'], 'string', 'n1-standard-1')
140 validate.path_val(root, path + ['source'], 'string')
141 validate.path_val(root, path + ['zone'], 'string')
142 validate.obj_only(root, path, {'cmds', 'machineType', 'source', 'zone'})
143
144 def compileProvider(self, environment_name, environment):
145 return {
146 'environment.%s.tf.json' % environment_name: {
147 'provider': {
148 'google': {
149 # 'alias': environment_name,
150 'credentials': json.dumps(environment['serviceAccount']),
151 'project': environment['project'],
152 'region' : environment['region'],
153 },
154 },
155 },
156 }
157
158 def getBuildArtefacts(self, environment, ctx, service):
159 service = copy.deepcopy(service)
160 barts = {} # Build artefacts.
161
162 instances = service['infrastructure']['google_compute_instance']
163 disks = service['infrastructure']['google_compute_disk']
164
165 # Process image configs
166 for inst_name, inst in instances.iteritems():
167 image = inst['boot_disk'].get('initialize_params', {}).get('image')
168 if isinstance(image, dict):
169 bart = GooglePackerBuildArtefact(image, environment)
170 barts[bart.name()] = bart
171 inst['boot_disk']['initialize_params']['image'] = bart.name()
172 for disk_name, disk in disks.iteritems():
173 image = disk.get('image')
174 if isinstance(image, dict):
175 bart = GooglePackerBuildArtefact(image, environment)
176 barts[bart.name()] = bart
177 disk['image'] = bart.name()
178
179 return service, barts
180
181
182 def compile(self, ctx, service_name, service, barts):
183 infra = service['infrastructure']
184
185 # Add provider attributes
186 for res_kind_name, res_kind_obj in infra.iteritems():
187 for res_name, res in res_kind_obj.iteritems():
188 # res['provider'] = 'google.%s' % service['environment']
189 pass
190
191 # Process instance commands
192 instances = infra.get('google_compute_instance', {})
193 for inst_name, inst in instances.iteritems():
194 cmds = inst['cmds']
195 boot_cmds = inst['bootCmds']
196 metadata = inst['metadata']
197 def curl_md(k):
198 md_pref = 'http://169.254.169.254/computeMetadata/v1/instance/attributes'
199 return 'curl -s -H Metadata-Flavor:Google %s/%s' % (md_pref, k)
200 if 'startup-script' in metadata:
201 # Move user startup script out of the way (but still run it at every boot).
202 metadata['micromanage-user-startup-script'] = metadata['startup-script']
203 metadata.pop('startup-script', None)
204 bootCmds += ['%s | bash' % curl_md('micromanage-user-startup-script')]
205 inst['metadata'] = metadata
206 inst['metadata_startup_script'] = self.compileStartupScript(cmds, boot_cmds)
207 inst.pop('cmds', None)
208 inst.pop('bootCmds', None)
209
210 return {
211 'service.%s.tf.json' % self.fullName(ctx + [service_name]): {
212 'resource': infra,
213 'output': {
214 k: { 'value': v }
215 for k, v in service['outputs'].iteritems()
216 }
217 }
218 }
219