Skip to content

worker added - #2

Merged
mintesin merged 1 commit into
mainfrom
mybranch
Aug 3, 2025
Merged

mintesin merged 1 commit into
mainfrom
mybranch

Conversation

@mintesin

@mintesin mintesin commented Aug 3, 2025 •

Copy link
Copy Markdown
Owner

The logic of Hadoop and Spark connection and connection management is defined. Besides, there is some data serializer logic added.

Summary by Sourcery

Introduce core worker components for Spark and Hadoop integration, including data serialization, HDFS management, and computation workflows

New Features:

  • Add SparkManager for creating and stopping Spark sessions
  • Add HadoopManager to read from and write data to HDFS
  • Add DataSerializer to combine CSV inputs, convert to Parquet, and store on HDFS
  • Add Compute module to calculate column-wise averages from Parquet data and save results back to HDFS

Chores:

  • Include placeholder dataset and text files in worker directory

@sourcery-ai

sourcery-ai Bot commented Aug 3, 2025 •

Copy link
Copy Markdown

Reviewer's Guide

Introduced worker modules to handle data serialization, Spark session management, HDFS interactions, and compute pipelines: DataSerializer orchestrates CSV-to-parquet conversion and storage in HDFS, HadoopManager wraps HDFS read/write operations, SparkManager manages SparkSession lifecycle, and Compute performs average aggregation and writes results back to HDFS.

Sequence diagram for data serialization and storage to HDFS

sequenceDiagram
    participant User
    participant DataSerializer
    participant SparkManager
    participant HadoopManager
    User->>DataSerializer: read_data_to_hdfs()
    DataSerializer->>SparkManager: create_spark_session()
    DataSerializer->>SparkManager: read CSV(s)
    DataSerializer->>DataSerializer: combine DataFrames
    DataSerializer->>DataSerializer: serialize_to_parquet(combined_data)
    DataSerializer->>HadoopManager: save_as_hdfs(parquet_data)
    HadoopManager->>HadoopManager: write_to_hdfs()
    HadoopManager->>HDFS: upload parquet file
Loading

Sequence diagram for compute average and write result to HDFS

sequenceDiagram
    participant User
    participant Compute
    participant SparkManager
    participant HadoopManager
    User->>Compute: compute_average()
    Compute->>SparkManager: create_spark_session()
    Compute->>SparkManager: read parquet from HDFS
    Compute->>Compute: aggregate (average) numeric columns
    Compute->>HadoopManager: write_to_hdfs(means, DATA_OUTPUT_PATH)
    HadoopManager->>HDFS: upload result
Loading

Class diagram for new worker modules (DataSerializer, HadoopManager, SparkManager, Compute)

classDiagram
    class DataSerializer {
        - data_paths: list
        - combined_data
        - spark
        + __init__(data_paths: list)
        + read_data_to_hdfs() DataFrame
        + serialize_to_parquet(data: str)
        + save_as_hdfs(data)
    }
    class HadoopManager {
        - hadoop_client
        - spark
        + __init__()
        + write_to_hdfs()
        + read_from_hdfs()
    }
    class SparkManager {
        - NAME_MASTER_NODE: str
        - APP_NAME: str
        + __init__(NAME_MASTER_NODE: str, APP_NAME: str)
        + create_spark_session() object
        + stop_spark_session()
    }
    class Compute {
        - DATA_PATH: str
        - DATA_OUTPUT_PATH
        - spark
        + __init__(DATA_PATH: str)
        + compute_average()
    }
    DataSerializer --> SparkManager : uses
    DataSerializer --> HadoopManager : uses
    HadoopManager --> SparkManager : uses
    Compute --> SparkManager : uses
    Compute --> HadoopManager : uses
Loading

File-Level Changes

Change Details Files
DataSerializer workflow added
  • Initialize Spark session and combine CSV files
  • Serialize combined data to Parquet in a temporary directory
  • Reload Parquet data and invoke HDFS write
worker/DataSerializer.py
HadoopManager for HDFS connectivity
  • Configured HDFS URL via environment variables
  • Instantiated InsecureClient for uploads
  • Stubbed write_to_hdfs and read_from_hdfs with error handling
worker/HadoopManager.py
SparkManager session lifecycle
  • Builder for SparkSession with master/app settings
  • create_spark_session method with exception handling
  • stop_spark_session to terminate active session
worker/SparkManager.py
Compute module for aggregation
  • Read Parquet data and identify numeric columns
  • Compute column averages and serialize to JSON
  • Write aggregated results back to HDFS via HadoopManager
worker/Compute.py
Placeholder resource files added
  • Added sample CSV dataset
  • Added placeholder text file
worker/Car_dataset_three - Sheet4.csv
worker/try.txt

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@mintesin
mintesin merged commit 75311fa into main Aug 3, 2025

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey @mintesin - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Missing 'path' parameter in 'write_to_hdfs' method. (link)
  • Undefined attribute 'HADOOP_OUTPUT_PATH' in 'read_from_hdfs'. (link)
  • DATA_OUTPUT_PATH is used but not defined or passed to init. (link)
  • Reference to undefined variable 'df' and incorrect attribute 'Schema'. (link)
  • Typo in method name: 'alais' should be 'alias'. (link)
  • Incorrect dictionary comprehension syntax for 'means'. (link)
  • Incorrect usage of 'write_to_hdfs' as a class method. (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `worker/DataSerializer.py:35` </location>
<code_context>
+            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):
+        try:
+            if self.combined_data is not None:
</code_context>

