Skip to content

Commit

Permalink
updated serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
dweinholz committed Sep 18, 2024
1 parent 449e759 commit e730027
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
26 changes: 8 additions & 18 deletions simple_vm_client/metadata_connector/metadata_connector.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import os
from urllib.parse import urljoin

Expand All @@ -6,6 +7,7 @@

from simple_vm_client.ttypes import VirtualMachineServerMetadata
from simple_vm_client.util.logger import setup_custom_logger
from simple_vm_client.util.thrift_converter import thrift_to_dict

logger = setup_custom_logger(__name__)

Expand Down Expand Up @@ -81,23 +83,9 @@ def remove_metadata(self, ip: str):
except requests.exceptions.RequestException as e:
logger.error(f"Failed to remove metadata for {ip}: {e}")

def _serialize_metadata(self, metadata: VirtualMachineServerMetadata):
userdata_dict = None
if metadata.userdata is not None:
userdata_dict = {
user_id: {
"username": user.username,
"user_id": user.user_id,
"public_keys": user.public_keys,
}
for user_id, user in metadata.userdata.data.items()
}

return {
"ip": metadata.ip,
"hashed_auth_token": metadata.hashed_auth_token,
"userdata": userdata_dict,
}
def _serialize_metadata(self, metadata: VirtualMachineServerMetadata) -> str:
metadata_dict = thrift_to_dict(metadata)
return json.dumps(metadata_dict)

def set_metadata(self, ip: str, metadata: VirtualMachineServerMetadata):
if not ip:
Expand All @@ -109,12 +97,14 @@ def set_metadata(self, ip: str, metadata: VirtualMachineServerMetadata):
logger.info(f"Setting Metadata for {ip}")
set_metadata_url = urljoin(self.METADATA_BASE_URL, f"metadata/{ip}")
try:
serialized_data = self._serialize_metadata(metadata=metadata)
response = requests.post(
set_metadata_url,
json=self._serialize_metadata(metadata=metadata),
data=serialized_data,
timeout=(30, 30),
headers={
"X-Auth-Token": self.METADATA_SERVER_TOKEN,
"Content-Type": "application/json",
},
verify=False,
)
Expand Down
17 changes: 17 additions & 0 deletions simple_vm_client/util/thrift_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,20 @@ def os_to_thrift_servers(openstack_servers: list[OpenStack_Server]) -> list[VM]:
os_to_thrift_server(openstack_server=openstack_server)
for openstack_server in openstack_servers
]


def thrift_to_dict(obj):
if hasattr(obj, "thrift_spec"):
result = {}
for k in obj.thrift_spec:
if obj.thrift_spec[k] is not None:
field = obj.thrift_spec[k][2]
value = getattr(obj, field)
result[field] = thrift_to_dict(value)
return result
elif isinstance(obj, list):
return [thrift_to_dict(x) for x in obj]
elif isinstance(obj, dict):
return {thrift_to_dict(k): thrift_to_dict(v) for k, v in obj.items()}
else:
return obj

0 comments on commit e730027

Please sign in to comment.