o
    ȷe_                     @   s   d Z ddlmZmZmZmZ ddlmZ ddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZmZmZ ddlmZ dd	lZe d
i Zdd Zdd ZG dd deZd	S )zc
This module provides an interface to the Elastic Compute Cloud (EC2)
CloudWatch service from AWS.
    )jsonmapsixzip)AWSQueryConnection)Metric)MetricAlarmMetricAlarmsAlarmHistoryItem)	Datapoint)
RegionInfoget_regionsload_regions)connectN
cloudwatchc                   C   s   t dtdS )z
    Get all available regions for the CloudWatch service.

    :rtype: list
    :return: A list of :class:`boto.RegionInfo` instances
    r   )connection_cls)r   CloudWatchConnection r   r   S/var/www/ideatree/venv/lib/python3.10/site-packages/boto/ec2/cloudwatch/__init__.pyregions&   s   r   c                 K   s   t d| fdti|S )aI  
    Given a valid region name, return a
    :class:`boto.ec2.cloudwatch.CloudWatchConnection`.

    :param str region_name: The name of the region to connect to.

    :rtype: :class:`boto.ec2.CloudWatchConnection` or ``None``
    :return: A connection to the given region, or None if an invalid region
        name is given
    r   r   )r   r   )region_name	kw_paramsr   r   r   connect_to_region0   s
   
r   c                       s  e Zd ZejdddZejdddZejdddZ			
		d, fdd	Z	dd Z
dd Zdd Z		d-ddZ		d.ddZ		d/ddZ		d-ddZ			d0ddZ				d0ddZ		d/d d!Zd"d# ZeZeZd$d% Z	d1d&d'Zd(d) Zd*d+ Z  ZS )2r   Botocloudwatch_versionz
2010-08-01cloudwatch_region_namez	us-east-1cloudwatch_region_endpointz"monitoring.us-east-1.amazonaws.comNTr   /c                    s`   |s
t | | j| j}|| _| jjdkrd}tt| j||||||||| jj|	|
||||d dS )z
        Init method to create a new connection to EC2 Monitoring Service.

        B{Note:} The host argument is overridden by the host specified in the
        boto configuration file.
        z	eu-west-1F)validate_certsprofile_nameN)	r   DefaultRegionNameDefaultRegionEndpointregionnamesuperr   __init__endpoint)selfaws_access_key_idaws_secret_access_key	is_secureportproxy
proxy_port
proxy_user
proxy_passdebughttps_connection_factoryr"   pathsecurity_tokenr   r   	__class__r   r   r%   H   s"   
zCloudWatchConnection.__init__c                 C   s   dgS )Nzhmac-v4r   )r'   r   r   r   _required_auth_capabilityg   s   z.CloudWatchConnection._required_auth_capabilityc                 C   s   d}d}|D ]=}|| }|r5t |tjr|g}|D ]}||d||d f < ||d||d f < |d7 }qq||d||d f < |d7 }qd S )NzDimensions.memberr   z
%s.%d.Name   z%s.%d.Value)
isinstancer   string_types)r'   	dimensionparamsprefixidim_name	dim_valuevaluer   r   r   build_dimension_paramj   s   

z*CloudWatchConnection.build_dimension_paramc           	      C   s   t |tjr	|g}t|D ]2\}}|d }t |tr9t|D ]\}}||||df < |d ur7||||df < qq|||| < qd S )Nr7   NameValue)r8   r   r9   	enumeratedict	iteritems)	r'   r;   itemslabelindexitemr=   kvr   r   r   build_list_paramsz   s   
z&CloudWatchConnection.build_list_paramsc                    s  ||||||f}t tdd |  fdd}	ttt|	| D ]l\}
\}}}}}}d|i}|r6| |d< |r<||d< |rD| || |rk|d |d	< |d
 |d< |d |d< |d |d< |d urjd}tj| n|d urt||d< nt	dt
|D ]\}}||d|
d |f < q}q d S )Nc                 S   s   t | tr	t| S dS )Nr7   )r8   listlenar   r   r   <lambda>   s    z7CloudWatchConnection.build_put_params.<locals>.<lambda>c                    s0   t | trt|  krtd  | S | g  S )Nz3Must specify equal number of elements; expected %d.)r8   rN   rO   	ExceptionrP   lengthr   r   aslist   s
   

