def notify(_context, message): """Notifies the recipient of the desired event given the model. Log notifications using openstack's default logging system""" priority = message.get("priority", CONF.default_notification_level) priority = priority.lower() logger = logging.getLogger("heat.openstack.common.notification.%s" % message["event_type"]) getattr(logger, priority)(jsonutils.dumps(message))
def load_paste_app(app_name=None): """ Builds and returns a WSGI app from a paste config file. We assume the last config file specified in the supplied ConfigOpts object is the paste config file. :param app_name: name of the application to load :raises RuntimeError when config file cannot be located or application cannot be loaded from config file """ if app_name is None: app_name = cfg.CONF.prog # append the deployment flavor to the application name, # in order to identify the appropriate paste pipeline app_name += _get_deployment_flavor() conf_file = _get_deployment_config_file() if conf_file is None: raise RuntimeError(_("Unable to locate config file")) try: app = wsgi.paste_deploy_app(conf_file, app_name, cfg.CONF) # Log the options used when starting if we're in debug mode... if cfg.CONF.debug: cfg.CONF.log_opt_values(logging.getLogger(app_name), sys_logging.DEBUG) return app except (LookupError, ImportError) as e: raise RuntimeError(_("Unable to load %(app_name)s from " "configuration file %(conf_file)s." "\nGot: %(e)r") % {'app_name': app_name, 'conf_file': conf_file, 'e': e})
# 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. from heat.openstack.common import log as logging from heat.engine.resources.quantum import quantum logger = logging.getLogger('heat.engine.quantum') class FloatingIP(quantum.QuantumResource): properties_schema = {'floating_network_id': {'Type': 'String', 'Required': True}, 'value_specs': {'Type': 'Map', 'Default': {}}, 'port_id': {'Type': 'String'}, 'fixed_ip_address': {'Type': 'String'}, } def handle_create(self): props = self.prepare_properties(self.properties, self.name) fip = self.quantum().create_floatingip({ 'floatingip': props})['floatingip']
# under the License. import binascii import os from urlparse import urlparse from heat.common import exception from heat.engine.resources import resource from heat.openstack.common import log as logging try: from swiftclient.client import ClientException swiftclient_present = True except ImportError: swiftclient_present = False logger = logging.getLogger('heat.engine.s3') class S3Bucket(resource.Resource): website_schema = { 'IndexDocument': { 'Type': 'String' }, 'ErrorDocument': { 'Type': 'String' } } properties_schema = { 'AccessControl': { 'Type': 'String',
# -*- coding:utf-8 -*- import sys sys.path.append("..") import os from heat.openstack.common import log as logging import json import vcloud_proxy_data_handler from pyvcloud import vcloudair LOG=logging.getLogger(__name__) _vcloud_proxy_install_conf = os.path.join("/home/hybrid_cloud/conf", "vcloud_proxy_install.conf") _vcloud_vdc_info = os.path.join("/home/hybrid_cloud/conf", "vcloud_vdc.conf") LOG = logging.getLogger(__name__) def _read_install_conf(): if not os.path.exists(_vcloud_proxy_install_conf): LOG.error("read %s : No such file." % _vcloud_proxy_install_conf) return None with open(_vcloud_proxy_install_conf, 'r+') as fd: tmp = fd.read() return json.loads(tmp)
try: from swiftclient import client as swiftclient swiftclient_present = True except ImportError: swiftclient_present = False from heat.common import exception from heat.common import config from heat.db import api as db_api from heat.engine import checkeddict from heat.engine import auth from heat.openstack.common import log as logging from heat.openstack.common import cfg logger = logging.getLogger('heat.engine.resources') class Metadata(object): ''' A descriptor for accessing the metadata of a resource while ensuring the most up-to-date data is always obtained from the database. ''' def __get__(self, resource, resource_class): '''Return the metadata for the owning resource.''' if resource is None: return None if resource.id is None: return resource.parsed_template('Metadata') rs = db_api.resource_get(resource.stack.context, resource.id)
import eventlet 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 import resources from heat.common import exception from heat.openstack.common import log as logging logger = logging.getLogger("heat.engine.instance") class Restarter(resources.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
# License for the specific language governing permissions and limitations # under the License. """ A filter middleware that inspects the requested URI for a version string and/or Accept headers and attempts to negotiate an API controller to return """ import re from heat.openstack.common import log as logging from heat.common import wsgi logger = logging.getLogger('heat.api.middleware.version_negotiation') class VersionNegotiationFilter(wsgi.Middleware): def __init__(self, version_controller, app, conf, **local_conf): self.versions_app = version_controller(conf) self.version_uri_regex = re.compile(r"^v(\d+)\.?(\d+)?") self.conf = conf super(VersionNegotiationFilter, self).__init__(app) def process_request(self, req): """ If there is a version identifier in the URI, simply return the correct API controller, otherwise, if we find an Accept: header, process it
# # 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 json from heat.common import exception from heat.engine.resources import stack from novaclient.exceptions import NotFound from heat.openstack.common import log as logging logger = logging.getLogger(__file__) lb_template = """ { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Built in HAProxy server", "Parameters" : { "KeyName" : { "Type" : "String" } }, "Resources": { "latency_watcher": { "Type": "AWS::CloudWatch::Alarm", "Properties": { "MetricName": "Latency",
# under the License. import urllib import urlparse from oslo.config import cfg from keystoneclient.contrib.ec2 import utils as ec2_utils from heat.common import exception from heat.engine import clients from heat.engine import resource from heat.openstack.common import log LOG = log.getLogger(__name__) SIGNAL_TYPES = ( WAITCONDITION, SIGNAL ) = ( '/waitcondition', '/signal' ) SIGNAL_VERB = {WAITCONDITION: 'PUT', SIGNAL: 'POST'} class SignalResponder(resource.Resource): def handle_create(self): # Create a keystone user so we can create a signed URL via FnGetRefId user_id = self.keystone().create_stack_user( self.physical_resource_name())
# # 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. from heat.common import exception from heat.engine.resources import Resource from novaclient.exceptions import NotFound from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.eip') class ElasticIp(Resource): properties_schema = {'Domain': {'Type': 'String', 'Implemented': False}, 'InstanceId': {'Type': 'String'}} def __init__(self, name, json_snippet, stack): super(ElasticIp, self).__init__(name, json_snippet, stack) self.ipaddress = None def _ipaddress(self): if self.ipaddress is None: if self.instance_id is not None: try:
# # 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 json from heat.common import exception from heat.engine import resources from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.wait_condition') class WaitConditionHandle(resources.Resource): ''' the main point of this class is to : have no dependancies (so the instance can reference it) generate a unique url (to be returned in the refernce) then the cfn-signal will use this url to post to and WaitCondition will poll it to see if has been written to. ''' properties_schema = {} def __init__(self, name, json_snippet, stack): super(WaitConditionHandle, self).__init__(name, json_snippet, stack)
import webob from heat.api.aws import exception from heat.api.aws import utils as api_utils from heat.common import wsgi from heat.common import config from heat.common import context from heat import utils from heat.engine import rpcapi as engine_rpcapi import heat.engine.api as engine_api from heat.engine import identifier from heat.openstack.common import rpc import heat.openstack.common.rpc.common as rpc_common from heat.openstack.common import log as logging logger = logging.getLogger('heat.api.cfn.v1.stacks') class StackController(object): """ WSGI controller for stacks resource in Heat CloudFormation v1 API Implements the API actions """ def __init__(self, options): self.options = options self.engine_rpcapi = engine_rpcapi.EngineAPI() def _stackid_format(self, resp): """ Add a host:port:stack prefix, this formats the StackId in the response more like the AWS spec
# 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 from heat.common import exception from heat.engine.resources import resource from heat.openstack.common import log as logging from heat.openstack.common import cfg logger = logging.getLogger('heat.engine.wait_condition') class WaitConditionHandle(resource.Resource): ''' the main point of this class is to : have no dependancies (so the instance can reference it) generate a unique url (to be returned in the refernce) then the cfn-signal will use this url to post to and WaitCondition will poll it to see if has been written to. ''' properties_schema = {} def __init__(self, name, json_snippet, stack): super(WaitConditionHandle, self).__init__(name, json_snippet, stack)
from heat.engine import api from heat.engine import identifier from heat.engine import parser from heat.engine import watchrule from heat.engine import auth from heat.openstack.common import cfg from heat.openstack.common import timeutils from heat.openstack.common import log as logging from novaclient.v1_1 import client from novaclient.exceptions import BadRequest from novaclient.exceptions import NotFound from novaclient.exceptions import AuthorizationFailure logger = logging.getLogger('heat.engine.manager') greenpool = eventlet.GreenPool() class EngineManager(manager.Manager): """ Manages the running instances from creation to destruction. All the methods in here are called from the RPC backend. This is all done dynamically so if a call is made via RPC that does not have a corresponding method here, an exception will be thrown when it attempts to call into this class. Arguments to these methods are also dynamically added and will be named as keyword arguments by the RPC caller. """ def __init__(self, *args, **kwargs): """Load configuration options and connect to the hypervisor."""
from Crypto.Cipher import AES from Crypto import Random from heat.openstack.common import cfg from heat.openstack.common import importutils auth_opts = [ cfg.StrOpt('auth_encryption_key', default='notgood', help="Encryption key used for authentication info in database") ] cfg.CONF.register_opts(auth_opts) logger = logging.getLogger('heat.engine.auth') def encrypt(auth_info): if auth_info is None: return None iv = Random.new().read(AES.block_size) cipher = AES.new(cfg.CONF.auth_encryption_key[:32], AES.MODE_CFB, iv) res = base64.b64encode(iv + cipher.encrypt(auth_info)) return res def decrypt(auth_info): if auth_info is None: return None auth = base64.b64decode(auth_info)
# # 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. import collections import re from copy import deepcopy from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.checkeddict') class CheckedDict(collections.MutableMapping): def __init__(self, name): self.data = {} self.name = name def addschema(self, key, schema): self.data[key] = deepcopy(schema) def get_attr(self, key, attr): return self.data[key].get(attr, '') def __setitem__(self, key, value): '''Since this function gets called whenever we modify the
# 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. from novaclient.exceptions import BadRequest from novaclient.exceptions import NotFound from heat.common import exception from heat.engine.resources import resource from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.security_group') class SecurityGroup(resource.Resource): properties_schema = {'GroupDescription': {'Type': 'String', 'Required': True}, 'VpcId': {'Type': 'String', 'Implemented': False}, 'SecurityGroupIngress': {'Type': 'List'}, 'SecurityGroupEgress': {'Type': 'List', 'Implemented': False}} def __init__(self, name, json_snippet, stack): super(SecurityGroup, self).__init__(name, json_snippet, stack) def handle_create(self):
import eventlet import json import functools import copy from heat.common import exception from heat.engine import checkeddict from heat.engine import dependencies from heat.engine import identifier from heat.engine import resources from heat.db import api as db_api from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.parser') SECTIONS = (VERSION, DESCRIPTION, MAPPINGS, PARAMETERS, RESOURCES, OUTPUTS) = \ ('AWSTemplateFormatVersion', 'Description', 'Mappings', 'Parameters', 'Resources', 'Outputs') (PARAM_STACK_NAME, PARAM_REGION) = ('AWS::StackName', 'AWS::Region') class Parameters(checkeddict.CheckedDict): ''' The parameters of a stack, with type checking, defaults &c. specified by the stack's template. ''' def __init__(self, stack_name, template, user_params={}):
# 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 json import os from heat.common import exception from heat.db import api as db_api from heat.engine import instance from heat.engine.resources import Resource from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.autoscaling') class AutoScalingGroup(Resource): tags_schema = {'Key': {'Type': 'String', 'Required': True}, 'Value': {'Type': 'String', 'Required': True}} properties_schema = { 'AvailabilityZones': {'Required': True, 'Type': 'List'}, 'LaunchConfigurationName': {'Required': True, 'Type': 'String'}, 'MaxSize': {'Required': True, 'Type': 'String'}, 'MinSize': {'Required': True,
# 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 urllib2 import json from heat.common import exception from heat.engine.resources import stack from heat.db import api as db_api from heat.engine import parser from novaclient.exceptions import NotFound from heat.openstack.common import log as logging logger = logging.getLogger(__file__) lb_template = ''' { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Built in HAProxy server", "Parameters" : { "KeyName" : { "Type" : "String" } }, "Resources": { "latency_watcher": { "Type": "AWS::CloudWatch::Alarm", "Properties": { "MetricName": "Latency",
# 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 datetime from heat.openstack.common import log as logging from heat.openstack.common import timeutils from heat.engine import timestamp from heat.db import api as db_api from heat.engine import parser from heat.common import context as ctxtlib import eventlet logger = logging.getLogger('heat.engine.watchrule') greenpool = eventlet.GreenPool() class WatchRule(object): WATCH_STATES = (ALARM, NORMAL, NODATA) = ('ALARM', 'NORMAL', 'NODATA') ACTION_MAP = { ALARM: 'AlarmActions', NORMAL: 'OKActions', NODATA: 'InsufficientDataActions' } created_at = timestamp.Timestamp(db_api.watch_rule_get, 'created_at') updated_at = timestamp.Timestamp(db_api.watch_rule_get, 'updated_at')
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ A filter middleware that inspects the requested URI for a version string and/or Accept headers and attempts to negotiate an API controller to return """ import re from heat.openstack.common import log as logging from heat.common import wsgi logger = logging.getLogger('heat.api.middleware.version_negotiation') class VersionNegotiationFilter(wsgi.Middleware): def __init__(self, version_controller, app, conf, **local_conf): self.versions_app = version_controller(conf) self.version_uri_regex = re.compile(r"^v(\d+)\.?(\d+)?") self.conf = conf super(VersionNegotiationFilter, self).__init__(app) def process_request(self, req): """ If there is a version identifier in the URI, simply return the correct API controller, otherwise, if we find an Accept: header, process it """
from functools import wraps from heat.common import wsgi from heat.common import config from heat.common import context from heat.common import exception from heat import utils from heat.engine import api as engine_api from heat.engine import identifier from heat.engine import rpcapi as engine_rpcapi from heat.openstack.common import rpc import heat.openstack.common.rpc.common as rpc_common from heat.openstack.common import log as logging logger = logging.getLogger('heat.api.openstack.v1.stacks') CREATE_PARAMS = ( PARAM_STACK_NAME, PARAM_TEMPLATE, PARAM_TEMPLATE_URL, PARAM_USER_PARAMS, ) = ( 'stack_name', 'template', 'template_url', 'parameters', ) def json_parse(self, data, data_type):
# # 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. from keystoneclient.v2_0 import client as kc from oslo.config import cfg from heat.common import exception from heat.openstack.common.gettextutils import _ from heat.openstack.common import importutils from heat.openstack.common import log as logging logger = logging.getLogger('heat.common.keystoneclient') logger.info(_("Keystone V2 loaded")) class KeystoneClientV2(object): """ Wrap keystone client so we can encapsulate logic used in resources Note this is intended to be initialized from a resource on a per-session basis, so the session context is passed in on initialization Also note that a copy of this is created every resource as self.keystone() via the code in engine/client.py, so there should not be any need to directly instantiate instances of this class inside resources themselves """ def __init__(self, context): # If a trust_id is specified in the context, we immediately # authenticate so we can populate the context with a trust token
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Session Handling for SQLAlchemy backend.""" import sqlalchemy.interfaces import sqlalchemy.orm from sqlalchemy.exc import DisconnectionError from heat.openstack.common import log as logging from heat.db import api as db_api from heat.openstack.common import cfg logger = logging.getLogger('heat.db.sqlalchemy.session') _ENGINE = None _MAKER = None def get_session(autocommit=True, expire_on_commit=False): """Return a SQLAlchemy session.""" global _ENGINE, _MAKER if _MAKER is None or _ENGINE is None: _ENGINE = get_engine() _MAKER = get_maker(_ENGINE, autocommit, expire_on_commit) return _MAKER() class SynchronousSwitchListener(sqlalchemy.interfaces.PoolListener):
# 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. from heat.openstack.common import log as logging from heat.engine.resources.quantum import quantum logger = logging.getLogger('heat.engine.quantum') class Net(quantum.QuantumResource): properties_schema = { 'name': { 'Type': 'String' }, 'value_specs': { 'Type': 'Map', 'Default': {} }, 'admin_state_up': { 'Default': True, 'Type': 'Boolean' },
from heat.engine import identifier from heat.engine import parser from heat.engine import resources from heat.engine import watchrule from heat.engine import auth from heat.openstack.common import cfg from heat.openstack.common import timeutils from heat.openstack.common import log as logging from novaclient.v1_1 import client from novaclient.exceptions import BadRequest from novaclient.exceptions import NotFound from novaclient.exceptions import AuthorizationFailure logger = logging.getLogger('heat.engine.manager') greenpool = eventlet.GreenPool() class EngineManager(manager.Manager): """ Manages the running instances from creation to destruction. All the methods in here are called from the RPC backend. This is all done dynamically so if a call is made via RPC that does not have a corresponding method here, an exception will be thrown when it attempts to call into this class. Arguments to these methods are also dynamically added and will be named as keyword arguments by the RPC caller. """ def __init__(self, *args, **kwargs):
import webob from heat.api.aws import exception from heat.api.aws import utils as api_utils from heat.common import wsgi from heat.common import config from heat.common import context from heat import utils from heat.engine import rpcapi as engine_rpcapi import heat.engine.api as engine_api from heat.engine import identifier from heat.openstack.common import rpc import heat.openstack.common.rpc.common as rpc_common from heat.openstack.common import log as logging logger = logging.getLogger('heat.api.cfn.v1.stacks') class StackController(object): """ WSGI controller for stacks resource in Heat CloudFormation v1 API Implements the API actions """ def __init__(self, options): self.options = options self.engine_rpcapi = engine_rpcapi.EngineAPI() def _stackid_format(self, resp): """
# under the License. import binascii import os from urlparse import urlparse from heat.common import exception from heat.engine.resources import resource from heat.openstack.common import log as logging try: from swiftclient.client import ClientException swiftclient_present = True except ImportError: swiftclient_present = False logger = logging.getLogger('heat.engine.s3') class S3Bucket(resource.Resource): website_schema = {'IndexDocument': {'Type': 'String'}, 'ErrorDocument': {'Type': 'String'}} properties_schema = {'AccessControl': { 'Type': 'String', 'AllowedValues': ['Private', 'PublicRead', 'PublicReadWrite', 'AuthenticatedRead', 'BucketOwnerRead', 'BucketOwnerFullControl']}, 'DeletionPolicy': { 'Type': 'String',
from heat.openstack.common import log as logging from heat.openstack.common.rpc import matchmaker as mm matchmaker_opts = [ # Matchmaker ring file cfg.StrOpt('ringfile', deprecated_name='matchmaker_ringfile', deprecated_group='DEFAULT', default='/etc/oslo/matchmaker_ring.json', help='Matchmaker ring file (JSON)'), ] CONF = cfg.CONF CONF.register_opts(matchmaker_opts, 'matchmaker_ring') LOG = logging.getLogger(__name__) class RingExchange(mm.Exchange): """Match Maker where hosts are loaded from a static JSON formatted file. __init__ takes optional ring dictionary argument, otherwise loads the ringfile from CONF.mathcmaker_ringfile. """ def __init__(self, ring=None): super(RingExchange, self).__init__() if ring: self.ring = ring else: fh = open(CONF.matchmaker_ring.ringfile, 'r')
# 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. import eventlet from heat.common import exception from heat.openstack.common import cfg from heat.engine.resources import resource from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.user') # # We are ignoring Policies and Groups as keystone does not support them. # # For now support users and accesskeys. # class DummyId: def __init__(self, id): self.id = id def __eq__(self, other): return self.id == other.id
# 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. from heat.common import exception from heat.engine import watchrule from heat.engine.resources import resource from heat.db import api as db_api from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.cloud_watch') class CloudWatchAlarm(resource.Resource): properties_schema = {'ComparisonOperator': {'Type': 'String', 'AllowedValues': ['GreaterThanOrEqualToThreshold', 'GreaterThanThreshold', 'LessThanThreshold', 'LessThanOrEqualToThreshold']}, 'AlarmDescription': {'Type': 'String'}, 'EvaluationPeriods': {'Type': 'String'}, 'MetricName': {'Type': 'String'}, 'Namespace': {'Type': 'String'}, 'Period': {'Type': 'String'}, 'Statistic': {'Type': 'String', 'AllowedValues': ['SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum']},
# 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. from heat.db import api as db_api from heat.common import exception from heat.engine import identifier from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.resources.event') class Event(object): '''Class representing a Resource state change.''' def __init__(self, context, stack, resource, new_state, reason, physical_resource_id, resource_properties, timestamp=None, id=None): ''' Initialise from a context, stack, resource, event information and current resource data. The timestamp and database ID may also be initialised if the event is already in the database. ''' self.context = context
# 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 datetime from heat.openstack.common import log as logging from heat.openstack.common import timeutils from heat.engine import resources from heat.db import api as db_api from heat.engine import parser from heat.common import context as ctxtlib import eventlet logger = logging.getLogger('heat.engine.watchrule') greenpool = eventlet.GreenPool() class WatchRule(object): WATCH_STATES = (ALARM, NORMAL, NODATA ) = ('ALARM', 'NORMAL', 'NODATA') ACTION_MAP = {ALARM: 'AlarmActions', NORMAL: 'OKActions', NODATA: 'InsufficientDataActions'} created_at = resources.Timestamp(db_api.watch_rule_get, 'created_at') updated_at = resources.Timestamp(db_api.watch_rule_get, 'updated_at') def __init__(self, context, watch_name, rule, stack_name, state=NORMAL,
# under the License. from heat.common import context from heat.common import exception import eventlet from keystoneclient.v2_0 import client as kc from keystoneclient.v3 import client as kc_v3 from oslo.config import cfg from heat.openstack.common import importutils from heat.openstack.common import log as logging from heat.openstack.common.gettextutils import _ logger = logging.getLogger('heat.common.keystoneclient') class KeystoneClient(object): """ Wrap keystone client so we can encapsulate logic used in resources Note this is intended to be initialized from a resource on a per-session basis, so the session context is passed in on initialization Also note that a copy of this is created every resource as self.keystone() via the code in engine/client.py, so there should not be any need to directly instantiate instances of this class inside resources themselves """ def __init__(self, context): # We have to maintain two clients authenticated with keystone: # - ec2 interface is v2.0 only # - trusts is v3 only
swiftclient_present = True except ImportError: swiftclient_present = False # quantumclient not available in all distributions - make quantum an optional # feature try: from quantumclient.v2_0 import client as quantumclient quantumclient_present = True except ImportError: quantumclient_present = False from heat.openstack.common import log as logging logger = logging.getLogger("heat.engine.clients") class Clients(object): """ Convenience class to create and cache client instances. """ def __init__(self, context): self.context = context self._nova = {} self._keystone = None self._swift = None self._quantum = None def keystone(self):
# 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. from heat.openstack.common import log as logging from heat.engine.resources.quantum import quantum logger = logging.getLogger("heat.engine.quantum") class Net(quantum.QuantumResource): properties_schema = { "name": {"Type": "String"}, "value_specs": {"Type": "Map", "Default": {}}, "admin_state_up": {"Default": True, "Type": "Boolean"}, } def __init__(self, name, json_snippet, stack): super(Net, self).__init__(name, json_snippet, stack) def handle_create(self): props = self.prepare_properties(self.properties, self.name) net = self.quantum().create_network({"network": props})["network"]
# License for the specific language governing permissions and limitations # under the License. """ endpoint for heat AWS-compatible CloudWatch API """ from heat.api.aws import exception from heat.api.aws import utils as api_utils from heat.common import wsgi from heat.engine import rpcapi as engine_rpcapi import heat.engine.api as engine_api import heat.openstack.common.rpc.common as rpc_common from heat.openstack.common import log as logging logger = logging.getLogger('heat.api.cloudwatch.controller') class WatchController(object): """ WSGI controller for CloudWatch resource in heat API Implements the API actions """ def __init__(self, options): self.options = options self.engine_rpcapi = engine_rpcapi.EngineAPI() @staticmethod def _reformat_dimensions(dims):
import eventlet 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 import resources from heat.common import exception from heat.openstack.common import log as logging logger = logging.getLogger('heat.engine.instance') class Restarter(resources.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
# 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. import eventlet from heat.openstack.common import log as logging import re from heat.common import exception from heat.engine.resources import Resource logger = logging.getLogger('heat.engine.volume') class Volume(Resource): properties_schema = {'AvailabilityZone': {'Type': 'String', 'Required': True}, 'Size': {'Type': 'Number'}, 'SnapshotId': {'Type': 'String'}, 'Tags': {'Type': 'List'}} def __init__(self, name, json_snippet, stack): super(Volume, self).__init__(name, json_snippet, stack) def handle_create(self): vol = self.nova('volume').volumes.create(self.properties['Size'], display_name=self.name,
# under the License. from heat.common import exception from heat.engine import clients from heat.engine.resource import SupportStatus from heat.engine.resources.neutron import neutron from heat.engine.resources.neutron import subnet from heat.engine import properties if clients.neutronclient is not None: from neutronclient.common.exceptions import NeutronClientException from neutronclient.neutron import v2_0 as neutronV20 from heat.openstack.common import log as logging logger = logging.getLogger(__name__) class Router(neutron.NeutronResource): PROPERTIES = ( NAME, EXTERNAL_GATEWAY, VALUE_SPECS, ADMIN_STATE_UP, ) = ( 'name', 'external_gateway_info', 'value_specs', 'admin_state_up', ) _EXTERNAL_GATEWAY_KEYS = ( EXTERNAL_GATEWAY_NETWORK, EXTERNAL_GATEWAY_ENABLE_SNAT, ) = ( 'network', 'enable_snat', )
try: from swiftclient import client as swiftclient swiftclient_present = True except ImportError: swiftclient_present = False from heat.common import exception from heat.common import config from heat.db import api as db_api from heat.engine import checkeddict from heat.engine import timestamp from heat.openstack.common import log as logging from heat.openstack.common import cfg logger = logging.getLogger('heat.engine.resources') class Metadata(object): ''' A descriptor for accessing the metadata of a resource while ensuring the most up-to-date data is always obtained from the database. ''' def __get__(self, resource, resource_class): '''Return the metadata for the owning resource.''' if resource is None: return None if resource.id is None: return resource.parsed_template('Metadata') rs = db_api.resource_get(resource.stack.context, resource.id) rs.refresh(attrs=['rsrc_metadata'])