bedger 0.0.4__py3-none-any.whl → 0.0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bedger might be problematic. Click here for more details.

bedger/edge/connection.py CHANGED
@@ -1,123 +1,65 @@
1
1
  from __future__ import annotations
2
2
 
3
- import logging
3
+ import json
4
4
  import socket
5
- from typing import Optional
5
+ from .config import Config
6
+ from . import entities
7
+ import logging
6
8
 
7
- from bedger.edge import errors
8
- from bedger.edge.config import Config
9
- from bedger.edge.entities import Message, Severity
10
9
 
11
10
  logger = logging.getLogger("bedger.edge.connection")
12
11
 
13
12
 
14
- class ConnectionManager:
15
- """Manages a connection to a UNIX socket for sending and receiving messages.
16
-
17
- This class provides context manager support for establishing and tearing
18
- down a connection to a UNIX socket.
19
-
20
- Attributes:
21
- _config (Config): The configuration containing the socket path.
22
- _socket (Optional[socket.socket]): The current socket connection.
23
- """
24
-
13
+ class BedgerConnection:
25
14
  def __init__(self, config: Config = Config()):
26
- """Initializes the ConnectionManager.
27
-
28
- Args:
29
- config (Config): Configuration for the connection. Defaults to a new `Config` instance.
30
- """
31
15
  self._config = config
32
- self._socket: Optional[socket.socket] = None
33
16
 
34
- def __enter__(self) -> ConnectionManager:
35
- """Establishes the socket connection when entering the context.
17
+ self._socket = None
36
18
 
37
- Returns:
38
- ConnectionManager: The instance of the ConnectionManager.
39
- """
19
+ def __enter__(self) -> BedgerConnection:
40
20
  self._connect()
41
21
  return self
42
22
 
43
- def __exit__(self, exc_type, exc_value, traceback) -> None:
44
- """Closes the socket connection when exiting the context."""
45
- self._disconnect()
46
-
47
23
  def _connect(self) -> None:
48
- """Establish a connection to the UNIX socket.
49
-
50
- Raises:
51
- errors.SocketPermissionDeniedError: If the application does not have permission to connect to the socket.
52
- errors.SocketFileNotFoundError: If the socket file is not found at the specified path.
53
- errors.SocketConnectionError: If any other error occurs during the connection attempt.
54
- """
55
- logger.info(f"Attempting to connect to socket at {self._config.socket_path}")
24
+ logger.info(f"Connecting to socket at {self._config.socket_path}")
56
25
  try:
57
26
  self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
58
27
  self._socket.connect(self._config.socket_path)
59
- logger.info("Successfully connected to the socket")
60
- except PermissionError:
61
- logger.error("Permission denied: Unable to connect to the socket. Ensure you have the correct permissions.")
62
- raise errors.SocketPermissionDeniedError("Permission denied to connect to socket. Are you running as root?")
63
- except FileNotFoundError:
64
- logger.error("Socket file not found. Verify the server is running and the socket path is correct.")
65
- raise errors.SocketFileNotFoundError("Socket file not found. Is the server running?")
28
+ logger.info("Connected to socket")
66
29
  except Exception as e:
67
- logger.exception(f"Unexpected error while connecting to the socket: {e}")
68
- raise errors.SocketConnectionError(f"An unexpected error occurred while connecting to the socket: {e}")
69
-
70
- def _disconnect(self) -> None:
71
- """Close the socket connection gracefully.
72
-
73
- Ensures the socket is closed and cleaned up properly, even in case of errors.
74
- """
75
- if self._socket:
76
- try:
77
- logger.info("Closing the socket connection")
78
- self._socket.close()
79
- except Exception as e:
80
- logger.warning(f"Error occurred while closing the socket: {e}")
81
- finally:
82
- self._socket = None
83
-
84
- def send_event(self, event_type: str, severity: str | Severity, payload: dict) -> None:
85
- """Send an event message through the socket.
86
-
87
- Args:
88
- event_type (str): The type of event being sent.
89
- severity (str | Severity): The severity level of the event.
90
- payload (dict): The event's payload details.
91
-
92
- Raises:
93
- errors.SocketNotConnectedError: If no active socket connection exists.
94
- errors.SocketBrokenPipeError: If the socket connection is lost during message transmission.
95
- errors.SocketCommunicationError: If any error occurs during socket communication.
96
- """
97
- if not self._socket:
98
- logger.error("Attempted to send a message without an active socket connection.")
99
- raise errors.SocketNotConnectedError("No active socket connection. Ensure the connection is established.")
30
+ logger.error(f"Error connecting to socket: {e}")
31
+ raise e
100
32
 
