Skip to content

Commit

Permalink
implement AlephApp.vm_hash property and test
Browse files Browse the repository at this point in the history
  • Loading branch information
MHHukiewitz committed Aug 24, 2023
1 parent e9e434f commit 9a80ad7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/aleph/sdk/vm/app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import base64
import socket
from dataclasses import dataclass
from typing import (
Any,
Expand Down Expand Up @@ -85,3 +87,22 @@ async def send_handler_result():
def __getattr__(self, name):
# Default all calls to the HTTP handler
return getattr(self.http_app, name)

@property
def vm_hash(self):
"""Returns the hash of the VM that is running this app."""
# Get hostname from environment
hostname = socket.gethostname()

# Add padding if necessary
padding_length = len(hostname) % 8
if padding_length != 0:
hostname += "=" * (8 - padding_length)

# Convert the hostname back to its original binary form
item_hash_binary = base64.b32decode(hostname.upper())

# Convert the binary form to the original vm_hash
vm_hash = base64.b16encode(item_hash_binary).decode().lower()

return vm_hash
15 changes: 15 additions & 0 deletions tests/unit/test_vm_app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import asyncio
import base64
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient
Expand Down Expand Up @@ -31,3 +33,16 @@ def test_app_http():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"index": "/"}


@patch("socket.gethostname")
def test_get_vm_hash(mock_gethostname):
vm_hash = "deadbeef" * 8
# Uses the same logic as
# https://github.com/aleph-im/aleph-vm/blob/main/runtimes/aleph-debian-11-python/init1.py#L488
item_hash_binary: bytes = base64.b16decode(vm_hash.encode().upper())
hostname = base64.b32encode(item_hash_binary).decode().strip("=").lower()

mock_gethostname.return_value = hostname

assert app.vm_hash == vm_hash

0 comments on commit 9a80ad7

Please sign in to comment.