-
Notifications
You must be signed in to change notification settings - Fork 178
Add REST plugin for user-defined policies #2631
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a756cf4
Add REST plugin
Nadine-H fa46f3a
Change rest-plugin to a builtin plugin
Nadine-H dc17969
Add plugin server example
Nadine-H a4bacac
Document rest-plugin in guides
Nadine-H e757a77
Refactor rest-plugin + polish models
Nadine-H f9036f5
Restructure rest_plugin modules
Nadine-H db04651
Doc updates
Nadine-H 32533ef
Additional type checks, type hints and field descriptions
Nadine-H 6f1f90e
Unskip postgres tests
Nadine-H File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
[TODO] |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
[project] | ||
name = "rest-plugin" | ||
version = "0.1.0" | ||
description = "A dstack plugin that enables validation and mutation of run specifications via REST API" | ||
readme = "README.md" | ||
requires-python = ">=3.9" | ||
dependencies = [] | ||
|
||
[build-system] | ||
requires = ["hatchling"] | ||
build-backend = "hatchling.build" | ||
|
||
[tool.hatch.build.targets.wheel] | ||
packages = ["src"] |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import json | ||
import os | ||
import pydantic | ||
import requests | ||
from dstack._internal.core.errors import ServerError | ||
from dstack._internal.core.models.fleets import FleetSpec | ||
from dstack._internal.core.models.gateways import GatewaySpec | ||
from dstack._internal.core.models.volumes import VolumeSpec | ||
from dstack.plugins import ApplyPolicy, Plugin, RunSpec, get_plugin_logger | ||
from dstack.plugins._models import ApplySpec | ||
|
||
logger = get_plugin_logger(__name__) | ||
|
||
PLUGIN_SERVICE_URI_ENV_VAR_NAME = "DSTACK_PLUGIN_SERVICE_URI" | ||
|
||
class PreApplyPolicy(ApplyPolicy): | ||
def __init__(self): | ||
self._plugin_service_uri = os.getenv(PLUGIN_SERVICE_URI_ENV_VAR_NAME) | ||
if not self._plugin_service_uri: | ||
logger.error(f"Cannot create policy as {PLUGIN_SERVICE_URI_ENV_VAR_NAME} is not set") | ||
raise ServerError(f"{PLUGIN_SERVICE_URI_ENV_VAR_NAME} is not set") | ||
|
||
def _call_plugin_service(self, user: str, project: str, spec: ApplySpec, endpoint: str) -> ApplySpec: | ||
# Make request to plugin service with run params | ||
params = { | ||
"user": user, | ||
"project": project, | ||
"spec": spec.json() | ||
} | ||
response = None | ||
try: | ||
response = requests.post(f"{self._plugin_service_uri}/{endpoint}", json=json.dumps(params)) | ||
response.raise_for_status() | ||
spec_json = json.loads(response.text) | ||
spec = RunSpec(**spec_json) | ||
except requests.RequestException as e: | ||
logger.error("Failed to call plugin service: %s", e) | ||
if response: | ||
logger.error(f"Error response from plugin service:\n{response.text}") | ||
logger.info("Returning original run spec") | ||
return spec | ||
except pydantic.ValidationError as e: | ||
# TODO: check response error status and report if plugin service rejected request as invalid | ||
logger.exception(f"Plugin service returned invalid response:\n{response.text if response else None}") | ||
logger.info("Returning original run spec") | ||
return spec | ||
logger.info(f"Using RunSpec from plugin service:\n{spec}") | ||
return spec | ||
def on_run_apply(self, user: str, project: str, spec: RunSpec) -> RunSpec: | ||
return self._call_plugin_service(user, project, spec, '/runs/pre_apply') | ||
Nadine-H marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def on_fleet_apply(self, user: str, project: str, spec: FleetSpec) -> FleetSpec: | ||
return self._call_plugin_service(user, project, spec, '/fleets/pre_apply') | ||
|
||
def on_volume_apply(self, user: str, project: str, spec: VolumeSpec) -> VolumeSpec: | ||
return self._call_plugin_service(user, project, spec, '/volumes/pre_apply') | ||
|
||
def on_gateway_apply(self, user: str, project: str, spec: GatewaySpec) -> GatewaySpec: | ||
return self._call_plugin_service(user, project, spec, '/gateways/pre_apply') | ||
|
||
class RESTPlugin(Plugin): | ||
def get_apply_policies(self) -> list[ApplyPolicy]: | ||
return [PreApplyPolicy()] |
Empty file.
Nadine-H marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
from dstack._internal.core.errors import ServerError | ||
from dstack._internal.server.models import ProjectModel, UserModel | ||
from plugins.rest_plugin.src.rest_plugin import PreApplyPolicy, PLUGIN_SERVICE_URI_ENV_VAR_NAME | ||
import pytest | ||
from sqlalchemy.ext.asyncio import AsyncSession | ||
from pydantic import parse_obj_as | ||
import os | ||
import json | ||
import requests | ||
from unittest.mock import Mock | ||
|
||
from dstack._internal.core.models.runs import RunSpec | ||
from dstack._internal.core.models.configurations import ServiceConfiguration | ||
from dstack._internal.core.models.profiles import Profile | ||
from dstack._internal.core.models.resources import Range | ||
from dstack._internal.server.testing.common import ( | ||
create_project, | ||
create_user, | ||
create_repo, | ||
get_run_spec, | ||
) | ||
from dstack._internal.server.testing.conf import session, test_db # noqa: F401 | ||
from dstack._internal.server.services import encryption as encryption # import for side-effect | ||
import pytest_asyncio | ||
from unittest import mock | ||
|
||
|
||
async def create_run_spec( | ||
session: AsyncSession, | ||
project: ProjectModel, | ||
replicas: str = 1, | ||
) -> RunSpec: | ||
repo = await create_repo(session=session, project_id=project.id) | ||
run_name = "test-run" | ||
profile = Profile(name="test-profile") | ||
spec = get_run_spec( | ||
repo_id=repo.name, | ||
run_name=run_name, | ||
profile=profile, | ||
configuration=ServiceConfiguration( | ||
commands=["echo hello"], | ||
port=8000, | ||
replicas=parse_obj_as(Range[int], replicas) | ||
), | ||
) | ||
return spec | ||
|
||
@pytest_asyncio.fixture | ||
async def project(session): | ||
return await create_project(session=session) | ||
|
||
@pytest_asyncio.fixture | ||
async def user(session): | ||
return await create_user(session=session) | ||
|
||
@pytest_asyncio.fixture | ||
async def run_spec(session, project): | ||
return await create_run_spec(session=session, project=project) | ||
|
||
|
||
class TestRESTPlugin: | ||
@pytest.mark.asyncio | ||
async def test_on_run_apply_plugin_service_uri_not_set(self): | ||
with pytest.raises(ServerError): | ||
policy = PreApplyPolicy() | ||
|
||
@pytest.mark.asyncio | ||
@mock.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) | ||
@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) | ||
async def test_on_run_apply_plugin_service_returns_mutated_spec(self, test_db, user, project, run_spec): | ||
policy = PreApplyPolicy() | ||
mock_response = Mock() | ||
run_spec_dict = run_spec.dict() | ||
run_spec_dict["profile"]["tags"] = {"env": "test", "team": "qa"} | ||
mock_response.text = json.dumps(run_spec_dict) | ||
mock_response.raise_for_status = Mock() | ||
with mock.patch("requests.post", return_value=mock_response): | ||
result = policy.on_apply(user=user.name, project=project.name, spec=run_spec) | ||
assert result == RunSpec(**run_spec_dict) | ||
|
||
@pytest.mark.asyncio | ||
@mock.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) | ||
@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) | ||
async def test_on_run_apply_plugin_service_call_fails(self, test_db, user, project, run_spec): | ||
policy = PreApplyPolicy() | ||
with mock.patch("requests.post", side_effect=requests.RequestException("fail")): | ||
result = policy.on_apply(user=user.name, project=project.name, spec=run_spec) | ||
assert result == run_spec | ||
|
||
@pytest.mark.asyncio | ||
@mock.patch.dict(os.environ, {PLUGIN_SERVICE_URI_ENV_VAR_NAME: "http://mock"}) | ||
@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) | ||
async def test_on_run_apply_plugin_service_returns_invalid_spec(self, test_db, user, project, run_spec): | ||
policy = PreApplyPolicy() | ||
mock_response = Mock() | ||
mock_response.text = json.dumps({"invalid-key": "abc"}) | ||
mock_response.raise_for_status = Mock() | ||
with mock.patch("requests.post", return_value=mock_response): | ||
result = policy.on_apply(user.name, project=project.name, spec=run_spec) | ||
# return original run spec | ||
assert result == run_spec | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.