101
- try:
102
- message = Message(
103
- event_type=event_type,
104
- severity=severity,
105
- details=payload,
106
- )
107
- message_json = message.model_dump_json()
108
- logger.debug(f"Prepared message: {message_json}")
33
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
34
+ self._socket.close()
35
+
36
+ def send_event(self, event_type, severity, payload):
37
+ message = entities.Message(
38
+ event_type=event_type,
39
+ severity=severity,
40
+ details=payload,
41
+ )
109
42
 
43
+ try:
110
44
  logger.debug("Sending message")
111
- self._socket.sendall(message_json.encode())
45
+ self._socket.sendall(json.dumps(message).encode())
112
46
 
113
47
  ack = self._socket.recv(1024)
114
- logger.info(f"Received acknowledgment from server: {ack.decode()}")
115
- except BrokenPipeError:
116
- logger.error("Broken pipe error: The socket connection was lost during message transmission.")
117
- raise errors.SocketBrokenPipeError("Socket connection lost. Unable to send message.")
118
- except socket.error as e:
119
- logger.error(f"Socket error occurred: {e}")
120
- raise errors.SocketCommunicationError(f"Socket error during communication: {e}")
48
+ logger.info(f"Received acknowledgment: {ack.decode()}")
121
49
  except Exception as e:
122
- logger.exception(f"Unexpected error while sending the message: {e}")
123
- raise errors.SocketCommunicationError(f"Unexpected error occurred: {e}")
50
+ logger.error(f"Error sending message: {e}")
51
+ raise e
52
+
53
+
54
+ # Example usage
55
+ if __name__ == "__main__":
56
+ import time
57
+
58
+ connection = BedgerConnection()
59
+
60
+ with connection:
61
+ for i in range(5):
62
+ connection.send_event(
63
+ event_type="TestEvent", severity=entities.Severity.INFO, payload={"message": f"Test message {i}"}
64
+ )
65
+ time.sleep(1)
@@ -1,4 +1,5 @@
1
1
  from .message import Message
2
2
  from .severity import Severity
3
3
 
4
- __all__ = [Message, Severity]
4
+
5
+ __all__ = [Message, Severity]
@@ -1,10 +1,7 @@
1
- import json
2
- from typing import Dict
3
-
4
- from pydantic import BaseModel, Field, field_serializer, field_validator
5
- from typing_extensions import Annotated
6
-
1
+ from typing import Dict, Annotated
2
+ from pydantic import BaseModel, Field, field_validator, field_serializer
7
3
  from .severity import Severity
4
+ import json
8
5
 
9
6
 
10
7
  class Message(BaseModel):
