~ntt-pf-lab/nova/monkey_patch_notification

« back to all changes in this revision

Viewing changes to vendor/boto/boto/ec2/autoscale/__init__.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
 
2
#
 
3
# Permission is hereby granted, free of charge, to any person obtaining a
 
4
# copy of this software and associated documentation files (the
 
5
# "Software"), to deal in the Software without restriction, including
 
6
# without limitation the rights to use, copy, modify, merge, publish, dis-
 
7
# tribute, sublicense, and/or sell copies of the Software, and to permit
 
8
# persons to whom the Software is furnished to do so, subject to the fol-
 
9
# lowing conditions:
 
10
#
 
11
# The above copyright notice and this permission notice shall be included
 
12
# in all copies or substantial portions of the Software.
 
13
#
 
14
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 
15
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
 
16
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
 
17
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 
18
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
19
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 
20
# IN THE SOFTWARE.
 
21
 
 
22
"""
 
23
This module provides an interface to the Elastic Compute Cloud (EC2)
 
24
Auto Scaling service.
 
25
"""
 
26
 
 
27
import boto
 
28
from boto.connection import AWSQueryConnection
 
29
from boto.ec2.autoscale.request import Request
 
30
from boto.ec2.autoscale.trigger import Trigger
 
31
from boto.ec2.autoscale.launchconfig import LaunchConfiguration
 
32
from boto.ec2.autoscale.group import AutoScalingGroup
 
33
from boto.ec2.autoscale.activity import Activity
 
34
 
 
35
 
 
36
class AutoScaleConnection(AWSQueryConnection):
 
37
    APIVersion = boto.config.get('Boto', 'autoscale_version', '2009-05-15')
 
38
    Endpoint = boto.config.get('Boto', 'autoscale_endpoint',
 
39
                               'autoscaling.amazonaws.com')
 
40
    SignatureVersion = '2'
 
41
 
 
42
    def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
 
43
                 is_secure=True, port=None, proxy=None, proxy_port=None,
 
44
                 proxy_user=None, proxy_pass=None, host=Endpoint, debug=1,
 
45
                 https_connection_factory=None, region=None, path='/'):
 
46
        """
 
47
        Init method to create a new connection to the AutoScaling service.
 
48
 
 
49
        B{Note:} The host argument is overridden by the host specified in the
 
50
                 boto configuration file.
 
51
        """
 
52
        AWSQueryConnection.__init__(self, aws_access_key_id,
 
53
                aws_secret_access_key, is_secure, port, proxy, proxy_port,
 
54
                proxy_user, proxy_pass, host, debug,
 
55
                https_connection_factory, path=path)
 
56
 
 
57
    def build_list_params(self, params, items, label):
 
58
        """ items is a list of dictionaries or strings:
 
59
                [{'Protocol' : 'HTTP',
 
60
                 'LoadBalancerPort' : '80',
 
61
                 'InstancePort' : '80'},..] etc.
 
62
             or
 
63
                ['us-east-1b',...]
 
64
        """
 
65
        # different from EC2 list params
 
66
        for i in xrange(1, len(items)+1):
 
67
            if isinstance(items[i-1], dict):
 
68
                for k, v in items[i-1].iteritems():
 
69
                    params['%s.member.%d.%s' % (label, i, k)] = v
 
70
            elif isinstance(items[i-1], basestring):
 
71
                params['%s.member.%d' % (label, i)] = items[i-1]
 
72
 
 
73
    def _update_group(self, op, as_group):
 
74
        params = {
 
75
                  'AutoScalingGroupName'    : as_group.name,
 
76
                  'Cooldown'                : as_group.cooldown,
 
77
                  'LaunchConfigurationName' : as_group.launch_config_name,
 
78
                  'MinSize'                 : as_group.min_size,
 
79
                  'MaxSize'                 : as_group.max_size,
 
80
                  }
 
81
        if op.startswith('Create'):
 
82
            if as_group.availability_zones:
 
83
                zones = self.availability_zones
 
84
            else:
 
85
                zones = [as_group.availability_zone]
 
86
            self.build_list_params(params, as_group.load_balancers,
 
87
                                   'LoadBalancerNames')
 
88
            self.build_list_params(params, zones,
 
89
                                    'AvailabilityZones')
 
90
        return self.get_object(op, params, Request)
 
91
 
 
92
    def create_auto_scaling_group(self, as_group):
 
93
        """
 
94
        Create auto scaling group.
 
95
        """
 
96
        return self._update_group('CreateAutoScalingGroup', as_group)
 
97
 
 
98
    def create_launch_configuration(self, launch_config):
 
99
        """
 
100
        Creates a new Launch Configuration.
 
101
 
 
102
        :type launch_config: boto.ec2.autoscale.launchconfig.LaunchConfiguration
 
103
        :param launch_config: LaunchConfiguraiton object.
 
104
 
 
105
        """
 
