bedger 0.0.5__tar.gz → 0.0.6__tar.gz

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-0.0.6/PKG-INFO ADDED
@@ -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,41 @@
1
+ [tool.poetry]
2
+ name = "bedger"
3
+ version = "0.0.6"
4
+ description = ""
5
+ authors = ["Henk van den Brink"]
6
+ readme = "README.md"
7
+ packages = [{include = "bedger", from = "src"}]
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "^3.8.1,<=4.0.0"
11
+
12
+ [tool.isort]
13
+ profile = "black"
14
+ line_length = 130
15
+
16
+ [tool.flake8]
17
+ max-line-length = 130
18
+ exclude = [
19
+ ".git",
20
+ "__pycache__",
21
+ ".venv"
22
+ ]
23
+
24
+ [tool.black]
25
+ line-length = 130
26
+ target-version = ['py310', 'py311']
27
+ exclude = '''
28
+ /(
29
+ \.git
30
+ | \.venv
31
+ | \.hg
32
+ | \.mypy_cache
33
+ | \.tox
34
+ | \.venv
35
+ | _build
36
+ | buck-out
37
+ | build
38
+ | dist
39
+ | node_modules
40
+ )/
41
+ '''
File without changes
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import socket
5
+ from .config import Config
6
+ from . import entities
7
+ import logging
8
+
9
+
10
+ logger = logging.getLogger("bedger.edge.connection")
11
+
12
+
13
+ class BedgerConnection:
14
+ def __init__(self, config: Config = Config()):
15
+ self._config = config
16
+
17
+ self._socket = None
18
+
19
+ def __enter__(self) -> BedgerConnection:
20
+ self._connect()
21
+ return self
22
+
23
+ def _connect(self) -> None:
24
+ logger.info(f"Connecting to socket at {self._config.socket_path}")
25
+ try:
26
+ self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
27
+ self._socket.connect(self._config.socket_path)
28
+ logger.info("Connected to socket")
29
+ except Exception as e:
30
+ logger.error(f"Error connecting to socket: {e}")
31
+ raise e
32
+
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
+ )
42
+
43
+ try:
44
+ logger.debug("Sending message")
45
+ self._socket.sendall(json.dumps(message).encode())
46
+
47
+ ack = self._socket.recv(1024)
48
+ logger.info(f"Received acknowledgment: {ack.decode()}")
49
+ except Exception as 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):
@@ -7,4 +7,3 @@ class Severity(str, Enum):
7
7
  MEDIUM = "MEDIUM"
8
8
  HIGH = "HIGH"
9
9
  CRITICAL = "CRITICAL"
