frontend.py 4.13 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

16
import logging
17
import os
18
import subprocess
19
from pathlib import Path
20

21
from components.planner_service import Planner
22
23
from components.processor import Processor
from components.worker import VllmWorker
24
25
from pydantic import BaseModel

26
from dynamo import sdk
27
from dynamo.sdk import api, async_on_shutdown, depends, service
28
from dynamo.sdk.lib.config import ServiceConfig
29
from dynamo.sdk.lib.image import DYNAMO_IMAGE
30

31
32
logger = logging.getLogger(__name__)

33
34
35
# TODO: temp workaround to avoid port conflict with subprocess HTTP server; remove this once ingress is fixed
os.environ["DYNAMO_PORT"] = "3999"

36

37
def get_http_binary_path():
38
    """Find the HTTP binary path in SDK or fallback to 'http' command."""
39
40
41
42
43
44
45
46
    sdk_path = Path(sdk.__file__)
    binary_path = sdk_path.parent / "cli/bin/http"
    if not binary_path.exists():
        return "http"
    else:
        return str(binary_path)


47
class FrontendConfig(BaseModel):
48
49
    """Configuration for the Frontend service including model and HTTP server settings."""

50
    served_model_name: str
51
52
53
54
    endpoint: str
    port: int = 8080


55
# todo this should be called ApiServer
56
@service(
57
58
59
    dynamo={
        "namespace": "dynamo",
    },
60
61
    resources={"cpu": "10", "memory": "20Gi"},
    workers=1,
62
    image=DYNAMO_IMAGE,
63
64
)
class Frontend:
65
    planner = depends(Planner)
66
67
68
69
    worker = depends(VllmWorker)
    processor = depends(Processor)

    def __init__(self):
70
        """Initialize Frontend service with HTTP server and model configuration."""
71
        frontend_config = FrontendConfig(**ServiceConfig.get_parsed_config("Frontend"))
72
73
74
75
76
77
        self.frontend_config = frontend_config
        self.process = None
        self.setup_model()
        self.start_http_server()

    def setup_model(self):
78
        """Configure the model for HTTP service using llmctl."""
79
        subprocess.run(
80
81
82
83
84
            [
                "llmctl",
                "http",
                "remove",
                "chat-models",
85
                self.frontend_config.served_model_name,
86
87
            ],
            check=False,
88
89
90
91
92
93
94
        )
        subprocess.run(
            [
                "llmctl",
                "http",
                "add",
                "chat-models",
95
96
                self.frontend_config.served_model_name,
                self.frontend_config.endpoint,
97
98
            ],
            check=False,
99
100
        )

101
    def start_http_server(self):
102
        """Start the HTTP server on the configured port."""
103
        logger.info("Starting HTTP server")
104
        http_binary = get_http_binary_path()
105

106
107
108
109
        self.process = subprocess.Popen(
            [http_binary, "-p", str(self.frontend_config.port)],
            stdout=None,
            stderr=None,
110
        )
111

112
113
114
115
116
117
118
119
120
121
122
    @api()
    def dummy_api(self) -> None:
        """
        Dummy API to enable the HTTP server for the Dynamo operator.
        This API is not used by the model.

        NOTE: this is a temporary solution to expose ingress
        for the LLM examples. Will be fixed and removed in the future.
        The resulting api_endpoints in dynamo.yaml will be incorrect.
        """

123
    @async_on_shutdown
124
    def cleanup(self):
125
126
127
        """Clean up resources before shutdown."""

        # circusd manages shutdown of http server process, we just need to remove the model using the on_shutdown hook
128
129
130
131
132
133
134
        subprocess.run(
            [
                "llmctl",
                "http",
                "remove",
                "chat-models",
                self.frontend_config.served_model_name,
135
136
            ],
            check=False,
137
        )