forked from bahrmichael/aws-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
135 lines (123 loc) · 4.85 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
from flask import Flask, request
from sns_client import publish_sns
from model import cron_table, table
from boto3.dynamodb.conditions import Key
from croniter import croniter
import os
import json
app = Flask(__name__)
@app.route("/api/schedule", methods=['POST'])
def scheduleTask():
event = request.get_json(force=True)
validationRes = validateEvent(event)
if len(validationRes) > 0:
return validationRes, 400
identifier = f"{event['application']}-{event['eventIdentifier']}"
items = cron_table.query(
KeyConditionExpression=Key('pk').eq(identifier)
).get('Items', [])
if ('cronExpression' in event and len(items) == 0) or 'date' in event:
try:
publish_sns(os.environ.get('TOPIC_URL'), json.dumps(event))
return "Event successfully created", 201
except Exception as e:
print(f"Failed to create event")
return "Event cannot be created.", 400
else:
return "Event already exist. You need to update it.", 400
@app.route("/api/schedule", methods=['GET'])
def getTask():
args = request.args
print(args)
app = ""
eid = ""
if "application" in args:
app = args["application"]
if "eventIdentifier" in args:
eid = args.get("eventIdentifier")
if app == "" or eid == "":
return "application and eventIdentifier are required as query string parameters.", 400
else:
identifier = f"{app}-{eid}"
items = cron_table.query(
KeyConditionExpression=Key('pk').eq(identifier),
ProjectionExpression='#d, target, #u, eventIdentifier, application, failure_topic, payload, start_date, end_date, cronExpression, last_date',
ExpressionAttributeNames={'#d': 'date', '#u': 'user'}
).get('Items', [])
date_items = table.query(
IndexName='appEventIndex',
KeyConditionExpression=Key('application').eq(
app) & Key('eventIdentifier').eq(eid),
ProjectionExpression='#d, target, eventIdentifier, application, failure_topic, payload',
ExpressionAttributeNames={'#d': 'date'}
).get('Items', [])
if len(items) == 0 and len(date_items) > 0:
items = date_items
elif len(date_items) > 0:
for item in date_items:
items.append(item)
print(items)
if len(items) == 0:
return "No such event exist.", 400
else:
return {"Count": len(items), "Items": json.loads(json.dumps(items))}, 200
@app.route("/api/schedule/<app>/<id>", methods=['PUT'])
def updateTask(app, id):
args = request.view_args['app']
event = request.get_json(force=True)
validationRes = validateEvent(event)
if len(validationRes) > 0:
return validationRes, 400
try:
publish_sns(os.environ.get('TOPIC_URL'), json.dumps(event))
return "Event updated successfully", 200
except Exception as e:
print(f"Failed to update event")
return "Event cannot be created.", 400
@app.route("/api/schedule/<app>/<id>", methods=['DELETE'])
def deleteTask(app, id):
cron_table.delete_item(
Key={
'pk': f"{app}-{id}",
},
)
date_items = table.query(
IndexName='appEventIndex',
KeyConditionExpression=Key('application').eq(app) & Key('eventIdentifier').eq(id),
ProjectionExpression='application, eventIdentifier, pk, sk'
).get('Items', [])
for item in date_items:
print(item)
table.delete_item(
Key={
'pk': item['pk'],
'sk': item['sk']
},
)
return "Date and cron events deleted successfully.", 200
def validateEvent(event):
if 'cronExpression' in event:
# if 'start_date' not in event:
# print('error.start_date %s' %
# (json.dumps({'event': event})))
# return "start_date is required."
if not(croniter.is_valid(event['cronExpression'])):
print('error.event_id_app_required %s' %
(json.dumps({'event': event})))
return "cron expression is not valid"
if ('eventIdentifier' not in event or 'application' not in event):
print('error.event_id_app_required %s' %
(json.dumps({'event': event})))
return "eventIdentifier and application is required."
if 'date' not in event and 'cronExpression' not in event:
print('error.date_required %s' % (json.dumps({'event': event})))
return "date or cronExpression is required."
if 'payload' not in event:
print('error.payload_required %s' %
(json.dumps({'event': event})))
return "payload is required."
if 'target' not in event:
print('error.target_required %s' %
(json.dumps({'event': event})))
return "target is required."
return ""