Full Module Docs

kingpin.actors.aws.base

The AWS Actors allow you to interact with the resources (such as SQS and ELB) inside your Amazon AWS account. These actors all support dry runs properly, but each actor has its own caveats with dry=True. Please read the instructions below for using each actor.

Required Environment Variables

AWS_ACCESS_KEY_ID:
 Your AWS access key
AWS_SECRET_ACCESS_KEY:
 Your AWS secret
exception kingpin.actors.aws.base.ELBNotFound[source]

Raised when an ELB is not found

exception kingpin.actors.aws.base.InvalidMetaData[source]

Raised when fetching AWS metadata.

kingpin.actors.aws.cloudformation

exception kingpin.actors.aws.cloudformation.CloudFormationError[source]

Raised on any generic CloudFormation error.

exception kingpin.actors.aws.cloudformation.InvalidTemplate[source]

An invalid CloudFormation template was supplied.

exception kingpin.actors.aws.cloudformation.StackAlreadyExists[source]

The requested CloudFormation stack already exists.

exception kingpin.actors.aws.cloudformation.StackNotFound[source]

The requested CloudFormation stack does not exist.

class kingpin.actors.aws.cloudformation.CloudFormationBaseActor(*args, **kwargs)[source]

Base Actor for CloudFormation tasks

class kingpin.actors.aws.cloudformation.Create(*args, **kwargs)[source]

Creates a CloudFormation stack.

Creates a CloudFormation stack from scratch and waits until the stack is fully built before exiting the actor.

Options

Capabilities:A list of CF capabilities to add to the stack.
Disable_rollback:
 Set to True to disable rollback of the stack if creation failed.
