-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
71 lines (60 loc) · 2.31 KB
/
main.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
import findspark
findspark.init() # Initializing Spark
from pyspark.sql import SparkSession
import datetime as dt
import time
from lib.collecting import fetch_sensors_data
from lib.processing import computeAQI
from lib.storing import keepOnlyUpdatedRows, writeToTimestream
if __name__ == "__main__":
# Define the Timestream database and table names
DATABASE_NAME = "iot_project"
TABLE_NAME = "iot_table"
# Initializing Spark Session
sparkSession = (
SparkSession.builder.appName("Cloud Computing Project")
.master("local[*]")
.config("spark.sql.inMemoryColumnarStorage.compressed", "true")
.config("spark.sql.inMemoryColumnarStorage.batchSize", "10000")
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.config("spark.ui.enabled", "true")
.config("spark.io.compression.codec", "snappy")
.config("spark.rdd.compress", "true")
.getOrCreate()
)
while True:
try:
print(
dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ " Starting the pipeline..."
)
# Fetch the data from the sensors
iotDfRaw = fetch_sensors_data(sparkSession)
# Compute the AQI for each sensor
iotDfFormatted = computeAQI(iotDfRaw)
# Filter the data to keep only the updated rows
dataFiltered = keepOnlyUpdatedRows(
DATABASE_NAME, TABLE_NAME, iotDfFormatted
)
# Write the data to Timestream
print(
dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ " 4. Writing the data to Timestream..."
)
dataFiltered.foreachPartition(
lambda partition: writeToTimestream(
DATABASE_NAME, TABLE_NAME, partition
)
)
print(
dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ " Done writing the data to Timestream.\n"
)
# Sleep for 10 seconds
print(
dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ " Done with the pipeline. Waiting for 10 seconds.\n"
)
time.sleep(10)
except Exception as e:
print(f"Exception: {e}")