volttron-platform-lookup 0.1.0rc0__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.
@@ -0,0 +1,216 @@
1
+ Copyright 2022 Battelle Memorial Institute
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
+ use this file except in compliance with the License. You may obtain a copy
5
+ of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ License for the specific language governing permissions and limitations
13
+ under the License.
14
+
15
+
16
+ Apache License
17
+ Version 2.0, January 2004
18
+ http://www.apache.org/licenses/
19
+
20
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
21
+
22
+ 1. Definitions.
23
+
24
+ "License" shall mean the terms and conditions for use, reproduction,
25
+ and distribution as defined by Sections 1 through 9 of this document.
26
+
27
+ "Licensor" shall mean the copyright owner or entity authorized by
28
+ the copyright owner that is granting the License.
29
+
30
+ "Legal Entity" shall mean the union of the acting entity and all
31
+ other entities that control, are controlled by, or are under common
32
+ control with that entity. For the purposes of this definition,
33
+ "control" means (i) the power, direct or indirect, to cause the
34
+ direction or management of such entity, whether by contract or
35
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
36
+ outstanding shares, or (iii) beneficial ownership of such entity.
37
+
38
+ "You" (or "Your") shall mean an individual or Legal Entity
39
+ exercising permissions granted by this License.
40
+
41
+ "Source" form shall mean the preferred form for making modifications,
42
+ including but not limited to software source code, documentation
43
+ source, and configuration files.
44
+
45
+ "Object" form shall mean any form resulting from mechanical
46
+ transformation or translation of a Source form, including but
47
+ not limited to compiled object code, generated documentation,
48
+ and conversions to other media types.
49
+
50
+ "Work" shall mean the work of authorship, whether in Source or
51
+ Object form, made available under the License, as indicated by a
52
+ copyright notice that is included in or attached to the work
53
+ (an example is provided in the Appendix below).
54
+
55
+ "Derivative Works" shall mean any work, whether in Source or Object
56
+ form, that is based on (or derived from) the Work and for which the
57
+ editorial revisions, annotations, elaborations, or other modifications
58
+ represent, as a whole, an original work of authorship. For the purposes
59
+ of this License, Derivative Works shall not include works that remain
60
+ separable from, or merely link (or bind by name) to the interfaces of,
61
+ the Work and Derivative Works thereof.
62
+
63
+ "Contribution" shall mean any work of authorship, including
64
+ the original version of the Work and any modifications or additions
65
+ to that Work or Derivative Works thereof, that is intentionally
66
+ submitted to Licensor for inclusion in the Work by the copyright owner
67
+ or by an individual or Legal Entity authorized to submit on behalf of
68
+ the copyright owner. For the purposes of this definition, "submitted"
69
+ means any form of electronic, verbal, or written communication sent
70
+ to the Licensor or its representatives, including but not limited to
71
+ communication on electronic mailing lists, source code control systems,
72
+ and issue tracking systems that are managed by, or on behalf of, the
73
+ Licensor for the purpose of discussing and improving the Work, but
74
+ excluding communication that is conspicuously marked or otherwise
75
+ designated in writing by the copyright owner as "Not a Contribution."
76
+
77
+ "Contributor" shall mean Licensor and any individual or Legal Entity
78
+ on behalf of whom a Contribution has been received by Licensor and
79
+ subsequently incorporated within the Work.
80
+
81
+ 2. Grant of Copyright License. Subject to the terms and conditions of
82
+ this License, each Contributor hereby grants to You a perpetual,
83
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
84
+ copyright license to reproduce, prepare Derivative Works of,
85
+ publicly display, publicly perform, sublicense, and distribute the
86
+ Work and such Derivative Works in Source or Object form.
87
+
88
+ 3. Grant of Patent License. Subject to the terms and conditions of
89
+ this License, each Contributor hereby grants to You a perpetual,
90
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
91
+ (except as stated in this section) patent license to make, have made,
92
+ use, offer to sell, sell, import, and otherwise transfer the Work,
93
+ where such license applies only to those patent claims licensable
94
+ by such Contributor that are necessarily infringed by their
95
+ Contribution(s) alone or by combination of their Contribution(s)
96
+ with the Work to which such Contribution(s) was submitted. If You
97
+ institute patent litigation against any entity (including a
98
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
99
+ or a Contribution incorporated within the Work constitutes direct
100
+ or contributory patent infringement, then any patent licenses
101
+ granted to You under this License for that Work shall terminate
102
+ as of the date such litigation is filed.
103
+
104
+ 4. Redistribution. You may reproduce and distribute copies of the
105
+ Work or Derivative Works thereof in any medium, with or without
106
+ modifications, and in Source or Object form, provided that You
107
+ meet the following conditions:
108
+
109
+ (a) You must give any other recipients of the Work or
110
+ Derivative Works a copy of this License; and
111
+
112
+ (b) You must cause any modified files to carry prominent notices
113
+ stating that You changed the files; and
114
+
115
+ (c) You must retain, in the Source form of any Derivative Works
116
+ that You distribute, all copyright, patent, trademark, and
117
+ attribution notices from the Source form of the Work,
118
+ excluding those notices that do not pertain to any part of
119
+ the Derivative Works; and
120
+
121
+ (d) If the Work includes a "NOTICE" text file as part of its
122
+ distribution, then any Derivative Works that You distribute must
123
+ include a readable copy of the attribution notices contained
124
+ within such NOTICE file, excluding those notices that do not
125
+ pertain to any part of the Derivative Works, in at least one
126
+ of the following places: within a NOTICE text file distributed
127
+ as part of the Derivative Works; within the Source form or
128
+ documentation, if provided along with the Derivative Works; or,
129
+ within a display generated by the Derivative Works, if and
130
+ wherever such third-party notices normally appear. The contents
131
+ of the NOTICE file are for informational purposes only and
132
+ do not modify the License. You may add Your own attribution
133
+ notices within Derivative Works that You distribute, alongside
134
+ or as an addendum to the NOTICE text from the Work, provided
135
+ that such additional attribution notices cannot be construed
136
+ as modifying the License.
137
+
138
+ You may add Your own copyright statement to Your modifications and
139
+ may provide additional or different license terms and conditions
140
+ for use, reproduction, or distribution of Your modifications, or
141
+ for any such Derivative Works as a whole, provided Your use,
142
+ reproduction, and distribution of the Work otherwise complies with
143
+ the conditions stated in this License.
144
+
145
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
146
+ any Contribution intentionally submitted for inclusion in the Work
147
+ by You to the Licensor shall be under the terms and conditions of
148
+ this License, without any additional terms or conditions.
149
+ Notwithstanding the above, nothing herein shall supersede or modify
150
+ the terms of any separate license agreement you may have executed
151
+ with Licensor regarding such Contributions.
152
+
153
+ 6. Trademarks. This License does not grant permission to use the trade
154
+ names, trademarks, service marks, or product names of the Licensor,
155
+ except as required for reasonable and customary use in describing the
156
+ origin of the Work and reproducing the content of the NOTICE file.
157
+
158
+ 7. Disclaimer of Warranty. Unless required by applicable law or
159
+ agreed to in writing, Licensor provides the Work (and each
160
+ Contributor provides its Contributions) on an "AS IS" BASIS,
161
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
162
+ implied, including, without limitation, any warranties or conditions
163
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
164
+ PARTICULAR PURPOSE. You are solely responsible for determining the
165
+ appropriateness of using or redistributing the Work and assume any
166
+ risks associated with Your exercise of permissions under this License.
167
+
168
+ 8. Limitation of Liability. In no event and under no legal theory,
169
+ whether in tort (including negligence), contract, or otherwise,
170
+ unless required by applicable law (such as deliberate and grossly
171
+ negligent acts) or agreed to in writing, shall any Contributor be
172
+ liable to You for damages, including any direct, indirect, special,
173
+ incidental, or consequential damages of any character arising as a
174
+ result of this License or out of the use or inability to use the
175
+ Work (including but not limited to damages for loss of goodwill,
176
+ work stoppage, computer failure or malfunction, or any and all
177
+ other commercial damages or losses), even if such Contributor
178
+ has been advised of the possibility of such damages.
179
+
180
+ 9. Accepting Warranty or Additional Liability. While redistributing
181
+ the Work or Derivative Works thereof, You may choose to offer,
182
+ and charge a fee for, acceptance of support, warranty, indemnity,
183
+ or other liability obligations and/or rights consistent with this
184
+ License. However, in accepting such obligations, You may act only
185
+ on Your own behalf and on Your sole responsibility, not on behalf
186
+ of any other Contributor, and only if You agree to indemnify,
187
+ defend, and hold each Contributor harmless for any liability
188
+ incurred by, or claims asserted against, such Contributor by reason
189
+ of your accepting any such warranty or additional liability.
190
+
191
+ END OF TERMS AND CONDITIONS
192
+
193
+ APPENDIX: How to apply the Apache License to your work.
194
+
195
+ To apply the Apache License to your work, attach the following
196
+ boilerplate notice, with the fields enclosed by brackets "[]"
197
+ replaced with your own identifying information. (Don't include
198
+ the brackets!) The text should be enclosed in the appropriate
199
+ comment syntax for the file format. We also recommend that a
200
+ file or class name and description of purpose be included on the
201
+ same "printed page" as the copyright notice for easier
202
+ identification within third-party archives.
203
+
204
+ Copyright [yyyy] [name of copyright owner]
205
+
206
+ Licensed under the Apache License, Version 2.0 (the "License");
207
+ you may not use this file except in compliance with the License.
208
+ You may obtain a copy of the License at
209
+
210
+ http://www.apache.org/licenses/LICENSE-2.0
211
+
212
+ Unless required by applicable law or agreed to in writing, software
213
+ distributed under the License is distributed on an "AS IS" BASIS,
214
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
+ See the License for the specific language governing permissions and
216
+ limitations under the License.
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.3
2
+ Name: volttron-platform-lookup
3
+ Version: 0.1.0rc0
4
+ Summary: Web service that runs outside of VOLTTRON server and let VOLTTRON instance to register itself and lookup for services that can be part of a federated group
5
+ License: Apache-2.0
6
+ Author: volttron
7
+ Author-email: volttron@pnnl.gov
8
+ Requires-Python: >=3.9
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Dist: fastapi (>=0.118.0)
17
+ Requires-Dist: uvicorn (>=0.37.0)
18
+ Project-URL: Documentation, https://github.com/eclipse-volttron/platform-lookup
19
+ Project-URL: Repository, https://github.com/eclipse-volttron/platform-lookup
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Platform Lookup Service
23
+
24
+ A FastAPI-based microservice for managing platform registrations and lookups. This service provides a RESTful API for registering and managing platforms with their associated credentials and network addresses.
25
+
26
+ ## Features
27
+
28
+ - Platform registration and management
29
+ - Thread-safe operations for concurrent access
30
+ - Input validation using Pydantic models
31
+ - Support for platform grouping
32
+ - JSON-based persistent storage
33
+ - RESTful API with OpenAPI documentation
34
+
35
+ ## Requirements
36
+
37
+ - Python 3.x
38
+ - FastAPI
39
+ - Uvicorn
40
+
41
+ ## Installation
42
+
43
+ 1. From pypi
44
+
45
+ ```bash
46
+ pip install volttron-platform-lookup
47
+ ```
48
+
49
+ 1. From source code:
50
+
51
+ ```bash
52
+ git clone [repository-url]
53
+ cd platform-lookup
54
+ poetry install
55
+ ```
56
+
57
+
58
+ ## Usage
59
+
60
+ 1. Start the server:
61
+
62
+ ```bash
63
+ volttron-platform-lookup <optional port. defaults to 8000>
64
+ ```
65
+
66
+ 2. The API will be available at `http://localhost:8000`
67
+ 3. Access the API documentation at `http://localhost:8000/docs`
68
+
69
+ ## API Endpoints
70
+
71
+ The service provides RESTful endpoints for platform management. All data is exchanged in JSON format.
72
+
73
+ ### Platform Model
74
+
75
+ Each platform registration includes:
76
+
77
+ - `id`: Unique identifier for the platform (alphanumeric, underscores, and hyphens allowed)
78
+ - `address`: Network address where the platform can be reached (IP, domain, or URI)
79
+ - `public_credentials`: Authentication credential (minimum 16 characters)
80
+ - `group`: Optional grouping parameter (defaults to "default")
81
+
82
+ Example platform registration:
83
+
84
+ ```json
85
+ {
86
+ "id": "platform-123",
87
+ "address": "tcp://example.com",
88
+ "public_credentials": "abcdef1234567890",
89
+ "group": "production"
90
+ }
91
+ ```
92
+
93
+ ## Data Storage
94
+
95
+ Platform data is stored in `platforms.json` with thread-safe access mechanisms to prevent race conditions during concurrent operations.
96
+
97
+ ## Security
98
+
99
+ - Input validation for all API endpoints
100
+ - Credential length requirements
101
+ - Address format validation
102
+ - Thread-safe operations
103
+
104
+ ## Contributing
105
+
106
+ 1. Fork the repository
107
+ 2. Create a feature branch
108
+ 3. Submit a pull request
109
+
110
+ ## License
111
+
112
+ This project is licensed under the Apache License, Version 2.0. See the [LICENSE](LICENSE) file for details.
113
+
114
+ Copyright 2025 Battelle Memorial Institute
115
+
116
+ ## Disclaimer Notice
117
+
118
+ This material was prepared as an account of work sponsored by an agency of the
119
+ United States Government. Neither the United States Government nor the United
120
+ States Department of Energy, nor Battelle, nor any of their employees, nor any
121
+ jurisdiction or organization that has cooperated in the development of these
122
+ materials, makes any warranty, express or implied, or assumes any legal
123
+ liability or responsibility for the accuracy, completeness, or usefulness or any
124
+ information, apparatus, product, software, or process disclosed, or represents
125
+ that its use would not infringe privately owned rights.
126
+
127
+ Reference herein to any specific commercial product, process, or service by
128
+ trade name, trademark, manufacturer, or otherwise does not necessarily
129
+ constitute or imply its endorsement, recommendation, or favoring by the United
130
+ States Government or any agency thereof, or Battelle Memorial Institute. The
131
+ views and opinions of authors expressed herein do not necessarily state or
132
+ reflect those of the United States Government or any agency thereof.
133
+
@@ -0,0 +1,111 @@
1
+ # Platform Lookup Service
2
+
3
+ A FastAPI-based microservice for managing platform registrations and lookups. This service provides a RESTful API for registering and managing platforms with their associated credentials and network addresses.
4
+
5
+ ## Features
6
+
7
+ - Platform registration and management
8
+ - Thread-safe operations for concurrent access
9
+ - Input validation using Pydantic models
10
+ - Support for platform grouping
11
+ - JSON-based persistent storage
12
+ - RESTful API with OpenAPI documentation
13
+
14
+ ## Requirements
15
+
16
+ - Python 3.x
17
+ - FastAPI
18
+ - Uvicorn
19
+
20
+ ## Installation
21
+
22
+ 1. From pypi
23
+
24
+ ```bash
25
+ pip install volttron-platform-lookup
26
+ ```
27
+
28
+ 1. From source code:
29
+
30
+ ```bash
31
+ git clone [repository-url]
32
+ cd platform-lookup
33
+ poetry install
34
+ ```
35
+
36
+
37
+ ## Usage
38
+
39
+ 1. Start the server:
40
+
41
+ ```bash
42
+ volttron-platform-lookup <optional port. defaults to 8000>
43
+ ```
44
+
45
+ 2. The API will be available at `http://localhost:8000`
46
+ 3. Access the API documentation at `http://localhost:8000/docs`
47
+
48
+ ## API Endpoints
49
+
50
+ The service provides RESTful endpoints for platform management. All data is exchanged in JSON format.
51
+
52
+ ### Platform Model
53
+
54
+ Each platform registration includes:
55
+
56
+ - `id`: Unique identifier for the platform (alphanumeric, underscores, and hyphens allowed)
57
+ - `address`: Network address where the platform can be reached (IP, domain, or URI)
58
+ - `public_credentials`: Authentication credential (minimum 16 characters)
59
+ - `group`: Optional grouping parameter (defaults to "default")
60
+
61
+ Example platform registration:
62
+
63
+ ```json
64
+ {
65
+ "id": "platform-123",
66
+ "address": "tcp://example.com",
67
+ "public_credentials": "abcdef1234567890",
68
+ "group": "production"
69
+ }
70
+ ```
71
+
72
+ ## Data Storage
73
+
74
+ Platform data is stored in `platforms.json` with thread-safe access mechanisms to prevent race conditions during concurrent operations.
75
+
76
+ ## Security
77
+
78
+ - Input validation for all API endpoints
79
+ - Credential length requirements
80
+ - Address format validation
81
+ - Thread-safe operations
82
+
83
+ ## Contributing
84
+
85
+ 1. Fork the repository
86
+ 2. Create a feature branch
87
+ 3. Submit a pull request
88
+
89
+ ## License
90
+
91
+ This project is licensed under the Apache License, Version 2.0. See the [LICENSE](LICENSE) file for details.
92
+
93
+ Copyright 2025 Battelle Memorial Institute
94
+
95
+ ## Disclaimer Notice
96
+
97
+ This material was prepared as an account of work sponsored by an agency of the
98
+ United States Government. Neither the United States Government nor the United
99
+ States Department of Energy, nor Battelle, nor any of their employees, nor any
100
+ jurisdiction or organization that has cooperated in the development of these
101
+ materials, makes any warranty, express or implied, or assumes any legal
102
+ liability or responsibility for the accuracy, completeness, or usefulness or any
103
+ information, apparatus, product, software, or process disclosed, or represents
104
+ that its use would not infringe privately owned rights.
105
+
106
+ Reference herein to any specific commercial product, process, or service by
107
+ trade name, trademark, manufacturer, or otherwise does not necessarily
108
+ constitute or imply its endorsement, recommendation, or favoring by the United
109
+ States Government or any agency thereof, or Battelle Memorial Institute. The
110
+ views and opinions of authors expressed herein do not necessarily state or
111
+ reflect those of the United States Government or any agency thereof.
@@ -0,0 +1,320 @@
1
+ import json
2
+ import sys
3
+ from threading import Lock
4
+ from fastapi import FastAPI, HTTPException, Depends, Request, Response
5
+ from pydantic import BaseModel, Field, field_validator
6
+ from typing import List, Optional
7
+
8
+ app = FastAPI(
9
+ title="Platform Management API",
10
+ description="API for managing platform registrations",
11
+ version="1.0.0"
12
+ )
13
+
14
+ platform_file = "platforms.json"
15
+ lock = Lock()
16
+ DEFAULT_GROUP = "default"
17
+
18
+ class PlatformWithIP(BaseModel):
19
+ """Internal model for storing platform data with IP tracking"""
20
+ id: str
21
+ address: str
22
+ public_credentials: str
23
+ group: str
24
+ last_modified_ip: Optional[str] = None
25
+
26
+ def to_platform(self) -> "Platform":
27
+ """Convert to Platform model (excluding last_modified_ip)"""
28
+ return Platform(
29
+ id=self.id,
30
+ address=self.address,
31
+ public_credentials=self.public_credentials,
32
+ group=self.group
33
+ )
34
+
35
+ class Platform(BaseModel):
36
+ id: str = Field(...,
37
+ description="""
38
+ # Unique id for the platform.
39
+
40
+ When external platforms refer to an agent on this platform they will use this as a prefix
41
+ to allow routing of messages to go to the proper location.
42
+ Only alphanumeric characters, underscores, and hyphens are allowed.
43
+ The id must be unique across all platforms.
44
+ """)
45
+ address: str = Field(...,
46
+ description="""
47
+ # Address of the platform.
48
+
49
+ This is the address where the platform can be reached.
50
+ It can be an IP address, a domain name, or a URI.
51
+ """)
52
+ public_credentials: str = Field(...,
53
+ description="""
54
+ # Public credential for the platform.
55
+ This is the credential that will be used to authenticate with the platform. For zmq this
56
+ is the publickey of the server to allow a client to connect to the zap loop. This may be
57
+ different for other protocols.
58
+ """)
59
+ group: str = Field(default=DEFAULT_GROUP,
60
+ description="""
61
+ # Group of the platform.
62
+
63
+ This is the group that the platform belongs to. It is used to group platforms together for
64
+ routing purposes. If not specified, the platform will be added to the default group.
65
+
66
+ This will allow partitioning of platforms in the future.
67
+ """)
68
+ @field_validator('address')
69
+ @classmethod
70
+ def address_must_be_valid(cls, v):
71
+ """Validate that address has a valid format"""
72
+ # Simple URL or IP check - you might want to use proper validation libraries
73
+ import re
74
+ # Basic check for IP or URL-like string
75
+ if not (v.startswith(('http://', 'https://', 'tcp://', 'ipc://')) or
76
+ re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$', v)):
77
+ raise ValueError("Address must be a valid URL, IP address, or protocol URI")
78
+ return v
79
+
80
+ @field_validator('public_credentials')
81
+ @classmethod
82
+ def credential_must_be_valid(cls, v):
83
+ """Validate credential format"""
84
+ if len(v) < 16: # Example minimum length requirement
85
+ raise ValueError("Public credential must be at least 16 characters long")
86
+ return v
87
+
88
+ model_config = {
89
+ "json_schema_extra": {
90
+ "examples": [
91
+ {
92
+ "id": "platform-123",
93
+ "address": "tcp://example.com",
94
+ "public_credentials": "abcdef1234567890",
95
+ "group": "production"
96
+ }
97
+ ]
98
+ }
99
+ }
100
+
101
+ def get_platforms():
102
+ """Dependency to get platforms with thread safety"""
103
+ with lock:
104
+ return _load_platforms()
105
+
106
+ def _store_platforms(platforms):
107
+ """Save platforms to file with proper JSON serialization"""
108
+ # Convert to dict for JSON serialization
109
+ platforms_json = [p.dict() for p in platforms]
110
+ with lock:
111
+ with open(platform_file, "w") as f:
112
+ json.dump(platforms_json, f, indent=2)
113
+
114
+ def _load_platforms():
115
+ """Load platforms from file with proper deserialization"""
116
+ try:
117
+ with open(platform_file, "r") as f:
118
+ platforms_data = json.load(f)
119
+ return [PlatformWithIP(**p) for p in platforms_data]
120
+ except FileNotFoundError:
121
+ return []
122
+
123
+ def _get_client_ip(request: Request) -> str:
124
+ """Extract client IP address from request"""
125
+ # Check for forwarded headers first (in case of proxy/load balancer)
126
+ forwarded_for = request.headers.get("X-Forwarded-For")
127
+ if forwarded_for:
128
+ # Take the first IP if there are multiple
129
+ return forwarded_for.split(",")[0].strip()
130
+
131
+ real_ip = request.headers.get("X-Real-IP")
132
+ if real_ip:
133
+ return real_ip
134
+
135
+ # Fall back to direct client IP
136
+ return request.client.host if request.client else "unknown"
137
+
138
+ @app.get("/", tags=["Root"])
139
+ async def root():
140
+ """API root endpoint"""
141
+ return {"message": app.title, "version": app.version}
142
+
143
+ @app.post("/platform", response_model=Platform, tags=["Platforms"])
144
+ async def register_platform(platform: Platform, request: Request, response: Response):
145
+ """
146
+ Register a new platform
147
+
148
+ This endpoint allows you to register a new platform with the system.
149
+
150
+ The following fields must be unique across all platforms:
151
+ - id: The platform's unique identifier
152
+ - address: The platform's network address
153
+ - public_credentials: The platform's public authentication credential
154
+
155
+ Returns:
156
+ - 200: If the same IP submits identical platform data
157
+ - 201: If new platform is created or existing platform is updated
158
+ """
159
+ platforms = get_platforms()
160
+ client_ip = _get_client_ip(request)
161
+
162
+ # Check if platform already exists
163
+ for i, existing_platform in enumerate(platforms):
164
+ if existing_platform.id == platform.id:
165
+ # Check if this is the same request from the same IP
166
+ if (existing_platform.last_modified_ip == client_ip and
167
+ existing_platform.address == platform.address and
168
+ existing_platform.public_credentials == platform.public_credentials and
169
+ existing_platform.group == platform.group):
170
+ # Same data from same IP - return 200
171
+ response.status_code = 200
172
+ return existing_platform.to_platform()
173
+
174
+ # Different data or different IP - check for conflicts with other platforms
175
+ for j, other_platform in enumerate(platforms):
176
+ if j != i: # Skip the current platform being updated
177
+ if other_platform.address == platform.address:
178
+ raise HTTPException(status_code=400, detail=f"Platform with address '{platform.address}' already exists")
179
+ if other_platform.public_credentials == platform.public_credentials:
180
+ raise HTTPException(status_code=400, detail=f"Platform with public credential '{platform.public_credentials}' already exists")
181
+
182
+ # Update existing platform
183
+ platforms[i] = PlatformWithIP(
184
+ id=platform.id,
185
+ address=platform.address,
186
+ public_credentials=platform.public_credentials,
187
+ group=platform.group,
188
+ last_modified_ip=client_ip
189
+ )
190
+ _store_platforms(platforms)
191
+ response.status_code = 201
192
+ return platforms[i].to_platform()
193
+
194
+ # Check for duplicate address or credentials with existing platforms
195
+ if any(p.address == platform.address for p in platforms):
196
+ raise HTTPException(status_code=400, detail=f"Platform with address '{platform.address}' already exists")
197
+
198
+ if any(p.public_credentials == platform.public_credentials for p in platforms):
199
+ raise HTTPException(status_code=400, detail=f"Platform with public credential '{platform.public_credentials}' already exists")
200
+
201
+ # Create new platform
202
+ new_platform = PlatformWithIP(
203
+ id=platform.id,
204
+ address=platform.address,
205
+ public_credentials=platform.public_credentials,
206
+ group=platform.group,
207
+ last_modified_ip=client_ip
208
+ )
209
+ platforms.append(new_platform)
210
+ _store_platforms(platforms)
211
+ response.status_code = 201
212
+ return new_platform.to_platform()
213
+
214
+ @app.get("/platform/{platform_id}", response_model=Platform, tags=["Platforms"])
215
+ async def read_platform(platform_id: str, platforms: List[PlatformWithIP] = Depends(get_platforms)):
216
+ """
217
+ Get platform details by ID
218
+
219
+ Retrieve detailed information about a specific platform
220
+ """
221
+ for platform in platforms:
222
+ if platform.id == platform_id:
223
+ return platform.to_platform()
224
+ raise HTTPException(status_code=404, detail=f"Platform with ID '{platform_id}' not found")
225
+
226
+ @app.put("/platform/{platform_id}", response_model=Platform, tags=["Platforms"])
227
+ async def update_platform(platform_id: str, updated_platform: Platform, request: Request, response: Response):
228
+ """
229
+ Update platform information
230
+
231
+ Update an existing platform's details
232
+
233
+ Returns:
234
+ - 200: If the same IP submits identical platform data
235
+ - 201: If platform is updated with new data
236
+ """
237
+ platforms = get_platforms()
238
+ client_ip = _get_client_ip(request)
239
+
240
+ for i, platform in enumerate(platforms):
241
+ if platform.id == platform_id:
242
+ # Ensure ID doesn't change
243
+ if updated_platform.id != platform_id:
244
+ raise HTTPException(status_code=400, detail="Cannot change platform ID")
245
+
246
+ # Check if this is the same request from the same IP
247
+ if (platform.last_modified_ip == client_ip and
248
+ platform.address == updated_platform.address and
249
+ platform.public_credentials == updated_platform.public_credentials and
250
+ platform.group == updated_platform.group):
251
+ # Same data from same IP - return 200
252
+ response.status_code = 200
253
+ return Platform(**platform.dict(exclude={'last_modified_ip'}))
254
+
255
+ # Check for conflicts with other platforms (excluding current one)
256
+ for j, other_platform in enumerate(platforms):
257
+ if j != i: # Skip the current platform being updated
258
+ if other_platform.address == updated_platform.address:
259
+ raise HTTPException(status_code=400, detail=f"Platform with address '{updated_platform.address}' already exists")
260
+ if other_platform.public_credentials == updated_platform.public_credentials:
261
+ raise HTTPException(status_code=400, detail=f"Platform with public credential '{updated_platform.public_credentials}' already exists")
262
+
263
+ # Update platform
264
+ platforms[i] = PlatformWithIP(
265
+ id=updated_platform.id,
266
+ address=updated_platform.address,
267
+ public_credentials=updated_platform.public_credentials,
268
+ group=updated_platform.group,
269
+ last_modified_ip=client_ip
270
+ )
271
+ _store_platforms(platforms)
272
+ response.status_code = 201
273
+ return Platform(**platforms[i].dict(exclude={'last_modified_ip'}))
274
+
275
+ raise HTTPException(status_code=404, detail=f"Platform with ID '{platform_id}' not found")
276
+
277
+ @app.delete("/platform/{platform_id}", tags=["Platforms"])
278
+ async def delete_platform(platform_id: str):
279
+ """
280
+ Delete a platform
281
+
282
+ Remove a platform from the system
283
+ """
284
+ platforms = get_platforms()
285
+ initial_count = len(platforms)
286
+
287
+ platforms = [p for p in platforms if p.id != platform_id]
288
+
289
+ if len(platforms) == initial_count:
290
+ raise HTTPException(status_code=404, detail=f"Platform with ID '{platform_id}' not found")
291
+
292
+ _store_platforms(platforms)
293
+ return {"message": f"Platform '{platform_id}' deleted successfully"}
294
+
295
+ @app.get("/platforms", response_model=List[Platform], tags=["Platforms"])
296
+ async def list_platforms(platforms: List[PlatformWithIP] = Depends(get_platforms)):
297
+ """
298
+ List all platforms
299
+
300
+ Get a list of all registered platforms
301
+ """
302
+ return [p.to_platform() for p in platforms]
303
+
304
+ def main():
305
+ # Default port
306
+ port = 8000
307
+
308
+ # Check if a custom port is provided as a command-line argument
309
+ if len(sys.argv) > 1:
310
+ try:
311
+ port = int(sys.argv[1])
312
+ except ValueError:
313
+ print("Invalid port number. Using default port 8000.")
314
+
315
+ import uvicorn
316
+ uvicorn.run("platform_lookup.app:app", host="0.0.0.0", port=port)
317
+
318
+ if __name__ == "__main__":
319
+ main()
320
+
@@ -0,0 +1,24 @@
1
+ [tool.poetry]
2
+ name = "volttron-platform-lookup"
3
+ version = "0.1.0rc0"
4
+ description = "Web service that runs outside of VOLTTRON server and let VOLTTRON instance to register itself and lookup for services that can be part of a federated group"
5
+ authors = [ "volttron <volttron@pnnl.gov>"]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ repository = "https://github.com/eclipse-volttron/platform-lookup"
9
+ documentation = "https://github.com/eclipse-volttron/platform-lookup"
10
+ packages = [
11
+ { include = "platform_lookup", from = "." }
12
+ ]
13
+
14
+ [tool.poetry.scripts]
15
+ volttron-platform-lookup = "platform_lookup.app:main"
16
+
17
+ [tool.poetry.dependencies]
18
+ python = ">=3.9"
19
+ fastapi = ">=0.118.0"
20
+ uvicorn = ">=0.37.0"
21
+
22
+ [build-system]
23
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
24
+ build-backend = "poetry.core.masonry.api"