OpenStack Orchestration (Heat)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
10 KiB

# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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
# 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.
import eventlet
import logging
import os
import json
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from novaclient.exceptions import NotFound
import heat
from heat.engine.resources import Resource
from heat.common import exception
logger = logging.getLogger('heat.engine.instance')
class Restarter(Resource):
properties_schema = {'InstanceId': {'Type': 'String',
'Required': True}}
def _find_resource(self, instance_id):
Return the resource with the specified instance ID, or None if it
cannot be found.
for resource in self.stack:
if resource.instance_id == instance_id:
return resource
return None
def alarm(self):
victim = self._find_resource(['InstanceId'])
if victim is None:'%s Alarm, can not find instance %s' %
return'%s Alarm, restarting resource: %s' %
class Instance(Resource):
# AWS does not require KeyName and InstanceType but we seem to
properties_schema = {'ImageId': {'Type': 'String',
'Required': True},
'InstanceType': {'Type': 'String',
'Required': True},
'KeyName': {'Type': 'String',
'Required': True},
'AvailabilityZone': {'Type': 'String',
'Default': 'nova'},
'DisableApiTermination': {'Type': 'String',
'Implemented': False},
'KernelId': {'Type': 'String',
'Implemented': False},
'Monitoring': {'Type': 'Boolean',
'Implemented': False},
'PlacementGroupName': {'Type': 'String',
'Implemented': False},
'PrivateIpAddress': {'Type': 'String',
'Implemented': False},
'RamDiskId': {'Type': 'String',
'Implemented': False},
'SecurityGroups': {'Type': 'List'},
'SecurityGroupIds': {'Type': 'List',
'Implemented': False},
'SourceDestCheck': {'Type': 'Boolean',
'Implemented': False},
'SubnetId': {'Type': 'String',
'Implemented': False},
'Tags': {'Type': 'List',
'Implemented': False},
'Tenancy': {'Type': 'String',
'AllowedValues': ['dedicated', 'default'],
'Implemented': False},
'UserData': {'Type': 'String'},
'Volumes': {'Type': 'List',
'Implemented': False}}
def __init__(self, name, json_snippet, stack):
super(Instance, self).__init__(name, json_snippet, stack)
self.ipaddress = None
self.mime_string = None
self.itype_oflavor = {'t1.micro': 'm1.tiny',
'm1.small': 'm1.small',
'm1.medium': 'm1.medium',
'm1.large': 'm1.large',
'm1.xlarge': 'm1.tiny', # TODO(sdake)
'm2.xlarge': 'm1.xlarge',
'm2.2xlarge': 'm1.large',
'm2.4xlarge': 'm1.large',
'c1.medium': 'm1.medium',
'c1.4xlarge': 'm1.large',
'cc2.8xlarge': 'm1.large',
'cg1.4xlarge': 'm1.large'}
def _set_ipaddress(self, networks):
Read the server's IP address from a list of networks provided by Nova
# Just record the first ipaddress
for n in networks:
self.ipaddress = networks[n][0]
def _ipaddress(self):
Return the server's IP address, fetching it from Nova if necessary
if self.ipaddress is None:
server = self.nova().servers.get(self.instance_id)
except NotFound as ex:
logger.warn('Instance IP address not found (%s)' % str(ex))
return self.ipaddress or ''
def FnGetAtt(self, key):
res = None
if key == 'AvailabilityZone':
res =['AvailabilityZone']
elif key == 'PublicIp':
res = self._ipaddress()
elif key == 'PrivateDnsName':
res = self._ipaddress()
raise exception.InvalidTemplateAttribute(,
# TODO(asalkeld) PrivateDnsName, PublicDnsName & PrivateIp'%s.GetAtt(%s) == %s' % (, key, res))
return unicode(res)
def _build_userdata(self, userdata):
if not self.mime_string:
# Build mime multipart data blob for cloudinit userdata
def make_subpart(content, filename, subtype=None):
if subtype is None:
subtype = os.path.splitext(filename)[0]
msg = MIMEText(content, _subtype=subtype)
msg.add_header('Content-Disposition', 'attachment',
return msg
def read_cloudinit_file(fn):
with open(os.path.join(heat.__path__[0], 'cloudinit', fn),
'r') as fp:
attachments = [(read_cloudinit_file('config'), 'cloud-config'),
(userdata, 'startup', 'x-shellscript')]
if 'Metadata' in self.t:
metadata = self.parsed_template()['Metadata']
'cfn-init-data', 'x-cfninitdata'))
if self.stack.metadata_server:
'cfn-metadata-server', 'x-cfninitdata'))
subparts = [make_subpart(*args) for args in attachments]
mime_blob = MIMEMultipart(_subparts=subparts)
self.mime_string = mime_blob.as_string()
return self.mime_string
def handle_create(self):
security_groups ='SecurityGroups')
userdata =['UserData']
flavor = self.itype_oflavor[['InstanceType']]
key_name =['KeyName']
keypairs = [ for k in self.nova().keypairs.list()]
if key_name not in keypairs:
raise exception.UserKeyPairMissing(key_name=key_name)
image_name =['ImageId']
image_id = None
image_list = self.nova().images.list()
for o in image_list:
if == image_name:
image_id =
if image_id is None:"Image %s was not found in glance" % image_name)
raise exception.ImageNotFound(image_name=image_name)
flavor_list = self.nova().flavors.list()
for o in flavor_list:
if == flavor:
flavor_id =
server_userdata = self._build_userdata(userdata)
server = self.nova().servers.create(, image=image_id,
while server.status == 'BUILD':
if server.status == 'ACTIVE':
raise exception.Error('%s instance[%s] status[%s]' %
('nova reported unexpected',, server.status))
def validate(self):
Validate any of the provided params
res = Resource.validate(self)
if res:
return res
#check validity of key
if self.stack.parms['KeyName']:
keypairs = self.nova().keypairs.list()
valid_key = False
for k in keypairs:
if == self.stack.parms['KeyName']:
valid_key = True
if not valid_key:
return {'Error':
'Provided KeyName is not registered with nova'}
return None
def handle_delete(self):
server = self.nova().servers.get(self.instance_id)
except NotFound:
self.instance_id = None