Skip to content
Merged
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
29 changes: 29 additions & 0 deletions worker/Car_dataset_three - Sheet4.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Car_ID,mileage(MPG)-max,top_spped-kph_max,accele(0-100kph)-max,price(USD)
1,30,20,6.5,8000
2,27,130,7,90562
3,26,110,7.5,80000
4,27,150,6.5,11500
5,30,180,5.5,103120
6,28,140,6.5,95625
7,32,125,6,98256
8,30,150,7.5,110500
9,27,120,7,88500
10,30,140,6.5,102652
11,33,150,6,105000
12,28,130,5,120526
13,27,120,5.5,115356
14,27,130,6.5,121489
15,26,140,7.5,134567
16,29,150,6.5,150000
17,30,160,5.5,145000
18,30,140,6.5,152000
19,30,100,7.5,100000
20,27,120,6.5,"90,000"
21,29,110,5.5,154654
22,33,130,5.5,145623
23,33,150,6.5,123540
24,32,180,6.5,153211
25,25,180,6,124321
26,25,150,6,98235
27,24,120,6.5,97324
28,26,110,5.5,99235
36 changes: 36 additions & 0 deletions worker/Compute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""
-This module reads data from hadoop cluster
-This process it go through the lines and
-cancluate the average
-and save it ot hadoop again

"""

from SparkManager import SparkManager
from HadoopManager import HadoopManager
import json, pathlib

class Compute:
def __init__(self,DATA_PATH:str):
self.DATA_PATH = DATA_PATH
Comment on lines +14 to +15

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): DATA_OUTPUT_PATH is used but not defined or passed to init.

'DATA_OUTPUT_PATH' is not defined or passed to 'init', which will cause a NameError. Please add it as a parameter to the constructor.

self.DATA_OUTPUT_PATH = DATA_OUTPUT_PATH
self.spark = SparkManager.create_spark_session()

def compute_average(self):
try:
data_frame = self.spark.read.parquet(self.DATA_PATH)
if data_frame is not None:
numeric_cols = [f.name for f in df.Schema.fields

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Reference to undefined variable 'df' and incorrect attribute 'Schema'.

Use 'data_frame.schema.fields' instead of 'df.Schema.fields' to reference the correct variable and attribute.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): We've found these issues:

if f.dataType.typeName() in {"double", "float", "long", "integer"}
]
aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (typo): Typo in method name: 'alais' should be 'alias'.

Using 'alais' instead of 'alias' will result in an AttributeError at runtime.

Suggested change
aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first()
aggregate_row = data_frame.agg(*[F.avg(c).alias(c) for c in numeric_cols]).first()

means = {c:float(aggregate_row[c] for c in numeric_cols)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Incorrect dictionary comprehension syntax for 'means'.

The current syntax will cause a SyntaxError. Use '{c: float(aggregate_row[c]) for c in numeric_cols}' instead.

json_data = json.dumps(means)
HadoopManager.write_to_hdfs(means, self.DATA_OUTPUT_PATH)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Incorrect usage of 'write_to_hdfs' as a class method.

Instantiate HadoopManager and call 'write_to_hdfs' on the instance instead of the class.

print(f"Data aggreagtion has been successfully done and saved to {self.DATA_OUTPUT_PATH}")
else:
print(f"Data aggreagation in the average format has failed ")
except Exception as e:
print(f"Data computation has failed.")


Empty file added worker/DataSaveExtract.py
Empty file.
56 changes: 56 additions & 0 deletions worker/DataSerializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""
This class is for active data serializer.
It converts csv data to the parquet.
Save it to hadoop
Read from hadoop
"""

from SparkManager import SparkManager
from pyspark.sql import DataFrame
from HadoopManager import HadoopManager
import tempfile

data_path= ["Data/half1_BTCUSDT_1s.csv","Data/half2_BTCUSDT_1s.csv"]

class DataSerializer:
def __init__(self,data_paths: list):
self.data_paths=data_paths
self.combined_data = None
self.spark = SparkManager.create_spark_session()

# Reading all csv data anc ombine them
def read_data_to_hdfs(self)->DataFrame:
try:
for i,path in enumerate(self.data_paths):
df = self.spark.read.option("header",True).csv(path)
if i == 0:
self.combined_data = df
else:
self.combined_data = self.combined_data.unionByName(df)
Comment on lines +26 to +29

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Replace if statement with if expression (assign-if-exp)

self.serialize_to_parquet(self.combined_data)
except Exception as e:
print(f"There has been an error in reading and combining {self.combined_data}: {e}")

# Saving the data aas a paquet file and finally returning parquet temporary file
def serialize_to_parquet(self, data: str):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The 'data' parameter type should be DataFrame, not str.

Update the type annotation to 'DataFrame' to match the expected input and avoid confusion.

Suggested implementation:

    def serialize_to_parquet(self, data: DataFrame):

You may need to import DataFrame at the top of your file if it is not already imported:

from pyspark.sql import DataFrame

try:
if self.combined_data is not None:
with tempfile.TemporaryDirectory() as tempdir:
print(f"Writing to temp path: {tempdir}")
data.write.mode('overwrite').parquet(tempdir)
parquet_data = self.spark.parquet(tempdir)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Incorrect method usage: 'self.spark.parquet' is not a valid SparkSession method.

Use 'self.spark.read.parquet(tempdir)' instead to read the Parquet file; the current code will raise an AttributeError.

self.save_as_hdfs(parquet_data)

else:
pass
Comment on lines +43 to +45

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Remove redundant pass statement (remove-redundant-pass)

Suggested change
else:
pass

except Exception as e:
print(f"There as an error in serializing the data: {e}")
#saving to hadoop is done here