10
- INFO = "INFO"
File without changes
bedger-0.0.5/PKG-INFO DELETED
@@ -1,105 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: bedger
3
- Version: 0.0.5
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
-
bedger-0.0.5/README.md DELETED
@@ -1,85 +0,0 @@
1
- # ConnectionManager Class Documentation
2
-
3
- The `ConnectionManager` class manages connections to a UNIX socket for sending and receiving messages.
4
- It provides context management capabilities to ensure connections are properly opened and closed.
5
-
6
- ## Features
7
- - Context manager support for connection lifecycle management.
8
- - Error handling for socket-related issues.
9
- - Sends event messages with acknowledgment handling.
10
-
11
- ## Installation
12
- Ensure you have the `bedger` package and its dependencies installed.
13
-
14
- ```bash
15
- pip install bedger
16
- ```
17
-
18
- ## Usage
19
- The following example demonstrates how to use the `ConnectionManager` to send events:
20
-
21
- ```python
22
- import time
23
- import bedger.edge.config as config
24
- import bedger.edge.connection as connection
25
- import bedger.edge.entities as entities
26
-
27
- if __name__ == "__main__":
28
- events = [
29
- {"event_type": "EventA", "severity": entities.Severity.HIGH, "payload": {"key": "value1"}},
30
- {"event_type": "EventB", "severity": entities.Severity.LOW, "payload": {"key": "value2"}},
31
- {"event_type": "EventC", "severity": entities.Severity.CRITICAL, "payload": {"key": "value3"}},
32
- ]
33
-
34
- with connection.ConnectionManager(config.Config()) as conn:
35
- for event in events:
36
- time.sleep(1)
37
- conn.send_event(event["event_type"], event["severity"], event["payload"])
38
- ```
39
-
40
- ## API Reference
41
-
42
- ### `ConnectionManager`
43
- Manages a connection to a UNIX socket for sending and receiving messages.
44
-
45
- #### Constructor
46
- - **`__init__(config: Config = Config())`**
47
- - Initializes the `ConnectionManager` with a specified configuration.
48
- - **Parameters:**
49
- - `config (Config)`: The configuration containing the socket path. Defaults to a new `Config` instance.
50
-
51
- #### Context Management
52
- - **`__enter__() -> ConnectionManager`**
53
- - Establishes the socket connection when entering the context.
54
- - **Returns:** The instance of the `ConnectionManager`.
55
-
56
- - **`__exit__(exc_type, exc_value, traceback) -> None`**
57
- - Closes the socket connection when exiting the context.
58
-
59
- #### Methods
60
- - **`send_event(event_type: str, severity: str | Severity, payload: dict) -> None`**
61
- - Sends an event message through the socket.
62
- - **Parameters:**
63
- - `event_type (str)`: The type of event being sent.
64
- - `severity (str | Severity)`: The severity level of the event.
65
- - `payload (dict)`: The event's payload details.
66
- - **Raises:**
67
- - `SocketNotConnectedError`: If no active socket connection exists.
68
- - `SocketBrokenPipeError`: If the socket connection is lost during transmission.
69
- - `SocketCommunicationError`: If an error occurs during socket communication.
70
-
71
- ## Error Handling
72
- The `ConnectionManager` raises custom errors from the `bedger.edge.errors` module for:
73
- - Permission issues (`SocketPermissionDeniedError`).
74
- - Missing socket files (`SocketFileNotFoundError`).
75
- - Connection problems (`SocketConnectionError`).
76
- - Communication errors (`SocketCommunicationError`, `SocketBrokenPipeError`).
77
-
78
- ## Logging
79
- The class uses the `logging` module to log the following:
80
- - Connection attempts and successes.
81
- - Errors during connection, disconnection, and message sending.
82
- - Debug information for message preparation and acknowledgments.
83
-
84
- ## License
85
- This project is licensed under the MIT License. See the LICENSE file for details.
@@ -1,51 +0,0 @@
1
- [tool.poetry]
2
- name = "bedger"
3
- version = "0.0.5"
4
- description = "Edge monitoring software for secure and efficient device management."
5
- authors = ["Henk van den Brink <henk.vandenbrink@bedger.io>"]
6
- readme = "README.md"
7
- packages = [{include = "bedger", from = "src"}]
8
-
9
- [tool.poetry.urls]
10
- homepage = "https://github.com/bedger-io/BEDGER-edgeservices-securitymonitoring-sdk"
11
- issues = "https://github.com/bedger-io/BEDGER-edgeservices-securitymonitoring-sdk/issues"
12
-
13
- [tool.poetry.dependencies]
14
- python = "^3.8.1,<=4.0.0"
15
- typing-extensions = "^4.12.2"
16
- pydantic = "^2.9.2"
17
-
18
- [tool.poetry.group.dev.dependencies]
19
- black = "^24.4.0"
20
- isort = "^5.13.2"
21
- flake8-pyproject = "^1.2.3"
22
-
23
- [build-system]
24
- requires = ["poetry>=1.6"]
25
- build-backend = "poetry.core.masonry.api"
26
-
27
- [tool.isort]
28
- profile = "black"
29
- line_length = 130
30
-
31
- [tool.flake8]
32
- max-line-length = 130
33
- exclude = [".git", "__pycache__", ".venv"]
34
-
35
- [tool.black]
36
- line-length = 130
37
- target-version = ["py310", "py311"]
38
- exclude = '''
39
- /(
40
- \.git
41
- | \.venv
42
- | \.hg
43
- | \.mypy_cache
44
- | \.tox
45
- | _build
46
- | buck-out
47
- | build
48
- | dist
49
- | node_modules
50
- )/
51
- '''
@@ -1,123 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- import socket
5
- from typing import Optional
6
-
7
- from bedger.edge import errors
8
- from bedger.edge.config import Config
9
- from bedger.edge.entities import Message, Severity
10
-
11
- logger = logging.getLogger("bedger.edge.connection")
12
-
13
-
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
-
25
- 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
- self._config = config
32
- self._socket: Optional[socket.socket] = None
33
-
34
- def __enter__(self) -> ConnectionManager:
35
- """Establishes the socket connection when entering the context.
36
-
37
- Returns:
38
- ConnectionManager: The instance of the ConnectionManager.
39
- """
40
- self._connect()
41
- return self
42
-
43
- def __exit__(self, exc_type, exc_value, traceback) -> None:
44
- """Closes the socket connection when exiting the context."""
45
- self._disconnect()
46
-
47
- 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}")
56
- try:
57
- self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
58
- 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?")
66
- 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.")
100
-
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}")
109
-
110
- logger.debug("Sending message")
111
- self._socket.sendall(message_json.encode())
112
-
113
- 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}")
121
- except Exception as e:
122
- logger.exception(f"Unexpected error while sending the message: {e}")
123
- raise errors.SocketCommunicationError(f"Unexpected error occurred: {e}")
@@ -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
File without changes
File without changes