<issue_to_address>
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:

```python
    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:
```python
from pyspark.sql import DataFrame
```
</issue_to_address>

### Comment 2
<location> `worker/DataSerializer.py:41` </location>
<code_context>
+                with tempfile.TemporaryDirectory() as tempdir:
+                    print(f"Writing to temp path: {tempdir}")
+                    data.write.mode('overwrite').parquet(tempdir) 
+                    parquet_data = self.spark.parquet(tempdir)
+                    self.save_as_hdfs(parquet_data)
+                    
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 3
<location> `worker/HadoopManager.py:32` </location>
<code_context>
+        self.spark = SparkManager.create_spark_session()
+    
+    # writing temporarly saved parquet data to hadoop
+    def write_to_hdfs(self):
+        try:
+            parquet_data = self.spark.read.parquet(path)
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 4
<location> `worker/HadoopManager.py:43` </location>
<code_context>
+    #reading parquet data from hadoop  
+    def read_from_hdfs(self):
+        try:
+            data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH)
+            return data 
+        except Exception as e:
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 5
<location> `worker/Compute.py:14` </location>
<code_context>
+import json, pathlib
+
+class Compute:
+    def __init__(self,DATA_PATH:str):
+        self.DATA_PATH = DATA_PATH
+        self.DATA_OUTPUT_PATH = DATA_OUTPUT_PATH
+        self.spark = SparkManager.create_spark_session()
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 6
<location> `worker/Compute.py:23` </location>
<code_context>
+        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 
+                                if f.dataType.typeName() in  {"double", "float", "long", "integer"}
+                                ]
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 7
<location> `worker/Compute.py:26` </location>
<code_context>
+                numeric_cols = [f.name for f in df.Schema.fields 
+                                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() 
+                means = {c:float(aggregate_row[c] for c in numeric_cols)} 
+                json_data = json.dumps(means)
</code_context>

<issue_to_address>
Typo in method name: 'alais' should be 'alias'.

Using 'alais' instead of 'alias' will result in an AttributeError at runtime.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                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() 
>>>>>>> REPLACE

</suggested_fix>

### Comment 8
<location> `worker/Compute.py:27` </location>
<code_context>
+                                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() 
+                means = {c:float(aggregate_row[c] for c in numeric_cols)} 
+                json_data = json.dumps(means)
+                HadoopManager.write_to_hdfs(means, self.DATA_OUTPUT_PATH) 
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 9
<location> `worker/Compute.py:29` </location>
<code_context>
+                aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first() 
+                means = {c:float(aggregate_row[c] for c in numeric_cols)} 
+                json_data = json.dumps(means)
+                HadoopManager.write_to_hdfs(means, self.DATA_OUTPUT_PATH) 
+                print(f"Data aggreagtion has been successfully done and saved to {self.DATA_OUTPUT_PATH}")
+            else:
</code_context>

<issue_to_address>
Incorrect usage of 'write_to_hdfs' as a class method.

Instantiate HadoopManager and call 'write_to_hdfs' on the instance instead of the class.
</issue_to_address>

### Comment 10
<location> `worker/SparkManager.py:11` </location>
<code_context>
+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'
+    # Creating spark session with master node names as bigdataproject
+    def create_spark_session(self)-> object:
</code_context>

<issue_to_address>
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.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    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
>>>>>>> REPLACE

</suggested_fix>

### Comment 11
<location> `worker/SparkManager.py:31` </location>
<code_context>
+    # Stopping the session whith master named as "bigdataproject"
+    def stop_spark_session(self):
+        try:
+            current_spark_session = SparkSession.active()
+        except Exception as e:
+            print(f"There is no active session running with app name {self.APP_NAME}",e)
</code_context>

<issue_to_address>
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.
</issue_to_address>

### Comment 12
<location> `worker/HadoopManager.py:26` </location>
<code_context>
+
+from SparkManager import SparkManager
+
+class HadoopManager:
+    def __init__(self):
+        self.hadoop_client = InsecureClient(hdfs_url,user="root")
</code_context>

<issue_to_address>
Consider refactoring HadoopManager to separate concerns, use explicit method parameters, and inject dependencies via the constructor.

```python
# 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.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread worker/DataSerializer.py
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

Comment thread worker/DataSerializer.py
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.

Comment thread worker/HadoopManager.py
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.

Comment thread worker/HadoopManager.py
#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.

Comment thread worker/Compute.py
Comment on lines +14 to +15
def __init__(self,DATA_PATH:str):
self.DATA_PATH = DATA_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): 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.

Comment thread worker/HadoopManager.py

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.

Comment thread worker/Compute.py
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 (code-quality): We've found these issues:

Comment thread worker/DataSerializer.py
Comment on lines +26 to +29
if i == 0:
self.combined_data = df
else:
self.combined_data = self.combined_data.unionByName(df)

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)

Comment thread worker/DataSerializer.py
Comment on lines +43 to +45

else:
pass

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

Comment thread worker/HadoopManager.py
Comment on lines +43 to +44
data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH)
return data

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant