Example #1
0
 def delete_policy(self, scaling_group, policy):
     """
     Deletes the specified policy from the scaling group.
     """
     uri = "/%s/%s/policies/%s" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy))
     resp, resp_body = self.api.method_delete(uri)
Example #2
0
    def create_alarm(self, entity, check, notification_plan, criteria=None,
            disabled=False, label=None, name=None, metadata=None):
        """
        Creates an alarm that binds the check on the given entity with a
        notification plan.

        Note that the 'criteria' parameter, if supplied, should be a string
        representing the DSL for describing alerting conditions and their
        output states. Pyrax does not do any validation of these criteria
        statements; it is up to you as the developer to understand the language
        and correctly form the statement. This alarm language is documented
        online in the Cloud Monitoring section of http://docs.rackspace.com.
        """
        uri = "/%s/%s/alarms" % (self.uri_base, utils.get_id(entity))
        body = {"check_id": utils.get_id(check),
                "notification_plan_id": utils.get_id(notification_plan),
                }
        if criteria:
            body["criteria"] = criteria
        if disabled is not None:
            body["disabled"] = disabled
        label_name = label or name
        if label_name:
            body["label"] = label_name
        if metadata:
            body["metadata"] = metadata
        resp, resp_body = self.api.method_post(uri, body=body)
        if resp.status_code == 201:
            alarm_id = resp.headers["x-object-id"]
            return self.get_alarm(entity, alarm_id)
Example #3
0
 def delete_check(self, entity, check):
     """
     Deletes the specified check from the entity.
     """
     uri = "/%s/%s/checks/%s" % (self.uri_base, utils.get_id(entity),
             utils.get_id(check))
     resp, resp_body = self.api.method_delete(uri)
Example #4
0
 def update_policy(self, scaling_group, policy, name=None, policy_type=None,
         cooldown=None, change=None, is_percent=False,
         desired_capacity=None, args=None):
     """
     Updates the specified policy. One or more of the parameters may be
     specified.
     """
     uri = "/%s/%s/policies/%s" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy))
     if not isinstance(policy, AutoScalePolicy):
         # Received an ID
         policy = self.get_policy(scaling_group, policy)
     body = {"name": name or policy.name,
             "type": policy_type or policy.type,
             "cooldown": cooldown or policy.cooldown,
             }
     if desired_capacity is not None:
         body["desiredCapacity"] = desired_capacity
     elif change is not None:
         if is_percent:
             body["changePercent"] = change
         else:
             body["change"] = change
     else:
         if getattr(policy, "changePercent", None) is not None:
             body["changePercent"] = policy.changePercent
         elif getattr(policy, "change", None) is not None:
             body["change"] = policy.change
         elif getattr(policy, "desiredCapacity", None) is not None:
             body["desiredCapacity"] = policy.desiredCapacity
     args = args or getattr(policy, "args", None)
     if args is not None:
         body["args"] = args
     resp, resp_body = self.api.method_put(uri, body=body)
     return None
Example #5
0
 def update_check(self, check, label=None, name=None, disabled=None,
         metadata=None, monitoring_zones_poll=None, timeout=None,
         period=None, target_alias=None, target_hostname=None,
         target_receiver=None):
     if monitoring_zones_poll:
         monitoring_zones_poll = utils.coerce_string_to_list(
                 monitoring_zones_poll)
         monitoring_zones_poll = [utils.get_id(mzp)
                 for mzp in monitoring_zones_poll]
     body = {}
     local_dict = locals()
     label = label or name
     params = ("label", "disabled", "metadata", "monitoring_zones_poll",
             "timeout", "period", "target_alias", "target_hostname",
             "target_receiver")
     body = _params_to_dict(params, body, locals())
     entity = check.entity
     uri = "/%s/%s/checks/%s" % (self.uri_base, utils.get_id(entity),
             utils.get_id(check))
     try:
         resp, resp_body = self.api.method_put(uri, body=body)
     except exc.BadRequest as e:
         msg = e.message
         dtls = e.details
         if msg.startswith("Validation error"):
             raise exc.InvalidMonitoringCheckUpdate("The update failed "
                     "validation: %s: %s" % (msg, dtls))
         else:
             # Some other issue.
             raise
     return resp_body