z5CloudWatchConnection.build_put_params.<locals>.aslist
MetricName	TimestampUnitmaximumzStatisticValues.MaximumminimumzStatisticValues.MinimumsamplecountzStatisticValues.SampleCountsumzStatisticValues.SumzRYou supplied a value and statistics for a metric.Posting statistics and not value.rC   z*Must specify a value or statistics to put.zMetricData.member.%d.%sr7   )maxr   rD   r   	isoformatrA   botologwarnrS   r   rF   )r'   r;   r#   r@   	timestampunit
dimensions
statisticsargsrV   rI   nrL   udstmetric_datamsgkeyvalr   rT   r   build_put_params   s6   &
z%CloudWatchConnection.build_put_paramsc	           
      C   sV   ||||  |  d}	| |	|d |r| ||	 |r!||	d< | d|	dtfgS )a  
        Get time-series data for one or more statistics of a given metric.

        :type period: integer
        :param period: The granularity, in seconds, of the returned datapoints.
            Period must be at least 60 seconds and must be a multiple
            of 60. The default value is 60.

        :type start_time: datetime
        :param start_time: The time stamp to use for determining the
            first datapoint to return. The value specified is
            inclusive; results include datapoints with the time stamp
            specified.

        :type end_time: datetime
        :param end_time: The time stamp to use for determining the
            last datapoint to return. The value specified is
            exclusive; results will include datapoints up to the time
            stamp specified.

        :type metric_name: string
        :param metric_name: The metric name.

        :type namespace: string
        :param namespace: The metric's namespace.

        :type statistics: list
        :param statistics: A list of statistics names Valid values:
            Average | Sum | SampleCount | Maximum | Minimum

        :type dimensions: dict
        :param dimensions: A dictionary of dimension key/values where
                           the key is the dimension name and the value
                           is either a scalar value or an iterator
                           of values to be associated with that
                           dimension.

        :type unit: string
        :param unit: The unit for the metric.  Value values are:
            Seconds | Microseconds | Milliseconds | Bytes | Kilobytes |
            Megabytes | Gigabytes | Terabytes | Bits | Kilobits |
            Megabits | Gigabits | Terabits | Percent | Count |
            Bytes/Second | Kilobytes/Second | Megabytes/Second |
            Gigabytes/Second | Terabytes/Second | Bits/Second |
            Kilobits/Second | Megabits/Second | Gigabits/Second |
            Terabits/Second | Count/Second | None

        :rtype: list
        )PeriodrW   	Namespace	StartTimeEndTimezStatistics.member.%drY   GetMetricStatisticsmember)r_   rM   rA   get_listr   )
r'   period
start_timeend_timemetric_name	namespacerf   re   rd   r;   r   r   r   get_metric_statistics   s   4z*CloudWatchConnection.get_metric_statisticsc                 C   sL   i }|r||d< |r|  || |r||d< |r||d< | d|dtfgS )a  
        Returns a list of the valid metrics for which there is recorded
        data available.

        :type next_token: str
        :param next_token: A maximum of 500 metrics will be returned
            at one time.  If more results are available, the ResultSet
            returned will contain a non-Null next_token attribute.
            Passing that token as a parameter to list_metrics will
            retrieve the next page of metrics.

        :type dimensions: dict
        :param dimensions: A dictionary containing name/value
            pairs that will be used to filter the results.  The key in
            the dictionary is the name of a Dimension.  The value in
            the dictionary is either a scalar value of that Dimension
            name that you want to filter on or None if you want all
            metrics with that Dimension name.  To be included in the
            result a metric must contain all specified dimensions,
            although the metric may contain additional dimensions beyond
            the requested metrics.  The Dimension names, and values must
            be strings between 1 and 250 characters long. A maximum of
            10 dimensions are allowed.

        :type metric_name: str
        :param metric_name: The name of the Metric to filter against.  If None,
            all Metric names will be returned.

        :type namespace: str
        :param namespace: A Metric namespace to filter against (e.g. AWS/EC2).
            If None, Metrics from all namespaces will be returned.
        	NextTokenrW   rs   ListMetricsrw   )rA   rx   r   )r'   
next_tokenre   r|   r}   r;   r   r   r   list_metrics   s   "z!CloudWatchConnection.list_metricsc           	   	   C   s0   d|i}| j |||||||d | jd|ddS )a  
        Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
        associates the data points with the specified metric. If the specified
        metric does not exist, Amazon CloudWatch creates the metric. If a list
        is specified for some, but not all, of the arguments, the remaining
        arguments are repeated a corresponding number of times.

        :type namespace: str
        :param namespace: The namespace of the metric.

        :type name: str or list
        :param name: The name of the metric.

        :type value: float or list
        :param value: The value for the metric.

        :type timestamp: datetime or list
        :param timestamp: The time stamp used for the metric. If not specified,
            the default value is set to the time the metric data was received.

        :type unit: string or list
        :param unit: The unit of the metric.  Valid Values: Seconds |
            Microseconds | Milliseconds | Bytes | Kilobytes |
            Megabytes | Gigabytes | Terabytes | Bits | Kilobits |
            Megabits | Gigabits | Terabits | Percent | Count |
            Bytes/Second | Kilobytes/Second | Megabytes/Second |
            Gigabytes/Second | Terabytes/Second | Bits/Second |
            Kilobits/Second | Megabits/Second | Gigabits/Second |
            Terabits/Second | Count/Second | None

        :type dimensions: dict
        :param dimensions: Add extra name value pairs to associate
            with the metric, i.e.:
            {'name1': value1, 'name2': (value2, value3)}

        :type statistics: dict or list
        :param statistics: Use a statistic set instead of a value, for example::

            {'maximum': 30, 'minimum': 1, 'samplecount': 100, 'sum': 10000}
        rs   )r@   rc   rd   re   rf   PutMetricDataPOST)verb)rq   
get_status)	r'   r}   r#   r@   rc   rd   re   rf   r;   r   r   r   put_metric_data  s
   *z$CloudWatchConnection.put_metric_datac           
      C   s|   i }|r||d< |r||d< n	|r|  ||d |r||d< |r$||d< |r*||d< | d|dtfg}|d	 }	|j|	_|	S )
a  
        Retrieves alarms with the specified names. If no name is specified, all
        alarms for the user are returned. Alarms can be retrieved by using only
        a prefix for the alarm name, the alarm state, or a prefix for any
        action.

        :type action_prefix: string
        :param action_prefix: The action name prefix.

        :type alarm_name_prefix: string
        :param alarm_name_prefix: The alarm name prefix. AlarmNames cannot
            be specified if this parameter is specified.

        :type alarm_names: list
        :param alarm_names: A list of alarm names to retrieve information for.

        :type max_records: int
        :param max_records: The maximum number of alarm descriptions
            to retrieve.

        :type state_value: string
        :param state_value: The state value to be used in matching alarms.

        :type next_token: string
        :param next_token: The token returned by a previous call to
            indicate that there is more data.

        :rtype list
        ActionPrefixAlarmNamePrefixAlarmNames.member.%s
MaxRecordsr   
StateValueDescribeAlarmsr	   r   )rM   rx   r	   r   )
r'   action_prefixalarm_name_prefixalarm_namesmax_recordsstate_valuer   r;   resultretr   r   r   describe_alarmsO  s&    
z$CloudWatchConnection.describe_alarmsc                 C   sh   i }|r||d< |r|  |d< |r|  |d< |r||d< |r$||d< |r*||d< | d|dtfgS )	a  
        Retrieves history for the specified alarm. Filter alarms by date range
        or item type. If an alarm name is not specified, Amazon CloudWatch
        returns histories for all of the owner's alarms.

        Amazon CloudWatch retains the history of deleted alarms for a period of
        six weeks. If an alarm has been deleted, its history can still be
        queried.

        :type alarm_name: string
        :param alarm_name: The name of the alarm.

        :type start_date: datetime
        :param start_date: The starting date to retrieve alarm history.

        :type end_date: datetime
        :param end_date: The starting date to retrieve alarm history.

        :type history_item_type: string
        :param history_item_type: The type of alarm histories to retreive
            (ConfigurationUpdate | StateUpdate | Action)

        :type max_records: int
        :param max_records: The maximum number of alarm descriptions
            to retrieve.

        :type next_token: string
        :param next_token: The token returned by a previous call to indicate
            that there is more data.

        :rtype list
        	AlarmName	StartDateEndDateHistoryItemTyper   r   DescribeAlarmHistoryrw   )r_   rx   r
   )r'   
alarm_name
start_dateend_dater   history_item_typer   r;   r   r   r   describe_alarm_history  s    $z+CloudWatchConnection.describe_alarm_historyc                 C   sR   ||d}|r||d< |r||d< |r|  || |r||d< | d|dtfgS )a
  
        Retrieves all alarms for a single metric. Specify a statistic, period,
        or unit to filter the set of alarms further.

        :type metric_name: string
        :param metric_name: The name of the metric.

        :type namespace: string
        :param namespace: The namespace of the metric.

        :type period: int
        :param period: The period in seconds over which the statistic
            is applied.

        :type statistic: string
        :param statistic: The statistic for the metric.

        :type dimensions: dict
        :param dimensions: A dictionary containing name/value
            pairs that will be used to filter the results. The key in
            the dictionary is the name of a Dimension. The value in
            the dictionary is either a scalar value of that Dimension
            name that you want to filter on, a list of values to
            filter on or None if you want all metrics with that
            Dimension name.

        :type unit: string

        :rtype list
        )rW   rs   rr   	StatisticrY   DescribeAlarmsForMetricrw   )rA   rx   r   )r'   r|   r}   ry   	statisticre   rd   r;   r   r   r   describe_alarms_for_metric  s    z/CloudWatchConnection.describe_alarms_for_metricc              	   C   s   |j |j|j|j|j|j|j|jd}|jdur|j|d< |j	r(| 
||j	d |jr0|j|d< |jr:| |j| |jrE| 
||jd |jrP| 
||jd |jrX|j|d< | |_| d	|S )
a  
        Creates or updates an alarm and associates it with the specified Amazon
        CloudWatch metric. Optionally, this operation can associate one or more
        Amazon Simple Notification Service resources with the alarm.

        When this operation creates an alarm, the alarm state is immediately
        set to INSUFFICIENT_DATA. The alarm is evaluated and its StateValue is
        set appropriately. Any actions associated with the StateValue is then
        executed.

        When updating an existing alarm, its StateValue is left unchanged.

        :type alarm: boto.ec2.cloudwatch.alarm.MetricAlarm
        :param alarm: MetricAlarm object.
        )r   rW   rs   r   ComparisonOperator	ThresholdEvaluationPeriodsrr   NActionsEnabledzAlarmActions.member.%sAlarmDescriptionz!InsufficientDataActions.member.%szOKActions.member.%srY   PutMetricAlarm)r#   metricr}   r   
comparison	thresholdevaluation_periodsry   actions_enabledalarm_actionsrM   descriptionre   rA   insufficient_data_actions
ok_actionsrd   
connectionr   )r'   alarmr;   r   r   r   put_metric_alarm  s>   







z%CloudWatchConnection.put_metric_alarmc                 C      i }|  ||d | d|S )z
        Deletes all specified alarms. In the event of an error, no
        alarms are deleted.

        :type alarms: list
        :param alarms: List of alarm names.
        r   DeleteAlarmsrM   r   )r'   alarmsr;   r   r   r   delete_alarms  s   z"CloudWatchConnection.delete_alarmsc                 C   s*   |||d}|rt ||d< | d|S )a  
        Temporarily sets the state of an alarm. When the updated StateValue
        differs from the previous value, the action configured for the
        appropriate state is invoked. This is not a permanent change. The next
        periodic alarm check (in about a minute) will set the alarm to its
        actual state.

        :type alarm_name: string
        :param alarm_name: Descriptive name for alarm.

        :type state_reason: string
        :param state_reason: Human readable reason.

        :type state_value: string
        :param state_value: OK | ALARM | INSUFFICIENT_DATA

        :type state_reason_data: string
        :param state_reason_data: Reason string (will be jsonified).
        )r   StateReasonr   StateReasonDataSetAlarmState)r   dumpsr   )r'   r   state_reasonr   state_reason_datar;   r   r   r   set_alarm_state   s   z$CloudWatchConnection.set_alarm_statec                 C   r   )z
        Enables actions for the specified alarms.

        :type alarms: list
        :param alarms: List of alarm names.
        r   EnableAlarmActionsr   r'   r   r;   r   r   r   enable_alarm_actions=     z)CloudWatchConnection.enable_alarm_actionsc                 C   r   )z
        Disables actions for the specified alarms.

        :type alarms: list
        :param alarms: List of alarm names.
        r   DisableAlarmActionsr   r   r   r   r   disable_alarm_actionsH  r   z*CloudWatchConnection.disable_alarm_actions)NNTNNNNNr   NNr   NTN)NNNNN)NN)NNNN)NNNNNN)N)__name__
__module____qualname__r`   configget
APIVersionr    r!   r%   r6   rA   rM   rq   r~   r   r   r   r   r   r   create_alarmupdate_alarmr   r   r   r   __classcell__r   r   r4   r   r   ?   sd    

*
A
.
0
4
4
--
r   )__doc__boto.compatr   r   r   r   boto.connectionr   boto.ec2.cloudwatch.metricr   boto.ec2.cloudwatch.alarmr   r	   r
   boto.ec2.cloudwatch.datapointr   boto.regioninfor   r   r   r   r`   r   
RegionDatar   r   r   r   r   r   r   <module>   s   
