Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
venv/
venv_clocks/
.idea/
__pycache__/
58 changes: 58 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Clock Exercise

We are interested in running code of course, but even more in your development process and understanding of Software Development Lifecycle Management.

**Fork this repo, then get to work.** Remember that this is a DevOps team, so make sure your repo reflects that. Spend however much time you feel is reasonable. It doesn’t matter if the project is ‘done’, nothing ever is. **When you’re ready push your changes back to Github and put in a pull request back to the base repo.**

This exercise is not meant to take an excessive amount of time. It is an opportunity for you to demonstrate your skills without the stress of an interview. If you start to run out of time, it’s ok to leave an imaginary team member a TODO list that details all the things you didn’t quite have time to do in order for your solution to go to prod.

If you need clarification, or would like to request additional information, pease reach out to the interviewer by email.

## Scenario

You have just joined a DevOps team. This team lives by DevOps principles and you want to let them know you mean business! This particular team is developing a product that is deployed in a Google Cloud Project.

This sprint, the team has been asked to work on a new feature that depends on being able to calculate the angle between the hands on a clock face. They’ve asked you to write some code to help out with that. This is an IOT project, and they have sensors emitting times at a pretty low frequency (about 10 a minute), and for some reason they need to be processed and stored as angles.

You may need to make some assupmtions, that's OK, just document what they are and move on.

The team loves innovation, so you can use whatever languages and technologies you like to complete this. Approach this problem as if your code will go to production. Whilst we don’t expect the code to be perfect, we are not looking for a hacked together script.

Your solution should offer the rest of the team a way to submit a time and receive an angle in return or store it somewhere. They are little fuzzy on the best way to get this low frequency data to your service, so if you can offer them any hints on that, they’d be really happy.

## How to proceed

**Fork this repo, then get to work.** Remember that this is a DevOps team, so make sure your repo reflects that. Spend however much time you feel is reasonable. It doesn’t matter if the project is ‘done’, nothing ever is. **When you’re ready push your changes back to Github and put in a pull request back to the base repo.**

Be sure to add in instructions for how to deploy your solution, and document things in a way that the rest of the team can pick this up and run with it. Remember you have all the tools in the GCP arsenal at your disposal.

We are looking for you to demonstrate your abilities in software practices and DevOps, including reusability, portability, reliability, ease of maintenance etc.

Think about how this will actually be deployed and maintained in the future as you build on it and expand it. You don’t have to implement deployment practices if you don’t have the time or resources, its ok to just document those.

---

## Product Backlog Item (Sprint Story)

Here is the story that is in the backlog.

As with all stories, the team may have been optimistic with how much can be done in the time permitted. It's ok to meet some of the acceptance criteria by documenting what you would do in the next sprint! Prioritize your time and make sure you have some technical content to deliver.

### Description:-

As a team<br>
We need a serivce that we can send a time value to and have it return or store an angle value<br>
So that we can use it in downstream processing

### Detail:-

We need to calculate the angle between the hands on a clock face. For example input 03:00 would yield 90 degrees.

### Acceptance Criteria:-

1) Code to perform the calculation
1) How will you deploy this solution (in code or as a todo list if time is limited). i.e. how and where will this run?
1) How will you manage any infrastructure needed?
1) Delivered as a feature branch in the repo fork
1) Bonus points for a working deployed solution in GCP that you can demo at the "sprint review" (ie interview)
1) Any DevOps/Cicd components that would support this feature in a production setting
19 changes: 19 additions & 0 deletions clock_angles/.gcloudignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# This file specifies files that are *not* uploaded to Google Cloud Platform
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
# $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore

# Python pycache:
__pycache__/
# Ignored by the build system
/setup.cfg
1 change: 1 addition & 0 deletions clock_angles/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions clock_angles/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
runtime: python37
Empty file added clock_angles/lib/__init__.py
Empty file.
73 changes: 73 additions & 0 deletions clock_angles/lib/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import json
import re

from flask import Response
import uuid

from google.cloud import datastore


class Helpers:
STATUS_OK = 200
STATUS_BAD_REQUEST = 400
STATUS_SERVER_ERROR = 500

@staticmethod
def standard_response(status, payload):
json_data = json.dumps({
'response': payload
}, sort_keys=True, indent=4, separators=(',', ': '))
resp = Response(json_data, status=status, mimetype='application/json')
return resp