bedger/edge/errors.py CHANGED
@@ -1,18 +0,0 @@
1
- class SocketPermissionDeniedError(Exception):
2
- pass
3
-
4
-
5
- class SocketFileNotFoundError(Exception):
6
- pass
7
-
8
-
9
- class SocketConnectionError(Exception):
10
- pass
11
-
12
-
13
- class SocketNotConnectedError(Exception):
14
- pass
15
-
16
-
17
- class SocketCommunicationError(Exception):
18
- pass
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.1
2
+ Name: bedger
3
+ Version: 0.0.6
4
+ Summary:
5
+ Author: Henk van den Brink
6
+ Requires-Python: >=3.8.1,<4.0.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.9
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Description-Content-Type: text/markdown
13
+
14
+
@@ -0,0 +1,12 @@
1
+ bedger/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ bedger/edge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ bedger/edge/config.py,sha256=0fUKThP0aJFk3WBF7JUtuKKhXlV07SX5VnqVOLNou-A,152
4
+ bedger/edge/connection.py,sha256=j5ICwK-kxsOUK-_HvWEF9iDYafoLfX3U01TNAnwj_dI,1792
5
+ bedger/edge/entities/__init__.py,sha256=8pu4RyMB-VfEPLiZPfLkS4j5p4cmHwFTsryYoBlb03k,91
6
+ bedger/edge/entities/message.py,sha256=VWJSadZe510Rggu7b1M8_E1qFzmcKatSwHN-SZgXYVg,882
7
+ bedger/edge/entities/severity.py,sha256=tUN7eDSEN5cc5eAqhvKzVHD1pSEmrdwvNEGsmh4Pnfw,157
8
+ bedger/edge/errors.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ bedger-0.0.6.dist-info/LICENSE,sha256=lVrf6pfElYZ_o6ETq-XR91_7GHTzKGyeNWAKghvcNUE,1075
10
+ bedger-0.0.6.dist-info/METADATA,sha256=kbJkOoIQSrf0HkK8SH-iPpIG5ZlGAz-cgrnVF9INKHM,412
11
+ bedger-0.0.6.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
12
+ bedger-0.0.6.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.9.1
2
+ Generator: poetry-core 1.9.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,105 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: bedger
3
- Version: 0.0.4
4
- Summary: Edge monitoring software for secure and efficient device management.
5
- Author: Henk van den Brink
6
- Author-email: henk.vandenbrink@bedger.io
7
- Requires-Python: >=3.8.1,<4.0.0
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.9
10
- Classifier: Programming Language :: Python :: 3.10
11
- Classifier: Programming Language :: Python :: 3.11
12
- Classifier: Programming Language :: Python :: 3.12
13
- Classifier: Programming Language :: Python :: 3.13
14
- Requires-Dist: pydantic (>=2.9.2,<3.0.0)
15
- Requires-Dist: typing-extensions (>=4.12.2,<5.0.0)
16
- Project-URL: homepage, https://github.com/bedger-io/BEDGER-edgeservices-securitymonitoring-sdk
17
- Project-URL: issues, https://github.com/bedger-io/BEDGER-edgeservices-securitymonitoring-sdk/issues
18
- Description-Content-Type: text/markdown
19
-
20
- # ConnectionManager Class Documentation
21
-
22
- The `ConnectionManager` class manages connections to a UNIX socket for sending and receiving messages.
23
- It provides context management capabilities to ensure connections are properly opened and closed.
24
-
25
- ## Features
26
- - Context manager support for connection lifecycle management.
27
- - Error handling for socket-related issues.
28
- - Sends event messages with acknowledgment handling.
29
-
30
- ## Installation
31
- Ensure you have the `bedger` package and its dependencies installed.
32
-
33
- ```bash
34
- pip install bedger
35
- ```
36
-
37
- ## Usage
38
- The following example demonstrates how to use the `ConnectionManager` to send events:
39
-
40
- ```python
41
- import time
42
- import bedger.edge.config as config
43
- import bedger.edge.connection as connection
44
- import bedger.edge.entities as entities
45
-
46
- if __name__ == "__main__":
47
- events = [
48
- {"event_type": "EventA", "severity": entities.Severity.HIGH, "payload": {"key": "value1"}},
49
- {"event_type": "EventB", "severity": entities.Severity.LOW, "payload": {"key": "value2"}},
50
- {"event_type": "EventC", "severity": entities.Severity.CRITICAL, "payload": {"key": "value3"}},
51
- ]
52
-
53
- with connection.ConnectionManager(config.Config()) as conn:
54
- for event in events:
55
- time.sleep(1)
56
- conn.send_event(event["event_type"], event["severity"], event["payload"])
57
- ```
58
-
59
- ## API Reference
60
-
61
- ### `ConnectionManager`
62
- Manages a connection to a UNIX socket for sending and receiving messages.
63
-
64
- #### Constructor
65
- - **`__init__(config: Config = Config())`**
66
- - Initializes the `ConnectionManager` with a specified configuration.
67
- - **Parameters:**
68
- - `config (Config)`: The configuration containing the socket path. Defaults to a new `Config` instance.
69
-
70
- #### Context Management
71
- - **`__enter__() -> ConnectionManager`**
72
- - Establishes the socket connection when entering the context.
73
- - **Returns:** The instance of the `ConnectionManager`.
74
-
75
- - **`__exit__(exc_type, exc_value, traceback) -> None`**
76
- - Closes the socket connection when exiting the context.
77
-
78
- #### Methods
79
- - **`send_event(event_type: str, severity: str | Severity, payload: dict) -> None`**
80
- - Sends an event message through the socket.
81
- - **Parameters:**
82
- - `event_type (str)`: The type of event being sent.
83
- - `severity (str | Severity)`: The severity level of the event.
84
- - `payload (dict)`: The event's payload details.
85
- - **Raises:**
86
- - `SocketNotConnectedError`: If no active socket connection exists.
87
- - `SocketBrokenPipeError`: If the socket connection is lost during transmission.
88
- - `SocketCommunicationError`: If an error occurs during socket communication.
89
-
90
- ## Error Handling
91
- The `ConnectionManager` raises custom errors from the `bedger.edge.errors` module for:
92
- - Permission issues (`SocketPermissionDeniedError`).
93
- - Missing socket files (`SocketFileNotFoundError`).
94
- - Connection problems (`SocketConnectionError`).
95
- - Communication errors (`SocketCommunicationError`, `SocketBrokenPipeError`).
96
-
97
- ## Logging
98
- The class uses the `logging` module to log the following:
99
- - Connection attempts and successes.
100
- - Errors during connection, disconnection, and message sending.
101
- - Debug information for message preparation and acknowledgments.
102
-
103
- ## License
104
- This project is licensed under the MIT License. See the LICENSE file for details.
105
-
@@ -1,12 +0,0 @@
1
- bedger/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- bedger/edge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- bedger/edge/config.py,sha256=0fUKThP0aJFk3WBF7JUtuKKhXlV07SX5VnqVOLNou-A,152
4
- bedger/edge/connection.py,sha256=25h7PzRhSw8m0w679p23M6X_o-wuIOl7M1P837bpy9I,5400
5
- bedger/edge/entities/__init__.py,sha256=_oKO_XdDerqOwVX8izhDPtGv4HqVDwQaT-otOdY8lYg,91
6
- bedger/edge/entities/message.py,sha256=wLbEZik_FBboyEAvX5Uvlto1t4BsjaeLXUFGOIjIHRU,913
7
- bedger/edge/entities/severity.py,sha256=tUN7eDSEN5cc5eAqhvKzVHD1pSEmrdwvNEGsmh4Pnfw,157
8
- bedger/edge/errors.py,sha256=6jdmhlKoWlD-kZ8-xRiAlObRHEo9PwrKqhWQ5su5TLk,266
9
- bedger-0.0.4.dist-info/LICENSE,sha256=lVrf6pfElYZ_o6ETq-XR91_7GHTzKGyeNWAKghvcNUE,1075
10
- bedger-0.0.4.dist-info/METADATA,sha256=4-TQzz5tqRT_YWfbDh3Zo7BK8vR-bRzcCtvFb2mgHt4,4144
11
- bedger-0.0.4.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
12
- bedger-0.0.4.dist-info/RECORD,,