Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Created November 24, 2014 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjhea0/e1436b693cc56ca82277 to your computer and use it in GitHub Desktop.
Save mjhea0/e1436b693cc56ca82277 to your computer and use it in GitHub Desktop.
import requests
import base64
import json
from apscheduler.schedulers.blocking import BlockingScheduler
from config import APP, KEY, PROCESS
#############
### tasks ###
#############
# Generate Base64 encoded API Key
BASEKEY = base64.b64encode(":" + KEY)
# Create headers for API call
HEADERS = {
"Accept": "application/vnd.heroku+json; version=3",
"Authorization": BASEKEY
}
def scale(size):
payload = {'quantity': size}
json_payload = json.dumps(payload)
url = "https://api.heroku.com/apps/" + APP + "/formation/" + PROCESS
try:
result = requests.patch(url, headers=HEADERS, data=json_payload)
except:
return None
if result.status_code == 200:
return "Success!"
else:
return "Failure"
def get_current_dyno_quantity():
url = "https://api.heroku.com/apps/" + APP + "/formation"
try:
result = requests.get(url, headers=HEADERS)
for formation in json.loads(result.text):
current_quantity = formation["quantity"]
return current_quantity
except:
return None
#################
### scheduler ###
#################
sched = BlockingScheduler()
@sched.scheduled_job('cron', hour=7)
def scale_out_to_three():
print 'Scaling out ...'
print scale(3)
@sched.scheduled_job('cron', hour=22)
def scale_in_to_two():
print 'Scaling in ...'
print scale(2)
@sched.scheduled_job('cron', hour=3)
def scale_in_to_one():
print 'Scaling in ...'
print scale(1)
@sched.scheduled_job('interval', minutes=3)
def fail_safe():
print "pinging ..."
r = requests.get('https://APPNAME.herokuapp.com/')
current_number_of_dynos = get_current_dyno_quantity()
if r.status_code == 200 and r.elapsed.microseconds / 1000 < 5000:
print "... success!"
if r.status_code < 200 or r.status_code > 299:
if current_number_of_dynos < 3:
print 'Scaling out ...'
print scale(3)
if r.elapsed.microseconds / 1000 > 5000:
if current_number_of_dynos < 3:
print 'Scaling out ...'
print scale(3)
sched.start()
APP = "<add your app name>"
KEY = "<add your API key>"
PROCESS = "web"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment