Skip to content

Commit

Permalink
initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
fractos committed Jul 17, 2018
0 parents commit 78a4fb0
Show file tree
Hide file tree
Showing 8 changed files with 282 additions and 0 deletions.
104 changes: 104 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
21 changes: 21 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
FROM alpine:3.6

RUN apk add --update --no-cache --virtual=run-deps \
python3 \
ca-certificates

ENV SLACK_WEBHOOK_URL example_value
ENV SLEEP_SECONDS 60
ENV ENDPOINT_DEFINITIONS_FILE /opt/app/config/endpoints.json

WORKDIR /opt/app
CMD ["/opt/app/run.sh"]

COPY run.sh /opt/app/
RUN chmod +x /opt/app/run.sh

COPY app/requirements.txt /opt/app/
RUN pip3 install --no-cache-dir -r /opt/app/requirements.txt

COPY config /opt/app/config/
COPY app /opt/app/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Adam Christie

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Cupcake

123 changes: 123 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
from logzero import logger
from urllib.parse import urlparse
from datetime import datetime, timezone
import re
import socket
import http.client
import json
import time
import settings

def main():
logger.info("starting...")

while True:
lifecycle()
time.sleep(settings.SLEEP_SECONDS)


def lifecycle():
endpoint_definitions = json.loads(
open(settings.ENDPOINT_DEFINITIONS_FILE).read()
)

# collect endpoint results
endpoints_check(endpoint_definitions)


def endpoints_check(endpoints):
logger.info('collecting endpoint health')

for group in endpoints['groups']:

for environment in group['environments']:
environment_id = environment['id']

for endpoint_group in environment['endpoint-groups']:
endpoint_group_name = endpoint_group['name']
endpoint_group_enabled = endpoint_group['enabled']

if endpoint_group_enabled == "true":
for endpoint in endpoint_group['endpoints']:
endpoint_name = endpoint['name']
endpoint_url = endpoint['url']

endpoint_expected = ''
if 'expected' in endpoint:
endpoint_expected = endpoint['expected']

# test the endpoint here

handle_result(
environment=environment_id,
namespace=endpoint_group_name,
key=endpoint_name,
result=test_endpoint(url=endpoint_url, expected=endpoint_expected),
url=endpoint_url,
expected=endpoint_expected
)


def test_endpoint(url, expected):
logger.info('testing endpoint ' + url)
parse_result = urlparse(url)

if parse_result.scheme == 'http' or parse_result.scheme == 'https':
try:
conn = None

if parse_result.scheme == 'http':
logger.debug('starting http connection')
conn = http.client.HTTPConnection(parse_result.netloc)
else:
logger.debug('starting https connection')
conn = http.client.HTTPSConnection(parse_result.netloc)

conn.request('GET', parse_result.path)
status = str(conn.getresponse().status)
logger.debug('status: %s, expected: %s' % (status, expected))
if re.match(expected, status):
return {
"result": True
}
else:
return {
"result": False,
"actual": status
}

except Exception:
pass

return {
"result": False
}


elif parse_result.scheme == 'tcp':
s = socket.socket()
try:
s.connect((parse_result.hostname, parse_result.port))
except Exception as e:
logger.info(
"tcp endpoint %s had a problem: %s" % (parse_result.netloc, e)
)
return {
"result": False
}
finally:
s.close()
return {
"result": True
}


def handle_result(environment, namespace, key, result, expected, url="none"):
timestamp = datetime.now(timezone.utc).astimezone().isoformat()
logger.info('result: timestamp: %s, environment: %s, namespace: %s, key: %s, result: %s, url: %s, expected: %s'
% (timestamp, environment, namespace, key, result['result'], url, expected))
if 'actual' in result:
logger.info('actual: %s' % result['actual'])

if __name__ == "__main__":
main()
3 changes: 3 additions & 0 deletions app/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
logzero
requests

5 changes: 5 additions & 0 deletions app/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os

SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
SLEEP_SECONDS = int(os.getenv("SLEEP_SECONDS"))
ENDPOINT_DEFINITIONS_FILE = os.getenv("ENDPOINT_DEFINITIONS_FILE")
3 changes: 3 additions & 0 deletions run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh

python3 -u main.py

0 comments on commit 78a4fb0

Please sign in to comment.