Example #6
0
 def delete_alarm(self, entity, alarm):
     """
     Deletes the specified alarm.
     """
     uri = "/%s/%s/alarms/%s" % (self.uri_base, utils.get_id(entity),
             utils.get_id(alarm))
     resp, resp_body = self.api.method_delete(uri)
Example #7
0
 def execute_policy(self, scaling_group, policy):
     """
     Executes the specified policy for this scaling group.
     """
     uri = "/%s/%s/policies/%s/execute" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy))
     resp, resp_body = self.api.method_post(uri)
     return None
Example #8
0
 def delete_record(self, domain, record):
     """
     Deletes an existing record for a domain.
     """
     uri = "/domains/%s/records/%s" % (utils.get_id(domain), utils.get_id(record))
     resp, ret_body = self._async_call(uri, method="DELETE",
             error_class=exc.DomainRecordDeletionFailed, has_response=False)
     return ret_body
Example #9
0
 def get_record(self, domain, record):
     """
     Gets the full information for an existing record for this domain.
     """
     rec_id = utils.get_id(record)
     uri = "/domains/%s/records/%s" % (utils.get_id(domain), rec_id)
     resp, ret_body = self.api.method_get(uri)
     return ret_body
Example #10
0
 def _get_node_base_uri(self, pool, node=None):
     if node is not None:
         template = "/%s/%s/nodes/%s"
         params = (self.uri_base, utils.get_id(pool), utils.get_id(node))
     else:
         template = "/%s/%s/nodes"
         params = (self.uri_base, utils.get_id(pool))
     return template % params
Example #11
0
 def test_get_id(self):
     target = "test_id"
     class Obj_with_id(object):
         id = target
     obj = Obj_with_id()
     self.assertEqual(utils.get_id(obj), target)
     self.assertEqual(utils.get_id(obj), target)
     self.assertEqual(utils.get_id(obj.id), target)
Example #12
0
 def get_check(self, entity, check):
     """
     Returns the current version of the check for the entity.
     """
     uri = "/%s/%s/checks/%s" % (self.uri_base, utils.get_id(entity),
             utils.get_id(check))
     resp, resp_body = self.api.method_get(uri)
     return CloudMonitorCheck(self, resp_body, entity)
Example #13
0
    def get_metric_data_points(self, entity, check, metric, start, end,
            points=None, resolution=None, stats=None):
        """
        Returns the data points for a given metric for the given period. The
        'start' and 'end' times must be specified; they can be be either Python
        date/datetime values, a string representing a date/datetime in either
        of 'YYYY-MM-DD HH:MM:SS' or 'YYYY-MM-DD' formats, or a Unix timestamp:

        The 'points' parameter represents the number of points to return. The
        'resolution' parameter represents the granularity of the data. You must
        specify either 'points' or 'resolution', but not both. The allowed
        values for resolution are: 'FULL', 'MIN5', 'MIN20', 'MIN60', 'MIN240',
        and 'MIN1440'.

        Finally, the 'stats' parameter specifies the stats you want returned.
        By default only the 'average' is returned. You omit this parameter,
        pass in a single value, or pass in a list of values. The allowed values
        are: 'average', 'variance', 'min', and 'max'
        """
        allowed_resolutions = ("FULL", "MIN5", "MIN20", "MIN60", "MIN240",
                "MIN1440")
        if not (points or resolution):
            raise exc.MissingMonitoringCheckGranularity("You must specify "
                    "either the 'points' or 'resolution' parameter when "
                    "fetching metrics.")
        if resolution:
            if resolution.upper() not in allowed_resolutions:
                raise exc.InvalidMonitoringMetricsResolution("The specified "
                        "resolution '%s' is not valid. The valid values are: "
                        "%s." % (resolution, str(allowed_resolutions)))
        start_tm = utils.to_timestamp(start)
        end_tm = utils.to_timestamp(end)
        qparms = []
        # Timestamps with fractional seconds currently cause a 408 (timeout)
        qparms.append("from=%s" % int(start_tm))
        qparms.append("to=%s" % int(end_tm))
        if points:
            qparms.append("points=%s" % points)
        if resolution:
            qparms.append("resolution=%s" % resolution.upper())
        if stats:
            stats = utils.coerce_string_to_list(stats)
            for stat in stats:
                qparms.append("select=%s" % stat)
        qparm = "&".join(qparms)
        uri = "/%s/%s/checks/%s/metrics/%s/plot?%s" % (self.uri_base,
                utils.get_id(entity), utils.get_id(check), metric, qparm)
        try:
            resp, resp_body = self.api.method_get(uri)
        except exc.BadRequest as e:
            msg = e.message
            dtls = e.details
            if msg.startswith("Validation error"):
                raise exc.InvalidMonitoringMetricsRequest("Your request was "
                        "invalid: '%s'" % dtls)
            else:
                raise
        return resp_body["values"]
Example #14
0
 def _make_pool_node_body(self, pool, server):
     return {
         'cloud_server': {
             'id': utils.get_id(server)
         },
         'load_balancer_pool': {
             'id': utils.get_id(pool),
         }
     }
Example #15
0
 def delete_webhook(self, scaling_group, policy, webhook):
     """
     Deletes the specified webhook from the specified policy.
     """
     uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy),
             utils.get_id(webhook))
     resp, resp_body = self.api.method_delete(uri)
     return None
Example #16
0
 def list_webhooks(self, scaling_group, policy):
     """
     Returns a list of all webhooks for the specified policy.
     """
     uri = "/%s/%s/policies/%s/webhooks" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy))
     resp, resp_body = self.api.method_get(uri)
     return [AutoScaleWebhook(self, data, policy)
             for data in resp_body.get("webhooks", [])]
Example #17
0
 def get_policy(self, scaling_group, policy):
     """
     Gets the detail for the specified policy.
     """
     uri = "/%s/%s/policies/%s" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy))
     resp, resp_body = self.api.method_get(uri)
     data = resp_body.get("policy")
     return AutoScalePolicy(self, data, scaling_group)
Example #18
0
 def get_webhook(self, scaling_group, policy, webhook):
     """
     Gets the detail for the specified webhook.
     """
     uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy),
             utils.get_id(webhook))
     resp, resp_body = self.api.method_get(uri)
     data = resp_body.get("webhook")
     return AutoScaleWebhook(self, data, policy)
Example #19
0
 def get_alarm(self, entity, alarm):
     """
     Returns the alarm with the specified ID for this entity. If a
     CloudMonitorAlarm instance is passed, returns a new CloudMonitorAlarm
     object with the current state from the API.
     """
     uri = "/%s/%s/alarms/%s" % (self.uri_base, utils.get_id(entity),
             utils.get_id(alarm))
     resp, resp_body = self.api.method_get(uri)
     return CloudMonitorAlarm(self, resp_body, entity)
Example #20
0
 def list_metrics(self, entity, check):
     """
     Returns a list of all the metrics associated with the specified check.
     """
     uri = "/%s/%s/checks/%s/metrics" % (self.uri_base,
             utils.get_id(entity), utils.get_id(check))
     resp, resp_body = self.api.method_get(uri)
     metrics = [val["name"]
             for val in resp_body["values"]]
     return metrics
Example #21
0
 def get_record(self, domain, record):
     """
     Gets the full information for an existing record for this domain.
     """
     rec_id = utils.get_id(record)
     domain_id = utils.get_id(domain)
     uri = "/domains/%s/records/%s" % (domain_id, rec_id)
     resp, resp_body = self.api.method_get(uri)
     resp_body['domain_id'] = domain_id
     return CloudDNSRecord(self, resp_body, loaded=False)
Example #22
0
    def test_get_id(self):
        target = utils.random_name()

        class ObjWithID(object):
            id = target

        obj = ObjWithID()
        self.assertEqual(utils.get_id(obj), target)
        self.assertEqual(utils.get_id(obj.id), target)
        plain = object()
        self.assertEqual(utils.get_id(plain), plain)
Example #23
0
 def test_delete_record(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     rec = CloudDNSRecord(mgr, {"id": utils.random_unicode()})
     mgr._async_call = Mock(return_value=({}, {}))
     uri = "/domains/%s/records/%s" % (utils.get_id(dom), utils.get_id(rec))
     clt.delete_record(dom, rec)
     mgr._async_call.assert_called_once_with(uri, method="DELETE",
             error_class=exc.DomainRecordDeletionFailed,
             has_response=False)
Example #24
0
 def add_webhook(self, scaling_group, policy, name, metadata=None):
     """
     Adds a webhook to the specified policy.
     """
     uri = "/%s/%s/policies/%s/webhooks" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy))
     body = self._create_webhook_body(name, metadata=metadata)
     # "body" needs to be a list
     body = [body]
     resp, resp_body = self.api.method_post(uri, body=body)
     data = resp_body.get("webhooks")[0]
     return AutoScaleWebhook(self, data, policy, scaling_group)
Example #25
0
 def update_entity(self, entity, agent=None, metadata=None):
     """
     Updates the specified entity's values with the supplied parameters.
     """
     body = {}
     if agent:
         body["agent_id"] = utils.get_id(agent)
     if metadata:
         body["metadata"] = metadata
     if body:
         uri = "/%s/%s" % (self.uri_base, utils.get_id(entity))
         resp, body = self.api.method_put(uri, body=body)
Example #26
0
 def update_record(self, domain, record, data=None, priority=None,
         ttl=None, comment=None):
     """
     Modifies an existing record for a domain.
     """
     rec_id = utils.get_id(record)
     uri = "/domains/%s/records/%s" % (utils.get_id(domain), rec_id)
     body = {"name": record.name}
     all_opts = (("data", data), ("priority", priority), ("ttl", ttl), ("comment", comment))
     opts = [(k, v) for k, v in all_opts if v is not None]
     body.update(dict(opts))
     resp, ret_body = self._async_call(uri, method="PUT", body=body,
             error_class=exc.DomainRecordUpdateFailed, has_response=False)
     return ret_body
Example #27
0
 def test_update_record(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     nm = utils.random_unicode()
     rec = fakes.FakeDNSRecord(mgr, {"id": utils.random_unicode(), "name": nm})
     ttl = 9999
     data = "0.0.0.0"
     mgr._async_call = Mock(return_value=({}, {}))
     uri = "/domains/%s/records/%s" % (utils.get_id(dom), utils.get_id(rec))
     req_body = {"name": nm, "data": data, "ttl": ttl}
     clt.update_record(dom, rec, data=data, ttl=ttl)
     mgr._async_call.assert_called_once_with(
         uri, method="PUT", body=req_body, error_class=exc.DomainRecordUpdateFailed, has_response=False
     )
Example #28
0
 def replace_policy(self, scaling_group, policy, name,
         policy_type, cooldown, change=None, is_percent=False,
         desired_capacity=None, args=None):
     """
     Replace an existing policy. All of the attributes must be specified. If
     you wish to delete any of the optional attributes, pass them in as
     None.
     """
     policy_id = utils.get_id(policy)
     group_id = utils.get_id(scaling_group)
     uri = "/%s/%s/policies/%s" % (self.uri_base, group_id, policy_id)
     body = self._create_policy_body(name=name, policy_type=policy_type,
             cooldown=cooldown, change=change, is_percent=is_percent,
             desired_capacity=desired_capacity, args=args)
     resp, resp_body = self.api.method_put(uri, body=body)
Example #29
0
 def resume(self, scaling_group):
     """
     Resumes execution of the policies for the specified scaling group.
     """
     uri = "/%s/%s/resume" % (self.uri_base, utils.get_id(scaling_group))
     resp, resp_body = self.api.method_post(uri)
     return None
Example #30
0
 def test_find_record_not_unique(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     typ = "A"
     nm = utils.random_unicode()
     data = "0.0.0.0"
     ret_body = {
         "records": [{
             "accountId": "728829",
             "created": "2012-09-21T21:32:27.000+0000",
             "emailAddress": "*****@*****.**",
             "id": "3448214",
             "name": "example.com",
             "updated": "2012-09-21T21:35:45.000+0000"
         }, {
             "accountId": "728829",
             "created": "2012-09-21T21:32:27.000+0000",
             "emailAddress": "*****@*****.**",
             "id": "3448214",
             "name": "example.com",
             "updated": "2012-09-21T21:35:45.000+0000"
         }]
     }
     clt.method_get = Mock(return_value=({}, ret_body))
     uri = "/domains/%s/records?type=%s&name=%s&data=%s" % (
         utils.get_id(dom), typ, nm, data)
     self.assertRaises(exc.DomainRecordNotUnique,
                       clt.find_record,
                       dom,
                       typ,
                       name=nm,
                       data=data)
Example #31
0
 def _create_body(self,
                  name,
                  img=None,
                  cont=None,
                  img_format=None,
                  img_name=None):
     """
     Used to create a new task. Since tasks don't have names, the required
     'name' parameter is used for the type of task: 'import' or 'export'.
     """
     img = utils.get_id(img)
     cont = utils.get_name(cont)
     body = {"type": name}
     if name == "export":
         body["input"] = {
             "image_uuid": img,
             "receiving_swift_container": cont
         }
     else:
         nm = "%s/%s" % (cont, utils.get_name(img))
         body["input"] = {
             "image_properties": {
                 "name": img_name or img
             },
             "import_from": nm,
             "import_from_format": img_format or DEFAULT_FORMAT
         }
     return body
Example #32
0
 def test_find_record_not_unique(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     typ = "A"
     nm = utils.random_unicode()
     data = "0.0.0.0"
     ret_body = {"records": [{
             "accountId": "728829",
             "created": "2012-09-21T21:32:27.000+0000",
             "emailAddress": "*****@*****.**",
             "id": "3448214",
             "name": "example.com",
             "updated": "2012-09-21T21:35:45.000+0000"
             }, {"accountId": "728829",
             "created": "2012-09-21T21:32:27.000+0000",
             "emailAddress": "*****@*****.**",
             "id": "3448214",
             "name": "example.com",
             "updated": "2012-09-21T21:35:45.000+0000"
             }]}
     clt.method_get = Mock(return_value=({}, ret_body))
     uri = "/domains/%s/records?type=%s&name=%s&data=%s" % (
             utils.get_id(dom), typ, nm, data)
     self.assertRaises(exc.DomainRecordNotUnique, clt.find_record, dom, typ,
             name=nm, data=data)
Example #33
0
 def get_configuration(self, scaling_group):
     """
     Returns the scaling group's configuration in a dictionary.
     """
     uri = "/%s/%s/config" % (self.uri_base, utils.get_id(scaling_group))
     resp, resp_body = self.api.method_get(uri)
     return resp_body.get("groupConfiguration")
Example #34
0
 def list_policies(self, scaling_group):
     """
     Returns a list of all policies defined for the specified scaling group.
     """
     uri = "/%s/%s/policies" % (self.uri_base, utils.get_id(scaling_group))
     resp, resp_body = self.api.method_get(uri)
     return [AutoScalePolicy(self, data, scaling_group)
             for data in resp_body.get("policies", [])]
Example #35
0
 def test_list_records(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     clt.method_get = Mock(return_value=({}, {}))
     uri = "/domains/%s/records" % utils.get_id(dom)
     clt.list_records(dom)
     clt.method_get.assert_called_once_with(uri)
Example #36
0
def _get_server_networks(network, public=False, private=False):
    net_id = utils.get_id(network)
    ret = [{"net-id": net_id}]
    if public:
        ret.append({"net-id": PUBLIC_NET_ID})
    if private:
        ret.append({"net-id": SERVICE_NET_ID})
    return ret
Example #37
0
 def __init__(self, manager, domain=None):
     self.manager = manager
     self.domain = domain
     self.domain_id = utils.get_id(domain) if domain else None
     self.results = []
     self.next_uri = ""
     self.extra_args = tuple()
     self._init_methods()
Example #38
0
 def get_user_credentials(self, user):
     """
     Returns a user's non-password credentials.
     """
     user_id = utils.get_id(user)
     base_uri = "users/%s/OS-KSADM/credentials/RAX-KSKEY:apiKeyCredentials"
     uri = base_uri % user_id
     return self.method_get(uri)
Example #39
0
 def list_credentials(self, user):
     """
     Returns a user's non-password credentials.
     """
     user_id = utils.get_id(user)
     uri = "users/%s/OS-KSADM/credentials" % user_id
     resp, resp_body = self.method_get(uri)
     return resp_body.get("credentials")
Example #40
0
 def _create_body(self, name, instance, description=None):
     body = {"backup": {
             "instance": utils.get_id(instance),
             "name": name,
             }}
     if description is not None:
         body["backup"]["description"] = description
     return body
Example #41
0
 def action(self, item, action_type, body={}):
     """
     Several API calls are lumped under the 'action' API. This
     is the generic handler for such calls.
     """
     uri = "/%s/%s/action" % (self.uri_base, utils.get_id(item))
     action_body = {action_type: body}
     return self.api.method_post(uri, body=action_body)
Example #42
0
 def test_update_record(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     nm = utils.random_name()
     rec = fakes.FakeDNSRecord(mgr, {"id": utils.random_name(), "name": nm})
     ttl = 9999
     data = "0.0.0.0"
     mgr._async_call = Mock(return_value=({}, {}))
     uri = "/domains/%s/records/%s" % (utils.get_id(dom), utils.get_id(rec))
     req_body = {"name": nm, "data": data, "ttl": ttl}
     clt.update_record(dom, rec, data=data, ttl=ttl)
     mgr._async_call.assert_called_once_with(
         uri,
         method="PUT",
         body=req_body,
         error_class=exc.DomainRecordUpdateFailed,
         has_response=False)
Example #43
0
def _get_server_networks(network, public=False, private=False, key=None):
    key = key or "net-id"
    net_id = utils.get_id(network)
    ret = [{key: net_id}]
    if public:
        ret.append({key: PUBLIC_NET_ID})
    if private:
        ret.append({key: SERVICE_NET_ID})
    return ret
Example #44
0
 def update_webhook(self, scaling_group, policy, webhook, name=None,
         metadata=None):
     """
     Updates the specified webhook. One or more of the parameters may be
     specified.
     """
     uri = "/%s/%s/policies/%s/webhooks/%s" % (self.uri_base,
             utils.get_id(scaling_group), utils.get_id(policy),
             utils.get_id(webhook))
     if not isinstance(webhook, AutoScaleWebhook):
         # Received an ID
         webhook = self.get_webhook(scaling_group, policy, webhook)
     body = {"name": name or webhook.name,
             "metadata": metadata or webhook.metadata,
             }
     resp, resp_body = self.api.method_put(uri, body=body)
     webhook.reload()
     return webhook
Example #45
0
 def list(self, entity=None):
     """
     Returns a dictionary of data, optionally filtered for a given entity.
     """
     uri = "/%s" % self.uri_base
     if entity:
         uri = "%s?entityId=%s" % (uri, utils.get_id(entity))
     resp, resp_body = self._list(uri, return_raw=True)
     return resp_body
Example #46
0
 def _list_backups_for_instance(self, instance):
     """
     Instance-specific backups are handled through the instance manager,
     not the backup manager.
     """
     uri = "/%s/%s/backups" % (self.uri_base, utils.get_id(instance))
     resp, resp_body = self.api.method_get(uri)
     mgr = self.api._backup_manager
     return [CloudDatabaseBackup(mgr, backup)
             for backup in resp_body.get("backups")]
Example #47
0
 def delete(self, domain, delete_subdomains=False):
     """
     Deletes the specified domain and all of its resource records. If the
     domain has subdomains, each subdomain will now become a root domain. If
     you wish to also delete any subdomains, pass True to 'delete_subdomains'.
     """
     uri = "/%s/%s" % (self.uri_base, utils.get_id(domain))
     if delete_subdomains:
         uri = "%s?deleteSubdomains=true" % uri
     _resp, ret_body = self._async_call(uri, method="DELETE",
             error_class=exc.DomainDeletionFailed, has_response=False)
Example #48
0
 def create(self, notification_type, label=None, name=None, details=None):
     """
     Defines a notification for handling an alarm.
     """
     uri = "/%s" % self.uri_base
     body = {"label": label or name,
             "type": utils.get_id(notification_type),
             "details": details,
             }
     resp, resp_body = self.api.method_post(uri, body=body)
     return self.get(resp.headers["x-object-id"])
Example #49
0
 def delete_tenant(self, tenant):
     """
     ADMIN ONLY. Removes the tenant from the system. There is no 'undo'
     available, so you should be certain that the tenant specified is the
     tenant you wish to delete.
     """
     tenant_id = utils.get_id(tenant)
     uri = "tenants/%s" % tenant_id
     resp = self.method_delete(uri)
     if resp.status_code == 404:
         raise exc.TenantNotFound("Tenant '%s' does not exist." % tenant)
Example #50
0
 def delete(self, msg, claim_id=None):
     """
     Deletes the specified message from its queue. If the message has been
     claimed, the ID of that claim must be passed as the 'claim_id'
     parameter.
     """
     msg_id = utils.get_id(msg)
     if claim_id:
         uri = "/%s/%s?claim_id=%s" % (self.uri_base, msg_id, claim_id)
     else:
         uri = "/%s/%s" % (self.uri_base, msg_id)
     return self._delete(uri)
Example #51
0
 def test_delete_subdomains(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     mgr._async_call = Mock(return_value=({}, {}))
     uri = "/domains/%s?deleteSubdomains=true" % utils.get_id(dom)
     clt.delete(dom, delete_subdomains=True)
     mgr._async_call.assert_called_once_with(
         uri,
         method="DELETE",
         error_class=exc.DomainDeletionFailed,
         has_response=False)
Example #52
0
 def test_search_records_params(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     typ = "A"
     nm = utils.random_name()
     data = "0.0.0.0"
     clt.method_get = Mock(return_value=({}, {}))
     uri = "/domains/%s/records?type=%s&name=%s&data=%s" % (
         utils.get_id(dom), typ, nm, data)
     clt.search_records(dom, typ, name=nm, data=data)
     clt.method_get.assert_called_once_with(uri)
Example #53
0
 def replace(self, scaling_group, name, cooldown, min_entities,
         max_entities, metadata=None):
     """
     Replace an existing ScalingGroup configuration. All of the attributes
     must be specified If you wish to delete any of the optional attributes,
     pass them in as None.
     """
     body = self._create_group_config_body(name, cooldown, min_entities,
             max_entities, metadata=metadata)
     group_id = utils.get_id(scaling_group)
     uri = "/%s/%s/config" % (self.uri_base, group_id)
     resp, resp_body = self.api.method_put(uri, body=body)
Example #54
0
 def set_metadata(self, queue, metadata, clear=False):
     """
     Accepts a dictionary and adds that to the specified queue's metadata.
     If the 'clear' argument is passed as True, any existing metadata is
     replaced with the new metadata.
     """
     uri = "/%s/%s/metadata" % (self.uri_base, utils.get_id(queue))
     if clear:
         curr = {}
     else:
         curr = self.get_metadata(queue)
     curr.update(metadata)
     resp, resp_body = self.api.method_put(uri, body=curr)
Example #55
0
 def list_roles_for_user(self, user):
     """
     ADMIN ONLY. Returns a list of roles for the specified user. Each role
     will be a 3-tuple, consisting of (role_id, role_name,
     role_description).
     """
     user_id = utils.get_id(user)
     uri = "users/%s/roles" % user_id
     resp = self.method_get(uri)
     if resp.status_code in (401, 403):
         raise exc.AuthorizationFailure("You are not authorized to list "
                                        "user roles.")
     roles = resp.json().get("roles")
     return roles
Example #56
0
 def delete_user(self, user):
     """
     ADMIN ONLY. Removes the user from the system. There is no 'undo'
     available, so you should be certain that the user specified is the user
     you wish to delete.
     """
     user_id = utils.get_id(user)
     uri = "users/%s" % user_id
     resp = self.method_delete(uri)
     if resp.status_code == 404:
         raise exc.UserNotFound("User '%s' does not exist." % user)
     elif resp.status_code in (401, 403):
         raise exc.AuthorizationFailure("You are not authorized to delete "
                                        "users.")
Example #57
0
 def test_add_records(self):
     clt = self.client
     mgr = clt._manager
     dom = self.domain
     rec = {"type": "A", "name": "example.com", "data": "0.0.0.0"}
     mgr._async_call = Mock(return_value=({}, {}))
     uri = "/domains/%s/records" % utils.get_id(dom)
     clt.add_records(dom, rec)
     mgr._async_call.assert_called_once_with(
         uri,
         method="POST",
         body={"records": [rec]},
         error_class=exc.DomainRecordAdditionFailed,
         has_response=False)
Example #58
0
    def test_notification(self, notification=None, notification_type=None,
            details=None):
        """
        This allows you to test either an existing notification, or a potential
        notification before creating it. The actual notification comes from the
        same server where the actual alert messages come from. This allow you
        to, among other things, verify that your firewall is configured
        properly.

        To test an existing notification, pass it as the 'notification'
        parameter and leave the other parameters empty. To pre-test a
        notification before creating it, leave 'notification' empty, but pass
        in the 'notification_type' and 'details'.
        """
        if notification:
            # Test an existing notification
            uri = "/%s/%s/test" % (self.uri_base, utils.get_id(notification))
            body = None
        else:
            uri = "/test-notification"
            body = {"type": utils.get_id(notification_type),
                    "details": details}
        resp, resp_body = self.api.method_post(uri, body=body)
Example #59
0
 def get_state(self, scaling_group):
     """
     Returns the current state of the specified scaling group as a
     dictionary.
     """
     uri = "/%s/%s/state" % (self.uri_base, utils.get_id(scaling_group))
     resp, resp_body = self.api.method_get(uri)
     data = resp_body["group"]
     ret = {}
     ret["active"] = [itm["id"] for itm in data["active"]]
     ret["active_capacity"] = data["activeCapacity"]
     ret["desired_capacity"] = data["desiredCapacity"]
     ret["pending_capacity"] = data["pendingCapacity"]
     ret["paused"] = data["paused"]
     return ret
Example #60
0
 def update(self, claim, ttl=None, grace=None):
     """
     Updates the specified claim with either a new TTL or grace period, or
     both.
     """
     body = {}
     if ttl is not None:
         body["ttl"] = ttl
     if grace is not None:
         body["grace"] = grace
     if not body:
         raise exc.MissingClaimParameters("You must supply a value for "
                 "'ttl' or 'grace' when calling 'update()'")
     uri = "/%s/%s" % (self.uri_base, utils.get_id(claim))
     resp, resp_body = self.api.method_patch(uri, body=body)