106
        params = {
 
107
                  'ImageId'                 : launch_config.image_id,
 
108
                  'KeyName'                 : launch_config.key_name,
 
109
                  'LaunchConfigurationName' : launch_config.name,
 
110
                  'InstanceType'            : launch_config.instance_type,
 
111
                 }
 
112
        if launch_config.user_data:
 
113
            params['UserData'] = launch_config.user_data
 
114
        if launch_config.kernel_id:
 
115
            params['KernelId'] = launch_config.kernel_id
 
116
        if launch_config.ramdisk_id:
 
117
            params['RamdiskId'] = launch_config.ramdisk_id
 
118
        if launch_config.block_device_mappings:
 
119
            self.build_list_params(params, launch_config.block_device_mappings,
 
120
                                   'BlockDeviceMappings')
 
121
        self.build_list_params(params, launch_config.security_groups,
 
122
                               'SecurityGroups')
 
123
        return self.get_object('CreateLaunchConfiguration', params,
 
124
                                  Request)
 
125
 
 
126
    def create_trigger(self, trigger):
 
127
        """
 
128
 
 
129
        """
 
130
        params = {'TriggerName'                 : trigger.name,
 
131
                  'AutoScalingGroupName'        : trigger.autoscale_group.name,
 
132
                  'MeasureName'                 : trigger.measure_name,
 
133
                  'Statistic'                   : trigger.statistic,
 
134
                  'Period'                      : trigger.period,
 
135
                  'Unit'                        : trigger.unit,
 
136
                  'LowerThreshold'              : trigger.lower_threshold,
 
137
                  'LowerBreachScaleIncrement'   : trigger.lower_breach_scale_increment,
 
138
                  'UpperThreshold'              : trigger.upper_threshold,
 
139
                  'UpperBreachScaleIncrement'   : trigger.upper_breach_scale_increment,
 
140
                  'BreachDuration'              : trigger.breach_duration}
 
141
        # dimensions should be a list of tuples
 
142
        dimensions = []
 
143
        for dim in trigger.dimensions:
 
144
            name, value = dim
 
145
            dimensions.append(dict(Name=name, Value=value))
 
146
        self.build_list_params(params, dimensions, 'Dimensions')
 
147
 
 
148
        req = self.get_object('CreateOrUpdateScalingTrigger', params,
 
149
                               Request)
 
150
        return req
 
151
 
 
152
    def get_all_groups(self, names=None):
 
153
        """
 
154
        """
 
155
        params = {}
 
156
        if names:
 
157
            self.build_list_params(params, names, 'AutoScalingGroupNames')
 
158
        return self.get_list('DescribeAutoScalingGroups', params,
 
159
                             [('member', AutoScalingGroup)])
 
160
 
 
161
    def get_all_launch_configurations(self, names=None):
 
162
        """
 
163
        """
 
164
        params = {}
 
165
        if names:
 
166
            self.build_list_params(params, names, 'LaunchConfigurationNames')
 
167
        return self.get_list('DescribeLaunchConfigurations', params,
 
168
                             [('member', LaunchConfiguration)])
 
169
 
 
170
    def get_all_activities(self, autoscale_group,
 
171
                           activity_ids=None,
 
172
                           max_records=100):
 
173
        """
 
174
        Get all activities for the given autoscaling group.
 
175
 
 
176
        :type autoscale_group: str or AutoScalingGroup object
 
177
        :param autoscale_group: The auto scaling group to get activities on.
 
178
 
 
179
        @max_records: int
 
180
        :param max_records: Maximum amount of activities to return.
 
181
        """
 
182
        name = autoscale_group
 
183
        if isinstance(autoscale_group, AutoScalingGroup):
 
184
            name = autoscale_group.name
 
185
        params = {'AutoScalingGroupName' : name}
 
186
        if activity_ids:
 
187
            self.build_list_params(params, activity_ids, 'ActivityIds')
 
188
        return self.get_list('DescribeScalingActivities', params,
 
189
                             [('member', Activity)])
 
190
 
 
191
    def get_all_triggers(self, autoscale_group):
 
192
        params = {'AutoScalingGroupName' : autoscale_group}
 
193
        return self.get_list('DescribeTriggers', params,
 
194
                             [('member', Trigger)])
 
195
 
 
196
    def terminate_instance(self, instance_id, decrement_capacity=True):
 
197
        params = {
 
198
                  'InstanceId' : instance_id,
 
199
                  'ShouldDecrementDesiredCapacity' : decrement_capacity
 
200
                  }
 
201
        return self.get_object('TerminateInstanceInAutoScalingGroup', params,
 
202
                               Activity)
 
203