forked from luksa/kubernetes-in-action-2nd-edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cj.aggregate-responses-daily.yaml
105 lines (97 loc) · 2.68 KB
/
cj.aggregate-responses-daily.yaml
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
apiVersion: batch/v1
kind: CronJob
metadata:
name: aggregate-responses-daily
spec:
schedule: "@daily"
jobTemplate:
metadata:
labels:
app: aggregate-responses-daily
spec:
template:
metadata:
labels:
app: aggregate-responses-daily
spec:
restartPolicy: OnFailure
containers:
- name: updater
image: mongo:5
command:
- mongosh
- mongodb+srv://quiz-pods.kiada.svc.cluster.local/kiada?tls=false
- --quiet
- --file
- /script.js
volumeMounts:
- name: script
subPath: script.js
mountPath: /script.js
volumes:
- name: script
configMap:
name: aggregate-responses-daily
---
apiVersion: v1
kind: ConfigMap
metadata:
name: aggregate-responses-daily
labels:
app: aggregate-responses-daily
data:
script.js: |
var dateTo = new Date();
dateTo.setHours(0,0,0,0);
var dateFrom = new Date(dateTo.getTime() - 24*3600*1000);
print("Processing quiz responses - yesterday");
print("=====================================");
print();
print("Query range:");
print(" From: " + dateFrom);
print(" To: " + dateTo);
print();
print("Results:")
var cursor = db.responses.aggregate(
{
$match: {
timestamp: { $gte: dateFrom, $lt: dateTo }
}
},
{
$group: {
_id: { $dateTrunc: { date: "$timestamp", unit: "day" } },
totalCount: { $sum: 1 },
correctCount: { $sum: { $cond: { if: "$correct", then: 1, else: 0 } } },
incorrectCount: { $sum: { $cond: { if: "$correct", then: 0, else: 1 } } },
}
}
);
var matched = 0;
var inserted = 0;
var updated = 0;
if (cursor.hasNext()) {
while (cursor.hasNext()) {
var result = cursor.next();
print(" " + JSON.stringify(result));
var writeResult = db.statistics.replaceOne(
{_id: result._id},
result,
{ upsert: true }
);
matched += writeResult.matchedCount;
inserted += writeResult.upsertedCount;
updated += writeResult.modifiedCount;
}
cursor.close();
print();
print("Matched: " + matched + "; Updated: " + updated + "; Inserted: " + inserted);
} else {
print(" No responses found.");
}
var sleepSeconds = Math.floor(30 + Math.random() * 30);
print();
print("Waiting " + sleepSeconds + "s to simulate long-running task.");
sleep(sleepSeconds * 1000);
print();
print("Done.");