# Saving to the hdfs
def save_as_hdfs(self,data):
if data is not None:
writer = HadoopManager().write_to_hdfs(data)
else:
print("There is no data saved to hadoop")

46 changes: 46 additions & 0 deletions worker/HadoopManager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""

This module is hadoop manager
- connects to hadoop manager
- write data to hadoop - hdfs
- read data from hadoop - hdfs

"""
import os
from hdfs import InsecureClient


hdfs_host = os.environ.get("HDFS_NAMENODE_HOST", "localhost")
hdfs_port = os.environ.get("HDFS_NAMENODE_PORT", "9870")

hdfs_url = f"http://{hdfs_host}:{hdfs_port}"

# print("Connecting to HDFS at:", hdfs_url)

# For example, using requests:



from SparkManager import SparkManager

class HadoopManager:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider refactoring HadoopManager to separate concerns, use explicit method parameters, and inject dependencies via the constructor.

# Split responsibilities & make interfaces explicit:
from hdfs import InsecureClient
from pyspark.sql import DataFrame, SparkSession

class HadoopManager:
    def __init__(self, spark: SparkSession, hdfs_url: str, user: str = "root"):
        self.spark = spark
        self.client = InsecureClient(hdfs_url, user=user)

    def write_dataframe(self, df: DataFrame, hdfs_path: str) -> None:
        """
        Persist a Spark DataFrame to HDFS via Spark’s native API.
        """
        df.write.mode("overwrite").parquet(hdfs_path)

    def read_dataframe(self, hdfs_path: str) -> DataFrame:
        """
        Load a Spark DataFrame from HDFS.
        """
        return self.spark.read.parquet(hdfs_path)

    def upload_file(self, local_path: str, hdfs_path: str) -> None:
        """
        Upload a single local file to HDFS via the hdfs client.
        """
        self.client.upload(hdfs_path, local_path)

Actionable steps:

  1. Remove parameterless write_to_hdfs / read_from_hdfs and undefined path / HADOOP_OUTPUT_PATH.
  2. Use write_dataframe(df, hdfs_path) and read_dataframe(hdfs_path) so callers supply both DataFrame and target path.
  3. If you really need raw-file upload, keep upload_file(local, hdfs) as a distinct method.
  4. Drop juggling Spark reads/writes with client uploads in one method – each method now does a single, well-scoped task.
  5. Inject SparkSession & hdfs_url via constructor to avoid globals and improve testability.

def __init__(self):
self.hadoop_client = InsecureClient(hdfs_url,user="root")
self.spark = SparkManager.create_spark_session()

# writing temporarly saved parquet data to hadoop
def write_to_hdfs(self):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Missing 'path' parameter in 'write_to_hdfs' method.

'path' is used in the method but is neither defined nor passed in, which will cause a NameError. Please add 'path' as a parameter to the method.

try:
parquet_data = self.spark.read.parquet(path)
self.hadoop_client.upload('/data','my local file text')
print("The data is saved to hadoop successfully")
except Exception as e:
print(f"Saving data to hadoop has failed: {e}" )

#reading parquet data from hadoop
def read_from_hdfs(self):
try:
data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Undefined attribute 'HADOOP_OUTPUT_PATH' in 'read_from_hdfs'.

Referencing 'self.HADOOP_OUTPUT_PATH' without defining it will raise an AttributeError. Please define this attribute or ensure it is set before use.

return data
Comment on lines +43 to +44

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH)
return data
return self.spark.read.parquet(self.HADOOP_OUTPUT_PATH)

except Exception as e:
print("reading data from hadoop has failed: {e}")
Empty file added worker/SparkConnection.py
Empty file.
36 changes: 36 additions & 0 deletions worker/SparkManager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""
This class is si for creating spark connection.
Returns spark connection
Parameters: Name of the master node


"""
from pyspark.sql import SparkSession

class SparkManager:
def __init__(self,NAME_MASTER_NODE: str, APP_NAME: str):
self.NAME_MASTER_NODE = 'bigdatamaster'
self.APP_NAME = 'bigdataproject'
Comment on lines +11 to +13

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Constructor parameters are ignored and hardcoded values are used.

The init method should use the provided parameters instead of hardcoded values to maintain flexibility and avoid redundancy.

Suggested change
def __init__(self,NAME_MASTER_NODE: str, APP_NAME: str):
self.NAME_MASTER_NODE = 'bigdatamaster'
self.APP_NAME = 'bigdataproject'
def __init__(self, NAME_MASTER_NODE: str, APP_NAME: str):
self.NAME_MASTER_NODE = NAME_MASTER_NODE
self.APP_NAME = APP_NAME

# Creating spark session with master node names as bigdataproject
def create_spark_session(self)-> object:
try:
spark =(SparkSession.builder
.master(self.NAME_MASTER_NODE)
.appName(self.APP_NAME)
.getOrCreate()
)
print(f"The session with master node {self.NAME_MASTER_NODE} and app name {self.APP_NAME} is created")
return spark

except:
print(f"Creating spark session with master name {self.NAME_MASTER_NODE} and app name {self.APP_NAME} has failed")
raise RuntimeError
# Stopping the session whith master named as "bigdataproject"
def stop_spark_session(self):
try:
current_spark_session = SparkSession.active()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Potential issue with stopping Spark session if none is active.

Ensure 'current_spark_session.stop()' is only called if a session exists to prevent exceptions.

except Exception as e:
print(f"There is no active session running with app name {self.APP_NAME}",e)
current_spark_session.stop()
print(f"The spark session on {self.NAME_MASTER_NODE} has stopped")

1 change: 1 addition & 0 deletions worker/try.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
this is hadoop storing file