@staticmethod
def success(payload):
return Helpers.standard_response(Helpers.STATUS_OK, payload)

@staticmethod
def error(status, error_info):
return Helpers.standard_response(status, {
'error': error_info
})

@staticmethod
def bad_request(error_info):
return Helpers.error(Helpers.STATUS_BAD_REQUEST, error_info)

@staticmethod
def validate_and_parse_input(time: str):
"""
Validates user input.

For an input to be valid, string should contain at least 3 characters
and the all characters except ':' should be digits
"""
if time is None or not re.match(r'^\d{1,2}:\d{1,2}$', time):
return False
hour, minute = map(int, time.split(r':'))
if type(hour) != int or type(minute) != int:
return False

if 0 <= hour < 24 and 0 <= minute < 60:
hour = hour % 12
minute = minute
return hour, minute
else:
return False


class DatastoreClient:
def __init__(self, kind):
self.client = datastore.Client(project='ci-cd-clock-angles', namespace='default')
self.kind = kind

def log_to_datastore(self, request_time, response_angle):
name = str(uuid.uuid4())
log_key = self.client.key(self.kind, name)

log_entry = datastore.Entity(key=log_key)
log_entry['time'] = request_time
log_entry['response'] = response_angle

# Saves the entity
self.client.put(log_entry)
44 changes: 44 additions & 0 deletions clock_angles/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from flask import Flask, redirect, request
from lib.helpers import Helpers, DatastoreClient


app = Flask(__name__)


@app.route('/')
def home():
return redirect('/clock_angles')


@app.route('/clock_angles', methods=['GET'])
def calculate_angles():
"""
returns the angle between the hour hand and the minute hand

Request to be sent should be GET and should have a query string with key time containing
the HH:MM information

Build demo
"""
time = request.args.get('time')

result = Helpers.validate_and_parse_input(time)
if result:
hour, minute = result

hour_angle = 0.5 * (hour * 60 + minute)
minute_angle = 6 * minute

angle = abs(hour_angle - minute_angle)
angle = min(360 - angle, angle)
DatastoreClient(kind='clock_angle_logs').log_to_datastore(time, angle)

return Helpers.success(angle)
else:
DatastoreClient(kind='clock_angle_logs').log_to_datastore(time, 'bad_request')
return Helpers.bad_request(r"query parameter time should follow regex ^\d{1,2}:\d{1,2}$ and value should be "
r"between 00:00 and 23:59")


if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
3 changes: 3 additions & 0 deletions clock_angles/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Flask==1.1.2
pytest==5.3.2
google-cloud-datastore==1.12.0
43 changes: 43 additions & 0 deletions clock_angles/test/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from clock_angles import main
import json


def test_positive():
main.app.testing = True
client = main.app.test_client()

r = client.get("/clock_angles?time=13:0")
assert r.status_code == 200
response_json = json.loads(r.data.decode('utf-8'))
assert {'response': 30.0} == response_json


def test_negative_out_of_bounds():
main.app.testing = True
client = main.app.test_client()
r = client.get("/clock_angles?time=24:40")
assert r.status_code == 400
response_json = json.loads(r.data.decode('utf-8'))
assert_json = {
'response': {
'error': r'query parameter time should follow regex '
r'^\d{1,2}:\d{1,2}$ and value should be between 00:00 and 23:59'
}
}
assert assert_json == response_json


def test_negetive_invalid_input():
main.app.testing = True
client = main.app.test_client()
r = client.get("/clock_angles?time=2A:40")
assert r.status_code == 400
response_json = json.loads(r.data.decode('utf-8'))
assert_json = {
'response': {
'error': r'query parameter time should follow regex '
r'^\d{1,2}:\d{1,2}$ and value should be between 00:00 and 23:59'
}
}
assert assert_json == response_json

12 changes: 12 additions & 0 deletions cloudbuild.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
steps:
- name: 'docker.io/library/python:3.7'
id: Test
entrypoint: /bin/sh
args:
- -c
- 'pip3 install -r clock_angles/requirements.txt && export PYTHONPATH=`pwd`:`pwd`/clock_angles && pytest -v clock_angles/test/test.py'
- name: "gcr.io/cloud-builders/gcloud"
args: ["config", "list"]
- name: "gcr.io/cloud-builders/gcloud"
args: ["app", "deploy", "clock_angles/app.yaml"]
timeout: "1600s"