Skip to content

Commit 8c048f4

Browse files
committed
Use a server URL to connect to the microgrid API
Instead of using host and port, we now use a URL. The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`, where the port should be an int between `0` and `65535` (defaulting to `9090`) and `ssl` should be a boolean (defaulting to `false`). For example: `grpc://localhost:1090?ssl=true`. This also removes the default host and port, as normally users always want to override it. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 59dd823 commit 8c048f4

File tree

13 files changed

+75
-81
lines changed

13 files changed

+75
-81
lines changed

RELEASE_NOTES.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@
1212

1313
- The `microgrid.*_pool` methods would only accept keyword arguments from now on.
1414

15+
- The `microgrid.initialize()` method now takes a `server_url` instead of a `host` and `port`.
16+
17+
The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`, where the port should be an int between `0` and `65535` (defaulting to `9090`) and `ssl` should be a boolean (defaulting to `false`). For example: `grpc://localhost` or `grpc://localhost:1090?ssl=true`.
18+
19+
The default was also removed, so you always need to specify the server URL.
20+
21+
This applies to the `ConnectionManager` as well, which also now doesn't expose the `host` and `port` attributes, only the `server_url`. If you need to extract the host or port from the `server_url`, you can use the standard Python `urllib.parse.urlparse()` function.
22+
23+
1524
## New Features
1625

1726
- Calls to `microgrid.*_pool` methods now accept an optional `in_shifting_group` parameter. Power requests sent to `*_pool` instances that have the `in_shifting_group` flag set, will get resolved separately, and their target power will be added to the target power calculated from regular actors, if any, which would, in effect, shift the zero for the regular actors by the target power from the shifting group.

benchmarks/power_distribution/power_distributor.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,8 @@ async def run() -> None:
140140
# pylint: disable=protected-access
141141

142142
await microgrid.initialize(
143-
HOST, PORT, ResamplerConfig(resampling_period=timedelta(seconds=1.0))
143+
"grpc://microgrid.sandbox.api.frequenz.io:62060",
144+
ResamplerConfig(resampling_period=timedelta(seconds=1.0)),
144145
)
145146

146147
all_batteries: set[Component] = connection_manager.get().component_graph.components(

docs/tutorials/getting_started.md

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,11 @@ microgrid.
4444
```python
4545
async def run() -> None:
4646
# This points to the default Frequenz microgrid sandbox
47-
microgrid_host = "microgrid.sandbox.api.frequenz.io"
48-
microgrid_port = 62060
47+
server_url = "grpc://microgrid.sandbox.api.frequenz.io:62060",
4948

5049
# Initialize the microgrid
5150
await microgrid.initialize(
52-
microgrid_host,
53-
microgrid_port,
51+
server_url,
5452
ResamplerConfig(resampling_period=timedelta(seconds=1)),
5553
)
5654

@@ -106,13 +104,11 @@ from frequenz.sdk.actor import ResamplerConfig
106104

107105
async def run() -> None:
108106
# This points to the default Frequenz microgrid sandbox
109-
microgrid_host = "microgrid.sandbox.api.frequenz.io"
110-
microgrid_port = 62060
107+
server_url = "grpc://microgrid.sandbox.api.frequenz.io:62060",
111108

112109
# Initialize the microgrid
113110
await microgrid.initialize(
114-
microgrid_host,
115-
microgrid_port,
111+
server_url,
116112
ResamplerConfig(resampling_period=timedelta(seconds=1)),
117113
)
118114

examples/battery_pool.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ async def main() -> None:
2323
level=logging.DEBUG, format="%(asctime)s %(name)s %(levelname)s:%(message)s"
2424
)
2525
await microgrid.initialize(
26-
host=HOST,
27-
port=PORT,
26+
"grpc://microgrid.sandbox.api.frequenz.io:62060",
2827
resampler_config=ResamplerConfig(resampling_period=timedelta(seconds=1.0)),
2928
)
3029

src/frequenz/sdk/microgrid/__init__.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -239,15 +239,18 @@
239239
)
240240

241241

242-
async def initialize(host: str, port: int, resampler_config: ResamplerConfig) -> None:
242+
async def initialize(server_url: str, resampler_config: ResamplerConfig) -> None:
243243
"""Initialize the microgrid connection manager and the data pipeline.
244244
245245
Args:
246-
host: Host to connect to, to reach the microgrid API.
247-
port: port to connect to.
246+
server_url: The location of the microgrid API server in the form of a URL.
247+
The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`,
248+
where the port should be an int between `0` and `65535` (defaulting to
249+
`9090`) and ssl should be a boolean (defaulting to false). For example:
250+
`grpc://localhost:1090?ssl=true`.
248251
resampler_config: Configuration for the resampling actor.
249252
"""
250-
await connection_manager.initialize(host, port)
253+
await connection_manager.initialize(server_url)
251254
await _data_pipeline.initialize(resampler_config)
252255

253256

src/frequenz/sdk/microgrid/connection_manager.py

Lines changed: 37 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -11,49 +11,33 @@
1111
import logging
1212
from abc import ABC, abstractmethod
1313

14-
import grpc.aio as grpcaio
1514
from frequenz.client.microgrid import ApiClient, Location, Metadata
1615

1716
from .component_graph import ComponentGraph, _MicrogridComponentGraph
1817

19-
# Not public default host and port
20-
_DEFAULT_MICROGRID_HOST = "[::1]"
21-
_DEFAULT_MICROGRID_PORT = 443
22-
2318
_logger = logging.getLogger(__name__)
2419

2520

2621
class ConnectionManager(ABC):
2722
"""Creates and stores core features."""
2823

29-
def __init__(self, host: str, port: int) -> None:
24+
def __init__(self, server_url: str) -> None:
3025
"""Create object instance.
3126
3227
Args:
33-
host: server host
34-
port: server port
28+
server_url: The location of the microgrid API server in the form of a URL.
29+
The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`,
30+
where the port should be an int between `0` and `65535` (defaulting to
31+
`9090`) and ssl should be a boolean (defaulting to false). For example:
32+
`grpc://localhost:1090?ssl=true`.
3533
"""
3634
super().__init__()
37-
self._host: str = host
38-
self._port: int = port
35+
self._server_url = server_url
3936

4037
@property
41-
def host(self) -> str:
42-
"""Get host of the currently connected server.
43-
44-
Returns:
45-
host
46-
"""
47-
return self._host
48-
49-
@property
50-
def port(self) -> int:
51-
"""Get port of the currently connected server.
52-
53-
Returns:
54-
port
55-
"""
56-
return self._port
38+
def server_url(self) -> str:
39+
"""The location of the microgrid API server in the form of a URL."""
40+
return self._server_url
5741

5842
@property
5943
@abstractmethod
@@ -91,9 +75,8 @@ def location(self) -> Location | None:
9175
the location of the microgrid if available, None otherwise.
9276
"""
9377

94-
async def _update_api(self, host: str, port: int) -> None:
95-
self._host = host
96-
self._port = port
78+
async def _update_api(self, server_url: str) -> None:
79+
self._server_url = server_url
9780

9881
@abstractmethod
9982
async def _initialize(self) -> None:
@@ -103,19 +86,18 @@ async def _initialize(self) -> None:
10386
class _InsecureConnectionManager(ConnectionManager):
10487
"""Microgrid Api with insecure channel implementation."""
10588

106-
def __init__(
107-
self, host: str = _DEFAULT_MICROGRID_HOST, port: int = _DEFAULT_MICROGRID_PORT
108-
) -> None:
89+
def __init__(self, server_url: str) -> None:
10990
"""Create and stores core features.
11091
11192
Args:
112-
host: host. Defaults to _DEFAULT_MICROGRID_HOST.
113-
port: port. Defaults to _DEFAULT_MICROGRID_PORT.
93+
server_url: The location of the microgrid API server in the form of a URL.
94+
The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`,
95+
where the port should be an int between `0` and `65535` (defaulting to
96+
`9090`) and ssl should be a boolean (defaulting to false). For example:
97+
`grpc://localhost:1090?ssl=true`.
11498
"""
115-
super().__init__(host, port)
116-
target = f"{host}:{port}"
117-
grpc_channel = grpcaio.insecure_channel(target)
118-
self._api = ApiClient(grpc_channel, target)
99+
super().__init__(server_url)
100+
self._api = ApiClient(server_url)
119101
# To create graph from the api we need await.
120102
# So create empty graph here, and update it in `run` method.
121103
self._graph = _MicrogridComponentGraph()
@@ -159,18 +141,20 @@ def component_graph(self) -> ComponentGraph:
159141
"""
160142
return self._graph
161143

162-
async def _update_api(self, host: str, port: int) -> None:
144+
async def _update_api(self, server_url: str) -> None:
163145
"""Update api with new host and port.
164146
165147
Args:
166-
host: new host
167-
port: new port
148+
server_url: The new location of the microgrid API server in the form of a
149+
URL. The following format is expected:
150+
`grpc://hostname{:port}{?ssl=ssl}`, where the port should be an int
151+
between `0` and `65535` (defaulting to `9090`) and ssl should be
152+
a boolean (defaulting to false). For example:
153+
`grpc://localhost:1090?ssl=true`.
168154
"""
169-
await super()._update_api(host, port) # pylint: disable=protected-access
155+
await super()._update_api(server_url) # pylint: disable=protected-access
170156

171-
target = f"{host}:{port}"
172-
grpc_channel = grpcaio.insecure_channel(target)
173-
self._api = ApiClient(grpc_channel, target)
157+
self._api = ApiClient(server_url)
174158
self._metadata = await self._api.metadata()
175159
await self._graph.refresh_from_api(self._api)
176160

@@ -183,12 +167,15 @@ async def _initialize(self) -> None:
183167
"""The ConnectionManager singleton instance."""
184168

185169

186-
async def initialize(host: str, port: int) -> None:
170+
async def initialize(server_url: str) -> None:
187171
"""Initialize the MicrogridApi. This function should be called only once.
188172
189173
Args:
190-
host: Microgrid host
191-
port: Microgrid port
174+
server_url: The location of the microgrid API server in the form of a URL.
175+
The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`,
176+
where the port should be an int between `0` and `65535` (defaulting to
177+
`9090`) and ssl should be a boolean (defaulting to false). For example:
178+
`grpc://localhost:1090?ssl=true`.
192179
193180
Raises:
194181
AssertionError: If method was called more then once.
@@ -200,9 +187,9 @@ async def initialize(host: str, port: int) -> None:
200187
if _CONNECTION_MANAGER is not None:
201188
raise AssertionError("MicrogridApi was already initialized.")
202189

203-
_logger.info("Connecting to microgrid at %s:%s", host, port)
190+
_logger.info("Connecting to microgrid at %s", server_url)
204191

205-
microgrid_api = _InsecureConnectionManager(host, port)
192+
microgrid_api = _InsecureConnectionManager(server_url)
206193
await microgrid_api._initialize() # pylint: disable=protected-access
207194

208195
# Check again that _MICROGRID_API is None in case somebody had the great idea of

src/frequenz/sdk/timeseries/_voltage_streamer.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,7 @@ class VoltageStreamer:
3939
from frequenz.sdk.timeseries import ResamplerConfig
4040
4141
await microgrid.initialize(
42-
"127.0.0.1",
43-
50051,
42+
"grpc://127.0.0.1:50051",
4443
ResamplerConfig(resampling_period=timedelta(seconds=1))
4544
)
4645

src/frequenz/sdk/timeseries/consumer.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@ class Consumer:
3838
from frequenz.sdk.timeseries import ResamplerConfig
3939
4040
await microgrid.initialize(
41-
"127.0.0.1",
42-
50051,
41+
"grpc://127.0.0.1:50051",
4342
ResamplerConfig(resampling_period=timedelta(seconds=1.0))
4443
)
4544

src/frequenz/sdk/timeseries/grid.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ class Grid:
5151
from frequenz.sdk.timeseries import ResamplerConfig
5252
5353
await microgrid.initialize(
54-
"127.0.0.1",
55-
50051,
54+
"grpc://127.0.0.1:50051",
5655
ResamplerConfig(resampling_period=timedelta(seconds=1))
5756
)
5857

src/frequenz/sdk/timeseries/logical_meter/_logical_meter.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,7 @@ class LogicalMeter:
3636
from frequenz.sdk.timeseries import ResamplerConfig
3737
3838
await microgrid.initialize(
39-
"127.0.0.1",
40-
50051,
39+
"grpc://127.0.0.1:50051",
4140
ResamplerConfig(resampling_period=timedelta(seconds=1))
4241
)
4342

0 commit comments

Comments
 (0)