Name:The name of the queue to create
Parameters:A dictionary of key/value pairs used to fill in the parameters for the CloudFormation template.
Region:AWS region (or zone) string, like ‘us-west-2’
Template:String of path to CloudFormation template. Can either be in the form of a local file path (ie, /my_template.json) or a URI (ie https://my_site.com/cf.json).
Timeout_in_minutes:
 The amount of time that can pass before the stack status becomes CREATE_FAILED.

Examples

{ "desc": "Create production backend stack",
  "actor": "aws.cloudformation.Create",
  "options": {
    "capabilities": [ "CAPABILITY_IAM" ],
    "disable_rollback": true,
    "name": "%CF_NAME%",
    "parameters": {
      "test_param": "%TEST_PARAM_NAME%",
    },
    "region": "us-west-1",
    "template": "/examples/cloudformation_test.json",
    "timeout_in_minutes": 45,
  }
}

Dry Mode

Validates the template, verifies that an existing stack with that name does not exist. Does not create the stack.

class kingpin.actors.aws.cloudformation.Delete(*args, **kwargs)[source]

Deletes a CloudFormation stack

Options

Name:The name of the queue to create
Region:AWS region (or zone) string, like ‘us-west-2’

Examples

{ "desc": "Create production backend stack",
  "actor": "aws.cloudformation.Create",
  "options" {
    "region": "us-west-1",
    "name": "%CF_NAME%",
  }
}

Dry Mode

Validates that the CF stack exists, but does not delete it.

kingpin.actors.aws.elb

exception kingpin.actors.aws.elb.CertNotFound[source]

Raised when an ELB is not found

kingpin.actors.aws.elb.p2f(string)[source]

Convert percentage string into float.

Converts string like ‘78.9%’ into 0.789

class kingpin.actors.aws.elb.ELBBaseActor(*args, **kwargs)[source]

Base class for ELB actors.

class kingpin.actors.aws.elb.WaitUntilHealthy(*args, **kwargs)[source]

Wait indefinitely until a specified ELB is considered “healthy”.

This actor will loop infinitely until a healthy threshold of the ELB is met. The threshold can be reached when the count as specified in the options is less than or equal to the number of InService instances in the ELB.

Another situation is for count to be a string specifying a percentage (see examples). In this case the percent of InService instances has to be greater than the count percentage.

Options

Name:The name of the ELB to operate on
Count:Number, or percentage of InService instance to consider this ELB healthy
Region:AWS region (or zone) name, such as us-east-1 or us-west-2

Examples

{ "actor": "aws.elb.WaitUntilHealthy",
  "desc": "Wait until production-frontend has 16 hosts",
  "options": {
    "name": "production-frontend",
    "count": 16,
    "region": "us-west-2"
  }
}
{ "actor": "aws.elb.WaitUntilHealthy",
  "desc": "Wait until production-frontend has 85% of hosts in-service",
  "options": {
    "name": "production-frontend",
    "count": "85%",
    "region": "us-west-2"
  }
}

Dry Mode

This actor performs the finding of the ELB as well as calculating its health at all times. The only difference in dry mode is that it will not re-count the instances if the ELB is not healthy. A log message will be printed indicating that the run is dry, and the actor will exit with success.

class kingpin.actors.aws.elb.SetCert(*args, **kwargs)[source]

Find a server cert in IAM and use it for a specified ELB.

Options

Region:(str) AWS region (or zone) name, like us-west-2
Name:(str) Name of the ELB
Cert_name:(str) Unique IAM certificate name, or ARN
Port:(int) Port associated with the cert. (default: 443)

Example

{ "actor": "aws.elb.SetCert",
  "desc": "Run SetCert",
  "options": {
    "cert_name": "new-cert",
    "name": "some-elb",
    "region": "us-west-2"
  }
}

Dry run

Will check that ELB and Cert names are existent, and will also check that the credentials provided for AWS have access to the new cert for ssl.

class kingpin.actors.aws.elb.RegisterInstance(*args, **kwargs)[source]

Add an EC2 instance to a load balancer.

Options

Elb:(str) Name of the ELB
Instances:(str, list) Instance id, or list of ids. Default “self” id.
Region:(str) AWS region (or zone) name, like us-west-2
Enable_zones:(bool) add all available AZ to the elb. Default: True

Example

{ "actor": "aws.elb.RegisterInstance",
  "desc": "Run RegisterInstance",
  "options": {
    "elb": "prod-loadbalancer",
    "instances": "i-123456",
    "region": "us-east-1",
  }
}

Dry run

Will find the specified ELB, but not take any actions regarding instances.

class kingpin.actors.aws.elb.DeregisterInstance(*args, **kwargs)[source]

Remove EC2 instance(s) from an ELB.

Options

Elb:(str) Name of the ELB
Instances:(str, list) Instance id, or list of ids
Region:(str) AWS region (or zone) name, like us-west-2

Example

{ "actor": "aws.elb.DeregisterInstance",
  "desc": "Run DeregisterInstance",
  "options": {
    "elb": "fill-in",
    "instances": "fill-in",
    "region": "fill-in"
  }
}

Dry run

Will find the ELB but not take any actions regarding the instances.

kingpin.actors.aws.iam

class kingpin.actors.aws.iam.IAMBaseActor(*args, **kwargs)[source]

Base class for IAM actors.

class kingpin.actors.aws.iam.UploadCert(*args, **kwargs)[source]

Uploads a new SSL Cert to AWS IAM.

Options

Private_key_path:
 (str) Path to the private key.
Path:(str) The AWS “path” for the server certificate. Default: “/”
Public_key_path:
 (str) Path to the public key certificate.
Name:(str) The name for the server certificate.
Cert_chain_path:
 (str) Path to the certificate chain. Optional.

Example

{ "actor": "aws.iam.UploadCert",
  "desc": "Upload a new cert",
  "options": {
    "name": "new-cert",
    "private_key_path": "/cert.key",
    "public_key_path": "/cert.pem",
    "cert_chain_path": "/cert-chain.pem"
  }
}

Dry run

Checks that the passed file paths are valid. In the future will also validate that the files are of correct format and content.

class kingpin.actors.aws.iam.DeleteCert(*args, **kwargs)[source]

Delete an existing SSL Cert in AWS IAM.

Options

Name:(str) The name for the server certificate.

Example

{ "actor": "aws.iam.DeleteCert",
  "desc": "Run DeleteCert",
  "options": {
    "name": "fill-in"
  }
}

Dry run

Will find the cert by name or raise an exception if it’s not found.

kingpin.actors.aws.settings

Common settings used by many of the kingpin.actors.aws modules.

kingpin.actors.aws.settings.is_retriable_exception(exception)[source]

Return true if this AWS exception is transient and should be retried.

Example:
>>> @retry(retry_on_exception=is_retriable_exception)

kingpin.actors.aws.sqs

exception kingpin.actors.aws.sqs.QueueNotFound[source]

Raised by SQS Actor when a needed queue is not found.

exception kingpin.actors.aws.sqs.QueueDeletionFailed[source]

Raised if Boto fails to delete an SQS queue.

http://boto.readthedocs.org/en/latest/ref/
sqs.html#boto.sqs.connection.SQSConnection.delete_queue
class kingpin.actors.aws.sqs.Create(*args, **kwargs)[source]

Creates a new SQS queue with the specified name

Options

Name:(str) The name of the queue to create
Region:(str) AWS region (or zone) string, like ‘us-west-2’

Examples

{ "actor": "aws.sqs.Create",
  "desc": "Create queue named async-tasks",
  "options": {
    "name": "async-tasks",
    "region": "us-east-1",
  }
}

Dry Mode

Will not create any queue, or even contact SQS. Will create a mock.Mock object and exit with success.

class kingpin.actors.aws.sqs.Delete(*args, **kwargs)[source]

Deletes the SQS queues

Note: even if it`s not empty

Options

Name:(str) The name of the queue to destroy
Region:(str) AWS region (or zone) string, like ‘us-west-2’
Idempotent:(bool) Will not raise errors if no matching queues are found. (default: False)

Examples

{ "actor": "aws.sqs.Delete",
  "desc": "Delete queue async-tasks",
  "options": {
    "name": "async-tasks",
    "region": "us-east-1"
  }
}
{ "actor": "aws.sqs.Delete",
  "desc": "Delete queues with 1234 in the name",
  "options": {
    "name": "1234",
    "region": "us-east-1"
  }
}

Dry Mode

Will find the specified queue, but will have a noop regarding its deletion. Dry mode will fail if no queues are found, and idempotent flag is set to False.

class kingpin.actors.aws.sqs.WaitUntilEmpty(*args, **kwargs)[source]

Wait indefinitely until for SQS queues to become empty

This actor will loop infinitely as long as the count of messages in at least one queue is greater than zero. SQS does not guarantee exact count, so this can return a stale value if the number of messages in the queue changes rapidly.

Options

Name:(str) The name or regex pattern of the queues to operate on
Region:(str) AWS region (or zone) string, like ‘us-west-2’
Required:(bool) Fail if no matching queues are found. (default: False)

Examples

{ "actor": "aws.sqs.WaitUntilEmpty",
  "desc": "Wait until release-0025a* queues are empty",
  "options": {
    "name": "release-0025a",
    "region": "us-east-1",
    "required": true
  }
}

Dry Mode

This actor performs the finding of the queue, but will pretend that the count is 0 and return success. Will fail even in dry mode if required option is set to True and no queues with the name pattern are found.

kingpin.actors.base

Base Actor object class

An Actor object is a class that executes a single logical action on a resource as part of your deployment structure. For example, you may have an Actor that launches a server array in RightScale, or you may have one that sends an email.

Each Actor object should do one thing, and one thing only. Its responsible for being able to execute the operation in both ‘dry’ and ‘non-dry’ modes.

The behavior for ‘dry’ mode can contain real API calls, but should not make any live changes. It is up to the developer of the Actor to define what ‘dry’ mode looks like for that particular action.

class kingpin.actors.base.BaseActor(desc, options, dry=False, warn_on_failure=False, condition=True, init_context={}, timeout=None)[source]

Abstract base class for Actor objects.

option(name)[source]

Return the value for a given Actor option.

readfile(path)[source]

Return file contents as a string.

Raises:
InvalidOptions if file is not found, or readable.
timer(f)[source]

Coroutine-compatible function timer.

Records statistics about how long a given function took, and logs them out in debug statements. Used primarily for tracking Actor execute() methods, but can be used elsewhere as well.

Example usage:
>>> @gen.coroutine
... @timer()
... def execute(self):
...     raise gen.Return()
timeout(*args, **kwargs)[source]

Wraps a Coroutine method in a timeout.

Used to wrap the self.execute() method in a timeout that will raise an ActorTimedOut exception if an actor takes too long to execute.

Note, Tornado 4+ does not allow you to actually kill a task on the IOLoop. This means that all we are doing here is notifying the caller (through the raised exception) that a problem has happened.

Fairly simple Actors should actually ‘stop executing’ when this exception is raised. Complex actors with very unique behaviors though (like the rightsacle.server_array.Execute actor) have the ability to continue to execute in the background until the Kingpin application quits. It is not the job of this method to try to kill these actors, but just to let the user know that a failure has happened.

class kingpin.actors.base.HTTPBaseActor(desc, options, dry=False, warn_on_failure=False, condition=True, init_context={}, timeout=None)[source]

Abstract base class for an HTTP-client based Actor object.

This class provides common methods for getting access to asynchronous HTTP clients, wrapping the executions in appropriate try/except blocks, timeouts, etc.

If you’re writing an Actor that uses a remote REST API, this is the base class you should subclass from.

kingpin.actors.exceptions

All common Actor exceptions

exception kingpin.actors.exceptions.ActorException[source]

Base Kingpin Actor Exception

exception kingpin.actors.exceptions.RecoverableActorFailure[source]

Base exception that allows script executions to continue on failure.

This exception class is used to throw an error when an Actor fails, but it was an expected and/or acceptable failure.

This should be used for exceptions that are somewhat normal ... for example, trying to delete a ServerArray thats already gone.

exception kingpin.actors.exceptions.UnrecoverableActorFailure[source]

Base exception for unrecoverable failures.

This exception class should be used for critical failures that should always stop a set of Kingpin actors in-place, regardless of the actors warn_on_failure setting.

Examples would be when credentials are incorrect, or an unexpected exception is caught and there is no known recovery point.

exception kingpin.actors.exceptions.ActorTimedOut[source]

Raised when an Actor takes too long to execute

exception kingpin.actors.exceptions.InvalidActor[source]

Raised when an invalid Actor name was supplied

exception kingpin.actors.exceptions.InvalidOptions[source]

Invalid option arguments passed into the Actor object.

This can be used both for the actual options dict passed into the actor, as well as if a the wrong options were used when connecting to a remote API.

exception kingpin.actors.exceptions.InvalidCredentials[source]

Invalid or missing credentials required for Actor object.

exception kingpin.actors.exceptions.UnparseableResponseFromEndpoint[source]

Invalid response returned from a remote REST endpoint.

exception kingpin.actors.exceptions.BadRequest[source]

An action failed due to a HTTP 400 error likely due to bad input.

kingpin.actors.group

Group a series of other BaseActor into either synchronous or asynchronous stages.

class kingpin.actors.group.BaseGroupActor(*args, **kwargs)[source]

Group together a series of other kingpin.actors.base.BaseActor objects

Acts:[ <list of kingpin.actors.base.BaseActor objects to execute> ]
class kingpin.actors.group.Sync(*args, **kwargs)[source]

Execute a series of kingpin.actors.base.BaseActor synchronously.

Groups together a series of Actors and executes them synchronously in the order that they were defined.

Options

Acts:An array of individual Actor definitions.
Contexts:A list of dictionaries with contextual tokens to pass into the actors at instantiation time. If the list has more than one element, then every actor defined in acts will be instantiated once for each item in the contexts list.

Timeouts

Timeouts are disabled specifically in this actor. The sub-actors can still raise their own kingpin.actors.exceptions.ActorTimedOut exceptions, but since the group actors run an arbitrary number of sub actors, we have chosen to not have this actor specifically raise its own kingpin.actors.exceptions.ActorTimedOut exception unless the user sets the timeout setting.

Examples

Creates two arrays ... but sleeps 60 seconds between the two, then does not sleep at all after the last one:

{ "desc": "Clone, then sleep ... then clone, then sleep shorter...",
  "actor": "group.Sync",
  "options": {
    "contexts": [
      { "ARRAY": "First", "SLEEP": "60", },
      { "ARRAY": "Second", "SLEEP": "0", }
    ],
    "acts": [
      { "desc": "do something",
        "actor": "server_array.Clone",
        "options": {
          "source": "template",
          "dest": "{ARRAY}"
        }
      },
      { "desc": "sleep",
        "actor": "misc.Sleep",
        "options": {
          "sleep": "{SLEEP}",
        }
      }
    ]
  }
}

Dry Mode

Passes on the Dry mode setting to the acts that are called. Does not stop execution when one of the acts fails. Instead Group actor will finish all acts with warnings, and raise an error at the end of execution.

This provides the user with an insight to all the errors that are possible to encounter, rather than abort and quit on the first one.

Failure

In the event that an act fails, this actor will return the failure immediately. Because the acts are executed in-order of definition, the failure will prevent any further acts from executing.

The behavior is different in the dry run (read above.)

class kingpin.actors.group.Async(*args, **kwargs)[source]

Execute several kingpin.actors.base.BaseActor objects asynchronously.

Groups together a series of Actors and executes them asynchronously - waiting until all of them finish before returning.

Options

Concurrency:Max number of concurrent executions. This will fire off N executions in parallel, and continue with the remained as soon as the first execution is done. This is faster than creating N Sync executions.
Acts:An array of individual Actor definitions.
Contexts:A list of dictionaries with contextual tokens to pass into the actors at instantiation time. If the list has more than one element, then every actor defined in acts will be instantiated once for each item in the contexts list.

Timeouts

Timeouts are disabled specifically in this actor. The sub-actors can still raise their own kingpin.actors.exceptions.ActorTimedOut exceptions, but since the group actors run an arbitrary number of sub actors, we have chosen to not have this actor specifically raise its own kingpin.actors.exceptions.ActorTimedOut exception unless the user sets the timeout setting.

Examples

Clone two arrays quickly.

{ "desc": "Clone two arrays",
  "actor": "group.Async",
  "options": {
    "contexts": [
      { "ARRAY": "NewArray1" },
      { "ARRAY": "NewArray2" }
    ],
    "acts": [
      { "desc": "do something",
        "actor": "server_array.Clone",
        "options": {
          "source": "template",
          "dest": "{ARRAY}",
        }
      }
    ]
  }
}

Dry Mode

Passes on the Dry mode setting to the sub-actors that are called.

Failure

In the event that one or more acts fail in this group, the entire group acts will return a failure to Kingpin. Because multiple actors are executing all at the same time, the all of these actors will be allowed to finish before the failure is returned.

kingpin.actors.hipchat

The Hipchat Actors allow you to send messages to a HipChat room at stages during your job execution. The actor supports dry mode by validating that the configured API Token has access to execute the methods, without actually sending the messages.

Required Environment Variables

HIPCHAT_TOKEN:HipChat API Token
HIPCHAT_NAME:HipChat message from name (defaults to Kingpin)
class kingpin.actors.hipchat.HipchatBase(*args, **kwargs)[source]

Simple Hipchat Abstract Base Object

class kingpin.actors.hipchat.Message(*args, **kwargs)[source]

Sends a message to a room in HipChat.

Options

Room:(str) The string-name (or ID) of the room to send a message to
Message:(str) Message to send

Examples

{ "actor": "hipchat.Message",
  "desc": "Send a message!",
  "options": {
    "room": "Operations",
    "message": "Beginning Deploy: v1.2"
  }
}

Dry Mode

Fully supported – does not actually send messages to a room, but validates that the API credentials would have access to send the message using the HipChat auth_test optional API argument.

class kingpin.actors.hipchat.Topic(*args, **kwargs)[source]

Sets a HipChat room topic.

Options

  • room - The string-name (or ID) of the room to set the topic of
  • topic - String of the topic to send

Examples

{ "actor": "hipchat.Topic",
  "desc": "set the room topic",
  "options": {
    "room": "Operations",
    "topic": "Latest Deployment: v1.2"
  }
}

Dry Mode

Fully supported – does not actually set a room topic, but validates that the API credentials would have access to set the topic of the room requested.

kingpin.actors.librato

The Librato Actor allows you to post an Annotation to Librato. This is specifically useful for marking when deployments occur on your graphs for cause/effect analysis.

Required Environment Variables

LIBRATO_TOKEN:Librato API Token
LIBRATO_EMAIL:Librato email account (i.e. username)
class kingpin.actors.librato.Annotation(*args, **kwargs)[source]

Librato Annotation Actor

Posts an Annotation to Librato.

Options

Title:The title of the annotation
Description:The description of the annotation
Name:Name of the metric to annotate

Examples

{ "actor": "librato.Annotation",
  "desc": "Mark our deployment",
  "options": {
    "title": "Deploy",
    "description": "Version: 0001a",
    "name": "production_releases"
  }
}

Dry Mode

Currently does not actually do anything, just logs dry mode.

kingpin.actors.misc

These are common utility Actors that don’t really need their own dedicated packages. Things like sleep timers, loggers, etc.

Optional Environment Variables

URLLIB_DEBUG:Set this variable to enable extreme debug logging of the URLLIB requests made by the RightScale/AWS actors. Note, this is very insecure as headers/cookies/etc. are exposed
class kingpin.actors.misc.Macro(*args, **kwargs)[source]

Parses a kingpin JSON file, instantiates and executes it.

Parse JSON

Kingpin JSON has 2 passes at its validity. JSON syntax must be valid, with the exception of a few useful deviations allowed by demjson parser. Main one being the permission of inline comments via /* this */ syntax.

The second pass is validating the Schema. The JSON file will be validated for schema-conformity as one of the first things that happens at load-time when the app starts up. If it fails, you will be notified immediately.

Lastly after JSON is established to be valid, all the tokens are replaced with their specified value. Any key/value pair passed in the tokens option will be available inside of the JSON file as %KEY% and replaced with the value at this time.

In a situation where nested Macro executions are invoked the tokens do not propagate from outter macro into the inner. This allows to reuse token names, but forces the user to specify every token needed. Similarly, if environment variables are used for token replacement in the main file, these tokens are not available in the subsequent macros.

Pre-Instantiation

In an effort to prevent mid-run errors, we pre-instantiate all Actor objects all at once before we ever begin executing code. This ensures that major typos or misconfigurations in the JSON will be caught early on.

Execution

misc.Macro actor simply calls the execute() method of the most-outter actor; be it a single action, or a group actor.

Options

File:String of local path to a JSON file.
Tokens:Dictionary to search/replace within the file.

Examples

{ "desc": "Stage 1",
  "actor": "misc.Macro",
  "options": {
    "file": "deployment/stage-1.json",
    "tokens": {
      "TIMEOUT": 360,
      "RELEASE": "%RELEASE%"
    }
  }
}

Dry Mode

Fully supported – instantiates the actor inside of JSON with dry=True. The behavior of the consecutive actor is unique to each; read their description for more information on dry mode.

class kingpin.actors.misc.Sleep(desc, options, dry=False, warn_on_failure=False, condition=True, init_context={}, timeout=None)[source]

Sleeps for an arbitrary number of seconds.

Options

Sleep:Integer of seconds to sleep.

Examples

{ "actor": "misc.Sleep",
  "desc": "Sleep for 60 seconds",
  "options": {
    "sleep": 60
  }
}

Dry Mode

Fully supported – does not actually sleep, just pretends to.

class kingpin.actors.misc.GenericHTTP(desc, options, dry=False, warn_on_failure=False, condition=True, init_context={}, timeout=None)[source]

A very simple actor that allows GET/POST methods over HTTP.

Does a GET or a POST to a specified URL.

Options

Url:Destination URL
Data:Optional POST data as a dict
Username:Optional for HTTPAuth.
Password:Optional for HTTPAuth.

Examples

{ "actor": "misc.GenericHTTP",
  "desc": "Make a simple web call",
  "options": {
    "url": "http://example.com/rest/api/v1?id=123&action=doit",
    "username": "secret",
    "password": "%SECRET_PASSWORD%"
  }
}

Dry Mode

Will not do anything in dry mode except print a log statement.

kingpin.actors.packagecloud

The packagecloud actor allows you to perform maintenance operations on repositories hosted by packagecloud.io using their API:

https://packagecloud.io/docs/api

Required Environment Variables

PACKAGECLOUD_ACCOUNT:
 packagecloud account name, i.e. https://packagecloud.io/PACKAGECLOUD_ACCOUNT
PACKAGECLOUD_TOKEN:
 packagecloud API Token
class kingpin.actors.packagecloud.PackagecloudBase(*args, **kwargs)[source]

Simple packagecloud Abstract Base Object

class kingpin.actors.packagecloud.Delete(*args, **kwargs)[source]

Deletes packages from a PackageCloud repo.

Searches for packages that match the packages_to_delete regex pattern and deletes them. If number_to_keep is set, we always at least this number of versions of the given package intact in the repo. Also if number_to_keep is set, the older versions of a package (based on upload time) packages will be deleted first effectively leaving newer packages in the repo.

Options

Number_to_keep:Keep at least this number of each package (defaults to 0)
Packages_to_delete:
 Regex of packages to delete, e.g. pkg1|pkg2
Repo:Which packagecloud repo to delete from

Examples

{ "desc": "packagecloud Delete example",
  "actor": "packagecloud.Delete",
  "options": {
    "number_to_keep": 10,
    "packages_to_delete": "deleteme",
    "repo": "test"
  }
}
class kingpin.actors.packagecloud.DeleteByDate(*args, **kwargs)[source]

Deletes packages from a PackageCloud repo older than X.

Adds additional functionality to the Delete class with a older_than option. Only packages older than that number of seconds will be deleted.

Options

Number_to_keep:Keep at least this number of each package (defaults to 0)
Older_than:Delete packages created before this number of seconds
Packages_to_delete:
 Regex of packages to delete, e.g. pkg1|pkg2
Repo:Which packagecloud repo to delete from

Examples

{ "desc": "packagecloud DeleteByDate example",
  "actor": "packagecloud.DeleteByDate",
  "options": {
    "number_to_keep": 10,
    "older_than": 600,
    "packages_to_delete": "deleteme",
    "repo": "test"
  }
}
class kingpin.actors.packagecloud.WaitForPackage(*args, **kwargs)[source]

Searches for a package that matches name and version until found or a timeout occurs.

Options

Name:Name of the package to search for as a regex
Version:Version of the package to search for as a regex
Repo:Which packagecloud repo to delete from
Sleep:Number of seconds to sleep for between each search

Examples

{ "desc": "packagecloud WaitForPackage example",
  "actor": "packagecloud.WaitForPackage",
  "options": {
    "name": "findme",
    "version": "0.1",
    "repo": "test",
    "sleep": 10,
  }
}

kingpin.actors.pingdom

Pingdom actors to pause and unpause checks. These are useful when you are aware of an expected downtime and don’t want to be alerted about it. Also known as Maintenance mode.

Required Environment Variables

PINGDOM_TOKEN:Pingdom API Token
PINGDOM_USER:Pingdom Username (email)
PINGDOM_PASS:Pingdom Password
class kingpin.actors.pingdom.PingdomBase(*args, **kwargs)[source]

Simple Pingdom Abstract Base Object

class kingpin.actors.pingdom.Pause(*args, **kwargs)[source]

Start Pingdom Maintenance.

Pause a particular “check” on Pingdom.

Options

Name:(Str) Name of the check

Example

{ "actor": "pingdom.Pause",
  "desc": "Run Pause",
  "options": {
    "name": "fill-in"
  }
}

Dry run

Will assert that the check name exists, but not take any action on it.

class kingpin.actors.pingdom.Unpause(*args, **kwargs)[source]

Stop Pingdom Maintenance.

Unpause a particular “check” on Pingdom.

Options

Name:(Str) Name of the check

Example

{ "actor": "pingdom.Unpause",
  "desc": "Run unpause",
  "options": {
    "name": "fill-in"
  }
}

Dry run

Will assert that the check name exists, but not take any action on it.

kingpin.actors.rightscale.api

Base RightScale API Access Object.

This package provides access to the RightScale API via Tornado-style @gen.coroutine wrapped methods. These methods are, however, just wrappers for threads that are being fired off in the background to make the API calls.

Async vs Threads

In the future, this will get re-factored to use a native Tornado AsyncHTTPClient object. The methods themselves will stay the same, but the underlying private methods will change.

The methods in this object are specifically designed to support common operations that the RightScale Actor objects need to do. Operations like ‘find server array’, ‘launch server array’, etc. This is not meant as a pure one-to-one mapping of the RightScale API, but rather a mapping of conceptual operations that the Actors need.

Method Design Note

RightScale mixes and matches their API calls... some of them you pass in a major method and then supply a resource ID to act on. Others you pass in the resource_id and get back a list of methods that you can execute.

For consistency in our programming model, this class relies o you passing in rightscale.Resource objects everywhere, and it does the resource->ID translation.

exception kingpin.actors.rightscale.api.ServerArrayException[source]

Raised when an operation on or looking for a ServerArray fails

kingpin.actors.rightscale.base

The RightScale Actors allow you to interact with resources inside your Rightscale account. These actors all support dry runs properly, but each actor has its own caveats with dry=True. Please read the instructions below for using each actor.

Required Environment Variables

RIGHTSCALE_TOKEN:
 RightScale API Refresh Token (from the Account Settings/API Credentials page)
RIGHTSCALE_ENDPOINT:
 Your account-specific API Endpoint (defaults to https://my.rightscale.com)
exception kingpin.actors.rightscale.base.ArrayNotFound[source]

Raised when a ServerArray could not be found.

exception kingpin.actors.rightscale.base.ArrayAlreadyExists[source]

Raised when a ServerArray already exists by a given name.

class kingpin.actors.rightscale.base.RightScaleBaseActor(*args, **kwargs)[source]

Abstract class for creating RightScale cloud actors.

kingpin.actors.rightscale.server_array

exception kingpin.actors.rightscale.server_array.InvalidInputs[source]

Raised when supplied inputs are invalid for a ServerArray.

exception kingpin.actors.rightscale.server_array.TaskExecutionFailed[source]

Raised when one or more RightScale Task executions fail.

class kingpin.actors.rightscale.server_array.ServerArrayBaseActor(*args, **kwargs)[source]

Abstract ServerArray Actor that provides some utility methods.

class kingpin.actors.rightscale.server_array.Clone(*args, **kwargs)[source]

Clones a RightScale Server Array.

Clones a ServerArray in RightScale and renames it to the newly supplied name. By default, this actor is extremely strict about validating that the source array already exists, and that the dest array does not yet exist. This behavior can be overridden though if your Kingpin script creates the source, or destroys an existing dest ServerArray sometime before this actor executes.

Options

Source:The name of the ServerArray to clone
Strict_source:Whether or not to fail if the source ServerArray does not exist. (default: True)
Dest:The new name for your cloned ServerArray
Strict_dest:Whether or not to fail if the destination ServerArray already exists. (default: True)

Examples

Clone my-template-array to my-new-array:

{ "desc": "Clone my array",
  "actor": "rightscale.server_array.Clone",
  "options": {
    "source": "my-template-array",
    "dest": "my-new-array"
  }
}

Clone an array that was created sometime earlier in the Kingpin JSON, and thus does not exist yet during the dry run:

{ "desc": "Clone that array we created earlier",
  "actor": "rightscale.server_array.Clone",
  "options": {
    "source": "my-template-array",
    "strict_source": false,
    "dest": "my-new-array"
  }
}

Clone an array into a destination name that was destroyed sometime earlier in the Kingpin JSON:

{ "desc": "Clone that array we created earlier",
  "actor": "rightscale.server_array.Clone",
  "options": {
    "source": "my-template-array",
    "dest": "my-new-array",
    "strict_dest": false,
  }
}

Dry Mode

In Dry mode this actor does validate that the source array exists. If it does not, a kingpin.actors.rightscale.api.ServerArrayException is thrown. Once that has been validated, the dry mode execution pretends to copy the array by creating a mocked cloned array resource. This mocked resource is then operated on during the rest of the execution of the actor, guaranteeing that no live resources are modified.

Example dry output:

[Copy Test (DRY Mode)] Verifying that array "temp" exists
[Copy Test (DRY Mode)] Verifying that array "new" does not exist
[Copy Test (DRY Mode)] Cloning array "temp"
[Copy Test (DRY Mode)] Renaming array "<mocked clone of temp>" to "new"
class kingpin.actors.rightscale.server_array.Update(*args, **kwargs)[source]

Update ServerArray Settings

Updates an existing ServerArray in RightScale with the supplied parameters. Can update any parameter that is described in the RightScale API docs here:

Parameters are passed into the actor in the form of a dictionary, and are then converted into the RightScale format. See below for examples.

Options

Array:(str) The name of the ServerArray to update
Exact:(bool) whether or not to search for the exact array name. (default: true)
Params:(dict) Dictionary of parameters to update
Inputs:(dict) Dictionary of next-instance server arryay inputs to update

Examples

{ "desc": "Update my array",
  "actor": "rightscale.server_array.Update",
  "options": {
    "array": "my-new-array",
    "params": {
      "elasticity_params": {
        "bounds": {
          "min_count": 4
        },
        "schedule": [
          {"day": "Sunday", "max_count": 2,
           "min_count": 1, "time": "07:00" },
          {"day": "Sunday", "max_count": 2,
           "min_count": 2, "time": "09:00" }
        ]
      },
      "name": "my-really-new-name"
    }
  }
}
{ "desc": "Update my array inputs",
  "actor": "rightscale.server_array.Update",
  "options": {
    "array": "my-new-array",
    "inputs": {
      "ELB_NAME": "text:foobar"
    }
  }
}

Dry Mode

In Dry mode this actor does search for the array, but allows it to be missing because its highly likely that the array does not exist yet. If the array does not exist, a mocked array object is created for the rest of the execution.

During the rest of the execution, the code bypasses making any real changes and just tells you what changes it would have made.

This means that the dry mode cannot validate that the supplied inputs will work.

Example dry output:

[Update Test (DRY Mode)] Verifying that array "new" exists
[Update Test (DRY Mode)] Array "new" not found -- creating a mock.
[Update Test (DRY Mode)] Would have updated "<mocked array new>" with
params: {'server_array[name]': 'my-really-new-name',
         'server_array[elasticity_params][bounds][min_count]': '4'}
class kingpin.actors.rightscale.server_array.UpdateNextInstance(*args, **kwargs)[source]

Update the Next Instance parameters for a Server Array

Updates an existing ServerArray in RightScale with the supplied parameters. Can update any parameter that is described in the RightScale ResourceInstances docs.

Note about the image_href parameter

If you pass in the string default to the image_href key in your params dictionary, we will search and find the default image that your ServerArray’s Multi Cloud Image refers to. This helper is useful if you update your ServerArrays to use custom AMIs, and then occasionally want to go back to using a stock AMI. For example, if you boot up your instances occasionally off a stock AMI, customize the host, and then bake that host into a custom AMI.

Parameters are passed into the actor in the form of a dictionary, and are then converted into the RightScale format. See below for examples.

Options

Array:(str) The name of the ServerArray to update
Exact:(bool) whether or not to search for the exact array name. (default: true)
Params:(dict) Dictionary of parameters to update

Examples

{ "desc": "Update my array",
  "actor": "rightscale.server_array.UpdateNextInstance",
  "options": {
    "array": "my-new-array",
    "params": {
      "associate_public_ip_address": true,
      "image_href": "/image/href/123",
    }
  }
}
{ "desc": "Reset the AMI image to the MCI default",
  "actor": "rightscale.server_array.UpdateNextInstance",
  "options": {
    "array": "my-new-array",
    "params": {
      "image_href": "default",
    }
  }
}

Dry Mode

In Dry mode this actor does search for the array, but allows it to be missing because its highly likely that the array does not exist yet. If the array does not exist, a mocked array object is created for the rest of the execution.

During the rest of the execution, the code bypasses making any real changes and just tells you what changes it would have made.

This means that the dry mode cannot validate that the supplied params will work.

Example dry output:

[Update my array (DRY Mode)] Verifying that array "new" exists
[Update my array (DRY Mode)] Array "new" not found -- creating a mock.
[Update my array (DRY Mode)] Would have updated "<mocked array new>"
with params: {'server_array[associate_public_ip_address]': true,
         'server_array[image_href]': '/image/href/'}
class kingpin.actors.rightscale.server_array.Terminate(*args, **kwargs)[source]

Terminate all instances in a ServerArray

Terminates all instances for a ServerArray in RightScale marking the array disabled.

Options

Array:(str) The name of the ServerArray to destroy
Exact:(bool) Whether or not to search for the exact array name. (default: true)
Strict:(bool) Whether or not to fail if the ServerArray does not exist. (default: true)

Examples

 { "desc": "Terminate my array",
  "actor": "rightscale.server_array.Terminate",
  "options": {
    "array": "my-array"
  }
}
{ "desc": "Terminate many arrays",
  "actor": "rightscale.server_array.Terminate",
  "options": {
    "array": "array-prefix",
    "exact": false,
  }
}

Dry Mode

Dry mode still validates that the server array you want to terminate is actually gone. If you want to bypass this check, then set the warn_on_failure flag for the actor.

class kingpin.actors.rightscale.server_array.Destroy(*args, **kwargs)[source]

Destroy a ServerArray in RightScale

Destroys a ServerArray in RightScale by first invoking the Terminate actor, and then deleting the array as soon as all of the running instances have been terminated.

Options

Array:(str) The name of the ServerArray to destroy
Exact:(bool) Whether or not to search for the exact array name. (default: true)
Strict:(bool) Whether or not to fail if the ServerArray does not exist. (default: true)

Examples

{ "desc": "Destroy my array",
  "actor": "rightscale.server_array.Destroy",
  "options": {
    "array": "my-array"
  }
}
{ "desc": "Destroy many arrays",
  "actor": "rightscale.server_array.Destroy",
  "options": {
    "array": "array-prefix",
    "exact": false,
  }
}

Dry Mode

In Dry mode this actor does search for the array, but allows it to be missing because its highly likely that the array does not exist yet. If the array does not exist, a mocked array object is created for the rest of the execution.

During the rest of the execution, the code bypasses making any real changes and just tells you what changes it would have made.

Example dry output:

[Destroy Test (DRY Mode)] Beginning
[Destroy Test (DRY Mode)] Terminating array before destroying it.
[Destroy Test (terminate) (DRY Mode)] Array "my-array" not found --
creating a mock.
[Destroy Test (terminate) (DRY Mode)] Disabling Array "my-array"
[Destroy Test (terminate) (DRY Mode)] Would have terminated all array
"<mocked array my-array>" instances.
[Destroy Test (terminate) (DRY Mode)] Pretending that array <mocked
array my-array> instances are terminated.
[Destroy Test (DRY Mode)] Pretending to destroy array "<mocked array
my-array>"
[Destroy Test (DRY Mode)] Finished successfully. Result: True
class kingpin.actors.rightscale.server_array.Launch(*args, **kwargs)[source]

Launch instances in a ServerArray

Launches instances in an existing ServerArray and waits until that array has become healthy before returning. Healthy means that the array has at least the user-specified count or min_count number of instances running as defined by the array definition in RightScale.

Options

Array:(str) The name of the ServerArray to launch
Count:(str, int) Optional number of instance to launch. Defaults to min_count of the array.
Enable:(bool) Should the autoscaling of the array be enabled? Settings this to false, or omitting the parameter will not disable an enabled array.
Exact:(bool) Whether or not to search for the exact array name. (default: true)

Examples

{ "desc": "Enable array and launch it",
  "actor": "rightscale.server_array.Launch",
  "options": {
    "array": "my-array",
    "enable": true
  }
}
{ "desc": "Enable arrays starting with my-array and launch them",
  "actor": "rightscale.server_array.Launch",
  "options": {
    "array": "my-array",
    "enable": true,
    "exact": false
  }
}
{ "desc": "Enable array and launch 1 instance",
  "actor": "rightscale.server_array.Launch",
  "options": {
    "array": "my-array",
    "count": 1
  }
}

Dry Mode

In Dry mode this actor does search for the array, but allows it to be missing because its highly likely that the array does not exist yet. If the array does not exist, a mocked array object is created for the rest of the execution.

During the rest of the execution, the code bypasses making any real changes and just tells you what changes it would have made.

Example dry output:

[Launch Array Test #0 (DRY Mode)] Verifying that array "my-array" exists
[Launch Array Test #0 (DRY Mode)] Array "my-array" not found -- creating
    a mock.
[Launch Array Test #0 (DRY Mode)] Enabling Array "my-array"
[Launch Array Test #0 (DRY Mode)] Launching Array "my-array" instances
[Launch Array Test #0 (DRY Mode)] Would have launched instances of array
    <MagicMock name='my-array.self.show().soul.__getitem__()'
    id='4420453200'>
[Launch Array Test #0 (DRY Mode)] Pretending that array <MagicMock
    name='my-array.self.show().soul.__getitem__()' id='4420453200'>
    instances are launched.
class kingpin.actors.rightscale.server_array.Execute(*args, **kwargs)[source]

Executes a RightScale script/recipe on a ServerArray

Executes a RightScript or Recipe on a set of hosts in a ServerArray in RightScale using individual calls to the live running instances. These can be found in your RightScale account under Design -> RightScript or Design -> Cookbooks

The RightScale API offers a multi_run_executable method that can be used to run a single script on all servers in an array – but unfortunately this API method provides no way to monitor the progress of the individual jobs on the hosts. Furthermore, the method often executes on recently terminated or terminating hosts, which throws false-negative error results.

Our actor explicitly retrieves a list of the operational hosts in an array and kicks off individual execution tasks for every host. It then tracks the execution of those tasks from start to finish and returns the results.

Options

Array:(str) The name of the ServerArray to operate on
Script:(str) The name of the RightScript or Recipe to execute
Expected_runtime:
 (str, int) Expected number of seconds to execute. (default: 5)
Concurrency:Max number of concurrent executions. This will fire off N executions in parallel, and continue with the remained as soon as the first execution is done. This is faster than creating N Sync executions. Note: When applied to multiple (M) arrays cumulative concurrency accross all arrays will remain at N. It will not be M x N.
Inputs:(dict) Dictionary of Key/Value pairs to use as inputs for the script
Exact:(str) Boolean whether or not to search for the exact array name. (default: true)

Examples

{ "desc":" Execute script on my-array",
  "actor": "rightscale.server_array.Execute",
  "options": {
    "array": "my-array",
    "script": "connect to elb",
    "expected_runtime": 3,
    "inputs": {
      "ELB_NAME": "text:my-elb"
    }
  }
}

Dry Mode

In Dry mode this actor does search for the array, but allows it to be missing because its highly likely that the array does not exist yet. If the array does not exist, a mocked array object is created for the rest of the execution.

During the rest of the execution, the code bypasses making any real changes and just tells you what changes it would have made.

Example dry output:

[Destroy Test (DRY Mode)] Verifying that array "my-array" exists
[Execute Test (DRY Mode)]
    kingpin.actors.rightscale.server_array.Execute Initialized
[Execute Test (DRY Mode)] Beginning execution
[Execute Test (DRY Mode)] Verifying that array "my-array" exists
[Execute Test (DRY Mode)] Would have executed "Connect instance to ELB"
    with inputs "{'inputs[ELB_NAME]': 'text:my-elb'}" on "my-array".
[Execute Test (DRY Mode)] Returning result: True

kingpin.actors.rollbar

The Rollbar Actor allows you to post Deploy messages to Rollbar when you execute a code deployment.

Required Environment Variables

ROLLBAR_TOKEN:Rollbar API Token
class kingpin.actors.rollbar.RollbarBase(*args, **kwargs)[source]

Simple Rollbar Base Abstract Actor

class kingpin.actors.rollbar.Deploy(*args, **kwargs)[source]

Posts a Deploy message to Rollbar.

https://rollbar.com/docs/deploys_other/

API Token

You must use an API token created in your Project Access Tokens account settings section. This token should have post_server_item permissions for the actual deploy, and read permissions for the Dry run.

Options

Environment:The environment to deploy to
Revision:The deployment revision
Local_username:The user who initiated the deploy
Rollbar_username:
 (Optional) The Rollbar Username to assign the deploy to
Comment:(Optional) Comment describing the deploy

Examples

{ "actor": "rollbar.Deploy",
  "desc": "update rollbar deploy",
  "options": {
    "environment": "Prod",
    "revision": "%DEPLOY%",
    "local_username": "Kingpin",
    "rollbar_username": "Kingpin",
    "comment": "some comment %DEPLOY%"
  }
}

Dry Mode

Accesses the Rollbar API and validates that the token can access your project.

kingpin.actors.slack

The Slack Actors allow you to send messages to a Slack channel at stages during your job execution. The actor supports dry mode by validating that the configured API Token has access to execute the methods, without actually sending the messages.

Required Environment Variables

SLACK_TOKEN:Slack API Token
SLACK_NAME:Slack message from name (defaults to Kingpin)
class kingpin.actors.slack.SlackBase(*args, **kwargs)[source]

Simple Slack Abstract Base Object

class kingpin.actors.slack.Message(*args, **kwargs)[source]

Sends a message to a channel in Slack.

Options

Channel:The string-name of the channel to send a message to
Message:String of the message to send

Examples

{ "desc": "Let the Engineers know things are happening",
  "actor": "slack.Message",
  "options": {
    "channel": "#operations",
    "message": "Beginning Deploy: %VER%"
  }
}

Dry Mode

Fully supported – does not actually send messages to a room, but validates that the API credentials would have access to send the message using the Slack auth.test API method.

This package provides a quick way of creating custom API clients for JSON-based REST APIs. The majority of the work is in the creation of a _CONFIG dictionary for the class. This dictionary dynamically configures the object at instantiation time with the appropriate @gen.coroutine wrapped HTTP fetch methods.

See the documentation in docs/DEVELOPMENT.md for more details on how to use this package to create your own API client.

kingpin.actors.support.api.create_http_method(name, http_method)[source]

Creates the get/put/delete/post coroutined-method for a resource.

This method is called during the __init__ of a RestConsumer object. The method creates a custom method thats handles a GET, PUT, POST or DELETE through the Tornado HTTPClient class.

Args:
http_method: Name of the method (get, put, post, delete)
Returns:
A method appropriately configured and named.
kingpin.actors.support.api.create_method(name, config)[source]

Creates a RestConsumer object.

Configures a fresh RestConsumer object with the supplied configuration bits. The configuration includes information about the name of the method being consumed and the configuration of that method (which HTTP methods it supports, etc).

The final created method accepts any args (*args, **kwargs) and passes them on to the RestConsumer object being created. This allows for passing in unique resource identifiers (ie, the ‘%res%’ in ‘/v2/rooms/%res%/history’).

Args:
name: The name passed into the RestConsumer object config: The config passed into the RestConsumer object
Returns:
A method that returns a fresh RestConsumer object
class kingpin.actors.support.api.RestConsumer(name=None, config=None, client=None, *args, **kwargs)[source]

An abstract object that self-defines its own API access methods.

At init time, this object reads its _CONFIG and pre-defines all of the API access methods that have been described. It does not handle actual HTTP calls directly, but is passed in a client object (anything that subclasses the RestClient class) and leverages that for the actual web calls.

class kingpin.actors.support.api.RestClient(client=None, headers=None)[source]

Very simple REST client for the RestConsumer. Implements a AsyncHTTPClient(), some convinience methods for URL escaping, and a single fetch() method that can handle GET/POST/PUT/DELETEs.

This code is nearly identical to the kingpin.actors.base.BaseHTTPActor class, but is not actor-specific.

Args:
headers: Headers to pass in on every HTTP request
class kingpin.actors.support.api.SimpleTokenRestClient(tokens, *args, **kwargs)[source]

Simple RestClient that appends a ‘token’ to every web request for authentication. Used in most simple APIs where a token is provided to the end user.

Args:
tokens: (dict) A dict with the token name/value(s) to append to every
we request.

kingpin.actors.utils

Misc methods for dealing with Actors.

kingpin.actors.utils.get_actor(config, dry)[source]

Returns an initialized Actor object.

Args:
config: A dictionary of configuration data that conforms to our v1

schema in kingpin.schema. Looks like this:

{
‘desc’: <string description of actor>, ‘actor’: <string name of actor> ‘options’: <dict of options to pass to actor> ‘warn_on_failure’: <bool> ‘condition’: <string or bool> }

dry: Boolean whether or not in Dry mode warn_on_failure: Boolean

Returns:
<actor object>
kingpin.actors.utils.get_actor_class(actor)[source]

Returns a Class Reference to an Actor by string name.

Args:
actor: String name of the actor to find.
Returns:
<Class Ref to Actor>
class kingpin.constants.REQUIRED[source]

Meta class to identify required arguments for actors.

exception kingpin.exceptions.KingpinException[source]

Base Exception

exception kingpin.exceptions.InvalidJSON[source]

Raised when an invalid JSON schema was detected

kingpin.schema.validate(config)[source]

Validates the JSON against our schemas.

TODO: Support multiple schema versions

Args:
config: Dictionary of parsed JSON
Returns:
None: if all is well
Raises:
Execption if something went wrong.

kingpin.utils

Common package for utility functions.

kingpin.utils.str_to_class(string)[source]

Method that converts a string name into a usable Class name

This is used to take the ‘actor’ value from the JSON object and convert it into a valid object reference.

Args:
cls: String name of the wanted class and package.
eg: kingpin.actor.foo.bar
Returns:
A reference to the actual Class to be instantiated
kingpin.utils.setup_root_logger(level='warn', syslog=None, color=False)[source]

Configures the root logger.

Args:
level: Logging level string (‘warn’ is default) syslog: String representing syslog facility to output to. If empty, logs are written to console. color: Colorize the log output
Returns:
A root Logger object
kingpin.utils.super_httplib_debug_logging()[source]

Enables DEBUG logging deep in HTTPLIB.

HTTPLib by default doens’t log out things like the raw HTTP headers, cookies, response body, etc – even when your main logger is in DEBUG mode. This is because its a security risk, as well as just highly verbose.

For the purposes of debugging though, this can be useful. This method enables deep debug logging of the HTTPLib web requests. This is highly insecure, but very useful when troubleshooting failures with remote API endpoints.

Returns:
Requests ‘logger’ object (mainly for unit testing)
kingpin.utils.exception_logger(func)[source]

Explicitly log Exceptions then Raise them.

Logging Exceptions and Tracebacks while inside of a thread is broken in the Tornado futures package for Python 2.7. It swallows most of the traceback and only gives you the raw exception object. This little helper method allows us to throw a log entry with the full traceback before raising the exception.

kingpin.utils.retry(excs, retries=3, delay=0.25)[source]

Coroutine-compatible Retry Decorator.

This decorator provides a simple retry mechanism that looks for a particular set of exceptions and retries async tasks in the event that those exceptions were caught.

Example usage:
>>> @gen.coroutine
... @retry(excs=(Exception), retries=3)
... def login(self):
...     raise gen.Return()
Args:
excs: A single (or tuple) exception type to catch. retries: The number of times to try the operation in total. delay: Time (in seconds) to wait between retries
kingpin.utils.tornado_sleep(*args, **kwargs)[source]

Async method equivalent to sleeping.

Args:
seconds: Float seconds. Default 1.0
kingpin.utils.populate_with_tokens(string, tokens, left_wrapper='%', right_wrapper='%', strict=True)[source]

Insert token variables into the string.

Will match any token wrapped in ‘%’s and replace it with the value of that token.

Args:
string: string to modify. tokens: dictionary of key:value pairs to inject into the string. left_wrapper: the character to use as the START of a token right_wrapper: the character to use as the END of a token strict: (bool) whether or not to make sure all tokens were replaced
Example:

export ME=biz

string=’foo %ME% %bar%’ populate_with_tokens(string, os.environ) # ‘foo biz %bar%’

kingpin.utils.convert_json_to_dict(json_file, tokens)[source]

Converts a JSON file to a config dict.

Reads in a JSON file, swaps out any environment variables that have been used inside the JSON, and then returns a dictionary.

Args:
json_file: Path to the JSON file to import, or file instance. tokens: dictionary to pass to populate_with_tokens.
Returns:
<Dictonary of Config Data>
kingpin.utils.create_repeating_log(logger, message, handle=None, **kwargs)[source]

Create a repeating log message.

This function sets up tornado to repeatedly log a message in a way that does not need to be yield-ed.

Example:

>>> yield do_tornado_stuff(1)
>>> log_handle = create_repeating_log('Computing...')
>>> yield do_slow_computation_with_insufficient_logging()
>>> clear_repeating_log(log_handle)

This is similar to javascript’s setInterval() and clearInterval().

Args:
message: String to pass to log.info() kwargs: values accepted by datetime.timedelta namely seconds, and milliseconds.

Must be cleared via clear_repeating_log() Only handles one interval per actor.

kingpin.utils.clear_repeating_log(handle)[source]

Stops the timeout function from being called.