python_code
stringlengths
0
108k
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
raise NotImplementedError( f"""\ Support for "{__name__}" is temporarily unavailable as BentoML transition to the new \ design in version 1.0.0 release. Before this module is officially implemented in \ BentoML, users may use Custom Runner as a workaround. Learn more at http://docs.bentoml.org """ )
from __future__ import annotations import os import typing as t import datetime from abc import ABC from abc import abstractmethod from contextlib import contextmanager import fs import fs.errors from fs.base import FS from .tag import Tag from .types import PathType from .exportable import Exportable from ..exceptions import NotFound from ..exceptions import BentoMLException T = t.TypeVar("T") class StoreItem(Exportable): @property @abstractmethod def tag(self) -> Tag: raise NotImplementedError @property def _fs(self) -> FS: raise NotImplementedError @classmethod def get_typename(cls) -> str: return cls.__name__ @property def _export_name(self) -> str: return f"{self.tag.name}-{self.tag.version}" @property @abstractmethod def creation_time(self) -> datetime.datetime: raise NotImplementedError def __repr__(self): return f'{self.get_typename()}(tag="{self.tag}")' Item = t.TypeVar("Item", bound=StoreItem) class Store(ABC, t.Generic[Item]): """An FsStore manages items under the given base filesystem. Note that FsStore has no consistency checks; it assumes that no direct modification of the files in its directory has occurred. """ _fs: FS _item_type: t.Type[Item] @abstractmethod def __init__(self, base_path: t.Union[PathType, FS], item_type: t.Type[Item]): self._item_type = item_type if isinstance(base_path, os.PathLike): base_path = base_path.__fspath__() self._fs = fs.open_fs(base_path) def list(self, tag: t.Optional[t.Union[Tag, str]] = None) -> t.List[Item]: if not tag: return [ ver for _d in sorted(self._fs.listdir("/")) if self._fs.isdir(_d) for ver in self.list(_d) ] _tag = Tag.from_taglike(tag) if _tag.version is None: if not self._fs.isdir(_tag.name): raise NotFound( f"no {self._item_type.get_typename()}s with name '{_tag.name}' found" ) tags = sorted( [ Tag(_tag.name, f.name) for f in self._fs.scandir(_tag.name) if f.is_dir ] ) return [self._get_item(t) for t in tags] else: return [self._get_item(_tag)] if self._fs.isdir(_tag.path()) else [] def _get_item(self, tag: Tag) -> Item: """ Creates a new instance of Item that represents the item with tag `tag`. """ return self._item_type.from_fs(self._fs.opendir(tag.path())) def _recreate_latest(self, tag: Tag): try: items = self.list(tag.name) except NotFound: raise NotFound( f"no {self._item_type.get_typename()}s with name '{tag.name}' exist in BentoML store {self._fs}" ) if len(items) == 0: raise NotFound( f"no {self._item_type.get_typename()}s with name '{tag.name}' exist in BentoML store {self._fs}" ) items.sort(reverse=True, key=lambda item: item.creation_time) tag.version = items[0].tag.version with self._fs.open(tag.latest_path(), "w") as latest_file: latest_file.write(tag.version) def get(self, tag: t.Union[Tag, str]) -> Item: """ store.get("my_bento") store.get("my_bento:v1.0.0") store.get(Tag("my_bento", "latest")) """ _tag = Tag.from_taglike(tag) if _tag.version is None or _tag.version == "latest": try: _tag.version = self._fs.readtext(_tag.latest_path()) if not self._fs.exists(_tag.path()): self._recreate_latest(_tag) except fs.errors.ResourceNotFound: self._recreate_latest(_tag) path = _tag.path() if self._fs.exists(path): return self._get_item(_tag) matches = self._fs.glob(f"{path}*/") counts = matches.count().directories if counts == 0: raise NotFound( f"{self._item_type.get_typename()} '{tag}' is not found in BentoML store {self._fs}" ) elif counts == 1: match = next(iter(matches)) return self._get_item(Tag(_tag.name, match.info.name)) else: vers: t.List[str] = [] for match in matches: vers += match.info.name raise BentoMLException( f"multiple versions matched by {_tag.version}: {vers}" ) @contextmanager def register(self, tag: t.Union[str, Tag]): _tag = Tag.from_taglike(tag) item_path = _tag.path() if self._fs.exists(item_path): raise BentoMLException( f"Item '{_tag}' already exists in the store {self._fs}" ) self._fs.makedirs(item_path) try: yield self._fs.getsyspath(item_path) finally: # item generation is most likely successful, link latest path if ( not self._fs.exists(_tag.latest_path()) or self.get(_tag).creation_time >= self.get(_tag.name).creation_time ): with self._fs.open(_tag.latest_path(), "w") as latest_file: latest_file.write(_tag.version) def delete(self, tag: t.Union[str, Tag]) -> None: _tag = Tag.from_taglike(tag) if not self._fs.exists(_tag.path()): raise NotFound(f"{self._item_type.get_typename()} '{tag}' not found") self._fs.removetree(_tag.path()) if self._fs.isdir(_tag.name): versions = self.list(_tag.name) if len(versions) == 0: # if we've removed all versions, remove the directory self._fs.removetree(_tag.name) else: new_latest = sorted(versions, key=lambda x: x.creation_time)[-1] # otherwise, update the latest version assert new_latest.tag.version is not None self._fs.writetext(_tag.latest_path(), new_latest.tag.version)
from __future__ import annotations from contextvars import ContextVar from opentelemetry import trace # type: ignore[import] class ServiceContextClass: def __init__(self) -> None: self.request_id_var: ContextVar[int | None] = ContextVar( "request_id_var", default=None ) self.component_name_var: ContextVar[str] = ContextVar( "component_name", default="cli" ) @property def sampled(self) -> int | None: span = trace.get_current_span() if span is None: return None return 1 if span.get_span_context().trace_flags.sampled else 0 @property def trace_id(self) -> int | None: span = trace.get_current_span() if span is None: return None return span.get_span_context().trace_id @property def span_id(self) -> int | None: span = trace.get_current_span() if span is None: return None return span.get_span_context().span_id @property def request_id(self) -> int | None: return self.request_id_var.get() @property def component_name(self) -> str | None: return self.component_name_var.get() ServiceContext = ServiceContextClass()
from __future__ import annotations import typing as t import logging import logging.config from .trace import ServiceContext from .configuration import get_debug_mode from .configuration import get_quiet_mode default_factory = logging.getLogRecordFactory() # TODO: remove this filter after implementing CLI output as something other than INFO logs class InfoFilter(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: return logging.INFO <= record.levelno < logging.WARNING # TODO: can be removed after the above is complete CLI_LOGGING_CONFIG: dict[str, t.Any] = { "version": 1, "disable_existing_loggers": True, "filters": {"infofilter": {"()": InfoFilter}}, "handlers": { "bentomlhandler": { "class": "logging.StreamHandler", "filters": ["infofilter"], "stream": "ext://sys.stdout", }, "defaulthandler": { "class": "logging.StreamHandler", "level": logging.WARNING, }, }, "loggers": { "bentoml": { "handlers": ["bentomlhandler", "defaulthandler"], "level": logging.INFO, "propagate": False, }, }, "root": {"level": logging.WARNING}, } TRACED_LOG_FORMAT = ( "%(asctime)s %(levelname_bracketed)s %(component)s %(message)s%(trace_msg)s" ) DATE_FORMAT = "%Y-%m-%dT%H:%M:%S%z" SERVER_LOGGING_CONFIG: dict[str, t.Any] = { "version": 1, "disable_existing_loggers": True, "formatters": { "traced": { "format": TRACED_LOG_FORMAT, "datefmt": DATE_FORMAT, } }, "handlers": { "tracehandler": { "class": "logging.StreamHandler", "formatter": "traced", }, }, "loggers": { "bentoml": { "level": logging.INFO, "handlers": ["tracehandler"], "propagate": False, }, }, "root": { "handlers": ["tracehandler"], "level": logging.WARNING, }, } def configure_logging(): # TODO: convert to simple 'logging.basicConfig' after we no longer need the filter if get_quiet_mode(): CLI_LOGGING_CONFIG["loggers"]["bentoml"]["level"] = logging.ERROR CLI_LOGGING_CONFIG["root"]["level"] = logging.ERROR elif get_debug_mode(): CLI_LOGGING_CONFIG["loggers"]["bentoml"]["level"] = logging.DEBUG CLI_LOGGING_CONFIG["root"]["level"] = logging.DEBUG else: CLI_LOGGING_CONFIG["loggers"]["bentoml"]["level"] = logging.INFO CLI_LOGGING_CONFIG["root"]["level"] = logging.WARNING logging.config.dictConfig(CLI_LOGGING_CONFIG) def trace_record_factory(*args: t.Any, **kwargs: t.Any): record = default_factory(*args, **kwargs) record.levelname_bracketed = f"[{record.levelname}]" # type: ignore (adding fields to record) record.component = f"[{ServiceContext.component_name}]" # type: ignore (adding fields to record) if ServiceContext.trace_id == 0: record.trace_msg = "" # type: ignore (adding fields to record) else: record.trace_msg = f" (trace={ServiceContext.trace_id},span={ServiceContext.span_id},sampled={ServiceContext.sampled})" # type: ignore (adding fields to record) record.request_id = ServiceContext.request_id # type: ignore (adding fields to record) return record def configure_server_logging(): if get_quiet_mode(): SERVER_LOGGING_CONFIG["loggers"]["bentoml"]["level"] = logging.ERROR SERVER_LOGGING_CONFIG["root"]["level"] = logging.ERROR elif get_debug_mode(): SERVER_LOGGING_CONFIG["loggers"]["bentoml"]["level"] = logging.DEBUG SERVER_LOGGING_CONFIG["root"]["level"] = logging.DEBUG else: SERVER_LOGGING_CONFIG["loggers"]["bentoml"]["level"] = logging.INFO SERVER_LOGGING_CONFIG["root"]["level"] = logging.WARNING logging.setLogRecordFactory(trace_record_factory) logging.config.dictConfig(SERVER_LOGGING_CONFIG)
from __future__ import annotations import os import re import typing as t import logging import urllib.parse from abc import ABC from abc import abstractmethod import fs import fs.copy import fs.errors import fs.mirror import fs.opener import fs.tempfs from fs import open_fs from fs.base import FS T = t.TypeVar("T", bound="Exportable") uriSchemeRe = re.compile(r".*[^\\](?=://)") class Exportable(ABC): @staticmethod @abstractmethod def _export_ext() -> str: raise NotImplementedError @property @abstractmethod def _export_name(self) -> str: raise NotImplementedError @property @abstractmethod def _fs(self) -> FS: raise NotImplementedError @classmethod @abstractmethod def from_fs(cls: t.Type[T], item_fs: FS) -> T: raise NotImplementedError @classmethod def guess_format(cls, path: str) -> str: _, ext = fs.path.splitext(path) if ext == "": return cls._export_ext() ext = ext[1:] if ext in [cls._export_ext(), "gz", "xz", "bz2", "tar", "zip"]: return ext else: return cls._export_ext() @classmethod def import_from( cls: t.Type[T], path: str, input_format: t.Optional[str] = None, *, protocol: t.Optional[str] = None, user: t.Optional[str] = None, passwd: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None, subpath: t.Optional[str] = None, ) -> T: try: parsedurl = fs.opener.parse(path) except fs.opener.errors.ParseError: # type: ignore (FS types) if protocol is None: protocol = "osfs" resource: str = path if os.sep == "/" else path.replace(os.sep, "/") else: resource: str = "" else: if any(v is not None for v in [protocol, user, passwd, params, subpath]): raise ValueError( "An FS URL was passed as the output path; all additional information should be passed as part of the URL." ) protocol = parsedurl.protocol # type: ignore (FS types) user = parsedurl.username # type: ignore (FS types) passwd = parsedurl.password # type: ignore (FS types) resource: str = parsedurl.resource # type: ignore (FS types) params = parsedurl.params # type: ignore (FS types) subpath = parsedurl.path # type: ignore (FS types) if protocol not in fs.opener.registry.protocols: # type: ignore (FS types) if protocol == "s3": raise ValueError( "Tried to open an S3 url but the protocol is not registered; did you 'pip install fs-s3fs'?" ) else: raise ValueError( f"Unknown or unsupported protocol {protocol}. Some supported protocols are 'ftp', 's3', and 'osfs'." ) isOSPath = protocol in [ "temp", "osfs", "userdata", "userconf", "sitedata", "siteconf", "usercache", "userlog", ] isCompressedPath = protocol in ["tar", "zip"] if input_format is not None: if isCompressedPath: raise ValueError( f"A {protocol} path was passed along with an input format ({input_format}); only pass one or the other." ) else: # try to guess output format if it hasn't been passed input_format = cls.guess_format(resource if subpath is None else subpath) if subpath is None: if isCompressedPath: subpath = "" else: resource, subpath = fs.path.split(resource) if isOSPath: # we can safely ignore user / passwd / params # get the path on the system so we can skip the copy step try: rsc_dir = fs.open_fs(f"{protocol}://{resource}") # if subpath is root, we can just open directly if (subpath == "" or subpath == "/") and input_format == "folder": return cls.from_fs(rsc_dir) # if subpath is specified, we need to create our own temp fs and mirror that subpath path = rsc_dir.getsyspath(subpath) res = cls._from_compressed(path, input_format) except fs.errors.CreateFailed: raise ValueError("Directory does not exist") else: userblock = "" if user is not None or passwd is not None: if user is not None: userblock += urllib.parse.quote(user) if passwd is not None: userblock += ":" + urllib.parse.quote(passwd) userblock += "@" resource = urllib.parse.quote(resource) query = "" if params is not None: query = "?" + urllib.parse.urlencode(params) input_uri = f"{protocol}://{userblock}{resource}{query}" if isCompressedPath: input_fs = fs.open_fs(input_uri) res = cls.from_fs(input_fs) else: filename = fs.path.basename(subpath) tempfs = fs.tempfs.TempFS(identifier=f"bentoml-{filename}-import") if input_format == "folder": input_fs = fs.open_fs(input_uri) fs.copy.copy_dir(input_fs, subpath, tempfs, filename) else: input_fs = fs.open_fs(input_uri) fs.copy.copy_file(input_fs, subpath, tempfs, filename) res = cls._from_compressed(tempfs.getsyspath(filename), input_format) input_fs.close() return res def export( self, path: str, output_format: t.Optional[str] = None, *, protocol: t.Optional[str] = None, user: t.Optional[str] = None, passwd: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None, subpath: t.Optional[str] = None, ) -> str: try: parsedurl = fs.opener.parse(path) except fs.opener.errors.ParseError: # type: ignore (incomplete FS types) if protocol is None: protocol = "osfs" resource = path if os.sep == "/" else path.replace(os.sep, "/") else: resource = "" else: if any(v is not None for v in [protocol, user, passwd, params, subpath]): raise ValueError( "An FS URL was passed as the output path; all additional information should be passed as part of the URL." ) protocol = parsedurl.protocol # type: ignore (incomplete FS types) user = parsedurl.username # type: ignore (incomplete FS types) passwd = parsedurl.password # type: ignore (incomplete FS types) resource: str = parsedurl.resource # type: ignore (incomplete FS types) params = parsedurl.params # type: ignore (incomplete FS types) subpath = parsedurl.path # type: ignore (incomplete FS types) if protocol not in fs.opener.registry.protocols: # type: ignore (incomplete FS types) if protocol == "s3": raise ValueError( "Tried to open an S3 url but the protocol is not registered; did you install fs-s3fs?" ) else: raise ValueError( f"Unknown or unsupported protocol {protocol}. Some supported protocols are 'ftp', 's3', and 'osfs'." ) isOSPath = protocol in [ "temp", "osfs", "userdata", "userconf", "sitedata", "siteconf", "usercache", "userlog", ] isCompressedPath = protocol in ["tar", "zip"] if output_format is not None: if isCompressedPath: raise ValueError( f"A {protocol} path was passed along with an output format ({output_format}); only pass one or the other." ) else: # try to guess output format if it hasn't been passed output_format = self.guess_format(resource if subpath is None else subpath) # use combine here instead of join because we don't want to fold subpath into path. fullpath = resource if subpath is None else fs.path.combine(resource, subpath) if fullpath == "" or (not output_format == "folder" and fullpath[-1] == "/"): subpath = "" if subpath is None else subpath # if the path has no filename or is empty, we generate a filename from the bento tag subpath = fs.path.join(subpath, self._export_name) if output_format in ["gz", "xz", "bz2", "tar", "zip"]: subpath += "." + output_format elif isOSPath: try: dirfs = fs.open_fs(path) except fs.errors.CreateFailed: pass else: if subpath is None or dirfs.isdir(subpath): subpath = "" if subpath is None else subpath # path exists and is a directory, we will create a file inside that directory subpath = fs.path.join(subpath, self._export_name) if output_format in ["gz", "xz", "bz2", "tar", "zip"]: subpath += "." + output_format if subpath is None: if isCompressedPath: subpath = "" else: resource, subpath = fs.path.split(resource) # as a special case, if the output format is the default we will always append the relevant # extension if the output filename does not have it if ( output_format == self._export_ext() and fs.path.splitext(subpath)[1] != "." + self._export_ext() ): logging.info( f"adding {self._export_ext} because ext is {fs.path.splitext(subpath)[1]}" ) subpath += "." + self._export_ext() if isOSPath: # we can safely ignore user / passwd / params # get the path on the system so we can skip the copy step try: rsc_dir = fs.open_fs(f"{protocol}://{resource}") path = rsc_dir.getsyspath(subpath) self._compress(path, output_format) except fs.errors.CreateFailed: raise ValueError( f"Output directory '{protocol}://{resource}' does not exist." ) else: userblock = "" if user is not None or passwd is not None: if user is not None: userblock += urllib.parse.quote(user) if passwd is not None: userblock += ":" + urllib.parse.quote(passwd) userblock += "@" resource = urllib.parse.quote(resource) query = "" if params is not None: query = "?" + urllib.parse.urlencode(params) dest_uri = f"{protocol}://{userblock}{resource}{query}" if isCompressedPath: destfs = fs.open_fs(dest_uri, writeable=True, create=True) fs.mirror.mirror(self._fs, destfs, copy_if_newer=False) else: tempfs = fs.tempfs.TempFS( identifier=f"bentoml-{self._export_name}-export" ) filename = fs.path.basename(subpath) self._compress(tempfs.getsyspath(filename), output_format) if output_format == "folder": destfs = fs.open_fs(dest_uri) fs.copy.copy_dir(tempfs, filename, destfs, subpath) else: destfs = fs.open_fs(dest_uri) fs.copy.copy_file(tempfs, filename, destfs, subpath) tempfs.close() destfs.close() return path def _compress(self, path: str, output_format: str): if output_format in ["gz", "xz", "bz2", "tar", self._export_ext()]: from fs.tarfs import WriteTarFS compression = output_format if compression == "tar": compression = None if compression == self._export_ext(): compression = "xz" out_fs = WriteTarFS(path, compression) elif output_format == "zip": from fs.zipfs import WriteZipFS out_fs = WriteZipFS(path) elif output_format == "folder": out_fs: FS = open_fs(path, writeable=True, create=True) else: raise ValueError(f"Unsupported format {output_format}") fs.mirror.mirror(self._fs, out_fs, copy_if_newer=False) out_fs.close() @classmethod def _from_compressed(cls: t.Type[T], path: str, input_format: str) -> T: if input_format in ["gz", "xz", "bz2", "tar", cls._export_ext()]: from fs.tarfs import ReadTarFS compression = input_format if compression == "tar": compression = None if compression == cls._export_ext(): compression = "xz" ret_fs = ReadTarFS(path) elif input_format == "zip": from fs.zipfs import ReadZipFS ret_fs = ReadZipFS(path) elif input_format == "folder": ret_fs: FS = open_fs(path) else: raise ValueError(f"Unsupported format {input_format}") return cls.from_fs(ret_fs)
from __future__ import annotations import io import os import sys import typing as t import logging from types import TracebackType from typing import TYPE_CHECKING from datetime import date from datetime import time from datetime import datetime from datetime import timedelta from dataclasses import dataclass from .utils.dataclasses import json_serializer if sys.version_info < (3, 8): from typing_extensions import get_args from typing_extensions import get_origin else: from typing import get_args from typing import get_origin if sys.version_info < (3, 10): from typing_extensions import ParamSpec else: from typing import ParamSpec __all__ = [ "ParamSpec", "MetadataType", "MetadataDict", "JSONSerializable", "LazyType", "is_compatible_type", "FileLike", ] logger = logging.getLogger(__name__) BATCH_HEADER = "Bentoml-Is-Batch-Request" # For non latin1 characters: https://tools.ietf.org/html/rfc8187 # Also https://github.com/benoitc/gunicorn/issues/1778 HEADER_CHARSET = "latin1" JSON_CHARSET = "utf-8" if TYPE_CHECKING: PathType = t.Union[str, os.PathLike[str]] else: PathType = t.Union[str, os.PathLike] MetadataType: t.TypeAlias = t.Union[ str, bytes, bool, int, float, complex, datetime, date, time, timedelta, t.List["MetadataType"], t.Tuple["MetadataType"], t.Dict[str, "MetadataType"], ] MetadataDict = t.Dict[str, MetadataType] JSONSerializable = t.NewType("JSONSerializable", object) T = t.TypeVar("T") class LazyType(t.Generic[T]): """ LazyType provides solutions for several conflicts when applying lazy dependencies, type annotations and runtime class checking. It works both for runtime and type checking phases. * conflicts 1 isinstance(obj, class) requires importing the class first, which breaks lazy dependencies solution: >>> LazyType("numpy.ndarray").isinstance(obj) * conflicts 2 `isinstance(obj, str)` will narrow obj types down to str. But it only works for the case that the class is the type at the same time. For numpy.ndarray which the type is actually numpy.typing.NDArray, we had to hack the type checking. solution: >>> if TYPE_CHECKING: >>> from numpy.typing import NDArray >>> LazyType["NDArray"]("numpy.ndarray").isinstance(obj)` >>> # this will narrow the obj to NDArray with PEP-647 * conflicts 3 compare/refer/map classes before importing them. >>> HANDLER_MAP = { >>> LazyType("numpy.ndarray"): ndarray_handler, >>> LazyType("pandas.DataFrame"): pdframe_handler, >>> } >>> >>> HANDLER_MAP[LazyType(numpy.ndarray)]](array) >>> LazyType("numpy.ndarray") == numpy.ndarray """ @t.overload def __init__(self, module_or_cls: str, qualname: str) -> None: """LazyType("numpy", "ndarray")""" @t.overload def __init__(self, module_or_cls: t.Type[T]) -> None: """LazyType(numpy.ndarray)""" @t.overload def __init__(self, module_or_cls: str) -> None: """LazyType("numpy.ndarray")""" def __init__( self, module_or_cls: str | t.Type[T], qualname: str | None = None, ) -> None: if isinstance(module_or_cls, str): if qualname is None: # LazyType("numpy.ndarray") parts = module_or_cls.rsplit(".", 1) if len(parts) == 1: raise ValueError("LazyType only works with classes") self.module, self.qualname = parts else: # LazyType("numpy", "ndarray") self.module = module_or_cls self.qualname = qualname self._runtime_class = None else: # LazyType(numpy.ndarray) self._runtime_class = module_or_cls self.module = module_or_cls.__module__ if hasattr(module_or_cls, "__qualname__"): self.qualname: str = getattr(module_or_cls, "__qualname__") else: self.qualname: str = getattr(module_or_cls, "__name__") def __instancecheck__(self, obj) -> "t.TypeGuard[T]": return self.isinstance(obj) @classmethod def from_type(cls, typ_: t.Union["LazyType[T]", "t.Type[T]"]) -> "LazyType[T]": if isinstance(typ_, LazyType): return typ_ return cls(typ_) def __eq__(self, o: object) -> bool: """ LazyType("numpy", "ndarray") == np.ndarray """ if isinstance(o, type): o = self.__class__(o) if isinstance(o, LazyType): return self.module == o.module and self.qualname == o.qualname return False def __hash__(self) -> int: return hash(f"{self.module}.{self.qualname}") def __repr__(self) -> str: return f'LazyType("{self.module}", "{self.qualname}")' def get_class(self, import_module: bool = True) -> t.Type[T]: if self._runtime_class is None: try: m = sys.modules[self.module] except KeyError: if import_module: import importlib m = importlib.import_module(self.module) else: raise ValueError(f"Module {self.module} not imported") self._runtime_class = t.cast("t.Type[T]", getattr(m, self.qualname)) return self._runtime_class def isinstance(self, obj: t.Any) -> "t.TypeGuard[T]": try: return isinstance(obj, self.get_class(import_module=False)) except ValueError: return False if TYPE_CHECKING: from types import UnionType AnyType: t.TypeAlias = t.Type[t.Any] | UnionType | LazyType[t.Any] def is_compatible_type(t1: AnyType, t2: AnyType) -> bool: """ A very loose check that it is possible for an object to be both an instance of ``t1`` and an instance of ``t2``. Note: this will resolve ``LazyType``s, so should not be used in any peformance-critical contexts. """ if get_origin(t1) is t.Union: return any((is_compatible_type(t2, arg_type) for arg_type in get_args(t1))) if get_origin(t2) is t.Union: return any((is_compatible_type(t1, arg_type) for arg_type in get_args(t2))) if isinstance(t1, LazyType): t1 = t1.get_class() if isinstance(t2, LazyType): t2 = t2.get_class() if isinstance(t1, type) and isinstance(t2, type): return issubclass(t1, t2) or issubclass(t2, t1) # catchall return true in unsupported cases so we don't error on unsupported types return True @json_serializer(fields=["uri", "name"], compat=True) @dataclass(frozen=False) class FileLike(t.Generic[t.AnyStr], io.IOBase): """ A wrapper for file-like objects that includes a custom name. """ _wrapped: t.IO[t.AnyStr] _name: str @property def mode(self) -> str: return self._wrapped.mode @property def name(self) -> str: return self._name def close(self): self._wrapped.close() @property def closed(self) -> bool: return self._wrapped.closed def fileno(self) -> int: return self._wrapped.fileno() def flush(self): self._wrapped.flush() def isatty(self) -> bool: return self._wrapped.isatty() def read(self, size: int = -1) -> t.AnyStr: # type: ignore # pylint: disable=arguments-renamed # python IO types return self._wrapped.read(size) def readable(self) -> bool: return self._wrapped.readable() def readline(self, size: int = -1) -> t.AnyStr: # type: ignore (python IO types) return self._wrapped.readline(size) def readlines(self, size: int = -1) -> t.List[t.AnyStr]: # type: ignore (python IO types) return self._wrapped.readlines(size) def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: return self._wrapped.seek(offset, whence) def seekable(self) -> bool: return self._wrapped.seekable() def tell(self) -> int: return self._wrapped.tell() def truncate(self, size: t.Optional[int] = None) -> int: return self._wrapped.truncate(size) def writable(self) -> bool: return self._wrapped.writable() def write(self, s: t.AnyStr) -> int: # type: ignore (python IO types) return self._wrapped.write(s) def writelines(self, lines: t.Iterable[t.AnyStr]): # type: ignore (python IO types) return self._wrapped.writelines(lines) def __next__(self) -> t.AnyStr: # type: ignore (python IO types) return next(self._wrapped) def __iter__(self) -> t.Iterator[t.AnyStr]: # type: ignore (python IO types) return self._wrapped.__iter__() def __enter__(self) -> t.IO[t.AnyStr]: return self._wrapped.__enter__() def __exit__( # type: ignore (python IO types) self, typ: t.Optional[t.Type[BaseException]], value: t.Optional[BaseException], traceback: t.Optional[TracebackType], ) -> t.Optional[bool]: return self._wrapped.__exit__(typ, value, traceback)
from __future__ import annotations import typing as t import contextvars from abc import ABC from abc import abstractmethod from typing import TYPE_CHECKING import attr import starlette.datastructures from .utils.http import Cookie if TYPE_CHECKING: import starlette.requests import starlette.responses class Metadata(t.Mapping[str, str], ABC): @abstractmethod def __setitem__(self, key: str, value: str) -> None: """ Set the header ``key`` to ``value``, removing any duplicate entries. Retains insertion order. """ @abstractmethod def __delitem__(self, key: str) -> None: """ Remove the header ``key``. """ @abstractmethod def __ior__(self, other: t.Mapping[t.Any, t.Any]) -> Metadata: """ Updates this metadata with the contents of ``other`` """ @abstractmethod def __or__(self, other: t.Mapping[t.Any, t.Any]) -> Metadata: """ Returns a new metadata object with the contents of this metadata object updated with the contents of ``other`` """ @abstractmethod def update(self, other: t.Mapping[t.Any, t.Any]) -> None: """ Sets all the headers in ``other`` in this object. For example, if this object is ``{"my-header": "my-value", "my-other-header": "my-other-value"}`` and other is {"my-header": 3¸ "other-header": 4} """ @abstractmethod def setdefault(self, key: str, value: str) -> str: """ If the header ``key`` does not exist, then set it to ``value``. Returns the header value. """ @abstractmethod def append(self, key: str, value: str) -> None: """ Append a header, preserving any duplicate entries. """ @abstractmethod def mutablecopy(self) -> Metadata: """ Returns a copy of this metadata object. """ @attr.define class InferenceApiContext: request: "RequestContext" response: "ResponseContext" def __init__(self, request: "RequestContext", response: "ResponseContext"): self.request = request self.response = response @staticmethod def from_http(request: "starlette.requests.Request") -> "InferenceApiContext": request_ctx = InferenceApiContext.RequestContext.from_http(request) response_ctx = InferenceApiContext.ResponseContext() return InferenceApiContext(request_ctx, response_ctx) @attr.define class RequestContext: metadata: Metadata headers: Metadata def __init__(self, metadata: Metadata): self.metadata = metadata self.headers = metadata @staticmethod def from_http( request: "starlette.requests.Request", ) -> "InferenceApiContext.RequestContext": return InferenceApiContext.RequestContext(request.headers) # type: ignore (coercing Starlette headers to Metadata) @attr.define class ResponseContext: metadata: Metadata cookies: list[Cookie] headers: Metadata status_code: int = 200 def __init__(self): self.metadata = starlette.datastructures.MutableHeaders() # type: ignore (coercing Starlette headers to Metadata) self.headers = self.metadata # type: ignore (coercing Starlette headers to Metadata) def set_cookie( self, key: str, value: str, max_age: int | None = None, expires: int | None = None, path: str = "/", domain: str | None = None, secure: bool = False, httponly: bool = False, samesite: str = "lax", ): self.cookies.append( Cookie( key, value, max_age, expires, path, domain, secure, httponly, samesite, ) ) class ServiceTraceContext: def __init__(self) -> None: self._request_id_var = contextvars.ContextVar( "_request_id_var", default=t.cast("t.Optional[int]", None) ) @property def trace_id(self) -> t.Optional[int]: from opentelemetry import trace span = trace.get_current_span() if span is None: return None return span.get_span_context().trace_id @property def span_id(self) -> t.Optional[int]: from opentelemetry import trace # type: ignore span = trace.get_current_span() if span is None: return None return span.get_span_context().span_id @property def request_id(self) -> t.Optional[int]: """ Different from span_id, request_id is unique for each inbound request. """ return self._request_id_var.get() @request_id.setter def request_id(self, request_id: t.Optional[int]) -> None: self._request_id_var.set(request_id) @request_id.deleter def request_id(self) -> None: self._request_id_var.set(None) trace_context = ServiceTraceContext()
import re import uuid import base64 import typing as t import logging import fs import attr from .utils import bentoml_cattr from ..exceptions import InvalidArgument from ..exceptions import BentoMLException logger = logging.getLogger(__name__) tag_fmt = "[a-z0-9]([-._a-z0-9]*[a-z0-9])?" tag_max_length = 63 tag_max_length_error_msg = ( "a tag's name or version must be at most {tag_max_length} characters in length" ) tag_invalid_error_msg = "a tag's name or version must consist of alphanumeric characters, '_', '-', or '.', and must start and end with an alphanumeric character" tag_regex = re.compile(f"^{tag_fmt}$") def validate_tag_str(value: str): """ Validate that a tag value (either name or version) is a simple string that: * Must be at most 63 characters long, * Begin and end with an alphanumeric character (`[a-z0-9A-Z]`), and * May contain dashes (`-`), underscores (`_`) dots (`.`), or alphanumerics between. """ errors = [] if len(value) > tag_max_length: errors.append(tag_max_length_error_msg) if tag_regex.match(value) is None: errors.append(tag_invalid_error_msg) if errors: raise InvalidArgument(f"{value} is not a valid tag: " + ", and ".join(errors)) @attr.define(slots=True) class Tag: name: str version: t.Optional[str] def __init__(self, name: str, version: t.Optional[str] = None): lname = name.lower() if name != lname: logger.warning(f"converting {name} to lowercase: {lname}") validate_tag_str(lname) self.name = lname if version is not None: lversion = version.lower() if version != lversion: logger.warning(f"converting {version} to lowercase: {lversion}") validate_tag_str(lversion) self.version = lversion else: self.version = None def __str__(self): if self.version is None: return self.name else: return f"{self.name}:{self.version}" def __repr__(self): return f"{self.__class__.__name__}(name={repr(self.name)}, version={repr(self.version)})" def __eq__(self, other: "Tag") -> bool: return self.name == other.name and self.version == other.version def __lt__(self, other: "Tag") -> bool: if self.name == other.name: if other.version is None: return False if self.version is None: return True return self.version < other.version return self.name < other.name def __hash__(self) -> int: return hash((self.name, self.version)) @classmethod def from_taglike(cls, taglike: t.Union["Tag", str]) -> "Tag": if isinstance(taglike, Tag): return taglike return cls.from_str(taglike) @classmethod def from_str(cls, tag_str: str) -> "Tag": if ":" not in tag_str: return cls(tag_str, None) try: name, _, version = tag_str.partition(":") if not version: # in case users mistakenly define "bento:" raise BentoMLException( f"{tag_str} contains trailing ':'. Maybe you meant to use `{tag_str}:latest`?" ) return cls(name, version) except ValueError: raise BentoMLException(f"Invalid {cls.__name__} {tag_str}") def make_new_version(self) -> "Tag": if self.version is not None: raise ValueError( "tried to run 'make_new_version' on a Tag that already has a version" ) ver_bytes = bytearray(uuid.uuid1().bytes) # cut out the time_hi and node bits of the uuid ver_bytes = ver_bytes[:6] + ver_bytes[8:12] encoded_ver = base64.b32encode(ver_bytes) return Tag(self.name, encoded_ver.decode("ascii").lower()) def path(self) -> str: if self.version is None: return self.name return fs.path.combine(self.name, self.version) def latest_path(self) -> str: return fs.path.combine(self.name, "latest") # Remove after attrs support ForwardRef natively attr.resolve_types(Tag, globals(), locals()) bentoml_cattr.register_structure_hook(Tag, lambda d, _: Tag.from_taglike(d)) # type: ignore[misc] bentoml_cattr.register_unstructure_hook(Tag, lambda tag: str(tag))
import os import uuid import typing as t import logging import multiprocessing from typing import TYPE_CHECKING from dataclasses import dataclass import yaml from schema import Or from schema import And from schema import Use from schema import Schema from schema import Optional from schema import SchemaError from deepmerge import always_merger from simple_di import Provide from simple_di import providers from . import expand_env_var from ..utils import validate_or_create_dir from ...exceptions import BentoMLConfigException if TYPE_CHECKING: from bentoml._internal.models import ModelStore from .. import external_typing as ext from ..utils.analytics import ServeInfo from ..server.metrics.prometheus import PrometheusClient LOGGER = logging.getLogger(__name__) SYSTEM_HOME = os.path.expanduser("~") BENTOML_HOME = expand_env_var( str(os.environ.get("BENTOML_HOME", os.path.join(SYSTEM_HOME, "bentoml"))) ) DEFAULT_BENTOS_PATH = os.path.join(BENTOML_HOME, "bentos") DEFAULT_MODELS_PATH = os.path.join(BENTOML_HOME, "models") validate_or_create_dir(BENTOML_HOME, DEFAULT_BENTOS_PATH, DEFAULT_MODELS_PATH) _check_tracing_type: t.Callable[[str], bool] = lambda s: s in ("zipkin", "jaeger") _larger_than: t.Callable[[int], t.Callable[[int], bool]] = ( lambda target: lambda val: val > target ) _larger_than_zero: t.Callable[[int], bool] = _larger_than(0) def _is_ip_address(addr: str) -> bool: import socket try: socket.inet_aton(addr) return True except socket.error: return False SCHEMA = Schema( { "bento_server": { "port": And(int, _larger_than_zero), "host": And(str, _is_ip_address), "backlog": And(int, _larger_than(64)), "workers": Or(And(int, _larger_than_zero), None), "timeout": And(int, _larger_than_zero), "max_request_size": And(int, _larger_than_zero), "batch_options": { Optional("enabled", default=True): bool, "max_batch_size": Or(And(int, _larger_than_zero), None), "max_latency_ms": Or(And(int, _larger_than_zero), None), }, "ngrok": {"enabled": bool}, "metrics": {"enabled": bool, "namespace": str}, "logging": { # TODO add logging level configuration "access": { "enabled": bool, "request_content_length": Or(bool, None), "request_content_type": Or(bool, None), "response_content_length": Or(bool, None), "response_content_type": Or(bool, None), }, }, "cors": { "enabled": bool, "access_control_allow_origin": Or(str, None), "access_control_allow_credentials": Or(bool, None), "access_control_allow_headers": Or([str], str, None), "access_control_allow_methods": Or([str], str, None), "access_control_max_age": Or(int, None), "access_control_expose_headers": Or([str], str, None), }, }, "runners": { "logging": { # TODO add logging level configuration "access": { "enabled": bool, "request_content_length": Or(bool, None), "request_content_type": Or(bool, None), "response_content_length": Or(bool, None), "response_content_type": Or(bool, None), }, }, }, "tracing": { "type": Or(And(str, Use(str.lower), _check_tracing_type), None), "sample_rate": Or(And(float, lambda i: i >= 0 and i <= 1), None), Optional("zipkin"): {"url": Or(str, None)}, Optional("jaeger"): {"address": Or(str, None), "port": Or(int, None)}, }, Optional("yatai"): { "default_server": Or(str, None), "servers": { str: { "url": Or(str, None), "access_token": Or(str, None), "access_token_header": Or(str, None), "tls": { "root_ca_cert": Or(str, None), "client_key": Or(str, None), "client_cert": Or(str, None), "client_certificate_file": Or(str, None), }, }, }, }, } ) class BentoMLConfiguration: def __init__( self, override_config_file: t.Optional[str] = None, validate_schema: bool = True, ): # Load default configuration default_config_file = os.path.join( os.path.dirname(__file__), "default_configuration.yaml" ) with open(default_config_file, "rb") as f: self.config: t.Dict[str, t.Any] = yaml.safe_load(f) if validate_schema: try: SCHEMA.validate(self.config) except SchemaError as e: raise BentoMLConfigException( "Default configuration 'default_configuration.yml' does not" " conform to the required schema." ) from e # User override configuration if override_config_file is not None: LOGGER.info("Applying user config override from %s" % override_config_file) if not os.path.exists(override_config_file): raise BentoMLConfigException( f"Config file {override_config_file} not found" ) with open(override_config_file, "rb") as f: override_config = yaml.safe_load(f) always_merger.merge(self.config, override_config) if validate_schema: try: SCHEMA.validate(self.config) except SchemaError as e: raise BentoMLConfigException( "Configuration after user override does not conform to" " the required schema." ) from e def override(self, keys: t.List[str], value: t.Any): if keys is None: raise BentoMLConfigException("Configuration override key is None.") if len(keys) == 0: raise BentoMLConfigException("Configuration override key is empty.") if value is None: return c = self.config for key in keys[:-1]: if key not in c: raise BentoMLConfigException( "Configuration override key is invalid, %s" % keys ) c = c[key] c[keys[-1]] = value try: SCHEMA.validate(self.config) except SchemaError as e: raise BentoMLConfigException( "Configuration after applying override does not conform" " to the required schema, key=%s, value=%s." % (keys, value) ) from e def as_dict(self) -> providers.ConfigDictType: return t.cast(providers.ConfigDictType, self.config) @dataclass class BentoMLContainerClass: config = providers.Configuration() bentoml_home: str = BENTOML_HOME default_bento_store_base_dir: str = DEFAULT_BENTOS_PATH default_model_store_base_dir: str = DEFAULT_MODELS_PATH @providers.SingletonFactory @staticmethod def bento_store(base_dir: str = default_bento_store_base_dir): from ..bento import BentoStore return BentoStore(base_dir) @providers.SingletonFactory @staticmethod def model_store(base_dir: str = default_model_store_base_dir) -> "ModelStore": from ..models import ModelStore return ModelStore(base_dir) @providers.SingletonFactory @staticmethod def session_id() -> str: return uuid.uuid1().hex BentoMLContainer = BentoMLContainerClass() @dataclass class DeploymentContainerClass: bentoml_container = BentoMLContainer config = bentoml_container.config api_server_config = config.bento_server runners_config = config.runners development_mode = providers.Static(True) @providers.SingletonFactory @staticmethod def serve_info() -> "ServeInfo": from ..utils.analytics import get_serve_info return get_serve_info() @providers.SingletonFactory @staticmethod def access_control_options( allow_origins: t.List[str] = Provide[ api_server_config.cors.access_control_allow_origin ], allow_credentials: t.List[str] = Provide[ api_server_config.cors.access_control_allow_credentials ], expose_headers: t.List[str] = Provide[ api_server_config.cors.access_control_expose_headers ], allow_methods: t.List[str] = Provide[ api_server_config.cors.access_control_allow_methods ], allow_headers: t.List[str] = Provide[ api_server_config.cors.access_control_allow_headers ], max_age: int = Provide[api_server_config.cors.access_control_max_age], ) -> t.Dict[str, t.Union[t.List[str], int]]: kwargs = dict( allow_origins=allow_origins, allow_credentials=allow_credentials, expose_headers=expose_headers, allow_methods=allow_methods, allow_headers=allow_headers, max_age=max_age, ) filtered_kwargs = {k: v for k, v in kwargs.items() if v is not None} return filtered_kwargs api_server_workers = providers.Factory[int]( lambda workers: workers or (multiprocessing.cpu_count() // 2) + 1, api_server_config.workers, ) service_port = api_server_config.port service_host = api_server_config.host prometheus_multiproc_dir = providers.Factory[str]( os.path.join, bentoml_container.bentoml_home, "prometheus_multiproc_dir", ) @providers.SingletonFactory @staticmethod def metrics_client( multiproc_dir: str = Provide[prometheus_multiproc_dir], namespace: str = Provide[api_server_config.metrics.namespace], ) -> "PrometheusClient": from ..server.metrics.prometheus import PrometheusClient return PrometheusClient( multiproc_dir=multiproc_dir, namespace=namespace, ) @providers.SingletonFactory @staticmethod def tracer_provider( tracer_type: str = Provide[config.tracing.type], sample_rate: t.Optional[float] = Provide[config.tracing.sample_rate], zipkin_server_url: t.Optional[str] = Provide[config.tracing.zipkin.url], jaeger_server_address: t.Optional[str] = Provide[config.tracing.jaeger.address], jaeger_server_port: t.Optional[int] = Provide[config.tracing.jaeger.port], ): from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from ..utils.telemetry import ParentBasedTraceIdRatio if sample_rate is None: sample_rate = 0.0 provider = TracerProvider( sampler=ParentBasedTraceIdRatio(sample_rate), # resource: Resource = Resource.create({}), # shutdown_on_exit: bool = True, # active_span_processor: Union[ # SynchronousMultiSpanProcessor, ConcurrentMultiSpanProcessor # ] = None, # id_generator: IdGenerator = None, ) if tracer_type == "zipkin" and zipkin_server_url is not None: from opentelemetry.exporter.zipkin.json import ZipkinExporter exporter = ZipkinExporter( endpoint=zipkin_server_url, ) provider.add_span_processor(BatchSpanProcessor(exporter)) return provider elif ( tracer_type == "jaeger" and jaeger_server_address is not None and jaeger_server_port is not None ): from opentelemetry.exporter.jaeger.thrift import JaegerExporter exporter = JaegerExporter( agent_host_name=jaeger_server_address, agent_port=jaeger_server_port, ) provider.add_span_processor(BatchSpanProcessor(exporter)) return provider else: return provider # Mapping from runner name to RunnerApp file descriptor remote_runner_mapping = providers.Static[t.Dict[str, str]]({}) plasma_db = providers.Static[t.Optional["ext.PlasmaClient"]](None) DeploymentContainer = DeploymentContainerClass()
import os import typing as t import logging from functools import lru_cache try: import importlib.metadata as importlib_metadata except ModuleNotFoundError: import importlib_metadata import yaml try: import bentoml._version as version_mod except ImportError: # Since we aren't VCS _version.py, which is generated by setuptools_scm class version_mod: version: str version_tuple: t.Tuple[t.Union[str, int], ...] # Note this file is loaded prior to logging being configured, thus logger is only # used within functions in this file logger = logging.getLogger(__name__) DEBUG_ENV_VAR = "BENTOML_DEBUG" QUIET_ENV_VAR = "BENTOML_QUIET" CONFIG_ENV_VAR = "BENTOML_CONFIG" def expand_env_var(env_var: str) -> str: """Expands potentially nested env var by repeatedly applying `expandvars` and `expanduser` until interpolation stops having any effect. """ while True: interpolated = os.path.expanduser(os.path.expandvars(str(env_var))) if interpolated == env_var: return interpolated else: env_var = interpolated # Find BentoML version managed by setuptools_scm BENTOML_VERSION: str = importlib_metadata.version("bentoml") @lru_cache(maxsize=1) def is_pypi_installed_bentoml() -> bool: """Returns true if BentoML is installed via PyPI official release or installed from source with a release tag, which should come with pre-built docker base image on dockerhub. BentoML uses setuptools_scm to manage its versions, it looks at three things: * the latest tag (with a version number) * the distance to this tag (e.g. number of revisions since latest tag) * workdir state (e.g. uncommitted changes since latest tag) BentoML uses setuptools_scm with `version_scheme = "post-release"` option, which uses roughly the following logic to render the version: * no distance and clean: {tag} * distance and clean: {tag}.post{distance}+{scm letter}{revision hash} * no distance and not clean: {tag}+dYYYYMMDD * distance and not clean: {tag}.post{distance}+{scm letter}{revision hash}.dYYYYMMDD This function looks at the version str and decide if BentoML installation is base on a recent official release. """ # In a git repo with no tag, setuptools_scm generated version starts with "0.1." is_tagged = not BENTOML_VERSION.startswith("0.1.") is_clean = not str(version_mod.version_tuple[-1]).split(".")[-1].startswith("d") not_been_modified = BENTOML_VERSION == BENTOML_VERSION.split("+")[0] return is_tagged and is_clean and not_been_modified def get_bentoml_config_file_from_env() -> t.Optional[str]: if CONFIG_ENV_VAR in os.environ: # User local config file for customizing bentoml return expand_env_var(os.environ.get(CONFIG_ENV_VAR, "")) return None def set_debug_mode(enabled: bool) -> None: os.environ[DEBUG_ENV_VAR] = str(enabled) logger.info( f"{'Enabling' if enabled else 'Disabling'} debug mode for current BentoML session" ) def get_debug_mode() -> bool: if DEBUG_ENV_VAR in os.environ: return os.environ[DEBUG_ENV_VAR].lower() == "true" return False def set_quiet_mode(enabled: bool) -> None: os.environ[DEBUG_ENV_VAR] = str(enabled) # do not log setting quiet mode def get_quiet_mode() -> bool: if QUIET_ENV_VAR in os.environ: return os.environ[QUIET_ENV_VAR].lower() == "true" return False def load_global_config(bentoml_config_file: t.Optional[str] = None): """Load global configuration of BentoML""" from .containers import BentoMLContainer from .containers import BentoMLConfiguration if not bentoml_config_file: bentoml_config_file = get_bentoml_config_file_from_env() if bentoml_config_file: if not bentoml_config_file.endswith((".yml", ".yaml")): raise Exception( "BentoML config file specified in ENV VAR does not end with `.yaml`: " f"`BENTOML_CONFIG={bentoml_config_file}`" ) if not os.path.isfile(bentoml_config_file): raise FileNotFoundError( "BentoML config file specified in ENV VAR not found: " f"`BENTOML_CONFIG={bentoml_config_file}`" ) bentoml_configuration = BentoMLConfiguration( override_config_file=bentoml_config_file, ) BentoMLContainer.config.set(bentoml_configuration.as_dict()) def save_global_config(config_file_handle: t.IO[t.Any]): from ..configuration.containers import BentoMLContainer content = yaml.safe_dump(BentoMLContainer.config) config_file_handle.write(content)
from typing import TYPE_CHECKING if TYPE_CHECKING: import typing as t from starlette.types import Send as ASGISend from starlette.types import Scope as ASGIScope from starlette.types import ASGIApp from starlette.types import Message as ASGIMessage from starlette.types import Receive as ASGIReceive class AsgiMiddleware(t.Protocol): def __call__(self, app: ASGIApp, **options: t.Any) -> ASGIApp: ... __all__ = [ "AsgiMiddleware", "ASGIApp", "ASGIScope", "ASGISend", "ASGIReceive", "ASGIMessage", ]
import typing as t from transformers.modeling_utils import PreTrainedModel from transformers.pipelines.base import Pipeline as TransformersPipeline from transformers.modeling_tf_utils import TFPreTrainedModel from transformers.tokenization_utils import PreTrainedTokenizer from transformers.configuration_utils import PretrainedConfig from transformers.modeling_flax_utils import FlaxPreTrainedModel from transformers.tokenization_utils_fast import PreTrainedTokenizerFast from transformers.feature_extraction_sequence_utils import ( SequenceFeatureExtractor as PreTrainedFeatureExtractor, ) TransformersModelType = t.Union[PreTrainedModel, TFPreTrainedModel, FlaxPreTrainedModel] TransformersTokenizerType = t.Union[PreTrainedTokenizer, PreTrainedTokenizerFast] __all__ = [ "TransformersPipeline", "TransformersModelType", "TransformersTokenizerType", "PreTrainedFeatureExtractor", "PretrainedConfig", ]
import typing as t from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Literal from pandas import Series as _PdSeries from pandas import DataFrame as PdDataFrame from pyarrow.plasma import ObjectID from pyarrow.plasma import PlasmaClient PdSeries = _PdSeries[t.Any] DataFrameOrient = Literal["split", "records", "index", "columns", "values", "table"] SeriesOrient = Literal["split", "records", "index", "table"] # numpy is always required by bentoml from numpy import generic as NpGeneric from numpy.typing import NDArray as _NDArray from numpy.typing import DTypeLike as NpDTypeLike # type: ignore (incomplete numpy types) NpNDArray = _NDArray[t.Any] from xgboost import DMatrix from .starlette import ASGIApp from .starlette import ASGISend from .starlette import ASGIScope from .starlette import ASGIMessage from .starlette import ASGIReceive from .starlette import AsgiMiddleware __all__ = [ "PdSeries", "PdDataFrame", "DataFrameOrient", "SeriesOrient", "ObjectID", "PlasmaClient", # xgboost "DMatrix", # numpy "NpNDArray", "NpGeneric", "NpDTypeLike", # starlette "AsgiMiddleware", "ASGIApp", "ASGIScope", "ASGISend", "ASGIReceive", "ASGIMessage", ]
import typing as t from tensorflow.python.framework.ops import Tensor from tensorflow.python.module.module import Module from tensorflow.python.client.session import Session from tensorflow.python.eager.function import FunctionSpec from tensorflow.python.eager.def_function import Function from tensorflow.python.framework.type_spec import TypeSpec from tensorflow.python.ops.tensor_array_ops import TensorArray from tensorflow.python.ops.tensor_array_ops import TensorArraySpec from tensorflow.python.framework.tensor_spec import TensorSpec from tensorflow.python.keras.engine.training import Model from tensorflow.python.training.tracking.base import Trackable from tensorflow.python.framework.sparse_tensor import SparseTensorSpec from tensorflow.python.keras.engine.sequential import Sequential from tensorflow.python.framework.indexed_slices import IndexedSlices from tensorflow.python.ops.ragged.ragged_tensor import RaggedTensorSpec from tensorflow.python.saved_model.save_options import SaveOptions from tensorflow.python.framework.composite_tensor import CompositeTensor from tensorflow.python.training.tracking.tracking import AutoTrackable from tensorflow.python.saved_model.function_deserialization import RestoredFunction try: from tensorflow.python.types.core import GenericFunction from tensorflow.python.types.core import ConcreteFunction from tensorflow.python.framework.ops import _EagerTensorBase as EagerTensor except ImportError: from tensorflow.python.eager.function import ConcreteFunction class GenericFunction(t.Protocol): def __call__(self, *args: t.Any, **kwargs: t.Any): ... # NOTE: future proof when tensorflow decided to remove EagerTensor # and enable eager execution on Tensor by default. This class only serves # as type fallback. class EagerTensor(Tensor): ... class SignatureMap(t.Mapping[str, t.Any], Trackable): """A collection of SavedModel signatures.""" _signatures: t.Dict[str, t.Union[ConcreteFunction, RestoredFunction, Function]] def __init__(self) -> None: ... def __getitem__( self, key: str ) -> t.Union[ConcreteFunction, RestoredFunction, Function]: ... def __iter__(self) -> t.Iterator[str]: ... def __len__(self) -> int: ... def __repr__(self) -> str: ... # This denotes all decorated function with `tf.function` DecoratedFunction = t.Union[RestoredFunction, ConcreteFunction, GenericFunction] # This denotes all possible tensor type that can be casted with `tf.cast` CastableTensorType = t.Union[Tensor, EagerTensor, CompositeTensor, IndexedSlices] # This encapsulates scenarios where input can be accepted as TensorArray TensorLike = t.Union[CastableTensorType, TensorArray] # This defines all possible TensorSpec from tensorflow API UnionTensorSpec = t.Union[ TensorSpec, RaggedTensorSpec, SparseTensorSpec, TensorArraySpec, ] # TODO(aarnphm): Specify types instead of t.Any TensorSignature = t.Tuple[TensorSpec, bool, t.Optional[t.Any]] InputSignature = t.Tuple[TensorSignature, t.Dict[str, TypeSpec]] # This denotes all Keras Model API KerasModel = t.Union[Model, Sequential] __all__ = [ "CastableTensorType", "TensorLike", "InputSignature", "TensorSignature", "UnionTensorSpec", "Trackable", "AutoTrackable", "ConcreteFunction", "RestoredFunction", "FunctionSpec", "SignatureMap", "Module", "TypeSpec", "SaveOptions", "Session", "KerasModel", ]
import time import typing as t import asyncio import logging import functools import traceback import collections import numpy as np from ..utils import cached_property from ..utils.alg import TokenBucket logger = logging.getLogger(__name__) class NonBlockSema: def __init__(self, count): self.sema = count def acquire(self): if self.sema < 1: return False self.sema -= 1 return True def is_locked(self): return self.sema < 1 def release(self): self.sema += 1 class Optimizer: """ Analyse historical data to optimize CorkDispatcher. """ N_KEPT_SAMPLE = 50 # amount of outbound info kept for inferring params N_SKIPPED_SAMPLE = 2 # amount of outbound info skipped after init INTERVAL_REFRESH_PARAMS = 5 # seconds between each params refreshing def __init__(self): """ assume the outbound duration follows duration = o_a * n + o_b (all in seconds) """ self.o_stat = collections.deque( maxlen=self.N_KEPT_SAMPLE ) # to store outbound stat data self.o_a = 2 self.o_b = 1 self.wait = 0.01 # the avg wait time before outbound called self._refresh_tb = TokenBucket(2) # to limit params refresh interval self._outbound_counter = 0 def log_outbound(self, n, wait, duration): if ( self._outbound_counter <= self.N_SKIPPED_SAMPLE ): # skip inaccurate info at beginning self._outbound_counter += 1 return self.o_stat.append((n, duration, wait)) if self._refresh_tb.consume(1, 1.0 / self.INTERVAL_REFRESH_PARAMS, 1): self.trigger_refresh() def trigger_refresh(self): x = tuple((i, 1) for i, _, _ in self.o_stat) y = tuple(i for _, i, _ in self.o_stat) _o_a, _o_b = np.linalg.lstsq(x, y, rcond=None)[0] _o_w = sum(w for _, _, w in self.o_stat) * 1.0 / len(self.o_stat) self.o_a, self.o_b = max(0.000001, _o_a), max(0, _o_b) self.wait = max(0, _o_w) logger.debug( "Dynamic batching optimizer params updated: o_a: %.6f, o_b: %.6f, wait: %.6f", _o_a, _o_b, _o_w, ) T_IN = t.TypeVar("T_IN") T_OUT = t.TypeVar("T_OUT") class CorkDispatcher: """ A decorator that: * wrap batch function * implement CORK algorithm to cork & release calling of wrapped function The wrapped function should be an async function. """ def __init__( self, max_latency_in_ms: int, max_batch_size: int, shared_sema: t.Optional[NonBlockSema] = None, fallback: t.Optional[t.Callable[[], t.Any]] = None, ): """ params: * max_latency_in_ms: max_latency_in_ms for inbound tasks in milliseconds * max_batch_size: max batch size of inbound tasks * shared_sema: semaphore to limit concurrent outbound tasks * fallback: callable to return fallback result raises: * all possible exceptions the decorated function has """ self.max_latency_in_ms = max_latency_in_ms / 1000.0 self.callback = None self.fallback = fallback self.optimizer = Optimizer() self.max_batch_size = int(max_batch_size) self.tick_interval = 0.001 self._controller = None self._queue = collections.deque() # TODO(hrmthw): maxlen self._sema = shared_sema if shared_sema else NonBlockSema(1) def shutdown(self): if self._controller is not None: self._controller.cancel() try: while True: _, _, fut = self._queue.pop() fut.cancel() except IndexError: pass @cached_property def _loop(self): return asyncio.get_event_loop() @cached_property def _wake_event(self): return asyncio.Condition() def __call__( self, callback: t.Callable[ [t.Iterable[T_IN]], t.Coroutine[None, None, t.Iterable[T_OUT]] ], ) -> t.Callable[[T_IN], t.Coroutine[None, None, T_OUT]]: self.callback = callback @functools.wraps(callback) async def _func(data): if self._controller is None: self._controller = self._loop.create_task(self.controller()) try: r = await self.inbound_call(data) except asyncio.CancelledError: return None if self.fallback is None else self.fallback() if isinstance(r, Exception): raise r return r return _func async def controller(self): """ A standalone coroutine to wait/dispatch calling. """ while True: try: async with self._wake_event: # block until there's any request in queue await self._wake_event.wait_for(self._queue.__len__) n = len(self._queue) dt = self.tick_interval decay = 0.95 # the decay rate of wait time now = time.time() w0 = now - self._queue[0][0] wn = now - self._queue[-1][0] a = self.optimizer.o_a b = self.optimizer.o_b if n > 1 and (w0 + a * n + b) >= self.max_latency_in_ms: self._queue.popleft()[2].cancel() continue if self._sema.is_locked(): if n == 1 and w0 >= self.max_latency_in_ms: self._queue.popleft()[2].cancel() continue await asyncio.sleep(self.tick_interval) continue if n * (wn + dt + (a or 0)) <= self.optimizer.wait * decay: await asyncio.sleep(self.tick_interval) continue n_call_out = min( self.max_batch_size, n, ) # call self._sema.acquire() inputs_info = tuple(self._queue.pop() for _ in range(n_call_out)) self._loop.create_task(self.outbound_call(inputs_info)) except asyncio.CancelledError: break except Exception: # pylint: disable=broad-except logger.error(traceback.format_exc()) async def inbound_call(self, data): now = time.time() future = self._loop.create_future() input_info = (now, data, future) self._queue.append(input_info) async with self._wake_event: self._wake_event.notify_all() return await future async def outbound_call(self, inputs_info): _time_start = time.time() _done = False logger.debug("Dynamic batching cork released, batch size: %d", len(inputs_info)) try: outputs = await self.callback(tuple(d for _, d, _ in inputs_info)) assert len(outputs) == len(inputs_info) for (_, _, fut), out in zip(inputs_info, outputs): if not fut.done(): fut.set_result(out) _done = True self.optimizer.log_outbound( n=len(inputs_info), wait=_time_start - inputs_info[-1][0], duration=time.time() - _time_start, ) except asyncio.CancelledError: pass except Exception as e: # pylint: disable=broad-except for _, _, fut in inputs_info: if not fut.done(): fut.set_result(e) _done = True finally: if not _done: for _, _, fut in inputs_info: if not fut.done(): fut.cancel() self._sema.release()
from __future__ import annotations import typing as t import logging from typing import TYPE_CHECKING from functools import lru_cache import attr from ..types import ParamSpec from ..utils import first_not_none from .resource import Resource from .runnable import Runnable from .strategy import Strategy from .strategy import DefaultStrategy from ...exceptions import StateException from .runner_handle import RunnerHandle from .runner_handle import DummyRunnerHandle if TYPE_CHECKING: from ..models import Model from .runnable import RunnableMethodConfig T = t.TypeVar("T", bound=Runnable) P = ParamSpec("P") R = t.TypeVar("R") logger = logging.getLogger(__name__) @attr.frozen(slots=False) class RunnerMethod(t.Generic[T, P, R]): runner: Runner name: str config: RunnableMethodConfig max_batch_size: int max_latency_ms: int def run(self, *args: t.Any, **kwargs: t.Any) -> t.Any: return self.runner._runner_handle.run_method( # type: ignore self, *args, **kwargs, ) async def async_run(self, *args: t.Any, **kwargs: t.Any) -> t.Any: return await self.runner._runner_handle.async_run_method( # type: ignore self, *args, **kwargs, ) # TODO: Move these to the default configuration file and allow user override GLOBAL_DEFAULT_MAX_BATCH_SIZE = 100 GLOBAL_DEFAULT_MAX_LATENCY_MS = 10000 @attr.define(slots=False, frozen=True, eq=False) class Runner: runnable_class: t.Type[Runnable] runnable_init_params: dict[str, t.Any] name: str models: list[Model] resource_config: Resource runner_methods: list[RunnerMethod[t.Any, t.Any, t.Any]] scheduling_strategy: t.Type[Strategy] _runner_handle: RunnerHandle = attr.field(init=False, factory=DummyRunnerHandle) def __init__( self, runnable_class: t.Type[Runnable], *, runnable_init_params: t.Dict[str, t.Any] | None = None, name: str | None = None, scheduling_strategy: t.Type[Strategy] = DefaultStrategy, models: t.List[Model] | None = None, cpu: int | None = None, # TODO: support str and float type here? e.g "500m" or "0.5" nvidia_gpu: int | None = None, custom_resources: t.Dict[str, float] | None = None, max_batch_size: int | None = None, max_latency_ms: int | None = None, method_configs: t.Dict[str, t.Dict[str, int]] | None = None, ) -> None: """ Args: runnable_class: runnable class runnable_init_params: runnable init params name: runner name scheduling_strategy: scheduling strategy models: list of required bento models cpu: cpu resource nvidia_gpu: nvidia gpu resource custom_resources: custom resources max_batch_size: max batch size config for micro batching max_latency_ms: max latency config for micro batching method_configs: per method configs """ name = runnable_class.__name__ if name is None else name models = [] if models is None else models runner_method_map: dict[str, RunnerMethod[t.Any, t.Any, t.Any]] = {} runnable_init_params = ( {} if runnable_init_params is None else runnable_init_params ) method_configs = {} if method_configs is None else {} custom_resources = {} if custom_resources is None else {} resource_config = Resource( cpu=cpu, nvidia_gpu=nvidia_gpu, custom_resources=custom_resources or {}, ) if runnable_class.methods is None: raise ValueError( f"Runnable class '{runnable_class.__name__}' has no methods!" ) for method_name, method in runnable_class.methods.items(): method_max_batch_size = method_configs.get(method_name, {}).get( "max_batch_size" ) method_max_latency_ms = method_configs.get(method_name, {}).get( "max_latency_ms" ) runner_method_map[method_name] = RunnerMethod( runner=self, name=method_name, config=method.config, max_batch_size=first_not_none( method_max_batch_size, max_batch_size, default=GLOBAL_DEFAULT_MAX_BATCH_SIZE, ), max_latency_ms=first_not_none( method_max_latency_ms, max_latency_ms, default=GLOBAL_DEFAULT_MAX_LATENCY_MS, ), ) self.__attrs_init__( # type: ignore runnable_class=runnable_class, runnable_init_params=runnable_init_params, name=name, models=models, resource_config=resource_config, runner_methods=list(runner_method_map.values()), scheduling_strategy=scheduling_strategy, ) # Choose the default method: # 1. if there's only one method, it will be set as default # 2. if there's a method named "__call__", it will be set as default # 3. otherwise, there's no default method if len(runner_method_map) == 1: default_method = next(iter(runner_method_map.values())) logger.debug( f"Default runner method set to `{default_method.name}`, it can be accessed both via `runner.run` and `runner.{default_method.name}.async_run`" ) elif "__call__" in runner_method_map: default_method = runner_method_map["__call__"] logger.debug( "Default runner method set to `__call__`, it can be accessed via `runner.run` or `runner.async_run`" ) else: default_method = None logger.warning( f'No default method found for Runner "{name}", all method access needs to be in the form of `runner.{{method}}.run`' ) # set default run method entrypoint if default_method is not None: object.__setattr__(self, "run", default_method.run) object.__setattr__(self, "async_run", default_method.async_run) # set all run method entrypoint for runner_method in self.runner_methods: object.__setattr__(self, runner_method.name, runner_method) @lru_cache(maxsize=1) def get_effective_resource_config(self) -> Resource: return ( Resource.from_config(self.name) | self.resource_config | Resource.from_system() ) def _init(self, handle_class: t.Type[RunnerHandle]) -> None: if not isinstance(self._runner_handle, DummyRunnerHandle): raise StateException("Runner already initialized") runner_handle = handle_class(self) object.__setattr__(self, "_runner_handle", runner_handle) def _init_local(self) -> None: from .runner_handle.local import LocalRunnerRef self._init(LocalRunnerRef) def init_local(self, quiet: bool = False) -> None: """ init local runnable instance, for testing and debugging only """ if not quiet: logger.warning("'Runner.init_local' is for debugging and testing only") self._init_local() def init_client(self): """ init client for a remote runner instance """ from .runner_handle.remote import RemoteRunnerClient self._init(RemoteRunnerClient) def destroy(self): object.__setattr__(self, "_runner_handle", DummyRunnerHandle()) @property def scheduled_worker_count(self) -> int: return self.scheduling_strategy.get_worker_count( self.runnable_class, self.get_effective_resource_config(), ) def setup_worker(self, worker_id: int) -> None: self.scheduling_strategy.setup_worker( self.runnable_class, self.get_effective_resource_config(), worker_id, )
from __future__ import annotations import os import re import math import typing as t import logging import functools import attr import psutil from cattrs.gen import override from cattrs.gen import make_dict_unstructure_fn from ..utils import bentoml_cattr from ...exceptions import BentoMLException logger = logging.getLogger(__name__) @attr.define(frozen=True) class Resource: cpu: t.Optional[float] = attr.field(default=None) nvidia_gpu: t.Optional[float] = attr.field(default=None) custom_resources: t.Dict[str, float] = attr.field(factory=dict) def __or__(self, right: Resource) -> Resource: """ Fill in missing values with values from another. """ cpu = right.cpu if self.cpu is None else self.cpu nvidia_gpu = right.nvidia_gpu if self.nvidia_gpu is None else self.nvidia_gpu custom_resources = dict( right.custom_resources, **{k: v for k, v in self.custom_resources.items() if v is not None}, ) return self.__class__( cpu=cpu, nvidia_gpu=nvidia_gpu, custom_resources=custom_resources, ) @classmethod def from_config(cls, runner_name: str) -> Resource: """ Create a Resource object from the BentoML config. """ # TODO(jiang) return cls() @classmethod def from_system(cls) -> Resource: """ Get Resource from system. """ cpu = query_cpu_count() nvidia_gpu = float(query_nvidia_gpu_count()) return cls(cpu=cpu, nvidia_gpu=nvidia_gpu) # Remove after attrs support ForwardRef natively attr.resolve_types(Resource, globals(), locals()) bentoml_cattr.register_unstructure_hook( Resource, make_dict_unstructure_fn( Resource, bentoml_cattr, cpu=override(omit_if_default=True), nvidia_gpu=override(omit_if_default=True), custom_resources=override(omit_if_default=True), ), ) def cpu_converter(cpu: t.Union[int, float, str]) -> float: """ Convert cpu to float. cpu can be a float, int or string. - 10m -> 0.01 - 1.0 -> 1.0 - 1 -> 1.0 - "1" -> 1.0 """ assert isinstance(cpu, (int, float, str)), "cpu must be int, float or str" if isinstance(cpu, (int, float)): return float(cpu) milli_match = re.match("([0-9]+)m", cpu) if milli_match: return float(milli_match[1]) / 1000.0 raise BentoMLException(f"Invalid CPU resource limit '{cpu}'. ") def mem_converter(mem: t.Union[int, str]) -> int: assert isinstance(mem, (int, str)), "mem must be int or str" if isinstance(mem, int): return mem unit_match = re.match("([0-9]+)([A-Za-z]{1,2})", mem) mem_multipliers = { "k": 1000, "M": 1000**2, "G": 1000**3, "T": 1000**4, "P": 1000**5, "E": 1000**6, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4, "Pi": 1024**5, "Ei": 1024**6, } if unit_match: base = int(unit_match[1]) unit = unit_match[2] if unit in mem_multipliers: return base * mem_multipliers[unit] raise ValueError(f"Invalid MEM resource limit '{mem}'") @functools.lru_cache(maxsize=1) def query_cgroup_cpu_count() -> float: # Query active cpu processor count using cgroup v1 API, based on OpenJDK # implementation for `active_processor_count` using cgroup v1: # https://github.com/openjdk/jdk/blob/master/src/hotspot/os/linux/cgroupSubsystem_linux.cpp # For cgroup v2, see: # https://github.com/openjdk/jdk/blob/master/src/hotspot/os/linux/cgroupV2Subsystem_linux.cpp # Possible supports: cpuset.cpus on kubernetes def _read_cgroup_file(filename: str) -> float: with open(filename, "r", encoding="utf-8") as f: return int(f.read().strip()) cgroup_root = "/sys/fs/cgroup/" cfs_quota_us_file = os.path.join(cgroup_root, "cpu", "cpu.cfs_quota_us") cfs_period_us_file = os.path.join(cgroup_root, "cpu", "cpu.cfs_period_us") shares_file = os.path.join(cgroup_root, "cpu", "cpu.shares") cpu_max_file = os.path.join(cgroup_root, "cpu.max") quota, shares = None, None if os.path.exists(cfs_quota_us_file) and os.path.exists(cfs_period_us_file): try: quota = _read_cgroup_file(cfs_quota_us_file) / _read_cgroup_file( cfs_period_us_file ) except FileNotFoundError as err: logger.warning(f"Caught exception while calculating CPU quota: {err}") # reading from cpu.max for cgroup v2 elif os.path.exists(cpu_max_file): try: with open(cpu_max_file, "r") as max_file: cfs_string = max_file.read() quota_str, period_str = cfs_string.split() if quota_str.isnumeric() and period_str.isnumeric(): quota = float(quota_str) / float(period_str) else: # quota_str is "max" meaning the cpu quota is unset quota = None except FileNotFoundError as err: logger.warning(f"Caught exception while calculating CPU quota: {err}") if quota is not None and quota < 0: quota = None elif quota == 0: quota = 1 if os.path.exists(shares_file): try: shares = _read_cgroup_file(shares_file) / float(1024) except FileNotFoundError as err: logger.warning(f"Caught exception while getting CPU shares: {err}") os_cpu_count = float(os.cpu_count() or 1.0) limit_count = math.inf if quota and shares: limit_count = min(quota, shares) elif quota: limit_count = quota elif shares: limit_count = shares return float(min(limit_count, os_cpu_count)) @functools.lru_cache(maxsize=1) def query_os_cpu_count() -> int: cpu_count = os.cpu_count() if cpu_count is not None: return cpu_count logger.warning("os.cpu_count() is NoneType") return 1 def query_cpu_count() -> float: # Default to the total CPU count available in current node or cgroup if psutil.POSIX: return query_cgroup_cpu_count() else: return float(query_os_cpu_count()) @functools.lru_cache(maxsize=1) def query_nvidia_gpu_count() -> int: """ query nvidia gpu count, available on Windows and Linux """ import pynvml # type: ignore try: pynvml.nvmlInit() device_count = pynvml.nvmlDeviceGetCount() return device_count except (pynvml.nvml.NVMLError, OSError): return 0 finally: try: pynvml.nvmlShutdown() except Exception: # pylint: disable=broad-except pass def gpu_converter(gpus: t.Optional[t.Union[int, str, t.List[str]]]) -> int: if isinstance(gpus, int): return gpus if isinstance(gpus, str): return int(gpus) return query_nvidia_gpu_count() def get_gpu_memory(dev: int) -> t.Tuple[float, float]: """ Return Total Memory and Free Memory in given GPU device. in MiB """ import pynvml.nvml # type: ignore from pynvml.smi import nvidia_smi # type: ignore unit_multiplier = { "PiB": 1024.0 * 1024 * 1024, "TiB": 1024.0 * 1024, "GiB": 1024.0, "MiB": 1.0, "KiB": 1.0 / 1024, "B": 1.0 / 1024 / 1024, } try: inst = nvidia_smi.getInstance() query: t.Dict[str, int] = inst.DeviceQuery(dev) # type: ignore except (pynvml.nvml.NVMLError, OSError): return 0.0, 0.0 try: gpus: t.List[t.Dict[str, t.Any]] = query.get("gpu", []) # type: ignore gpu = gpus[dev] unit = gpu["fb_memory_usage"]["unit"] total = gpu["fb_memory_usage"]["total"] * unit_multiplier[unit] free = gpu["fb_memory_usage"]["free"] * unit_multiplier[unit] return total, free except IndexError: raise ValueError(f"Invalid GPU device index {dev}") except KeyError: raise RuntimeError(f"unexpected nvml query result: {query}")
from .runner import Runner from .runnable import Runnable __all__ = ["Runner", "Runnable"]
import os import abc import math import typing as t import logging from .resource import Resource from .runnable import Runnable logger = logging.getLogger(__name__) class Strategy(abc.ABC): @classmethod @abc.abstractmethod def get_worker_count( cls, runnable_class: t.Type[Runnable], resource_request: Resource, ) -> int: ... @classmethod @abc.abstractmethod def setup_worker( cls, runnable_class: t.Type[Runnable], resource_request: Resource, worker_index: int, ) -> None: ... THREAD_ENVS = [ "OMP_NUM_THREADS", "TF_NUM_INTEROP_THREADS", "TF_NUM_INTRAOP_THREADS", "BENTOML_NUM_THREAD", ] # TODO(jiang): make it configurable? class DefaultStrategy(Strategy): @classmethod def get_worker_count( cls, runnable_class: t.Type[Runnable], resource_request: Resource, ) -> int: # use nvidia gpu if ( resource_request.nvidia_gpu is not None and resource_request.nvidia_gpu > 0 and runnable_class.SUPPORT_NVIDIA_GPU ): return math.ceil(resource_request.nvidia_gpu) # use CPU if resource_request.cpu is not None and resource_request.cpu > 0: if runnable_class.SUPPORT_CPU_MULTI_THREADING: return 1 return math.ceil(resource_request.cpu) # this would not be reached by user since we always read system resource as default logger.warning("No resource request found, always use single worker") return 1 @classmethod def setup_worker( cls, runnable_class: t.Type[Runnable], resource_request: Resource, worker_index: int, ) -> None: # use nvidia gpu if ( resource_request.nvidia_gpu is not None and resource_request.nvidia_gpu > 0 and runnable_class.SUPPORT_NVIDIA_GPU ): os.environ["CUDA_VISIBLE_DEVICES"] = str(worker_index - 1) logger.info( "Setting up worker: set CUDA_VISIBLE_DEVICES to %s", worker_index - 1, ) return # use CPU if resource_request.cpu is not None and resource_request.cpu > 0: os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # disable gpu if runnable_class.SUPPORT_CPU_MULTI_THREADING: thread_count = math.ceil(resource_request.cpu) for thread_env in THREAD_ENVS: os.environ[thread_env] = str(thread_count) logger.info( "Setting up worker: set CPU thread count to %s", thread_count ) return else: for thread_env in THREAD_ENVS: os.environ[thread_env] = "1" return
from __future__ import annotations import abc import pickle import typing as t import itertools from typing import TYPE_CHECKING from simple_di import inject from simple_di import Provide from ..types import LazyType from ..configuration.containers import DeploymentContainer SingleType = t.TypeVar("SingleType") BatchType = t.TypeVar("BatchType") if TYPE_CHECKING: from .. import external_typing as ext class Payload(t.NamedTuple): data: bytes meta: dict[str, bool | int | float | str] container: str batch_size: int = -1 class DataContainer(t.Generic[SingleType, BatchType]): @classmethod def create_payload( cls, data: bytes, batch_size: int, meta: dict[str, bool | int | float | str] | None = None, ) -> Payload: return Payload(data, meta or {}, container=cls.__name__, batch_size=batch_size) @classmethod @abc.abstractmethod def to_payload(cls, batch: BatchType, batch_dim: int) -> Payload: ... @classmethod @abc.abstractmethod def from_payload(cls, payload: Payload) -> BatchType: ... @classmethod @abc.abstractmethod def batches_to_batch( cls, batches: t.Sequence[BatchType], batch_dim: int ) -> tuple[BatchType, list[int]]: ... @classmethod @abc.abstractmethod def batch_to_batches( cls, batch: BatchType, indices: t.Sequence[int], batch_dim: int ) -> list[BatchType]: ... @classmethod @abc.abstractmethod def batch_to_payloads( cls, batch: BatchType, indices: t.Sequence[int], batch_dim: int ) -> list[Payload]: ... @classmethod @abc.abstractmethod def from_batch_payloads( cls, payloads: t.Sequence[Payload], batch_dim: int, ) -> tuple[BatchType, list[int]]: ... class NdarrayContainer( DataContainer[ "ext.NpNDArray", "ext.NpNDArray", ] ): @classmethod def batches_to_batch( cls, batches: t.Sequence[ext.NpNDArray], batch_dim: int = 0, ) -> tuple[ext.NpNDArray, list[int]]: import numpy as np # numpy.concatenate may consume lots of memory, need optimization later batch: ext.NpNDArray = np.concatenate( # type: ignore (no numpy types) batches, axis=batch_dim, ) indices = list( itertools.accumulate(subbatch.shape[batch_dim] for subbatch in batches) ) indices = [0] + indices return batch, indices @classmethod def batch_to_batches( cls, batch: ext.NpNDArray, indices: t.Sequence[int], batch_dim: int = 0, ) -> list[ext.NpNDArray]: import numpy as np return np.split(batch, indices[1:-1], axis=batch_dim) # type: ignore (no numpy types) @classmethod @inject def to_payload( cls, batch: ext.NpNDArray, batch_dim: int, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> Payload: if plasma_db: return cls.create_payload( plasma_db.put(batch).binary(), batch.shape[batch_dim], {"plasma": True}, ) return cls.create_payload( pickle.dumps(batch), batch.shape[batch_dim], {"plasma": False}, ) @classmethod @inject def from_payload( cls, payload: Payload, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> ext.NpNDArray: if payload.meta.get("plasma"): import pyarrow.plasma as plasma assert plasma_db return plasma_db.get(plasma.ObjectID(payload.data)) return pickle.loads(payload.data) @classmethod @inject def batch_to_payloads( cls, batch: ext.NpNDArray, indices: t.Sequence[int], batch_dim: int = 0, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> list[Payload]: batches = cls.batch_to_batches(batch, indices, batch_dim) payloads = [ cls.to_payload(subbatch, batch_dim, plasma_db) for subbatch in batches ] return payloads @classmethod @inject def from_batch_payloads( cls, payloads: t.Sequence[Payload], batch_dim: int = 0, plasma_db: "ext.PlasmaClient" | None = Provide[DeploymentContainer.plasma_db], ) -> t.Tuple["ext.NpNDArray", list[int]]: batches = [cls.from_payload(payload, plasma_db) for payload in payloads] return cls.batches_to_batch(batches, batch_dim) class DMatrixContainer( DataContainer[ "ext.DMatrix", "ext.DMatrix", ] ): @classmethod def batches_to_batch( cls, batches: t.Sequence[ext.DMatrix], batch_dim: int = 0, ) -> tuple[ext.DMatrix, list[int]]: raise NotImplementedError @classmethod def batch_to_batches( cls, batch: ext.DMatrix, indices: t.Sequence[int], batch_dim: int = 0, ) -> list[ext.DMatrix]: raise NotImplementedError @classmethod @inject def to_payload( cls, batch: ext.DMatrix, batch_dim: int, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> Payload: raise NotImplementedError @classmethod @inject def from_payload( cls, payload: Payload, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> ext.DMatrix: raise NotImplementedError @classmethod @inject def batch_to_payloads( cls, batch: ext.DMatrix, indices: t.Sequence[int], batch_dim: int = 0, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> list[Payload]: raise NotImplementedError @classmethod @inject def from_batch_payloads( cls, payloads: t.Sequence[Payload], batch_dim: int = 0, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> tuple[ext.DMatrix, list[int]]: raise NotImplementedError class PandasDataFrameContainer( DataContainer[t.Union["ext.PdDataFrame", "ext.PdSeries"], "ext.PdDataFrame"] ): @classmethod def batches_to_batch( cls, batches: t.Sequence[ext.PdDataFrame], batch_dim: int = 0, ) -> tuple[ext.PdDataFrame, list[int]]: import pandas as pd assert ( batch_dim == 0 ), "PandasDataFrameContainer does not support batch_dim other than 0" indices = list( itertools.accumulate(subbatch.shape[batch_dim] for subbatch in batches) ) indices = [0] + indices return pd.concat(batches, ignore_index=True), indices # type: ignore (incomplete panadas types) @classmethod def batch_to_batches( cls, batch: ext.PdDataFrame, indices: t.Sequence[int], batch_dim: int = 0, ) -> list[ext.PdDataFrame]: assert ( batch_dim == 0 ), "PandasDataFrameContainer does not support batch_dim other than 0" return [ batch.iloc[indices[i] : indices[i + 1]].reset_index(drop=True) for i in range(len(indices) - 1) ] @classmethod @inject def to_payload( cls, batch: ext.PdDataFrame | ext.PdSeries, batch_dim: int, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> Payload: import pandas as pd assert ( batch_dim == 0 ), "PandasDataFrameContainer does not support batch_dim other than 0" if isinstance(batch, pd.Series): batch = pd.DataFrame([batch]) if plasma_db: return cls.create_payload( plasma_db.put(batch).binary(), batch.size, {"plasma": True}, ) return cls.create_payload( pickle.dumps(batch), batch.size, {"plasma": False}, ) @classmethod @inject def from_payload( cls, payload: Payload, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> ext.PdDataFrame: if payload.meta.get("plasma"): import pyarrow.plasma as plasma assert plasma_db return plasma_db.get(plasma.ObjectID(payload.data)) return pickle.loads(payload.data) @classmethod @inject def batch_to_payloads( cls, batch: ext.PdDataFrame, indices: t.Sequence[int], batch_dim: int = 0, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> list[Payload]: batches = cls.batch_to_batches(batch, indices, batch_dim) payloads = [ cls.to_payload(subbatch, batch_dim, plasma_db) for subbatch in batches ] return payloads @classmethod @inject def from_batch_payloads( # pylint: disable=arguments-differ cls, payloads: t.Sequence[Payload], batch_dim: int = 0, plasma_db: ext.PlasmaClient | None = Provide[DeploymentContainer.plasma_db], ) -> tuple[ext.PdDataFrame, list[int]]: batches = [cls.from_payload(payload, plasma_db) for payload in payloads] return cls.batches_to_batch(batches, batch_dim) class DefaultContainer(DataContainer[t.Any, t.List[t.Any]]): @classmethod def batches_to_batch( cls, batches: t.Sequence[list[t.Any]], batch_dim: int = 0 ) -> tuple[list[t.Any], list[int]]: assert ( batch_dim == 0 ), "Default Runner DataContainer does not support batch_dim other than 0" batch: list[t.Any] = [] for subbatch in batches: batch.extend(subbatch) indices = list(itertools.accumulate(len(subbatch) for subbatch in batches)) indices = [0] + indices return batch, indices @classmethod def batch_to_batches( cls, batch: list[t.Any], indices: t.Sequence[int], batch_dim: int = 0 ) -> list[list[t.Any]]: assert ( batch_dim == 0 ), "Default Runner DataContainer does not support batch_dim other than 0" return [batch[indices[i] : indices[i + 1]] for i in range(len(indices) - 1)] @classmethod def to_payload(cls, batch: t.Any, batch_dim: int) -> Payload: if isinstance(batch, t.Generator): # Generators can't be pickled batch = list(t.cast(t.Generator[t.Any, t.Any, t.Any], batch)) if isinstance(batch, list): return cls.create_payload( pickle.dumps(batch), len(t.cast(t.List[t.Any], batch)) ) else: return cls.create_payload(pickle.dumps(batch), 1) @classmethod @inject def from_payload(cls, payload: Payload) -> t.Any: return pickle.loads(payload.data) @classmethod @inject def batch_to_payloads( cls, batch: list[t.Any], indices: t.Sequence[int], batch_dim: int = 0, ) -> list[Payload]: batches = cls.batch_to_batches(batch, indices, batch_dim) payloads = [cls.to_payload(subbatch, batch_dim) for subbatch in batches] return payloads @classmethod @inject def from_batch_payloads( cls, payloads: t.Sequence[Payload], batch_dim: int = 0, ) -> tuple[list[t.Any], list[int]]: batches = [cls.from_payload(payload) for payload in payloads] return cls.batches_to_batch(batches, batch_dim) class DataContainerRegistry: CONTAINER_SINGLE_TYPE_MAP: t.Dict[ LazyType[t.Any], t.Type[DataContainer[t.Any, t.Any]] ] = dict() CONTAINER_BATCH_TYPE_MAP: t.Dict[ LazyType[t.Any], type[DataContainer[t.Any, t.Any]] ] = dict() @classmethod def register_container( cls, single_type: LazyType[t.Any] | type, batch_type: LazyType[t.Any] | type, container_cls: t.Type[DataContainer[t.Any, t.Any]], ): single_type = LazyType.from_type(single_type) batch_type = LazyType.from_type(batch_type) cls.CONTAINER_BATCH_TYPE_MAP[batch_type] = container_cls cls.CONTAINER_SINGLE_TYPE_MAP[single_type] = container_cls @classmethod def find_by_single_type( cls, type_: t.Type[SingleType] | LazyType[SingleType] ) -> t.Type[DataContainer[SingleType, t.Any]]: typeref = LazyType.from_type(type_) return cls.CONTAINER_SINGLE_TYPE_MAP.get( typeref, DefaultContainer, ) @classmethod def find_by_batch_type( cls, type_: t.Type[BatchType] | LazyType[BatchType] ) -> t.Type[DataContainer[t.Any, BatchType]]: typeref = LazyType.from_type(type_) return cls.CONTAINER_BATCH_TYPE_MAP.get( typeref, DefaultContainer, ) @classmethod def find_by_name(cls, name: str) -> t.Type[DataContainer[t.Any, t.Any]]: for container_cls in cls.CONTAINER_BATCH_TYPE_MAP.values(): if container_cls.__name__ == name: return container_cls if name == DefaultContainer.__name__: return DefaultContainer raise ValueError(f"can not find specified container class by name {name}") def register_builtin_containers(): DataContainerRegistry.register_container( LazyType("numpy", "ndarray"), LazyType("numpy", "ndarray"), NdarrayContainer ) # DataContainerRegistry.register_container(np.ndarray, np.ndarray, NdarrayContainer) # DataContainerRegistry.register_container( # LazyType("xgboost", "DMatrix"), LazyType("xgboost", "DMatrix"), DMatrixContainer # ) DataContainerRegistry.register_container( LazyType("pandas.core.series", "Series"), LazyType("pandas.core.frame", "DataFrame"), PandasDataFrameContainer, ) DataContainerRegistry.register_container( LazyType("pandas.core.frame", "DataFrame"), LazyType("pandas.core.frame", "DataFrame"), PandasDataFrameContainer, ) register_builtin_containers() class AutoContainer(DataContainer[t.Any, t.Any]): @classmethod def to_payload(cls, batch: t.Any, batch_dim: int) -> Payload: container_cls: t.Type[ DataContainer[t.Any, t.Any] ] = DataContainerRegistry.find_by_batch_type(type(batch)) return container_cls.to_payload(batch, batch_dim) @classmethod def from_payload(cls, payload: Payload) -> t.Any: container_cls = DataContainerRegistry.find_by_name(payload.container) return container_cls.from_payload(payload) @classmethod def batches_to_batch( cls, batches: t.Sequence[BatchType], batch_dim: int = 0 ) -> tuple[BatchType, list[int]]: container_cls: t.Type[ DataContainer[t.Any, t.Any] ] = DataContainerRegistry.find_by_batch_type(type(batches[0])) return container_cls.batches_to_batch(batches, batch_dim) @classmethod def batch_to_batches( cls, batch: BatchType, indices: t.Sequence[int], batch_dim: int = 0 ) -> list[BatchType]: container_cls: t.Type[ DataContainer[t.Any, t.Any] ] = DataContainerRegistry.find_by_batch_type(type(batch)) return container_cls.batch_to_batches(batch, indices, batch_dim) @classmethod def batch_to_payloads( cls, batch: t.Any, indices: t.Sequence[int], batch_dim: int = 0, ) -> list[Payload]: container_cls: t.Type[ DataContainer[t.Any, t.Any] ] = DataContainerRegistry.find_by_batch_type(type(batch)) return container_cls.batch_to_payloads(batch, indices, batch_dim) @classmethod def from_batch_payloads( cls, payloads: t.Sequence[Payload], batch_dim: int = 0 ) -> tuple[t.Any, list[int]]: container_cls = DataContainerRegistry.find_by_name(payloads[0].container) return container_cls.from_batch_payloads(payloads, batch_dim)
from __future__ import annotations import typing as t import logging import itertools from typing import TYPE_CHECKING from bentoml.exceptions import InvalidArgument logger = logging.getLogger(__name__) if TYPE_CHECKING: from aiohttp import MultipartWriter from starlette.requests import Request from ..runner.container import Payload T = t.TypeVar("T") To = t.TypeVar("To") CUDA_SUCCESS = 0 def pass_through(i: T) -> T: return i class Params(t.Generic[T]): """ A container for */** parameters. It helps to perform an operation on all the params values at the same time. """ args: tuple[T, ...] kwargs: dict[str, T] def __init__( self, *args: T, **kwargs: T, ): self.args = args self.kwargs = kwargs def items(self) -> t.Iterator[t.Tuple[t.Union[int, str], T]]: return itertools.chain(enumerate(self.args), self.kwargs.items()) @classmethod def from_dict(cls, data: dict[str | int, T]) -> Params[T]: return cls( *(data[k] for k in sorted(k for k in data if isinstance(k, int))), **{k: v for k, v in data.items() if isinstance(k, str)}, ) def all_equal(self) -> bool: value_iter = iter(self.items()) _, first = next(value_iter) return all(v == first for _, v in value_iter) def map(self, function: t.Callable[[T], To]) -> Params[To]: """ Apply a function to all the values in the Params and return a Params of the return values. """ args = tuple(function(a) for a in self.args) kwargs = {k: function(v) for k, v in self.kwargs.items()} return Params[To](*args, **kwargs) def iter(self: Params[tuple[t.Any, ...]]) -> t.Iterator[Params[t.Any]]: """ Iter over a Params of iterable values into a list of Params. All values should have the same length. """ iter_params = self.map(iter) try: while True: args = tuple(next(a) for a in iter_params.args) kwargs = {k: next(v) for k, v in iter_params.kwargs.items()} yield Params[To](*args, **kwargs) except StopIteration: pass @classmethod def agg( cls, params_list: t.Sequence[Params[T]], agg_func: t.Callable[[t.Sequence[T]], To] = pass_through, ) -> Params[To]: """ Aggregate a list of Params into a single Params by performing the aggregate function on the list of values at the same position. """ if not params_list: return Params() args = tuple( agg_func(tuple(params.args[i] for params in params_list)) for i, _ in enumerate(params_list[0].args) ) kwargs = { k: agg_func(tuple(params.kwargs[k] for params in params_list)) for k in params_list[0].kwargs } return Params(*args, **kwargs) @property def sample(self) -> T: """ Return a sample value (the first value of args or kwargs if args is empty) of the Params. """ if self.args: return self.args[0] return next(iter(self.kwargs.values())) PAYLOAD_META_HEADER = "Bento-Payload-Meta" def payload_paramss_to_batch_params( paramss: t.Sequence[Params[Payload]], batch_dim: int, # TODO: support mapping from arg to batch dimension ) -> tuple[Params[t.Any], list[int]]: from ..runner.container import AutoContainer _converted_params = Params.agg( paramss, agg_func=lambda i: AutoContainer.from_batch_payloads( i, batch_dim=batch_dim, ), ).iter() batched_params = next(_converted_params) indice_params: Params[list[int]] = next(_converted_params) # considering skip this check if the CPU overhead of each inference is too high if not indice_params.all_equal(): raise InvalidArgument( f"argument lengths for parameters do not matchs: {tuple(indice_params.items())}" ) return batched_params, indice_params.sample def payload_params_to_multipart(params: Params[Payload]) -> MultipartWriter: import json from multidict import CIMultiDict from aiohttp.multipart import MultipartWriter multipart = MultipartWriter(subtype="form-data") for key, payload in params.items(): multipart.append( payload.data, headers=CIMultiDict( ( (PAYLOAD_META_HEADER, json.dumps(payload.meta)), ("Content-Type", f"application/vnd.bentoml.{payload.container}"), ("Content-Disposition", f'form-data; name="{key}"'), ) ), ) return multipart async def multipart_to_payload_params(request: Request) -> Params[Payload]: import json from bentoml._internal.runner.container import Payload from bentoml._internal.utils.formparser import populate_multipart_requests parts = await populate_multipart_requests(request) max_arg_index = -1 kwargs: t.Dict[str, Payload] = {} args_map: t.Dict[int, Payload] = {} for field_name, req in parts.items(): payload = Payload( data=await req.body(), meta=json.loads(req.headers[PAYLOAD_META_HEADER]), container=req.headers["Content-Type"].strip("application/vnd.bentoml."), ) if field_name.isdigit(): arg_index = int(field_name) args_map[arg_index] = payload max_arg_index = max(max_arg_index, arg_index) else: kwargs[field_name] = payload args = tuple(args_map[i] for i in range(max_arg_index + 1)) return Params(*args, **kwargs)
from __future__ import annotations import typing as t import logging from abc import ABC from abc import abstractmethod from typing import overload from typing import TYPE_CHECKING import attr from ..types import LazyType from ..types import ParamSpec if TYPE_CHECKING: from ..types import AnyType T = t.TypeVar("T", bound="Runnable") P = ParamSpec("P") R = t.TypeVar("R") logger = logging.getLogger(__name__) RUNNABLE_METHOD_MARK: str = "_bentoml_runnable_method" class Runnable(ABC): SUPPORT_NVIDIA_GPU: bool SUPPORT_CPU_MULTI_THREADING: bool methods: dict[str, RunnableMethod[t.Any, t.Any, t.Any]] | None = None @abstractmethod def __init__(self, **kwargs: t.Any): ... @classmethod def add_method( cls: t.Type[T], method: t.Callable[t.Concatenate[T, P], t.Any], name: str, *, batchable: bool = False, batch_dim: tuple[int, int] | int = 0, input_spec: LazyType[t.Any] | t.Tuple[LazyType[t.Any], ...] | None = None, output_spec: LazyType[t.Any] | None = None, ): meth = Runnable.method( method, batchable=batchable, batch_dim=batch_dim, input_spec=input_spec, output_spec=output_spec, ) setattr(cls, name, meth) meth.__set_name__(cls, name) @overload @staticmethod def method( meth: t.Callable[t.Concatenate[T, P], R], *, batchable: bool = False, batch_dim: tuple[int, int] | int = 0, input_spec: AnyType | tuple[AnyType, ...] | None = None, output_spec: AnyType | None = None, ) -> RunnableMethod[T, P, R]: ... @overload @staticmethod def method( meth: None = None, *, batchable: bool = False, batch_dim: tuple[int, int] | int = 0, input_spec: AnyType | tuple[AnyType, ...] | None = None, output_spec: AnyType | None = None, ) -> t.Callable[[t.Callable[t.Concatenate[T, P], R]], RunnableMethod[T, P, R]]: ... @staticmethod def method( meth: t.Callable[t.Concatenate[T, P], R] | None = None, *, batchable: bool = False, batch_dim: tuple[int, int] | int = 0, input_spec: AnyType | tuple[AnyType, ...] | None = None, output_spec: AnyType | None = None, ) -> t.Callable[ [t.Callable[t.Concatenate[T, P], R]], RunnableMethod[T, P, R] ] | RunnableMethod[T, P, R]: def method_decorator( meth: t.Callable[t.Concatenate[T, P], R] ) -> RunnableMethod[T, P, R]: return RunnableMethod( meth, RunnableMethodConfig( batchable=batchable, batch_dim=(batch_dim, batch_dim) if isinstance(batch_dim, int) else batch_dim, input_spec=input_spec, output_spec=output_spec, ), ) if callable(meth): return method_decorator(meth) return method_decorator @attr.define class RunnableMethod(t.Generic[T, P, R]): func: t.Callable[t.Concatenate[T, P], R] config: RunnableMethodConfig _bentoml_runnable_method: None = None def __get__(self, obj: T, _: t.Type[T] | None = None) -> t.Callable[P, R]: def method(*args: P.args, **kwargs: P.kwargs) -> R: return self.func(obj, *args, **kwargs) return method def __set_name__(self, owner: t.Any, name: str): if owner.methods is None: owner.methods = {} owner.methods[name] = self @attr.define() class RunnableMethodConfig: batchable: bool batch_dim: tuple[int, int] input_spec: AnyType | t.Tuple[AnyType, ...] | None = None output_spec: AnyType | None = None
from __future__ import annotations import json import typing as t import asyncio import functools from typing import TYPE_CHECKING from json.decoder import JSONDecodeError from urllib.parse import urlparse from . import RunnerHandle from ..container import Payload from ...utils.uri import uri_to_path from ....exceptions import RemoteException from ...runner.utils import Params from ...runner.utils import PAYLOAD_META_HEADER from ...runner.utils import payload_params_to_multipart from ...configuration.containers import DeploymentContainer if TYPE_CHECKING: # pragma: no cover from aiohttp import BaseConnector from aiohttp.client import ClientSession from ..runner import Runner from ..runner import RunnerMethod P = t.ParamSpec("P") R = t.TypeVar("R") class RemoteRunnerClient(RunnerHandle): def __init__(self, runner: Runner): # pylint: disable=super-init-not-called self._runner = runner self._conn: BaseConnector | None = None self._client: ClientSession | None = None self._loop: asyncio.AbstractEventLoop | None = None self._addr: str | None = None @property def _remote_runner_server_map(self) -> dict[str, str]: return DeploymentContainer.remote_runner_mapping.get() def _close_conn(self) -> None: if self._conn: self._conn.close() def _get_conn(self) -> BaseConnector: import aiohttp if ( self._loop is None or self._conn is None or self._conn.closed or self._loop.is_closed() ): self._loop = asyncio.get_event_loop() # get the loop lazily bind_uri = self._remote_runner_server_map[self._runner.name] parsed = urlparse(bind_uri) if parsed.scheme == "file": path = uri_to_path(bind_uri) self._conn = aiohttp.UnixConnector( path=path, loop=self._loop, limit=800, # TODO(jiang): make it configurable keepalive_timeout=1800.0, ) self._addr = "http://127.0.0.1:8000" # addr doesn't matter with UDS elif parsed.scheme == "tcp": self._conn = aiohttp.TCPConnector( loop=self._loop, verify_ssl=False, limit=800, # TODO(jiang): make it configurable keepalive_timeout=1800.0, ) self._addr = f"http://{parsed.netloc}" else: raise ValueError(f"Unsupported bind scheme: {parsed.scheme}") return self._conn def _get_client( self, timeout_sec: float | None = None, ) -> ClientSession: import aiohttp if ( self._loop is None or self._client is None or self._client.closed or self._loop.is_closed() ): import yarl from opentelemetry.instrumentation.aiohttp_client import ( create_trace_config, # type: ignore (missing type stubs) ) def strip_query_params(url: yarl.URL) -> str: return str(url.with_query(None)) jar = aiohttp.DummyCookieJar() if timeout_sec is not None: timeout = aiohttp.ClientTimeout(total=timeout_sec) else: DEFAULT_TIMEOUT = aiohttp.ClientTimeout(total=5 * 60) timeout = DEFAULT_TIMEOUT self._client = aiohttp.ClientSession( trace_configs=[ create_trace_config( # Remove all query params from the URL attribute on the span. url_filter=strip_query_params, # type: ignore tracer_provider=DeploymentContainer.tracer_provider.get(), ) ], connector=self._get_conn(), auto_decompress=False, cookie_jar=jar, connector_owner=False, timeout=timeout, loop=self._loop, ) return self._client async def async_run_method( self, __bentoml_method: RunnerMethod[t.Any, P, R], *args: P.args, **kwargs: P.kwargs, ) -> R: from ...runner.container import AutoContainer # TODO: validate call signature inp_batch_dim = __bentoml_method.config.batch_dim[0] payload_params = Params[Payload](*args, **kwargs).map( functools.partial(AutoContainer.to_payload, batch_dim=inp_batch_dim) ) if __bentoml_method.config.batchable: if not payload_params.map(lambda i: i.batch_size).all_equal(): raise ValueError( "All batchable arguments must have the same batch size." ) multipart = payload_params_to_multipart(payload_params) client = self._get_client() path = "" if __bentoml_method.name == "__call__" else __bentoml_method.name async with client.post( f"{self._addr}/{path}", data=multipart, ) as resp: body = await resp.read() if resp.status != 200: raise RemoteException( f"An exception occurred in remote runner {self._runner.name}: [{resp.status}] {body.decode()}" ) try: meta_header = resp.headers[PAYLOAD_META_HEADER] except KeyError: raise RemoteException( f"Bento payload decode error: {PAYLOAD_META_HEADER} header not set. " "An exception might have occurred in the remote server." f"[{resp.status}] {body.decode()}" ) from None try: content_type = resp.headers["Content-Type"] except KeyError: raise RemoteException( f"Bento payload decode error: Content-Type header not set. " "An exception might have occurred in the remote server." f"[{resp.status}] {body.decode()}" ) from None if not content_type.lower().startswith("application/vnd.bentoml."): raise RemoteException( f"Bento payload decode error: invalid Content-Type '{content_type}'." ) container = content_type.strip("application/vnd.bentoml.") try: payload = Payload( data=body, meta=json.loads(meta_header), container=container ) except JSONDecodeError: raise ValueError(f"Bento payload decode error: {meta_header}") return AutoContainer.from_payload(payload) def run_method( self, __bentoml_method: RunnerMethod[t.Any, P, R], *args: P.args, **kwargs: P.kwargs, ) -> R: import anyio return anyio.from_thread.run( # type: ignore (pyright cannot infer the return type) self.async_run_method, __bentoml_method, *args, **kwargs, ) def __del__(self) -> None: self._close_conn()
from __future__ import annotations import typing as t import functools from typing import TYPE_CHECKING from bentoml._internal.runner.utils import Params from bentoml._internal.runner.container import Payload from bentoml._internal.runner.container import AutoContainer from . import RunnerHandle if TYPE_CHECKING: from ..runner import Runner from ..runner import RunnerMethod P = t.ParamSpec("P") R = t.TypeVar("R") class LocalRunnerRef(RunnerHandle): def __init__(self, runner: Runner) -> None: # pylint: disable=super-init-not-called self._runnable = runner.runnable_class(**runner.runnable_init_params) def run_method( self, __bentoml_method: RunnerMethod[t.Any, P, R], *args: P.args, **kwargs: P.kwargs, ) -> R: if __bentoml_method.config.batchable: inp_batch_dim = __bentoml_method.config.batch_dim[0] payload_params = Params[Payload](*args, **kwargs).map( lambda arg: AutoContainer.to_payload(arg, batch_dim=inp_batch_dim) ) if not payload_params.map(lambda i: i.batch_size).all_equal(): raise ValueError( "All batchable arguments must have the same batch size." ) return getattr(self._runnable, __bentoml_method.name)(*args, **kwargs) async def async_run_method( self, __bentoml_method: RunnerMethod[t.Any, P, R], *args: P.args, **kwargs: P.kwargs, ) -> R: import anyio method = getattr(self._runnable, __bentoml_method.name) return await anyio.to_thread.run_sync( functools.partial(method, **kwargs), *args, limiter=anyio.CapacityLimiter(1) )
from __future__ import annotations import typing as t import logging from abc import ABC from abc import abstractmethod from typing import TYPE_CHECKING from ....exceptions import StateException if TYPE_CHECKING: from ..runner import Runner from ..runner import RunnerMethod R = t.TypeVar("R") P = t.ParamSpec("P") logger = logging.getLogger(__name__) class RunnerHandle(ABC): @abstractmethod def __init__(self, runner: Runner) -> None: ... @abstractmethod def run_method( self, __bentoml_method: RunnerMethod[t.Any, P, R], *args: P.args, **kwargs: P.kwargs, ) -> R: ... @abstractmethod async def async_run_method( self, __bentoml_method: RunnerMethod[t.Any, P, R], *args: P.args, **kwargs: P.kwargs, ) -> R: ... class DummyRunnerHandle(RunnerHandle): def __init__( # pylint: disable=super-init-not-called self, runner: Runner | None = None ) -> None: pass def run_method( self, __bentoml_method: RunnerMethod[t.Any, t.Any, t.Any], *args: t.Any, **kwargs: t.Any, ) -> t.Any: raise StateException("Runner is not initialized") async def async_run_method( self, __bentoml_method: RunnerMethod[t.Any, t.Any, t.Any], *args: t.Any, **kwargs: t.Any, ) -> t.Any: raise StateException("Runner is not initialized")
from __future__ import annotations import typing as t from typing import TYPE_CHECKING from starlette.requests import Request from multipart.multipart import parse_options_header from starlette.responses import Response from .base import IODescriptor from ...exceptions import InvalidArgument from ...exceptions import BentoMLException from ..utils.formparser import populate_multipart_requests from ..utils.formparser import concat_to_multipart_response if TYPE_CHECKING: from types import UnionType from ..types import LazyType from ..context import InferenceApiContext as Context class Multipart(IODescriptor[t.Any]): """ :code:`Multipart` defines API specification for the inputs/outputs of a Service, where inputs/outputs of a Service can receive/send a *multipart* request/responses as specified in your API function signature. Sample implementation of a sklearn service: .. code-block:: python # sklearn_svc.py import bentoml from bentoml.io import NumpyNdarray, Multipart, JSON import bentoml.sklearn runner = bentoml.sklearn.load_runner("sklearn_model_clf") svc = bentoml.Service("iris-classifier", runners=[runner]) input_spec = Multipart(arr=NumpyNdarray(), annotations=JSON()) output_spec = Multipart(output=NumpyNdarray(), result=JSON()) @svc.api(input=input_spec, output=output_spec) def predict(arr, annotations): res = runner.run(arr) return {"output":res, "result":annotations} Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./sklearn_svc.py:svc --reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "iris-classifier" defined in "sklearn_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-tab:: python import requests from requests_toolbelt.multipart.encoder import MultipartEncoder m = MultipartEncoder( fields={'field0': 'value', 'field1': 'value', 'field2': ('filename', open('test.json', 'rb'), 'application/json')} ) requests.post('http://0.0.0.0:3000/predict', data=m, headers={'Content-Type': m.content_type}) .. code-tab:: bash % curl -X POST -H "Content-Type: multipart/form-data" -F [email protected] -F arr='[5,4,3,2]' http://0.0.0.0:3000/predict --b1d72c201a064ecd92a17a412eb9208e Content-Disposition: form-data; name="output" content-length: 1 content-type: application/json 1 --b1d72c201a064ecd92a17a412eb9208e Content-Disposition: form-data; name="result" content-length: 13 content-type: application/json {"foo":"bar"} --b1d72c201a064ecd92a17a412eb9208e-- Args: inputs (:code:`Dict[str, IODescriptor]`): Dictionary consisting keys as inputs definition for a Multipart request/response, values as IODescriptor supported by BentoML. Currently, Multipart supports Image, NumpyNdarray, PandasDataFrame, PandasSeries, Text, and File. Make sure to match the input params in an API function to the keys defined under :code:`Multipart`: .. code-block:: bash +----------------------------------------------------------------+ | | | +--------------------------------------------------------+ | | | | | | | Multipart(arr=NumpyNdarray(), annotations=JSON() | | | | | | | +----------------+-----------------------+---------------+ | | | | | | | | | | | | | | +----+ +---------+ | | | | | | +---------------v--------v---------+ | | | def predict(arr, annotations): | | | +----------------------------------+ | | | +----------------------------------------------------------------+ Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that Multipart request/response. """ def __init__(self, **inputs: IODescriptor[t.Any]): for descriptor in inputs.values(): if isinstance(descriptor, Multipart): # pragma: no cover raise InvalidArgument( "Multipart IO can not contain nested Multipart IO descriptor" ) self._inputs: dict[str, t.Any] = inputs def input_type( self, ) -> dict[str, t.Type[t.Any] | UnionType | LazyType[t.Any]]: res: dict[str, t.Type[t.Any] | UnionType | LazyType[t.Any]] = {} for (k, v) in self._inputs.items(): inp_type = v.input_type() if isinstance(inp_type, dict): raise TypeError( "A multipart descriptor cannot take a multi-valued I/O descriptor as input" ) res[k] = inp_type return res def openapi_schema_type(self) -> dict[str, t.Any]: return { "type": "object", "properties": { k: io.openapi_schema_type() for (k, io) in self._inputs.items() }, } def openapi_request_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {"multipart/form-data": {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {"multipart/form-data": {"schema": self.openapi_schema_type()}} async def from_http_request(self, request: Request) -> dict[str, t.Any]: ctype, _ = parse_options_header(request.headers["content-type"]) if ctype != b"multipart/form-data": raise BentoMLException( f"{self.__class__.__name__} only accepts `multipart/form-data` as Content-Type header, got {ctype} instead." ) res: dict[str, t.Any] = dict() reqs = await populate_multipart_requests(request) for k, i in self._inputs.items(): req = reqs[k] v = await i.from_http_request(req) res[k] = v return res async def to_http_response( self, obj: dict[str, t.Any], ctx: Context | None = None ) -> Response: res_mapping: dict[str, Response] = {} for k, io_ in self._inputs.items(): data = obj[k] resp = io_.init_http_response() res_mapping[k] = await io_.finalize_http_response(resp, data) return await concat_to_multipart_response(res_mapping, ctx)
from __future__ import annotations import io import typing as t import logging import functools import importlib.util from enum import Enum from typing import TYPE_CHECKING from starlette.requests import Request from starlette.responses import Response from .base import IODescriptor from .json import MIME_TYPE_JSON from ..types import LazyType from ..utils.http import set_cookies from ...exceptions import BadInput from ...exceptions import InvalidArgument from ...exceptions import MissingDependencyException from ..utils.lazy_loader import LazyLoader if TYPE_CHECKING: import pandas as pd # type: ignore[import] from .. import external_typing as ext from ..context import InferenceApiContext as Context else: pd = LazyLoader( "pd", globals(), "pandas", exc_msg="`pandas` is required to use PandasDataFrame or PandasSeries. Install with `pip install -U pandas`", ) logger = logging.getLogger(__name__) # Check for parquet support @functools.lru_cache(maxsize=1) def get_parquet_engine() -> str: if importlib.util.find_spec("pyarrow") is not None: return "pyarrow" elif importlib.util.find_spec("fastparquet") is not None: return "fastparquet" else: logger.warning( "Neither pyarrow nor fastparquet packages found. Parquet de/serialization will not be available." ) raise MissingDependencyException( "Parquet serialization is not available. Try installing pyarrow or fastparquet first." ) def _infer_type(item: str) -> str: # pragma: no cover if item.startswith("int"): return "integer" elif item.startswith("float") or item.startswith("double"): return "number" elif item.startswith("str") or item.startswith("date"): return "string" elif item.startswith("bool"): return "boolean" else: return "object" def _schema_type( dtype: bool | t.Dict[str, t.Any] | None ) -> t.Dict[str, t.Any]: # pragma: no cover if isinstance(dtype, dict): return { "type": "object", "properties": { k: {"type": "array", "items": {"type": _infer_type(v)}} for k, v in dtype.items() }, } else: return {"type": "object"} class SerializationFormat(Enum): JSON = "application/json" PARQUET = "application/octet-stream" CSV = "text/csv" def __init__(self, mime_type: str): self.mime_type = mime_type def _infer_serialization_format_from_request( request: Request, default_format: SerializationFormat ) -> SerializationFormat: """Determine the serialization format from the request's headers['content-type']""" content_type = request.headers.get("content-type") if content_type == "application/json": return SerializationFormat.JSON elif content_type == "application/octet-stream": return SerializationFormat.PARQUET elif content_type == "text/csv": return SerializationFormat.CSV elif content_type: logger.debug( "Unknown content-type (%s), falling back to %s serialization format.", content_type, default_format, ) return default_format else: logger.debug( "Content-type not specified, falling back to %s serialization format.", default_format, ) return default_format def _validate_serialization_format(serialization_format: SerializationFormat): if ( serialization_format is SerializationFormat.PARQUET and get_parquet_engine() is None ): raise MissingDependencyException( "Parquet serialization is not available. Try installing pyarrow or fastparquet first." ) class PandasDataFrame(IODescriptor["ext.PdDataFrame"]): """ :code:`PandasDataFrame` defines API specification for the inputs/outputs of a Service, where either inputs will be converted to or outputs will be converted from type :code:`numpy.ndarray` as specified in your API function signature. Sample implementation of a sklearn service: .. code-block:: python # sklearn_svc.py import bentoml import pandas as pd import numpy as np from bentoml.io import PandasDataFrame import bentoml.sklearn input_spec = PandasDataFrame.from_sample(pd.DataFrame(np.array([[5,4,3,2]]))) runner = bentoml.sklearn.load_runner("sklearn_model_clf") svc = bentoml.Service("iris-classifier", runners=[runner]) @svc.api(input=input_spec, output=PandasDataFrame()) def predict(input_arr): res = runner.run_batch(input_arr) # type: np.ndarray return pd.DataFrame(res) Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./sklearn_svc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "iris-classifier" defined in "sklearn_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-tab:: python import requests requests.post( "http://0.0.0.0:3000/predict", headers={"content-type": "application/json"}, data='[{"0":5,"1":4,"2":3,"3":2}]' ).text .. code-tab:: bash % curl -X POST -H "Content-Type: application/json" --data '[{"0":5,"1":4,"2":3,"3":2}]' http://0.0.0.0:3000/predict [{"0": 1}]% Args: orient (:code:`str`, `optional`, default to :code:`records`): Indication of expected JSON string format. Compatible JSON strings can be produced by :func:`pandas.io.json.to_json()` with a corresponding orient value. Possible orients are: - :obj:`split` - :code:`Dict[str, Any]`: {idx -> [idx], columns -> [columns], data -> [values]} - :obj:`records` - :code:`List[Any]`: [{column -> value}, ..., {column -> value}] - :obj:`index` - :code:`Dict[str, Any]`: {idx -> {column -> value}} - :obj:`columns` - :code:`Dict[str, Any]`: {column -> {index -> value}} - :obj:`values` - :code:`Dict[str, Any]`: Values arrays columns (:code:`List[str]`, `optional`, default to :code:`None`): List of columns name that users wish to update. apply_column_names (:code:`bool`, `optional`, default to :code:`False`): Whether to update incoming DataFrame columns. If :code:`apply_column_names`=True, then `columns` must be specified. dtype (:code:`Union[bool, Dict[str, Any]]`, `optional`, default to :code:`None`): Data Type users wish to convert their inputs/outputs to. If it is a boolean, then pandas will infer dtypes. Else if it is a dictionary of column to dtype, then applies those to incoming dataframes. If False, then don't infer dtypes at all (only applies to the data). This is not applicable when :code:`orient='table'`. enforce_dtype (:code:`bool`, `optional`, default to :code:`False`): Whether to enforce a certain data type. if :code:`enforce_dtype=True` then :code:`dtype` must be specified. shape (:code:`Tuple[int, ...]`, `optional`, default to :code:`None`): Optional shape check that users can specify for their incoming HTTP requests. We will only check the number of columns you specified for your given shape: .. code-block:: python import pandas as pd from bentoml.io import PandasDataFrame df = pd.DataFrame([[1,2,3]]) # shape (1,3) inp = PandasDataFrame.from_sample(arr) @svc.api(input=PandasDataFrame( shape=(51,10), enforce_shape=True ), output=PandasDataFrame()) def infer(input_df: pd.DataFrame) -> pd.DataFrame:... # if input_df have shape (40,9), it will throw out errors enforce_shape (`bool`, `optional`, default to :code:`False`): Whether to enforce a certain shape. If `enforce_shape=True` then `shape` must be specified default_format (:code:`str`, `optional`, default to :obj:`json`): The default serialization format to use if the request does not specify a :code:`headers['content-type']`. It is also the serialization format used for the response. Possible values are: - :obj:`json` - JSON text format (inferred from content-type "application/json") - :obj:`parquet` - Parquet binary format (inferred from content-type "application/octet-stream") - :obj:`csv` - CSV text format (inferred from content-type "text/csv") Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that `pd.DataFrame`. """ def __init__( self, orient: ext.DataFrameOrient = "records", apply_column_names: bool = False, columns: list[str] | None = None, dtype: bool | dict[str, t.Any] | None = None, enforce_dtype: bool = False, shape: tuple[int, ...] | None = None, enforce_shape: bool = False, default_format: t.Literal["json", "parquet", "csv"] = "json", ): self._orient = orient self._columns = columns self._apply_column_names = apply_column_names self._dtype = dtype self._enforce_dtype = enforce_dtype self._shape = shape self._enforce_shape = enforce_shape self._default_format = SerializationFormat[default_format.upper()] _validate_serialization_format(self._default_format) def input_type( self, ) -> LazyType[ext.PdDataFrame]: return LazyType("pandas", "DataFrame") def openapi_schema_type(self) -> dict[str, t.Any]: return _schema_type(self._dtype) def openapi_request_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {self._default_format.mime_type: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {self._default_format.mime_type: {"schema": self.openapi_schema_type()}} async def from_http_request(self, request: Request) -> ext.PdDataFrame: """ Process incoming requests and convert incoming objects to `pd.DataFrame` Args: request (`starlette.requests.Requests`): Incoming Requests Returns: a `pd.DataFrame` object. This can then be used inside users defined logics. Raises: BadInput: Raised when the incoming requests are bad formatted. """ serialization_format = _infer_serialization_format_from_request( request, self._default_format ) _validate_serialization_format(serialization_format) obj = await request.body() if self._enforce_dtype: if self._dtype is None: logger.warning( "`dtype` is None or undefined, while `enforce_dtype`=True" ) # TODO(jiang): check dtype if serialization_format is SerializationFormat.JSON: res = pd.read_json( # type: ignore[arg-type] io.BytesIO(obj), dtype=self._dtype, orient=self._orient, ) elif serialization_format is SerializationFormat.PARQUET: res = pd.read_parquet( # type: ignore[arg-type] io.BytesIO(obj), engine=get_parquet_engine(), ) elif serialization_format is SerializationFormat.CSV: res: ext.PdDataFrame = pd.read_csv( # type: ignore[arg-type] io.BytesIO(obj), dtype=self._dtype, # type: ignore[arg-type] ) else: raise InvalidArgument( f"Unknown serialization format ({serialization_format})." ) assert isinstance(res, pd.DataFrame) if self._apply_column_names: if self._columns is None: logger.warning( "`columns` is None or undefined, while `apply_column_names`=True" ) elif len(self._columns) == res.shape[1]: raise BadInput( "length of `columns` does not match the columns of incoming data" ) else: res.columns = pd.Index(self._columns) if self._enforce_shape: if self._shape is None: logger.warning( "`shape` is None or undefined, while `enforce_shape`=True" ) else: assert all( left == right for left, right in zip(self._shape, res.shape) # type: ignore (shape type) if left != -1 and right != -1 ), f"incoming has shape {res.shape} where enforced shape to be {self._shape}" return res async def to_http_response( self, obj: ext.PdDataFrame, ctx: Context | None = None ) -> Response: """ Process given objects and convert it to HTTP response. Args: obj (`pd.DataFrame`): `pd.DataFrame` that will be serialized to JSON or parquet Returns: HTTP Response of type `starlette.responses.Response`. This can be accessed via cURL or any external web traffic. """ # For the response it doesn't make sense to enforce the same serialization format as specified # by the request's headers['content-type']. Instead we simply use the _default_format. serialization_format = self._default_format if not LazyType["ext.PdDataFrame"](pd.DataFrame).isinstance(obj): raise InvalidArgument( f"return object is not of type `pd.DataFrame`, got type {type(obj)} instead" ) if serialization_format is SerializationFormat.JSON: resp = obj.to_json(orient=self._orient) # type: ignore[arg-type] elif serialization_format is SerializationFormat.PARQUET: resp = obj.to_parquet(engine=get_parquet_engine()) # type: ignore elif serialization_format is SerializationFormat.CSV: resp = obj.to_csv() # type: ignore else: raise InvalidArgument( f"Unknown serialization format ({serialization_format})." ) if ctx is not None: res = Response( resp, media_type=serialization_format.mime_type, headers=ctx.response.headers, # type:ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response(resp, media_type=serialization_format.mime_type) @classmethod def from_sample( cls, sample_input: "pd.DataFrame", orient: "ext.DataFrameOrient" = "records", apply_column_names: bool = True, enforce_shape: bool = True, enforce_dtype: bool = False, default_format: "t.Literal['json', 'parquet', 'csv']" = "json", ) -> "PandasDataFrame": """ Create a PandasDataFrame IO Descriptor from given inputs. Args: sample_input (`pd.DataFrame`): Given sample pd.DataFrame data orient (:code:`str`, `optional`, default to :code:`records`): Indication of expected JSON string format. Compatible JSON strings can be produced by :func:`pandas.io.json.to_json()` with a corresponding orient value. Possible orients are: - :obj:`split` - :code:`Dict[str, Any]`: {idx -> [idx], columns -> [columns], data -> [values]} - :obj:`records` - :code:`List[Any]`: [{column -> value}, ..., {column -> value}] - :obj:`index` - :code:`Dict[str, Any]`: {idx -> {column -> value}} - :obj:`columns` - :code:`Dict[str, Any]`: {column -> {index -> value}} - :obj:`values` - :code:`Dict[str, Any]`: Values arrays apply_column_names (`bool`, `optional`, default to :code:`True`): Update incoming DataFrame columns. `columns` must be specified at function signature. If you don't want to enforce a specific columns name then change `apply_column_names=False`. enforce_dtype (`bool`, `optional`, default to :code:`True`): Enforce a certain data type. `dtype` must be specified at function signature. If you don't want to enforce a specific dtype then change `enforce_dtype=False`. enforce_shape (`bool`, `optional`, default to :code:`False`): Enforce a certain shape. `shape` must be specified at function signature. If you don't want to enforce a specific shape then change `enforce_shape=False`. default_format (:code:`str`, `optional`, default to :code:`json`): The default serialization format to use if the request does not specify a :code:`headers['content-type']`. It is also the serialization format used for the response. Possible values are: - :obj:`json` - JSON text format (inferred from content-type "application/json") - :obj:`parquet` - Parquet binary format (inferred from content-type "application/octet-stream") - :obj:`csv` - CSV text format (inferred from content-type "text/csv") Returns: :obj:`bentoml._internal.io_descriptors.PandasDataFrame`: :code:`PandasDataFrame` IODescriptor from given users inputs. Example: .. code-block:: python import pandas as pd from bentoml.io import PandasDataFrame arr = [[1,2,3]] inp = PandasDataFrame.from_sample(pd.DataFrame(arr)) ... @svc.api(input=inp, output=PandasDataFrame()) def predict(inputs: pd.DataFrame) -> pd.DataFrame:... """ columns = [str(x) for x in list(sample_input.columns)] # type: ignore[reportUnknownVariableType] return cls( orient=orient, enforce_shape=enforce_shape, shape=sample_input.shape, apply_column_names=apply_column_names, columns=columns, enforce_dtype=enforce_dtype, dtype=None, # TODO: not breaking atm default_format=default_format, ) class PandasSeries(IODescriptor["ext.PdSeries"]): """ :code:`PandasSeries` defines API specification for the inputs/outputs of a Service, where either inputs will be converted to or outputs will be converted from type :code:`numpy.ndarray` as specified in your API function signature. Sample implementation of a sklearn service: .. code-block:: python # sklearn_svc.py import bentoml import pandas as pd import numpy as np from bentoml.io import PandasSeries import bentoml.sklearn input_spec = PandasSeries.from_sample(pd.Series(np.array([[5,4,3,2]]))) runner = bentoml.sklearn.load_runner("sklearn_model_clf") svc = bentoml.Service("iris-classifier", runners=[runner]) @svc.api(input=input_spec, output=PandasSeries()) def predict(input_arr): res = runner.run_batch(input_arr) # type: np.ndarray return pd.Series(res) Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./sklearn_svc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "iris-classifier" defined in "sklearn_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-tab:: python import requests requests.post( "http://0.0.0.0:3000/predict", headers={"content-type": "application/json"}, data='[{"0":5,"1":4,"2":3,"3":2}]' ).text .. code-tab:: bash % curl -X POST -H "Content-Type: application/json" --data '[{"0":5,"1":4,"2":3,"3":2}]' http://0.0.0.0:3000/predict [{"0": 1}]% Args: orient (:code:`str`, `optional`, default to :code:`records`): Indication of expected JSON string format. Compatible JSON strings can be produced by :func:`pandas.io.json.to_json()` with a corresponding orient value. Possible orients are: - :obj:`split` - :code:`Dict[str, Any]`: {idx -> [idx], columns -> [columns], data -> [values]} - :obj:`records` - :code:`List[Any]`: [{column -> value}, ..., {column -> value}] - :obj:`index` - :code:`Dict[str, Any]`: {idx -> {column -> value}} - :obj:`columns` - :code:`Dict[str, Any]`: {column -> {index -> value}} - :obj:`values` - :code:`Dict[str, Any]`: Values arrays columns (`List[str]`, `optional`, default to :code:`None`): List of columns name that users wish to update apply_column_names (`bool`, `optional`, default to :code:`False`): Whether to update incoming DataFrame columns. If :code:`apply_column_names=True`, then `columns` must be specified. dtype (:code:`Union[bool, Dict[str, Any]]`, `optional`, default to :code:`None`): Data Type users wish to convert their inputs/outputs to. If it is a boolean, then pandas will infer dtypes. Else if it is a dictionary of column to dtype, then applies those to incoming dataframes. If False, then don't infer dtypes at all (only applies to the data). This is not applicable when :code:`orient='table'`. enforce_dtype (`bool`, `optional`, default to :code:`False`): Whether to enforce a certain data type. if :code:`enforce_dtype=True` then :code:`dtype` must be specified. shape (`Tuple[int, ...]`, `optional`, default to :code:`None`): Optional shape check that users can specify for their incoming HTTP requests. We will only check the number of columns you specified for your given shape. Examples usage: .. code-block:: python import pandas as pd from bentoml.io import PandasSeries df = pd.DataFrame([[1,2,3]]) # shape (1,3) inp = PandasSeries.from_sample(arr) ... @svc.api(input=inp, output=PandasSeries()) # the given shape above is valid def predict(input_df: pd.DataFrame) -> pd.DataFrame: result = await runner.run(input_df) return result @svc.api(input=PandasSeries(shape=(51,10), enforce_shape=True), output=PandasSeries()) def infer(input_df: pd.DataFrame) -> pd.DataFrame: ... # if input_df have shape (40,9), it will throw out errors enforce_shape (`bool`, `optional`, default to :code:`False`): Whether to enforce a certain shape. If `enforce_shape=True` then `shape` must be specified Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that `pd.DataFrame`. """ def __init__( self, orient: "ext.SeriesOrient" = "records", dtype: t.Optional[t.Union[bool, t.Dict[str, t.Any]]] = None, enforce_dtype: bool = False, shape: t.Optional[t.Tuple[int, ...]] = None, enforce_shape: bool = False, ): self._orient = orient self._dtype = dtype self._enforce_dtype = enforce_dtype self._shape = shape self._enforce_shape = enforce_shape self._mime_type = "application/json" def input_type( self, ) -> LazyType[ext.PdSeries]: return LazyType("pandas", "Series") def openapi_schema_type(self) -> t.Dict[str, t.Any]: return _schema_type(self._dtype) def openapi_request_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {self._mime_type: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for outgoing responses""" return {self._mime_type: {"schema": self.openapi_schema_type()}} async def from_http_request(self, request: Request) -> ext.PdSeries: """ Process incoming requests and convert incoming objects to `pd.Series` Args: request (`starlette.requests.Requests`): Incoming Requests Returns: a `pd.Series` object. This can then be used inside users defined logics. """ obj = await request.body() if self._enforce_dtype: if self._dtype is None: logger.warning( "`dtype` is None or undefined, while `enforce_dtype`=True" ) # TODO(jiang): check dtypes when enforce_dtype is set res: ext.PdDataFrame = pd.read_json( # type: ignore[arg-type] obj, # type: ignore[arg-type] typ="series", orient=self._orient, dtype=self._dtype, # type: ignore[arg-type] ) assert isinstance(res, pd.Series) if self._enforce_shape: if self._shape is None: logger.warning( "`shape` is None or undefined, while `enforce_shape`=True" ) else: assert all( left == right for left, right in zip(self._shape, res.shape) if left != -1 and right != -1 ), f"incoming has shape {res.shape} where enforced shape to be {self._shape}" return res async def init_http_response(self) -> Response: return Response(None, media_type=MIME_TYPE_JSON) async def to_http_response( self, obj: t.Any, ctx: Context | None = None ) -> Response: """ Process given objects and convert it to HTTP response. Args: obj (`pd.Series`): `pd.Series` that will be serialized to JSON Returns: HTTP Response of type `starlette.responses.Response`. This can be accessed via cURL or any external web traffic. """ if not LazyType["ext.PdSeries"](pd.Series).isinstance(obj): raise InvalidArgument( f"return object is not of type `pd.Series`, got type {type(obj)} instead" ) if ctx is not None: res = Response( obj.to_json(orient=self._orient), # type: ignore[arg-type] media_type=MIME_TYPE_JSON, headers=ctx.response.headers, # type: ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response( obj.to_json(orient=self._orient), # type: ignore[arg-type] media_type=MIME_TYPE_JSON, )
from .base import IODescriptor from .file import File from .json import JSON from .text import Text from .image import Image from .numpy import NumpyNdarray from .pandas import PandasSeries from .pandas import PandasDataFrame from .multipart import Multipart __all__ = [ "File", "Image", "IODescriptor", "JSON", "Multipart", "NumpyNdarray", "PandasDataFrame", "PandasSeries", "Text", ]
from __future__ import annotations import json import typing as t import logging from typing import TYPE_CHECKING from starlette.requests import Request from starlette.responses import Response from .base import IODescriptor from .json import MIME_TYPE_JSON from ..types import LazyType from ..utils.http import set_cookies from ...exceptions import BadInput from ...exceptions import InternalServerError if TYPE_CHECKING: import numpy as np from .. import external_typing as ext from ..context import InferenceApiContext as Context logger = logging.getLogger(__name__) def _is_matched_shape( left: t.Optional[t.Tuple[int, ...]], right: t.Optional[t.Tuple[int, ...]], ) -> bool: # pragma: no cover if (left is None) or (right is None): return False if len(left) != len(right): return False for i, j in zip(left, right): if i == -1 or j == -1: continue if i == j: continue return False return True class NumpyNdarray(IODescriptor["ext.NpNDArray"]): """ :code:`NumpyNdarray` defines API specification for the inputs/outputs of a Service, where either inputs will be converted to or outputs will be converted from type :code:`numpy.ndarray` as specified in your API function signature. Sample implementation of a sklearn service: .. code-block:: python # sklearn_svc.py import bentoml from bentoml.io import NumpyNdarray import bentoml.sklearn runner = bentoml.sklearn.load_runner("sklearn_model_clf") svc = bentoml.Service("iris-classifier", runners=[runner]) @svc.api(input=NumpyNdarray(), output=NumpyNdarray()) def predict(input_arr): res = runner.run(input_arr) return res Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./sklearn_svc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "iris-classifier" defined in "sklearn_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-block:: bash % curl -X POST -H "Content-Type: application/json" --data '[[5,4,3,2]]' http://0.0.0.0:3000/predict [1]% Args: dtype (:code:`numpy.typings.DTypeLike`, `optional`, default to :code:`None`): Data Type users wish to convert their inputs/outputs to. Refers to `arrays dtypes <https://numpy.org/doc/stable/reference/arrays.dtypes.html>`_ for more information. enforce_dtype (:code:`bool`, `optional`, default to :code:`False`): Whether to enforce a certain data type. if :code:`enforce_dtype=True` then :code:`dtype` must be specified. shape (:code:`Tuple[int, ...]`, `optional`, default to :code:`None`): Given shape that an array will be converted to. For example: .. code-block:: python from bentoml.io import NumpyNdarray @svc.api(input=NumpyNdarray(shape=(3,1), enforce_shape=True), output=NumpyNdarray()) def predict(input_array: np.ndarray) -> np.ndarray: # input_array will have shape (3,1) result = await runner.run(input_array) enforce_shape (:code:`bool`, `optional`, default to :code:`False`): Whether to enforce a certain shape. If `enforce_shape=True` then `shape` must be specified Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that :code:`np.ndarray`. """ def __init__( self, dtype: t.Optional[t.Union[str, "np.dtype[t.Any]"]] = None, enforce_dtype: bool = False, shape: t.Optional[t.Tuple[int, ...]] = None, enforce_shape: bool = False, ): import numpy as np if isinstance(dtype, str): dtype = np.dtype(dtype) self._dtype = dtype self._shape = shape self._enforce_dtype = enforce_dtype self._enforce_shape = enforce_shape def _infer_types(self) -> str: # pragma: no cover if self._dtype is not None: name = self._dtype.name if name.startswith("int") or name.startswith("uint"): var_type = "integer" elif name.startswith("float") or name.startswith("complex"): var_type = "number" else: var_type = "object" else: var_type = "object" return var_type def _items_schema(self) -> t.Dict[str, t.Any]: if self._shape is not None: if len(self._shape) > 1: return {"type": "array", "items": {"type": self._infer_types()}} return {"type": self._infer_types()} return {} def input_type(self) -> LazyType["ext.NpNDArray"]: return LazyType("numpy", "ndarray") def openapi_schema_type(self) -> t.Dict[str, t.Any]: return {"type": "array", "items": self._items_schema()} def openapi_request_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {MIME_TYPE_JSON: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {MIME_TYPE_JSON: {"schema": self.openapi_schema_type()}} def _verify_ndarray( self, obj: "ext.NpNDArray", exception_cls: t.Type[Exception] = BadInput, ) -> "ext.NpNDArray": if self._dtype is not None and self._dtype != obj.dtype: if self._enforce_dtype: raise exception_cls( f"{self.__class__.__name__}: enforced dtype mismatch" ) try: obj = obj.astype(self._dtype) # type: ignore except ValueError as e: logger.warning(f"{self.__class__.__name__}: {e}") if self._shape is not None and not _is_matched_shape(self._shape, obj.shape): if self._enforce_shape: raise exception_cls( f"{self.__class__.__name__}: enforced shape mismatch" ) try: obj = obj.reshape(self._shape) except ValueError as e: logger.warning(f"{self.__class__.__name__}: {e}") return obj async def from_http_request(self, request: Request) -> "ext.NpNDArray": """ Process incoming requests and convert incoming objects to `numpy.ndarray` Args: request (`starlette.requests.Requests`): Incoming Requests Returns: a `numpy.ndarray` object. This can then be used inside users defined logics. """ import numpy as np obj = await request.json() res: "ext.NpNDArray" try: res = np.array(obj, dtype=self._dtype) # type: ignore[arg-type] except ValueError: res = np.array(obj) # type: ignore[arg-type] res = self._verify_ndarray(res, BadInput) return res async def to_http_response(self, obj: ext.NpNDArray, ctx: Context | None = None): """ Process given objects and convert it to HTTP response. Args: obj (`np.ndarray`): `np.ndarray` that will be serialized to JSON Returns: HTTP Response of type `starlette.responses.Response`. This can be accessed via cURL or any external web traffic. """ obj = self._verify_ndarray(obj, InternalServerError) if ctx is not None: res = Response( json.dumps(obj.tolist()), media_type=MIME_TYPE_JSON, headers=ctx.response.metadata, # type: ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response(json.dumps(obj.tolist()), media_type=MIME_TYPE_JSON) @classmethod def from_sample( cls, sample_input: "ext.NpNDArray", enforce_dtype: bool = True, enforce_shape: bool = True, ) -> "NumpyNdarray": """ Create a NumpyNdarray IO Descriptor from given inputs. Args: sample_input (:code:`np.ndarray`): Given sample np.ndarray data enforce_dtype (;code:`bool`, `optional`, default to :code:`True`): Enforce a certain data type. :code:`dtype` must be specified at function signature. If you don't want to enforce a specific dtype then change :code:`enforce_dtype=False`. enforce_shape (:code:`bool`, `optional`, default to :code:`False`): Enforce a certain shape. :code:`shape` must be specified at function signature. If you don't want to enforce a specific shape then change :code:`enforce_shape=False`. Returns: :obj:`~bentoml._internal.io_descriptors.NumpyNdarray`: :code:`NumpyNdarray` IODescriptor from given users inputs. Example: .. code-block:: python import numpy as np from bentoml.io import NumpyNdarray arr = [[1,2,3]] inp = NumpyNdarray.from_sample(arr) ... @svc.api(input=inp, output=NumpyNdarray()) def predict() -> np.ndarray:... """ return cls( dtype=sample_input.dtype, shape=sample_input.shape, enforce_dtype=enforce_dtype, enforce_shape=enforce_shape, )
from __future__ import annotations import io import typing as t import logging from typing import TYPE_CHECKING from starlette.requests import Request from multipart.multipart import parse_options_header from starlette.responses import Response from starlette.datastructures import UploadFile from .base import IODescriptor from ..types import FileLike from ..utils.http import set_cookies from ...exceptions import BentoMLException logger = logging.getLogger(__name__) if TYPE_CHECKING: from ..context import InferenceApiContext as Context FileKind: t.TypeAlias = t.Literal["binaryio", "textio"] FileType: t.TypeAlias = t.Union[io.IOBase, t.IO[bytes], FileLike[bytes]] class File(IODescriptor[FileType]): """ :code:`File` defines API specification for the inputs/outputs of a Service, where either inputs will be converted to or outputs will be converted from file-like objects as specified in your API function signature. Sample implementation of a ViT service: .. code-block:: python # vit_svc.py import bentoml from bentoml.io import File svc = bentoml.Service("vit-object-detection") @svc.api(input=File(), output=File()) def predict(input_pdf): return input_pdf Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./vit_svc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "vit-object-detection" defined in "vit_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-tab:: python import requests requests.post( "http://0.0.0.0:3000/predict", files = {"upload_file": open('test.pdf', 'rb')}, headers = {"content-type": "multipart/form-data"} ).text .. code-tab:: bash % curl -H "Content-Type: multipart/form-data" -F '[email protected];type=application/pdf' http://0.0.0.0:3000/predict Args: mime_type (:code:`str`, `optional`, default to :code:`None`): Return MIME type of the :code:`starlette.response.Response`, only available when used as output descriptor Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that file-like objects. """ _mime_type: str def __new__( # pylint: disable=arguments-differ # returning subclass from new cls, kind: FileKind = "binaryio", mime_type: str | None = None ) -> File: mime_type = mime_type if mime_type is not None else "application/octet-stream" if kind == "binaryio": res = object.__new__(BytesIOFile) else: raise ValueError(f"invalid File kind '{kind}'") res._mime_type = mime_type return res def input_type(self) -> t.Type[t.Any]: return FileLike[bytes] def openapi_schema_type(self) -> dict[str, str]: return {"type": "string", "format": "binary"} def openapi_request_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {self._mime_type: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {self._mime_type: {"schema": self.openapi_schema_type()}} async def to_http_response( self, obj: FileType, ctx: Context | None = None, ): if isinstance(obj, bytes): body = obj else: body = obj.read() if ctx is not None: res = Response( body, headers=ctx.response.metadata, # type: ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) else: res = Response(body) return res class BytesIOFile(File): async def from_http_request(self, request: Request) -> t.IO[bytes]: content_type, _ = parse_options_header(request.headers["content-type"]) if content_type.decode("utf-8") == "multipart/form-data": form = await request.form() found_mimes: t.List[str] = [] val: t.Union[str, UploadFile] for val in form.values(): # type: ignore if isinstance(val, UploadFile): found_mimes.append(val.content_type) # type: ignore (bad starlette types) if val.content_type == self._mime_type: # type: ignore (bad starlette types) res = FileLike[bytes](val.file, val.filename) # type: ignore (bad starlette types) break else: if len(found_mimes) == 0: raise BentoMLException("no File found in multipart form") else: raise BentoMLException( f"multipart File should have Content-Type '{self._mime_type}', got files with content types {', '.join(found_mimes)}" ) return res # type: ignore if content_type.decode("utf-8") == self._mime_type: body = await request.body() return t.cast(t.IO[bytes], FileLike(io.BytesIO(body), "<request body>")) raise BentoMLException( f"File should have Content-Type '{self._mime_type}' or 'multipart/form-data', got {content_type} instead" )
from __future__ import annotations import typing as t from typing import TYPE_CHECKING from starlette.requests import Request from starlette.responses import Response from .base import IODescriptor from ..utils.http import set_cookies if TYPE_CHECKING: from ..context import InferenceApiContext as Context MIME_TYPE = "text/plain" class Text(IODescriptor[str]): """ :code:`Text` defines API specification for the inputs/outputs of a Service. :code:`Text` represents strings for all incoming requests/outcoming responses as specified in your API function signature. Sample implementation of a GPT2 service: .. code-block:: python # gpt2_svc.py import bentoml from bentoml.io import Text import bentoml.transformers # If you don't have a gpt2 model previously saved under BentoML modelstore # tag = bentoml.transformers.import_from_huggingface_hub('gpt2') runner = bentoml.transformers.load_runner('gpt2',tasks='text-generation') svc = bentoml.Service("gpt2-generation", runners=[runner]) @svc.api(input=Text(), output=Text()) def predict(input_arr): res = runner.run_batch(input_arr) return res[0]['generated_text'] Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./gpt2_svc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "gpt2-generation" defined in "gpt2_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-block:: python import requests requests.post( "http://0.0.0.0:3000/predict", headers = {"content-type":"text/plain"}, data = 'Not for nothing did Orin say that people outdoors down here just scuttle in vectors from air conditioning to air conditioning.' ).text .. code-block:: bash % curl -X POST -H "Content-Type: text/plain" --data 'Not for nothing did Orin say that people outdoors down here just scuttle in vectors from air conditioning to air conditioning.' http://0.0.0.0:3000/predict .. note:: `Text` is not designed to take any `args` or `kwargs` during initialization Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that strings type. """ def input_type(self) -> t.Type[str]: return str def openapi_schema_type(self) -> t.Dict[str, t.Any]: return {"type": "string"} def openapi_request_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {MIME_TYPE: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {MIME_TYPE: {"schema": self.openapi_schema_type()}} async def from_http_request(self, request: Request) -> str: obj = await request.body() return str(obj.decode("utf-8")) async def to_http_response(self, obj: str, ctx: Context | None = None) -> Response: if ctx is not None: res = Response( obj, media_type=MIME_TYPE, headers=ctx.response.metadata, # type: ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response(obj, media_type=MIME_TYPE)
from __future__ import annotations import json import typing as t import dataclasses from typing import TYPE_CHECKING from starlette.requests import Request from starlette.responses import Response from .base import IODescriptor from ..types import LazyType from ..utils.http import set_cookies from ...exceptions import BadInput from ...exceptions import MissingDependencyException if TYPE_CHECKING: from types import UnionType import pydantic from .. import external_typing as ext from ..context import InferenceApiContext as Context _SerializableObj: t.TypeAlias = t.Union[ "ext.NpNDArray", "ext.PdDataFrame", t.Type["pydantic.BaseModel"], t.Any, ] JSONType = t.Union[str, t.Dict[str, t.Any], "pydantic.BaseModel"] MIME_TYPE_JSON = "application/json" class DefaultJsonEncoder(json.JSONEncoder): # pragma: no cover def default(self, o: _SerializableObj) -> t.Any: if dataclasses.is_dataclass(o): return dataclasses.asdict(o) if LazyType["ext.NpNDArray"]("numpy.ndarray").isinstance(o): return o.tolist() if LazyType["ext.NpGeneric"]("numpy.generic").isinstance(o): return o.item() if LazyType["ext.PdDataFrame"]("pandas.DataFrame").isinstance(o): return o.to_dict() # type: ignore if LazyType["ext.PdSeries"]("pandas.Series").isinstance(o): return o.to_dict() # type: ignore if LazyType["pydantic.BaseModel"]("pydantic.BaseModel").isinstance(o): obj_dict = o.dict() if "__root__" in obj_dict: obj_dict = obj_dict.get("__root__") return obj_dict return super().default(o) class JSON(IODescriptor[JSONType]): """ :code:`JSON` defines API specification for the inputs/outputs of a Service, where either inputs will be converted to or outputs will be converted from a JSON representation as specified in your API function signature. Sample implementation of a sklearn service: .. code-block:: python # sklearn_svc.py import pandas as pd import numpy as np from bentoml.io import PandasDataFrame, JSON import bentoml.sklearn input_spec = PandasDataFrame.from_sample(pd.DataFrame(np.array([[5,4,3,2]]))) runner = bentoml.sklearn.load_runner("sklearn_model_clf") svc = bentoml.Service("iris-classifier", runners=[runner]) @svc.api(input=input_spec, output=JSON()) def predict(input_arr: pd.DataFrame): res = runner.run_batch(input_arr) # type: np.ndarray return {"res":pd.DataFrame(res).to_json(orient='record')} Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./sklearn_svc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "iris-classifier" defined in "sklearn_svc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-tab:: python import requests requests.post( "http://0.0.0.0:3000/predict", headers={"content-type": "application/json"}, data='[{"0":5,"1":4,"2":3,"3":2}]' ).text .. code-tab:: bash % curl -X POST -H "Content-Type: application/json" --data '[{"0":5,"1":4,"2":3,"3":2}]' http://0.0.0.0:3000/predict {"res":"[{\"0\":1}]"}% Args: pydantic_model (:code:`pydantic.BaseModel`, `optional`, default to :code:`None`): Pydantic model schema. validate_json (:code:`bool`, `optional`, default to :code:`True`): If True, then use Pydantic model specified above to validate given JSON. json_encoder (:code:`Type[json.JSONEncoder]`, default to :code:`~bentoml._internal.io_descriptor.json.DefaultJsonEncoder`): JSON encoder class. Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that in JSON format. """ def __init__( self, pydantic_model: t.Type[pydantic.BaseModel] | None = None, validate_json: bool = True, json_encoder: t.Type[json.JSONEncoder] = DefaultJsonEncoder, ): if pydantic_model is not None: try: import pydantic except ImportError: raise MissingDependencyException( "`pydantic` must be installed to use `pydantic_model`" ) assert issubclass( pydantic_model, pydantic.BaseModel ), "`pydantic_model` must be a subclass of `pydantic.BaseModel`" self._pydantic_model = pydantic_model self._validate_json = validate_json self._json_encoder = json_encoder def input_type(self) -> "UnionType": return JSONType def openapi_schema_type(self) -> t.Dict[str, t.Any]: if self._pydantic_model is None: return {"type": "object"} return self._pydantic_model.schema() def openapi_request_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {MIME_TYPE_JSON: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> t.Dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {MIME_TYPE_JSON: {"schema": self.openapi_schema_type()}} async def from_http_request(self, request: Request) -> JSONType: json_str = await request.body() if self._pydantic_model is not None and self._validate_json: try: import pydantic except ImportError: raise MissingDependencyException( "`pydantic` must be installed to use `pydantic_model`" ) from None try: pydantic_model = self._pydantic_model.parse_raw(json_str) return pydantic_model except pydantic.ValidationError as e: raise BadInput(f"Json validation error: {e}") from None else: try: return json.loads(json_str) except json.JSONDecodeError as e: raise BadInput(f"Json validation error: {e}") from None async def to_http_response(self, obj: JSONType, ctx: Context | None = None): json_str = json.dumps( obj, cls=self._json_encoder, ensure_ascii=False, allow_nan=False, indent=None, separators=(",", ":"), ) if ctx is not None: res = Response( json_str, media_type=MIME_TYPE_JSON, headers=ctx.response.metadata, # type: ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response(json_str, media_type=MIME_TYPE_JSON)
from __future__ import annotations import io import typing as t from typing import TYPE_CHECKING from urllib.parse import quote from starlette.requests import Request from multipart.multipart import parse_options_header from starlette.responses import Response from .base import IODescriptor from ..types import LazyType from ..utils import LazyLoader from ..utils.http import set_cookies from ...exceptions import BadInput from ...exceptions import InvalidArgument from ...exceptions import InternalServerError if TYPE_CHECKING: from types import UnionType import PIL.Image from .. import external_typing as ext from ..context import InferenceApiContext as Context _Mode = t.Literal[ "1", "CMYK", "F", "HSV", "I", "L", "LAB", "P", "RGB", "RGBA", "RGBX", "YCbCr" ] else: # NOTE: pillow-simd only benefits users who want to do preprocessing # TODO: add options for users to choose between simd and native mode _exc = f"""\ `Pillow` is required to use {__name__} Instructions: `pip install -U Pillow` """ PIL = LazyLoader("PIL", globals(), "PIL", exc_msg=_exc) PIL.Image = LazyLoader("PIL.Image", globals(), "PIL.Image", exc_msg=_exc) # NOTES: we will keep type in quotation to avoid backward compatibility # with numpy < 1.20, since we will use the latest stubs from the main branch of numpy. # that enable a new way to type hint an ndarray. ImageType: t.TypeAlias = t.Union["PIL.Image.Image", "ext.NpNDArray"] DEFAULT_PIL_MODE = "RGB" class Image(IODescriptor[ImageType]): """ :code:`Image` defines API specification for the inputs/outputs of a Service, where either inputs will be converted to or outputs will be converted from images as specified in your API function signature. Sample implementation of a transformers service for object detection: .. code-block:: python #obj_detc.py import bentoml from bentoml.io import Image, JSON import bentoml.transformers tag='google_vit_large_patch16_224:latest' runner = bentoml.transformers.load_runner(tag, tasks='image-classification', device=-1, feature_extractor="google/vit-large-patch16-224") svc = bentoml.Service("vit-object-detection", runners=[runner]) @svc.api(input=Image(), output=JSON()) def predict(input_img): res = runner.run_batch(input_img) return res Users then can then serve this service with :code:`bentoml serve`: .. code-block:: bash % bentoml serve ./obj_detc.py:svc --auto-reload (Press CTRL+C to quit) [INFO] Starting BentoML API server in development mode with auto-reload enabled [INFO] Serving BentoML Service "vit-object-detection" defined in "obj_detc.py" [INFO] API Server running on http://0.0.0.0:3000 Users can then send requests to the newly started services with any client: .. tabs:: .. code-tab:: python import requests requests.post( "http://0.0.0.0:3000/predict", files = {"upload_file": open('test.jpg', 'rb')}, headers = {"content-type": "multipart/form-data"} ).text .. code-tab:: bash # we will run on our input image test.png # image can get from http://images.cocodataset.org/val2017/000000039769.jpg % curl -H "Content-Type: multipart/form-data" -F '[email protected];type=image/jpeg' http://0.0.0.0:3000/predict [{"score":0.8610631227493286,"label":"Egyptian cat"}, {"score":0.08770329505205154,"label":"tabby, tabby cat"}, {"score":0.03540956228971481,"label":"tiger cat"}, {"score":0.004140055272728205,"label":"lynx, catamount"}, {"score":0.0009498853469267488,"label":"Siamese cat, Siamese"}]% Args: pilmode (:code:`str`, `optional`, default to :code:`RGB`): Color mode for PIL. mime_type (:code:`str`, `optional`, default to :code:`image/jpeg`): Return MIME type of the :code:`starlette.response.Response`, only available when used as output descriptor. Returns: :obj:`~bentoml._internal.io_descriptors.IODescriptor`: IO Descriptor that either a :code:`PIL.Image.Image` or a :code:`np.ndarray` representing an image. """ # noqa MIME_EXT_MAPPING: t.Dict[str, str] = {} def __init__( self, pilmode: _Mode | None = DEFAULT_PIL_MODE, mime_type: str = "image/jpeg", ): try: import PIL.Image except ImportError: raise InternalServerError( "`Pillow` is required to use {__name__}\n Instructions: `pip install -U Pillow`" ) PIL.Image.init() self.MIME_EXT_MAPPING.update({v: k for k, v in PIL.Image.MIME.items()}) if mime_type.lower() not in self.MIME_EXT_MAPPING: # pragma: no cover raise InvalidArgument( f"Invalid Image mime_type '{mime_type}', " f"Supported mime types are {', '.join(PIL.Image.MIME.values())} " ) if pilmode is not None and pilmode not in PIL.Image.MODES: # pragma: no cover raise InvalidArgument( f"Invalid Image pilmode '{pilmode}', " f"Supported PIL modes are {', '.join(PIL.Image.MODES)} " ) self._mime_type = mime_type.lower() self._pilmode: _Mode | None = pilmode self._format = self.MIME_EXT_MAPPING[mime_type] def input_type(self) -> UnionType: return ImageType def openapi_schema_type(self) -> dict[str, str]: return {"type": "string", "format": "binary"} def openapi_request_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for incoming requests""" return {self._mime_type: {"schema": self.openapi_schema_type()}} def openapi_responses_schema(self) -> dict[str, t.Any]: """Returns OpenAPI schema for outcoming responses""" return {self._mime_type: {"schema": self.openapi_schema_type()}} async def from_http_request(self, request: Request) -> ImageType: content_type, _ = parse_options_header(request.headers["content-type"]) mime_type = content_type.decode().lower() if mime_type == "multipart/form-data": form = await request.form() bytes_ = await next(iter(form.values())).read() elif mime_type.startswith("image/") or mime_type == self._mime_type: bytes_ = await request.body() else: raise BadInput( f"{self.__class__.__name__} should get `multipart/form-data`, " f"`{self._mime_type}` or `image/*`, got {content_type} instead" ) return PIL.Image.open(io.BytesIO(bytes_)) async def init_http_response(self) -> Response: return Response(None, media_type=self._mime_type) async def to_http_response( self, obj: ImageType, ctx: Context | None = None ) -> Response: if LazyType["ext.NpNDArray"]("numpy.ndarray").isinstance(obj): image = PIL.Image.fromarray(obj, mode=self._pilmode) elif LazyType[PIL.Image.Image]("PIL.Image.Image").isinstance(obj): image = obj else: raise InternalServerError( f"Unsupported Image type received: {type(obj)}, `{self.__class__.__name__}`" " only supports `np.ndarray` and `PIL.Image`" ) filename = f"output.{self._format.lower()}" ret = io.BytesIO() image.save(ret, format=self._format) # rfc2183 content_disposition_filename = quote(filename) if content_disposition_filename != filename: content_disposition = "attachment; filename*=utf-8''{}".format( content_disposition_filename ) else: content_disposition = f'attachment; filename="{filename}"' if ctx is not None: if "content-disposition" not in ctx.response.headers: ctx.response.headers["content-disposition"] = content_disposition res = Response( ret.getvalue(), media_type=self._mime_type, headers=ctx.response.headers, # type: ignore (bad starlette types) status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response( ret.getvalue(), media_type=self._mime_type, headers={"content-disposition": content_disposition}, )
from __future__ import annotations import typing as t from abc import ABC from abc import abstractmethod from typing import TYPE_CHECKING from starlette.requests import Request from starlette.responses import Response if TYPE_CHECKING: from types import UnionType from ..types import LazyType from ..context import InferenceApiContext as Context IOPyObj = t.TypeVar("IOPyObj") _T = t.TypeVar("_T") class IODescriptor(ABC, t.Generic[IOPyObj]): """ IODescriptor describes the input/output data format of an InferenceAPI defined in a :code:`bentoml.Service`. This is an abstract base class for extending new HTTP endpoint IO descriptor types in BentoServer. """ HTTP_METHODS = ["POST"] _init_str: str = "" def __new__(cls: t.Type[_T], *args: t.Any, **kwargs: t.Any) -> _T: self = super().__new__(cls) arg_strs = tuple(repr(i) for i in args) + tuple( f"{k}={repr(v)}" for k, v in kwargs.items() ) setattr(self, "_init_str", f"{cls.__name__}({', '.join(arg_strs)})") return self def __repr__(self) -> str: return self._init_str @abstractmethod def input_type( self, ) -> t.Union[ "UnionType", t.Type[t.Any], "LazyType[t.Any]", t.Dict[str, t.Union[t.Type[t.Any], "UnionType", "LazyType[t.Any]"]], ]: ... @abstractmethod def openapi_schema_type(self) -> t.Dict[str, str]: ... @abstractmethod def openapi_request_schema(self) -> t.Dict[str, t.Any]: ... @abstractmethod def openapi_responses_schema(self) -> t.Dict[str, t.Any]: ... @abstractmethod async def from_http_request(self, request: Request) -> IOPyObj: ... @abstractmethod async def to_http_response( self, obj: IOPyObj, ctx: Context | None = None ) -> Response: ... # TODO: gRPC support # @abstractmethod # def generate_protobuf(self): ... # @abstractmethod # async def from_grpc_request(self, request: GRPCRequest) -> IOType: ... # @abstractmethod # async def to_grpc_response(self, obj: IOType) -> GRPCResponse: ...
import abc import typing as t import logging from typing import TYPE_CHECKING from starlette.responses import PlainTextResponse from starlette.exceptions import HTTPException if TYPE_CHECKING: from starlette.routing import BaseRoute from starlette.requests import Request from starlette.responses import Response from starlette.middleware import Middleware from starlette.applications import Starlette logger = logging.getLogger(__name__) class BaseAppFactory(abc.ABC): _is_ready: bool = False @property @abc.abstractmethod def name(self) -> str: ... @property def on_startup(self) -> t.List[t.Callable[[], None]]: return [self.mark_as_ready] @property def on_shutdown(self) -> t.List[t.Callable[[], None]]: return [] def mark_as_ready(self) -> None: self._is_ready = True async def livez(self, _: "Request") -> "Response": """ Health check for BentoML API server. Make sure it works with Kubernetes liveness probe """ return PlainTextResponse("\n", status_code=200) async def readyz(self, _: "Request") -> "Response": if self._is_ready: return PlainTextResponse("\n", status_code=200) raise HTTPException(500) def __call__(self) -> "Starlette": from starlette.applications import Starlette from bentoml._internal.configuration import get_debug_mode return Starlette( debug=get_debug_mode(), routes=self.routes, middleware=self.middlewares, on_startup=self.on_startup, on_shutdown=self.on_shutdown, ) @property def routes(self) -> t.List["BaseRoute"]: from starlette.routing import Route routes: t.List["BaseRoute"] = [] routes.append(Route(path="/livez", name="livez", endpoint=self.livez)) routes.append(Route(path="/healthz", name="healthz", endpoint=self.livez)) routes.append(Route(path="/readyz", name="readyz", endpoint=self.readyz)) return routes @property def middlewares(self) -> t.List["Middleware"]: return []
from __future__ import annotations import json import typing as t import asyncio import logging import functools from typing import TYPE_CHECKING from functools import partial from ..trace import ServiceContext from ..runner.utils import PAYLOAD_META_HEADER from ..runner.utils import multipart_to_payload_params from ..runner.utils import payload_paramss_to_batch_params from ..server.base_app import BaseAppFactory from ..runner.container import AutoContainer from ..marshal.dispatcher import CorkDispatcher from ..configuration.containers import DeploymentContainer feedback_logger = logging.getLogger("bentoml.feedback") logger = logging.getLogger(__name__) if TYPE_CHECKING: from starlette.routing import BaseRoute from starlette.requests import Request from starlette.responses import Response from starlette.middleware import Middleware from opentelemetry.sdk.trace import Span from ..runner.runner import Runner from ..runner.runner import RunnerMethod class RunnerAppFactory(BaseAppFactory): def __init__( self, runner: Runner, worker_index: int = 0, ) -> None: self.runner = runner self.worker_index = worker_index from starlette.responses import Response TooManyRequests = partial(Response, status_code=429) self.dispatchers: dict[str, CorkDispatcher] = {} for method in runner.runner_methods: if not method.config.batchable: continue self.dispatchers[method.name] = CorkDispatcher( max_latency_in_ms=method.max_latency_ms, max_batch_size=method.max_batch_size, fallback=TooManyRequests, ) @property def name(self) -> str: return self.runner.name @property def on_startup(self) -> t.List[t.Callable[[], None]]: on_startup = super().on_startup on_startup.insert(0, functools.partial(self.runner.init_local, quiet=True)) on_startup.insert( 0, functools.partial( self.runner.setup_worker, worker_id=self.worker_index, ), ) return on_startup @property def on_shutdown(self) -> t.List[t.Callable[[], None]]: on_shutdown = [self.runner.destroy] for dispatcher in self.dispatchers.values(): on_shutdown.append(dispatcher.shutdown) on_shutdown.extend(super().on_shutdown) return on_shutdown @property def routes(self) -> t.List[BaseRoute]: """ Setup routes for Runner server, including: /healthz liveness probe endpoint /readyz Readiness probe endpoint /metrics Prometheus metrics endpoint /run /run_batch """ from starlette.routing import Route routes = super().routes for method in self.runner.runner_methods: path = "/" if method.name == "__call__" else "/" + method.name if method.config.batchable: _func = self.dispatchers[method.name]( self._async_cork_run(runner_method=method) ) routes.append( Route( path=path, endpoint=_func, methods=["POST"], ) ) else: routes.append( Route( path=path, endpoint=self.async_run(runner_method=method), methods=["POST"], ) ) return routes @property def middlewares(self) -> list[Middleware]: middlewares = super().middlewares # otel middleware import opentelemetry.instrumentation.asgi as otel_asgi # type: ignore[import] from starlette.middleware import Middleware def client_request_hook(span: Span, _scope: t.Dict[str, t.Any]) -> None: if span is not None: span_id: int = span.context.span_id ServiceContext.request_id_var.set(span_id) def client_response_hook(span: Span, _message: t.Any) -> None: if span is not None: ServiceContext.request_id_var.set(None) middlewares.append( Middleware( otel_asgi.OpenTelemetryMiddleware, excluded_urls=None, default_span_details=None, server_request_hook=None, client_request_hook=client_request_hook, client_response_hook=client_response_hook, tracer_provider=DeploymentContainer.tracer_provider.get(), ) ) access_log_config = DeploymentContainer.runners_config.logging.access if access_log_config.enabled.get(): from .access import AccessLogMiddleware access_logger = logging.getLogger("bentoml.access") if access_logger.getEffectiveLevel() <= logging.INFO: middlewares.append( Middleware( AccessLogMiddleware, has_request_content_length=access_log_config.request_content_length.get(), has_request_content_type=access_log_config.request_content_type.get(), has_response_content_length=access_log_config.response_content_length.get(), has_response_content_type=access_log_config.response_content_type.get(), ) ) return middlewares def _async_cork_run( self, runner_method: RunnerMethod[t.Any, t.Any, t.Any], ) -> t.Callable[[t.Iterable[Request]], t.Coroutine[None, None, list[Response]]]: from starlette.responses import Response async def _run(requests: t.Iterable[Request]) -> list[Response]: assert self._is_ready if not requests: return [] params_list = await asyncio.gather( *tuple(multipart_to_payload_params(r) for r in requests) ) input_batch_dim, output_batch_dim = runner_method.config.batch_dim batched_params, indices = payload_paramss_to_batch_params( params_list, input_batch_dim, ) batch_ret = await runner_method.async_run( *batched_params.args, **batched_params.kwargs, ) payloads = AutoContainer.batch_to_payloads( batch_ret, indices, batch_dim=output_batch_dim, ) return [ Response( payload.data, headers={ PAYLOAD_META_HEADER: json.dumps(payload.meta), "Content-Type": f"application/vnd.bentoml.{payload.container}", "Server": f"BentoML-Runner/{self.runner.name}/{runner_method.name}/{self.worker_index}", }, ) for payload in payloads ] return _run def async_run( self, runner_method: RunnerMethod[t.Any, t.Any, t.Any], ) -> t.Callable[[Request], t.Coroutine[None, None, Response]]: from starlette.responses import Response async def _run(request: Request) -> Response: assert self._is_ready params = await multipart_to_payload_params(request) params = params.map(AutoContainer.from_payload) ret = await runner_method.async_run(*params.args, **params.kwargs) payload = AutoContainer.to_payload(ret, 0) return Response( payload.data, headers={ PAYLOAD_META_HEADER: json.dumps(payload.meta), "Content-Type": f"application/vnd.bentoml.{payload.container}", "Server": f"BentoML-Runner/{self.runner.name}/{runner_method.name}/{self.worker_index}", }, ) return _run
from __future__ import annotations import os import sys import typing as t import asyncio import logging import functools from typing import TYPE_CHECKING from simple_di import inject from simple_di import Provide from ..context import trace_context from ..context import InferenceApiContext as Context from ...exceptions import BentoMLException from ..server.base_app import BaseAppFactory from ..service.service import Service from ..configuration.containers import DeploymentContainer from ..io_descriptors.multipart import Multipart if TYPE_CHECKING: from starlette.routing import BaseRoute from starlette.requests import Request from starlette.responses import Response from starlette.middleware import Middleware from starlette.applications import Starlette from opentelemetry.sdk.trace import Span from ..service.inference_api import InferenceAPI feedback_logger = logging.getLogger("bentoml.feedback") logger = logging.getLogger(__name__) DEFAULT_INDEX_HTML = """\ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Swagger UI</title> <link rel="stylesheet" type="text/css" href="./static_content/swagger-ui.css" /> <link rel="stylesheet" type="text/css" href="./static_content/index.css" /> <link rel="icon" type="image/png" href="./static_content/favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="./static_content/favicon-96x96.png" sizes="96x96" /> </head> <body> <div id="swagger-ui"></div> <script src="./static_content/swagger-ui-bundle.js" charset="UTF-8"> </script> <script src="./static_content/swagger-ui-standalone-preset.js" charset="UTF-8"> </script> <script src="./static_content/swagger-initializer.js" charset="UTF-8"> </script> </body> </html> """ def log_exception(request: Request, exc_info: t.Any) -> None: """ Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. """ logger.error( "Exception on %s [%s]", request.url.path, request.method, exc_info=exc_info ) class ServiceAppFactory(BaseAppFactory): """ ServiceApp creates a REST API server based on APIs defined with a BentoService via BentoService#apis. Each InferenceAPI will become one endpoint exposed on the REST server, and the RequestHandler defined on each InferenceAPI object will be used to handle Request object before feeding the request data into a Service API function """ @inject def __init__( self, bento_service: Service, enable_access_control: bool = Provide[ DeploymentContainer.api_server_config.cors.enabled ], access_control_options: dict[str, list[str] | int] = Provide[ DeploymentContainer.access_control_options ], enable_metrics: bool = Provide[ DeploymentContainer.api_server_config.metrics.enabled ], ) -> None: self.bento_service = bento_service self.enable_access_control = enable_access_control self.access_control_options = access_control_options self.enable_metrics = enable_metrics @property def name(self) -> str: return self.bento_service.name async def index_view_func(self, _: Request) -> Response: """ The default index view for BentoML API server. This includes the readme generated from docstring and swagger UI """ from starlette.responses import Response return Response( content=DEFAULT_INDEX_HTML.format(readme=self.bento_service.doc), status_code=200, media_type="text/html", ) async def docs_view_func(self, _: Request) -> Response: from starlette.responses import JSONResponse docs = self.bento_service.openapi_doc() return JSONResponse(docs) @property def routes(self) -> list[BaseRoute]: """ Setup routes for bento model server, including: / Index Page, shows readme docs, metadata, and Swagger UI /docs.json Returns Swagger/OpenAPI definition file in json format /healthz liveness probe endpoint /readyz Readiness probe endpoint /metrics Prometheus metrics endpoint And user defined InferenceAPI list into routes, e.g.: /classify /predict """ from starlette.routing import Mount from starlette.routing import Route from starlette.staticfiles import StaticFiles routes = super().routes routes.append(Route(path="/", name="home", endpoint=self.index_view_func)) routes.append( Route( path="/docs.json", name="docs", endpoint=self.docs_view_func, ) ) parent_dir_path = os.path.dirname(os.path.realpath(__file__)) routes.append( Mount( "/static_content", app=StaticFiles( directory=os.path.join(parent_dir_path, "static_content") ), name="static_content", ) ) for _, api in self.bento_service.apis.items(): api_route_endpoint = self._create_api_endpoint(api) routes.append( Route( path="/{}".format(api.route), name=api.name, endpoint=api_route_endpoint, methods=api.input.HTTP_METHODS, ) ) return routes @property def middlewares(self) -> list[Middleware]: middlewares = super().middlewares from starlette.middleware import Middleware for middleware_cls, options in self.bento_service.middlewares: middlewares.append(Middleware(middleware_cls, **options)) if self.enable_access_control: assert ( self.access_control_options.get("allow_origins") is not None ), "To enable cors, access_control_allow_origin must be set" from starlette.middleware.cors import CORSMiddleware middlewares.append( Middleware(CORSMiddleware, **self.access_control_options) ) # metrics middleware if self.enable_metrics: from .instruments import MetricsMiddleware middlewares.append( Middleware( MetricsMiddleware, bento_service=self.bento_service, ) ) # otel middleware import opentelemetry.instrumentation.asgi as otel_asgi # type: ignore def client_request_hook(span: Span, _scope: dict[str, t.Any]) -> None: if span is not None: trace_context.request_id = span.context.span_id def client_response_hook(span: Span, _message: t.Any) -> None: if span is not None: del trace_context.request_id middlewares.append( Middleware( otel_asgi.OpenTelemetryMiddleware, excluded_urls=None, default_span_details=None, server_request_hook=None, client_request_hook=client_request_hook, client_response_hook=client_response_hook, tracer_provider=DeploymentContainer.tracer_provider.get(), ) ) access_log_config = DeploymentContainer.api_server_config.logging.access if access_log_config.enabled.get(): from .access import AccessLogMiddleware access_logger = logging.getLogger("bentoml.access") if access_logger.getEffectiveLevel() <= logging.INFO: middlewares.append( Middleware( AccessLogMiddleware, has_request_content_length=access_log_config.request_content_length.get(), has_request_content_type=access_log_config.request_content_type.get(), has_response_content_length=access_log_config.response_content_length.get(), has_response_content_type=access_log_config.response_content_type.get(), ) ) return middlewares @property def on_startup(self) -> list[t.Callable[[], None]]: on_startup = [self.bento_service.on_asgi_app_startup] if DeploymentContainer.development_mode.get(): for runner in self.bento_service.runners: on_startup.append(functools.partial(runner.init_local, quiet=True)) else: for runner in self.bento_service.runners: on_startup.append(runner.init_client) on_startup.extend(super().on_startup) return on_startup @property def on_shutdown(self) -> list[t.Callable[[], None]]: on_shutdown = [self.bento_service.on_asgi_app_shutdown] for runner in self.bento_service.runners: on_shutdown.append(runner.destroy) on_shutdown.extend(super().on_shutdown) return on_shutdown def __call__(self) -> Starlette: app = super().__call__() for mount_app, path, name in self.bento_service.mount_apps: app.mount(app=mount_app, path=path, name=name) return app @staticmethod def _create_api_endpoint( api: InferenceAPI, ) -> t.Callable[[Request], t.Coroutine[t.Any, t.Any, Response]]: """ Create api function for flask route, it wraps around user defined API callback and adapter class, and adds request logging and instrument metrics """ from starlette.responses import JSONResponse from starlette.concurrency import run_in_threadpool # type: ignore async def api_func(request: Request) -> Response: # handle_request may raise 4xx or 5xx exception. try: input_data = await api.input.from_http_request(request) ctx = None if asyncio.iscoroutinefunction(api.func): if isinstance(api.input, Multipart): if api.needs_ctx: ctx = Context.from_http(request) input_data[api.ctx_param] = ctx output = await api.func(**input_data) else: if api.needs_ctx: ctx = Context.from_http(request) output = await api.func(input_data, ctx) else: output = await api.func(input_data) else: if isinstance(api.input, Multipart): if api.needs_ctx: ctx = Context.from_http(request) input_data[api.ctx_param] = ctx output: t.Any = await run_in_threadpool(api.func, **input_data) else: if api.needs_ctx: ctx = Context.from_http(request) output = await run_in_threadpool(api.func, input_data, ctx) else: output = await run_in_threadpool(api.func, input_data) response = await api.output.to_http_response(output, ctx) except BentoMLException as e: log_exception(request, sys.exc_info()) status = e.error_code.value if 400 <= status < 500 and status not in (401, 403): response = JSONResponse( content="BentoService error handling API request: %s" % str(e), status_code=status, ) else: response = JSONResponse("", status_code=status) except Exception: # pylint: disable=broad-except # For all unexpected error, return 500 by default. For example, # if users' model raises an error of division by zero. log_exception(request, sys.exc_info()) response = JSONResponse( "An error has occurred in BentoML user code when handling this request, find the error details in server logs", status_code=500, ) return response return api_func
import logging from timeit import default_timer from typing import TYPE_CHECKING from contextvars import ContextVar if TYPE_CHECKING: from .. import external_typing as ext REQ_CONTENT_LENGTH = "REQUEST_CONTENT_LENGTH" REQ_CONTENT_TYPE = "REQUEST_CONTENT_TYPE" RESP_CONTENT_LENGTH = "RESPONSE_CONTENT_LENGTH" RESP_CONTENT_TYPE = "RESPONSE_CONTENT_TYPE" CONTENT_LENGTH = b"content-length" CONTENT_TYPE = b"content-type" status: ContextVar[int] = ContextVar("ACCESS_LOG_STATUS_CODE") request_content_length: ContextVar[bytes] = ContextVar( "ACCESS_LOG_REQ_CONTENT_LENGTH", default=b"", ) request_content_type: ContextVar[bytes] = ContextVar( "ACCESS_LOG_REQ_CONTENT_TYPE", default=b"", ) response_content_length: ContextVar[bytes] = ContextVar( "ACCESS_LOG_RESP_CONTENT_LENGTH", default=b"", ) response_content_type: ContextVar[bytes] = ContextVar( "ACCESS_LOG_RESP_CONTENT_TYPE", default=b"", ) class AccessLogMiddleware: """ ASGI Middleware implementation that intercepts and decorates the send and receive callables to generate the BentoML access log. """ def __init__( self, app: "ext.ASGIApp", has_request_content_length: bool = False, has_request_content_type: bool = False, has_response_content_length: bool = False, has_response_content_type: bool = False, ) -> None: self.app = app self.has_request_content_length = has_request_content_length self.has_request_content_type = has_request_content_type self.has_response_content_length = has_response_content_length self.has_response_content_type = has_response_content_type self.logger = logging.getLogger("bentoml.access") async def __call__( self, scope: "ext.ASGIScope", receive: "ext.ASGIReceive", send: "ext.ASGISend", ) -> None: if not scope["type"].startswith("http"): await self.app(scope, receive, send) return start = default_timer() client = scope["client"] scheme = scope["scheme"] method = scope["method"] path = scope["path"] if self.has_request_content_length or self.has_request_content_type: for key, value in scope["headers"]: if key == CONTENT_LENGTH: request_content_length.set(value) elif key == CONTENT_TYPE: request_content_type.set(value) async def wrapped_send(message: "ext.ASGIMessage") -> None: if message["type"] == "http.response.start": status.set(message["status"]) if self.has_response_content_length or self.has_response_content_type: for key, value in message["headers"]: if key == CONTENT_LENGTH: response_content_length.set(value) elif key == CONTENT_TYPE: response_content_type.set(value) elif message["type"] == "http.response.body": if "more_body" in message and message["more_body"]: await send(message) return if client: address = f"{client[0]}:{client[1]}" else: address = "_" request = [f"scheme={scheme}", f"method={method}", f"path={path}"] if self.has_request_content_type: request.append(f"type={request_content_type.get().decode()}") if self.has_request_content_length: request.append(f"length={request_content_length.get().decode()}") response = [f"status={status.get()}"] if self.has_response_content_type: response.append(f"type={response_content_type.get().decode()}") if self.has_response_content_length: response.append(f"length={response_content_length.get().decode()}") latency = max(default_timer() - start, 0) self.logger.info( "%s (%s) (%s) %.3fms", address, ",".join(request), ",".join(response), latency, ) await send(message) await self.app(scope, receive, wrapped_send)
import os import sys import json import math import shutil import typing as t import logging import tempfile import contextlib import psutil from simple_di import inject from simple_di import Provide from bentoml import load from ..utils import reserve_free_port from ..utils.uri import path_to_uri from ..utils.circus import create_standalone_arbiter from ..runner.resource import query_cpu_count from ..utils.analytics import track_serve from ..configuration.containers import DeploymentContainer logger = logging.getLogger(__name__) SCRIPT_RUNNER = "bentoml._internal.server.cli.runner" SCRIPT_API_SERVER = "bentoml._internal.server.cli.api_server" SCRIPT_DEV_API_SERVER = "bentoml._internal.server.cli.dev_api_server" SCRIPT_NGROK = "bentoml._internal.server.cli.ngrok" @inject def ensure_prometheus_dir( prometheus_multiproc_dir: str = Provide[ DeploymentContainer.prometheus_multiproc_dir ], clean: bool = True, ): if os.path.exists(prometheus_multiproc_dir): if not os.path.isdir(prometheus_multiproc_dir): shutil.rmtree(prometheus_multiproc_dir) elif clean or os.listdir(prometheus_multiproc_dir): shutil.rmtree(prometheus_multiproc_dir) os.makedirs(prometheus_multiproc_dir, exist_ok=True) @inject def serve_development( bento_identifier: str, working_dir: str, port: int = Provide[DeploymentContainer.api_server_config.port], host: str = Provide[DeploymentContainer.api_server_config.host], backlog: int = Provide[DeploymentContainer.api_server_config.backlog], with_ngrok: bool = False, reload: bool = False, reload_delay: float = 0.25, ) -> None: working_dir = os.path.realpath(os.path.expanduser(working_dir)) svc = load(bento_identifier, working_dir=working_dir) # verify service loading from circus.sockets import CircusSocket # type: ignore from circus.watcher import Watcher # type: ignore watchers: t.List[Watcher] = [] if with_ngrok: watchers.append( Watcher( name="ngrok", cmd=sys.executable, args=[ "-m", SCRIPT_NGROK, ], copy_env=True, stop_children=True, working_dir=working_dir, ) ) circus_sockets: t.List[CircusSocket] = [] circus_sockets.append( CircusSocket( name="_bento_api_server", host=host, port=port, backlog=backlog, ) ) watchers.append( Watcher( name="dev_api_server", cmd=sys.executable, args=[ "-m", SCRIPT_DEV_API_SERVER, bento_identifier, "--bind", "fd://$(circus.sockets._bento_api_server)", "--working-dir", working_dir, ], copy_env=True, stop_children=True, use_sockets=True, working_dir=working_dir, ) ) if reload: plugins = [ dict( use="bentoml._internal.utils.circus.BentoChangeReloader", bento_identifier=bento_identifier, working_dir=working_dir, reload_delay=reload_delay, ), ] else: plugins = [] arbiter = create_standalone_arbiter( watchers, sockets=circus_sockets, plugins=plugins, debug=True, ) ensure_prometheus_dir() with track_serve(svc, production=False): arbiter.start( cb=lambda _: logger.info( # type: ignore f'Starting development BentoServer from "{bento_identifier}" ' f"running on http://{host}:{port} (Press CTRL+C to quit)" ), ) MAX_AF_UNIX_PATH_LENGTH = 103 @inject def serve_production( bento_identifier: str, working_dir: str, port: int = Provide[DeploymentContainer.api_server_config.port], host: str = Provide[DeploymentContainer.api_server_config.host], backlog: int = Provide[DeploymentContainer.api_server_config.backlog], api_workers: t.Optional[int] = None, ) -> None: working_dir = os.path.realpath(os.path.expanduser(working_dir)) svc = load(bento_identifier, working_dir=working_dir, change_global_cwd=True) from circus.sockets import CircusSocket # type: ignore from circus.watcher import Watcher # type: ignore watchers: t.List[Watcher] = [] circus_socket_map: t.Dict[str, CircusSocket] = {} runner_bind_map: t.Dict[str, str] = {} uds_path = None if psutil.POSIX: # use AF_UNIX sockets for Circus uds_path = tempfile.mkdtemp() for runner in svc.runners: sockets_path = os.path.join(uds_path, f"{id(runner)}.sock") assert len(sockets_path) < MAX_AF_UNIX_PATH_LENGTH runner_bind_map[runner.name] = path_to_uri(sockets_path) circus_socket_map[runner.name] = CircusSocket( name=runner.name, path=sockets_path, backlog=backlog, ) watchers.append( Watcher( name=f"runner_{runner.name}", cmd=sys.executable, args=[ "-m", SCRIPT_RUNNER, bento_identifier, "--runner-name", runner.name, "--bind", f"fd://$(circus.sockets.{runner.name})", "--working-dir", working_dir, "--worker-id", "$(CIRCUS.WID)", ], copy_env=True, stop_children=True, working_dir=working_dir, use_sockets=True, numprocesses=runner.scheduled_worker_count, ) ) elif psutil.WINDOWS: # Windows doesn't (fully) support AF_UNIX sockets with contextlib.ExitStack() as port_stack: for runner in svc.runners: runner_port = port_stack.enter_context(reserve_free_port()) runner_host = "127.0.0.1" runner_bind_map[runner.name] = f"tcp://{runner_host}:{runner_port}" circus_socket_map[runner.name] = CircusSocket( name=runner.name, host=runner_host, port=runner_port, backlog=backlog, ) watchers.append( Watcher( name=f"runner_{runner.name}", cmd=sys.executable, args=[ "-m", SCRIPT_RUNNER, bento_identifier, "--runner-name", runner.name, "--bind", f"fd://$(circus.sockets.{runner.name})", "--working-dir", working_dir, "--no-access-log", "--worker-id", "$(circus.wid)", ], copy_env=True, stop_children=True, use_sockets=True, working_dir=working_dir, numprocesses=runner.scheduled_worker_count, ) ) port_stack.enter_context( reserve_free_port() ) # reserve one more to avoid conflicts else: raise NotImplementedError("Unsupported platform: {}".format(sys.platform)) logger.debug("Runner map: %s", runner_bind_map) circus_socket_map["_bento_api_server"] = CircusSocket( name="_bento_api_server", host=host, port=port, backlog=backlog, ) watchers.append( Watcher( name="api_server", cmd=sys.executable, args=[ "-m", SCRIPT_API_SERVER, bento_identifier, "--bind", "fd://$(circus.sockets._bento_api_server)", "--runner-map", json.dumps(runner_bind_map), "--working-dir", working_dir, "--backlog", f"{backlog}", "--worker-id", "$(CIRCUS.WID)", ], copy_env=True, numprocesses=api_workers or math.ceil(query_cpu_count()), stop_children=True, use_sockets=True, working_dir=working_dir, ) ) arbiter = create_standalone_arbiter( watchers=watchers, sockets=list(circus_socket_map.values()), ) ensure_prometheus_dir() with track_serve(svc, production=True): try: arbiter.start( cb=lambda _: logger.info( # type: ignore f'Starting production BentoServer from "{bento_identifier}" ' f"running on http://{host}:{port} (Press CTRL+C to quit)" ), ) finally: if uds_path is not None: shutil.rmtree(uds_path)
import logging import contextvars from timeit import default_timer from typing import TYPE_CHECKING from simple_di import inject from simple_di import Provide from ..configuration.containers import DeploymentContainer if TYPE_CHECKING: from .. import external_typing as ext from ..service import Service from ..server.metrics.prometheus import PrometheusClient logger = logging.getLogger(__name__) START_TIME_VAR: "contextvars.ContextVar[float]" = contextvars.ContextVar( "START_TIME_VAR" ) class MetricsMiddleware: def __init__( self, app: "ext.ASGIApp", bento_service: "Service", ): self.app = app self.bento_service = bento_service self._is_setup = False @inject def _setup( self, metrics_client: "PrometheusClient" = Provide[ DeploymentContainer.metrics_client ], ): self.metrics_client = metrics_client service_name = self.bento_service.name # a valid tag name may includes invalid characters, so we need to escape them # ref: https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels service_name = service_name.replace("-", ":").replace(".", "::") self.metrics_request_duration = metrics_client.Histogram( name=service_name + "_request_duration_seconds", documentation=service_name + " API HTTP request duration in seconds", labelnames=["endpoint", "service_version", "http_response_code"], ) self.metrics_request_total = metrics_client.Counter( name=service_name + "_request_total", documentation="Total number of HTTP requests", labelnames=["endpoint", "service_version", "http_response_code"], ) self.metrics_request_in_progress = metrics_client.Gauge( name=service_name + "_request_in_progress", documentation="Total number of HTTP requests in progress now", labelnames=["endpoint", "service_version"], multiprocess_mode="livesum", ) self._is_setup = True async def __call__( self, scope: "ext.ASGIScope", receive: "ext.ASGIReceive", send: "ext.ASGISend", ) -> None: if not self._is_setup: self._setup() if not scope["type"].startswith("http"): await self.app(scope, receive, send) return if scope["path"] == "/metrics": from starlette.responses import Response response = Response( self.metrics_client.generate_latest(), status_code=200, media_type=self.metrics_client.CONTENT_TYPE_LATEST, ) await response(scope, receive, send) return service_version = ( self.bento_service.tag.version if self.bento_service.tag is not None else "" ) endpoint = scope["path"] START_TIME_VAR.set(default_timer()) async def wrapped_send(message: "ext.ASGIMessage") -> None: if message["type"] == "http.response.start": status_code = message["status"] # instrument request total count self.metrics_request_total.labels( endpoint=endpoint, service_version=service_version, http_response_code=status_code, ).inc() # instrument request duration assert START_TIME_VAR.get() != 0 total_time = max(default_timer() - START_TIME_VAR.get(), 0) self.metrics_request_duration.labels( # type: ignore endpoint=endpoint, service_version=service_version, http_response_code=status_code, ).observe(total_time) START_TIME_VAR.set(0) await send(message) with self.metrics_request_in_progress.labels( endpoint=endpoint, service_version=service_version ).track_inprogress(): await self.app(scope, receive, wrapped_send) return
# type: ignore[reportMissingTypeStubs] import os import sys import typing as t import logging from functools import partial logger = logging.getLogger(__name__) class PrometheusClient: def __init__( self, *, namespace: str = "", multiproc: bool = True, multiproc_dir: t.Optional[str] = None, ): """ Set up multiproc_dir for prometheus to work in multiprocess mode, which is required when working with Gunicorn server Warning: for this to work, prometheus_client library must be imported after this function is called. It relies on the os.environ['PROMETHEUS_MULTIPROC_DIR'] to properly setup for multiprocess mode """ if multiproc: assert multiproc_dir is not None, "multiproc_dir must be provided" self.multiproc = multiproc self.namespace = namespace self.multiproc_dir: t.Optional[str] = multiproc_dir self._registry = None self._imported = False self._pid: t.Optional[int] = None @property def prometheus_client(self): if self.multiproc and not self._imported: # step 1: check environment assert ( "prometheus_client" not in sys.modules ), "prometheus_client is already imported, multiprocessing will not work properly" assert ( self.multiproc_dir ), f"Invalid prometheus multiproc directory: {self.multiproc_dir}" assert os.path.isdir(self.multiproc_dir) os.environ["PROMETHEUS_MULTIPROC_DIR"] = self.multiproc_dir # step 2: import prometheus_client import prometheus_client.multiprocess self._imported = True return prometheus_client @property def registry(self): if self._registry is None: if self.multiproc: self._pid = os.getpid() self._registry = self.prometheus_client.REGISTRY else: if self.multiproc: assert self._pid is not None assert ( os.getpid() == self._pid ), "The current process's different than the process which the prometheus client gets created" return self._registry def __del__(self): self.mark_process_dead() def mark_process_dead(self) -> None: if self.multiproc: assert self._pid is not None assert ( os.getpid() == self._pid ), "The current process's different than the process which the prometheus client gets created" self.prometheus_client.multiprocess.mark_process_dead(self._pid) def start_http_server(self, port: int, addr: str = "") -> None: self.prometheus_client.start_http_server( port=port, addr=addr, registry=self.registry, ) def generate_latest(self): if self.multiproc: registry = self.prometheus_client.CollectorRegistry() self.prometheus_client.multiprocess.MultiProcessCollector(registry) return self.prometheus_client.generate_latest(registry) else: return self.prometheus_client.generate_latest() @property def CONTENT_TYPE_LATEST(self) -> str: return self.prometheus_client.CONTENT_TYPE_LATEST @property def Histogram(self): return partial( self.prometheus_client.Histogram, namespace=self.namespace, registry=self.registry, ) @property def Counter(self): return partial( self.prometheus_client.Counter, namespace=self.namespace, registry=self.registry, ) @property def Summary(self): return partial( self.prometheus_client.Summary, namespace=self.namespace, registry=self.registry, ) @property def Gauge(self): return partial( self.prometheus_client.Gauge, namespace=self.namespace, registry=self.registry, )
from __future__ import annotations import sys import socket import typing as t from typing import TYPE_CHECKING from urllib.parse import urlparse import psutil from bentoml import load from bentoml._internal.utils.uri import uri_to_path from ...log import SERVER_LOGGING_CONFIG from ...trace import ServiceContext if TYPE_CHECKING: from asgiref.typing import ASGI3Application import click @click.command() @click.argument("bento_identifier", type=click.STRING, required=False, default=".") @click.option("--runner-name", type=click.STRING, required=True) @click.option("--bind", type=click.STRING, required=True) @click.option("--working-dir", required=False, default=None, help="Working directory") @click.option( "--no-access-log", required=False, type=click.BOOL, is_flag=True, default=False, help="Disable the runner server's access log", ) @click.option( "--worker-id", required=False, type=click.INT, default=None, help="If set, start the server as a bare worker with the given worker ID. Otherwise start a standalone server with a supervisor process.", ) @click.pass_context def main( ctx: click.Context, bento_identifier: str, runner_name: str, bind: str, working_dir: t.Optional[str], no_access_log: bool, worker_id: int | None, ) -> None: """ Start a runner server. Args: bento_identifier: the Bento identifier name: the name of the runner bind: the bind address URI. Can be: - tcp://host:port - unix://path/to/unix.sock - file:///path/to/unix.sock - fd://12 working_dir: (Optional) the working directory worker_id: (Optional) if set, the runner will be started as a worker with the given ID """ from ...log import configure_server_logging configure_server_logging() if worker_id is None: # Start a standalone server with a supervisor process from circus.watcher import Watcher from bentoml._internal.utils.click import unparse_click_params from bentoml._internal.utils.circus import create_standalone_arbiter from bentoml._internal.utils.circus import create_circus_socket_from_uri circus_socket = create_circus_socket_from_uri(bind, name=runner_name) params = ctx.params params["bind"] = f"fd://$(circus.sockets.{runner_name})" params["worker_id"] = "$(circus.wid)" params["no_access_log"] = no_access_log watcher = Watcher( name=f"runner_{runner_name}", cmd=sys.executable, args=["-m", "bentoml._internal.server.cli.runner"] + unparse_click_params(params, ctx.command.params, factory=str), copy_env=True, numprocesses=1, stop_children=True, use_sockets=True, working_dir=working_dir, ) arbiter = create_standalone_arbiter(watchers=[watcher], sockets=[circus_socket]) arbiter.start() return import uvicorn # type: ignore if no_access_log: from bentoml._internal.configuration.containers import DeploymentContainer access_log_config = DeploymentContainer.runners_config.logging.access access_log_config.enabled.set(False) from bentoml._internal.server.runner_app import RunnerAppFactory ServiceContext.component_name_var.set(f"{runner_name}:{worker_id}") service = load(bento_identifier, working_dir=working_dir, change_global_cwd=True) for runner in service.runners: if runner.name == runner_name: break else: raise ValueError(f"Runner {runner_name} not found") app = t.cast("ASGI3Application", RunnerAppFactory(runner, worker_index=worker_id)()) parsed = urlparse(bind) uvicorn_options = { "log_level": SERVER_LOGGING_CONFIG["root"]["level"], "log_config": SERVER_LOGGING_CONFIG, "workers": 1, } if psutil.WINDOWS: uvicorn_options["loop"] = "asyncio" import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # type: ignore if parsed.scheme in ("file", "unix"): uvicorn.run( app, uds=uri_to_path(bind), **uvicorn_options, ) elif parsed.scheme == "tcp": uvicorn.run( app, host=parsed.hostname, port=parsed.port, **uvicorn_options, ) elif parsed.scheme == "fd": # when fd is provided, we will skip the uvicorn internal supervisor, thus there is only one process fd = int(parsed.netloc) sock = socket.socket(fileno=fd) config = uvicorn.Config(app, **uvicorn_options) uvicorn.Server(config).run(sockets=[sock]) else: raise ValueError(f"Unsupported bind scheme: {bind}") if __name__ == "__main__": main() # pylint: disable=no-value-for-parameter
def main(): from ...utils.ngrok import start_ngrok from ...configuration.containers import DeploymentContainer start_ngrok(DeploymentContainer.api_server_config.port.get()) if __name__ == "__main__": main()
from __future__ import annotations import sys import json import socket import typing as t from typing import TYPE_CHECKING from urllib.parse import urlparse import psutil import bentoml from ...log import SERVER_LOGGING_CONFIG from ...trace import ServiceContext if TYPE_CHECKING: from asgiref.typing import ASGI3Application import click @click.command() @click.argument("bento_identifier", type=click.STRING, required=False, default=".") @click.option( "--bind", type=click.STRING, required=True, help="Bind address sent to circus. This address accepts the following values: 'tcp://127.0.0.1:3000','unix:///tmp/bento_api.sock', 'fd://12'", ) @click.option( "--runner-map", type=click.STRING, envvar="BENTOML_RUNNER_MAP", help="JSON string of runners map, default sets to envars `BENTOML_RUNNER_MAP`", ) @click.option( "--backlog", type=click.INT, default=2048, help="Backlog size for the socket" ) @click.option( "--working-dir", type=click.Path(exists=True), help="Working directory for the API server", ) @click.option( "--worker-id", required=False, type=click.INT, default=None, help="If set, start the server as a bare worker with the given worker ID. Otherwise start a standalone server with a supervisor process.", ) @click.pass_context def main( ctx: click.Context, bento_identifier: str, bind: str, runner_map: str | None, backlog: int, working_dir: str | None, worker_id: int | None, ): """ Start BentoML API server. \b This is an internal API, users should not use this directly. Instead use `bentoml serve <path> [--options]` """ from ...log import configure_server_logging from ...configuration.containers import DeploymentContainer DeploymentContainer.development_mode.set(False) configure_server_logging() if worker_id is None: # Start a standalone server with a supervisor process from circus.watcher import Watcher from bentoml._internal.server import ensure_prometheus_dir from bentoml._internal.utils.click import unparse_click_params from bentoml._internal.utils.circus import create_standalone_arbiter from bentoml._internal.utils.circus import create_circus_socket_from_uri ensure_prometheus_dir() circus_socket = create_circus_socket_from_uri(bind, name="_bento_api_server") params = ctx.params params["bind"] = "fd://$(circus.sockets._bento_api_server)" params["worker_id"] = "$(circus.wid)" watcher = Watcher( name="bento_api_server", cmd=sys.executable, args=["-m", "bentoml._internal.server.cli.api_server"] + unparse_click_params(params, ctx.command.params, factory=str), copy_env=True, numprocesses=1, stop_children=True, use_sockets=True, working_dir=working_dir, ) arbiter = create_standalone_arbiter(watchers=[watcher], sockets=[circus_socket]) arbiter.start() return import uvicorn # type: ignore ServiceContext.component_name_var.set(f"api_server:{worker_id}") if runner_map is not None: DeploymentContainer.remote_runner_mapping.set(json.loads(runner_map)) svc = bentoml.load( bento_identifier, working_dir=working_dir, change_global_cwd=True ) parsed = urlparse(bind) uvicorn_options: dict[str, t.Any] = { "log_level": SERVER_LOGGING_CONFIG["root"]["level"], "backlog": backlog, "log_config": SERVER_LOGGING_CONFIG, "workers": 1, } if psutil.WINDOWS: uvicorn_options["loop"] = "asyncio" import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # type: ignore app = t.cast("ASGI3Application", svc.asgi_app) assert parsed.scheme == "fd" # skip the uvicorn internal supervisor fd = int(parsed.netloc) sock = socket.socket(fileno=fd) config = uvicorn.Config(app, **uvicorn_options) uvicorn.Server(config).run(sockets=[sock]) if __name__ == "__main__": main() # pylint: disable=no-value-for-parameter
import socket import typing as t from urllib.parse import urlparse import click import psutil from bentoml import load from ...log import SERVER_LOGGING_CONFIG from ...trace import ServiceContext @click.command() @click.argument("bento_identifier", type=click.STRING, required=False, default=".") @click.option("--bind", type=click.STRING, required=True) @click.option("--backlog", type=click.INT, default=2048) @click.option("--working-dir", required=False, type=click.Path(), default=None) def main( bento_identifier: str, bind: str, working_dir: t.Optional[str], backlog: int, ): import uvicorn # type: ignore from ...log import configure_server_logging configure_server_logging() ServiceContext.component_name_var.set("dev_api_server") parsed = urlparse(bind) if parsed.scheme == "fd": fd = int(parsed.netloc) sock = socket.socket(fileno=fd) svc = load(bento_identifier, working_dir=working_dir, change_global_cwd=True) uvicorn_options = { "log_level": SERVER_LOGGING_CONFIG["root"]["level"], "backlog": backlog, "log_config": SERVER_LOGGING_CONFIG, "workers": 1, "lifespan": "on", } if psutil.WINDOWS: uvicorn_options["loop"] = "asyncio" import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # type: ignore config = uvicorn.Config(svc.asgi_app, **uvicorn_options) uvicorn.Server(config).run(sockets=[sock]) else: raise ValueError(f"Unsupported bind scheme: {bind}") if __name__ == "__main__": main() # pylint: disable=no-value-for-parameter
import time class FixedBucket: """ Fixed size FIFO container. """ def __init__(self, size): self._data = [None] * size self._cur = 0 self._size = size self._flag_full = False def put(self, v): self._data[self._cur] = v self._cur += 1 if self._cur == self._size: self._cur = 0 self._flag_full = True @property def data(self): if not self._flag_full: return self._data[: self._cur] return self._data def __len__(self): if not self._flag_full: return self._cur return self._size def __getitem__(self, sl): if not self._flag_full: return self._data[: self._cur][sl] return (self._data[self._cur :] + self._data[: self._cur])[sl] class TokenBucket: """ Dynamic token bucket """ def __init__(self, init_amount=0): self._amount = init_amount self._last_consume_time = time.time() def consume(self, take_amount, avg_rate, burst_size): now = time.time() inc = (now - self._last_consume_time) * avg_rate current_amount = min(inc + self._amount, burst_size) if take_amount > current_amount: return False self._amount, self._last_consume_time = current_amount - take_amount, now return True
from __future__ import annotations import typing as t import logging import click logger = logging.getLogger(__name__) def unparse_click_params( params: dict[str, t.Any], command_params: list[click.Parameter], *, factory: t.Callable[..., t.Any] | None = None, ) -> list[str]: """ Unparse click call to a list of arguments. Used to modify some parameters and restore to system command. The goal is to unpack cases where parameters can be parsed multiple times. Refers to ./buildx.py for examples of this usage. This is also used to unparse parameters for running API server. Args: params (`dict[str, t.Any]`): The dictionary of the parameters that is parsed from click.Context. command_params (`list[click.Parameter]`): The list of paramters (Arguments/Options) that is part of a given command. Returns: Unparsed list of arguments that can be redirected to system commands. Implementation: For cases where options is None, or the default value is None, we will remove it from the first params list. Currently it doesn't support unpacking `prompt_required` or `confirmation_prompt`. """ args: list[str] = [] # first filter out all parsed parameters that have value None # This means that the parameter was not set by the user params = {k: v for k, v in params.items() if v not in [None, (), []]} for command_param in command_params: if isinstance(command_param, click.Argument): # Arguments.nargs, Arguments.required if command_param.name in params: if command_param.nargs > 1: # multiple arguments are passed as a list. # In this case we try to convert all None to an empty string args.extend( list( filter( lambda x: "" if x is None else x, params[command_param.name], ) ) ) else: args.append(params[command_param.name]) elif isinstance(command_param, click.Option): if command_param.name in params: if ( command_param.confirmation_prompt or command_param.prompt is not None ): logger.warning( f"{command_params} is a prompt, skip parsing it for now." ) pass if command_param.is_flag: args.append(command_param.opts[-1]) else: cmd = f"--{command_param.name.replace('_','-')}" if command_param.multiple: for var in params[command_param.name]: args.extend([cmd, var]) else: args.extend([cmd, params[command_param.name]]) else: logger.warning( "Given command params is a subclass of click.Parameter, but not a click.Argument or click.Option. Passing through..." ) # We will also convert values if factory is parsed: if factory is not None: return list(map(factory, args)) return args
import shutil import logging import os.path import tempfile from ..configuration import get_debug_mode logger = logging.getLogger(__name__) class TempDirectory(object): """ Helper class that creates and cleans up a temporary directory, can be used as a context manager. >>> with TempDirectory() as tempdir: >>> print(os.path.isdir(tempdir)) """ def __init__( self, cleanup=True, prefix="temp", ): self._cleanup = cleanup self._prefix = prefix self.path = None def __repr__(self): return "<{} {!r}>".format(self.__class__.__name__, self.path) def __enter__(self): self.create() return self.path def __exit__(self, exc_type, exc_val, exc_tb): if get_debug_mode(): logger.debug( 'BentoML in debug mode, keeping temp directory "%s"', self.path ) return if self._cleanup: self.cleanup() def create(self): if self.path is not None: logger.debug("Skipped temp directory creation: %s", self.path) return self.path tempdir = tempfile.mkdtemp(prefix="bentoml-{}-".format(self._prefix)) self.path = os.path.realpath(tempdir) logger.debug("Created temporary directory: %s", self.path) def cleanup(self, ignore_errors=False): """ Remove the temporary directory created """ if self.path is not None and os.path.exists(self.path): shutil.rmtree(self.path, ignore_errors=ignore_errors) self.path = None
from __future__ import annotations import typing as t from datetime import datetime import cattr from attr import fields from cattr import override # type: ignore from cattr.gen import AttributeOverride bentoml_cattr = cattr.Converter() def omit_if_init_false(cls: t.Any) -> dict[str, AttributeOverride]: return {f.name: override(omit=True) for f in fields(cls) if not f.init} def omit_if_default(cls: t.Any) -> dict[str, AttributeOverride]: return {f.name: override(omit_if_default=True) for f in fields(cls)} def datetime_decoder(dt_like: str | datetime, _: t.Any) -> datetime: if isinstance(dt_like, str): return datetime.fromisoformat(dt_like) elif isinstance(dt_like, datetime): return dt_like else: raise Exception(f"Unable to parse datetime from '{dt_like}'") bentoml_cattr.register_unstructure_hook(datetime, lambda dt: dt.isoformat()) # type: ignore bentoml_cattr.register_structure_hook(datetime, datetime_decoder)
from __future__ import annotations import os import typing as t import logging import functools import subprocess from typing import TYPE_CHECKING from ..types import PathType from ...exceptions import BentoMLException if TYPE_CHECKING: P = t.ParamSpec("P") logger = logging.getLogger(__name__) DOCKER_BUILDX_CMD = ["docker", "buildx"] # https://stackoverflow.com/questions/45125516/possible-values-for-uname-m UNAME_M_TO_PLATFORM_MAPPING = { "x86_64": "linux/amd64", "arm64": "linux/arm64/v8", "ppc64le": "linux/ppc64le", "s390x": "linux/s390x", "riscv64": "linux/riscv64", "mips64": "linux/mips64le", } @functools.lru_cache(maxsize=1) def health() -> None: """ Check whether buildx is available in given system. """ cmds = DOCKER_BUILDX_CMD + ["--help"] try: output = subprocess.check_output(cmds, stderr=subprocess.STDOUT) assert "--builder string" in output.decode("utf-8") except (subprocess.CalledProcessError, AssertionError): raise BentoMLException( "BentoML requires Docker Buildx to be installed to support multi-arch builds. " "Buildx comes with Docker Desktop, but one can also install it manually by following " "instructions via https://docs.docker.com/buildx/working-with-buildx/#install." ) def lists() -> list[str]: # Should only be used for testing purposes. cmds = DOCKER_BUILDX_CMD + ["ls"] proc = subprocess.run(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stream = proc.stdout.decode("utf-8") if len(stream) != 0 and stream[-1] == "\n": stream = stream[:-1] output = stream.splitlines()[1:] # first line is a header # lines starting with a blank space are builders metadata, not builder name output = list(filter(lambda x: not x.startswith(" "), output)) return [s.split(" ")[0] for s in output] def use( builder: str, default: bool = False, global_: bool = False ) -> None: # pragma: no cover # Should only be used for testing purposes. cmds = DOCKER_BUILDX_CMD + ["use"] if default: cmds.append("--default") if global_: cmds.append("--global") cmds.append(builder) run_docker_cmd(cmds) def create( subprocess_env: dict[str, str] | None = None, cwd: PathType | None = None, *, context_or_endpoints: str | None = None, buildkitd_flags: str | None = None, config: PathType | None = None, driver: t.Literal["docker", "kubernetes", "docker-container"] | None = None, driver_opt: dict[str, str] | None = None, name: str | None = None, platform: list[str] | None = None, use: bool = False, ) -> None: """ Create a new buildx instance. Args: context_or_endpoints: Custom docker context or endpoints (DOCKER_HOSTS). buildkitd_flags: Flags to pass to buildkitd. config: Path to a buildx configuration file. driver: Driver to use for buildx. driver_opt: Driver options. name: Name of the buildx context. platform: List of platform for a given builder instance. use: whether to use the builder instance after create. """ cmds = DOCKER_BUILDX_CMD + ["create"] if buildkitd_flags is not None: cmds.extend(["--buildkitd-flags", buildkitd_flags]) if config is not None: cmds.extend(["--config", str(config)]) if driver is not None: cmds.extend(["--driver", driver]) if driver_opt is not None: cmds.extend( ["--driver-opt", ",".join([f"{k}={v}" for k, v in driver_opt.items()])] ) if name is not None: cmds.extend(["--name", name]) if platform is None: platform = [ "linux/amd64", "linux/arm64/v8", "linux/ppc64le", "linux/s390x", "linux/riscv64", "linux/mips64le", ] cmds.extend(["--platform", ",".join(platform)]) if use: cmds.append("--use") if context_or_endpoints is not None: cmds.append(context_or_endpoints) run_docker_cmd(cmds, env=subprocess_env, cwd=cwd) def build( subprocess_env: dict[str, str] | None, cwd: PathType | None, *, context_path: PathType = ".", add_host: dict[str, str] | None, allow: list[str] | None, build_args: dict[str, str] | None, build_context: dict[str, str] | None, builder: str | None, cache_from: str | list[str] | dict[str, str] | None, cache_to: str | list[str] | dict[str, str] | None, cgroup_parent: str | None, file: PathType | None, iidfile: PathType | None, labels: dict[str, str] | None, load: bool, metadata_file: PathType | None, network: str | None, no_cache: bool, no_cache_filter: list[str] | None, output: str | dict[str, str] | None, platform: str | list[str] | None, progress: t.Literal["auto", "tty", "plain"], pull: bool, push: bool, quiet: bool, secrets: str | list[str] | None, shm_size: str | int | None, rm: bool, ssh: str | None, tags: str | list[str] | None, target: str | None, ulimit: str | None, ) -> None: cmds = DOCKER_BUILDX_CMD + ["build"] cmds += ["--progress", progress] if tags is None: tags = [] tags = [tags] if not isinstance(tags, list) else tags for tag in tags: cmds.extend(["--tag", tag]) if add_host is not None: hosts = [f"{k}:{v}" for k, v in add_host.items()] for host in hosts: cmds.extend(["--add-host", host]) if allow is not None: for allow_arg in allow: cmds.extend(["--allow", allow_arg]) if platform is not None and len(platform) > 0: if isinstance(platform, str): platform = [platform] cmds += ["--platform", ",".join(platform)] if build_args is not None: args = [f"{k}={v}" for k, v in build_args.items()] for arg in args: cmds.extend(["--build-arg", arg]) if build_context is not None: args = [f"{k}={v}" for k, v in build_context.items()] for arg in args: cmds.extend(["--build-context", arg]) if builder is not None: cmds.extend(["--builder", builder]) if cache_from is not None: if isinstance(cache_from, str): cmds.extend(["--cache-from", cache_from]) elif isinstance(cache_from, list): for arg in cache_from: cmds.extend(["--cache-from", arg]) else: args = [f"{k}={v}" for k, v in cache_from.items()] cmds.extend(["--cache-from", ",".join(args)]) if cache_to is not None: if isinstance(cache_to, str): cmds.extend(["--cache-to", cache_to]) elif isinstance(cache_to, list): for arg in cache_to: cmds.extend(["--cache-to", arg]) else: args = [f"{k}={v}" for k, v in cache_to.items()] cmds.extend(["--cache-to", ",".join(args)]) if cgroup_parent is not None: cmds.extend(["--cgroup-parent", cgroup_parent]) if file is not None: cmds.extend(["--file", str(file)]) if iidfile is not None: cmds.extend(["--iidfile", str(iidfile)]) if load: cmds.append("--load") if metadata_file is not None: cmds.extend(["--metadata-file", str(metadata_file)]) if network is not None: cmds.extend(["--network", network]) if no_cache: cmds.append("--no-cache") if no_cache_filter is not None: for arg in no_cache_filter: cmds.extend(["--no-cache-filter", arg]) if labels is not None: args = [f"{k}={v}" for k, v in labels.items()] for arg in args: cmds.extend(["--label", arg]) if output is not None: if isinstance(output, str): cmds.extend(["--output", output]) else: args = [f"{k}={v}" for k, v in output.items()] cmds += ["--output", ",".join(args)] if pull: cmds.append("--pull") if push: cmds.append("--push") if quiet: cmds.append("--quiet") if secrets is not None: if isinstance(secrets, str): cmds.extend(["--secret", secrets]) else: for secret in secrets: cmds.extend(["--secret", secret]) if rm: cmds.append("--rm") if shm_size is not None: cmds.extend(["--shm-size", str(shm_size)]) if ssh is not None: cmds.extend(["--ssh", ssh]) if target is not None: cmds.extend(["--target", target]) if ulimit is not None: cmds.extend(["--ulimit", ulimit]) cmds.append(str(context_path)) logger.debug(f"docker buildx build cmd: `{cmds}`") run_docker_cmd(cmds, env=subprocess_env, cwd=cwd) def run_docker_cmd( cmds: list[str], *, env: dict[str, str] | None = None, cwd: PathType | None = None, ) -> None: subprocess_env = os.environ.copy() if env is not None: subprocess_env.update(env) subprocess.check_output(list(map(str, cmds)), env=subprocess_env, cwd=cwd)
import sys import types import typing as t import logging import importlib from ...exceptions import MissingDependencyException logger = logging.getLogger(__name__) class LazyLoader(types.ModuleType): """ LazyLoader module borrowed from Tensorflow https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/util/lazy_loader.py with a addition of "module caching". This will throw an exception if module cannot be imported. Lazily import a module, mainly to avoid pulling in large dependencies. `contrib`, and `ffmpeg` are examples of modules that are large and not always needed, and this allows them to only be loaded when they are used. """ def __init__( self, local_name: str, parent_module_globals: t.Dict[str, t.Any], name: str, warning: t.Optional[str] = None, exc_msg: t.Optional[str] = None, ): self._local_name = local_name self._parent_module_globals = parent_module_globals self._warning = warning self._exc_msg = exc_msg self._module: t.Optional[types.ModuleType] = None super(LazyLoader, self).__init__(str(name)) def _load(self) -> types.ModuleType: """Load the module and insert it into the parent's globals.""" # Import the target module and insert it into the parent's namespace try: module = importlib.import_module(self.__name__) self._parent_module_globals[self._local_name] = module # The additional add to sys.modules ensures library is actually loaded. sys.modules[self._local_name] = module except ModuleNotFoundError as err: raise MissingDependencyException(f"{self._exc_msg}") from err # Emit a warning if one was specified if self._warning: logger.warning(self._warning) # Make sure to only warn once. self._warning = None # Update this object's dict so that if someone keeps a reference to the # LazyLoader, lookups are efficient (__getattr__ is only called on lookups # that fail). self.__dict__.update(module.__dict__) return module def __getattr__(self, item: t.Any) -> t.Any: if self._module is None: self._module = self._load() return getattr(self._module, item) def __dir__(self) -> t.List[str]: if self._module is None: self._module = self._load() return dir(self._module)
import math import time import asyncio from collections import defaultdict from tabulate import tabulate def wrap_line(s, line_width=120, sep="\n"): ls = s.split(sep) outs = [] for line in ls: while len(line) > line_width: outs.append(line[:line_width]) line = line[line_width:] outs.append(line) return sep.join(outs) def dict_tab(d, in_row=False): try: if in_row: return tabulate( [(str(k), str(v)) for k, v in d.items()], tablefmt="fancy_grid" ) else: return tabulate( (map(str, d.values()),), headers=map(str, d.keys()), tablefmt="fancy_grid", ) except ImportError: return repr(d) def percentile(data, pers): if not data: return [math.nan] * len(pers) size = len(data) sorted_data = sorted(data) return tuple(sorted_data[max(math.ceil(size * p) - 1, 0)] for p in pers) class DynamicBucketMerge: """ real time speed stat """ def __init__(self, sample_range=1, bucket_num=10): self.bucket_num = bucket_num self.sample_range = sample_range self.bucket = [0] * bucket_num self.bucket_sample = [0] * bucket_num self.bucket_ver = [0] * bucket_num def put(self, timestamp, num): timestamp = timestamp / self.sample_range ver = int(timestamp * self.bucket_num // 1) i = int(timestamp % 1 * self.bucket_num // 1) if ver > self.bucket_ver[i]: self.bucket_ver[i], self.bucket[i], self.bucket_sample[i] = ver, num, 1 else: self.bucket[i] += num self.bucket_sample[i] += 1 def sum(self, timestamp): timestamp = timestamp / self.sample_range ver = int(timestamp * self.bucket_num // 1) return ( sum( n for n, v in zip(self.bucket, self.bucket_ver) if v >= ver - self.bucket_num ) / self.sample_range ) def mean(self, timestamp): timestamp = timestamp / self.sample_range ver = int(timestamp * self.bucket_num // 1) num_n_count = [ (n, s) for n, s, v in zip(self.bucket, self.bucket_sample, self.bucket_ver) if v >= ver - self.bucket_num and s > 0 ] return ( sum(n for n, _ in num_n_count) / sum(s for _, s in num_n_count) if num_n_count else math.nan ) class Stat: def __init__(self): self.success = 0 self.fail = 0 self.succ_ps = DynamicBucketMerge(2, 10) self.exec_ps = DynamicBucketMerge(2, 10) self.succ_times = [] self.exec_times = [] self.succ_time_ps = DynamicBucketMerge(2, 10) self.exec_time_ps = DynamicBucketMerge(2, 10) self.client_busy = 0 self.exceptions = defaultdict(list) self._sess_start_time = 0 self._sess_stop_time = 0 @property def req_total(self): return self.fail + self.success @property def sess_time(self): if self._sess_stop_time: return self._sess_stop_time - self._sess_start_time else: return time.time() - self._sess_start_time def log_succeed(self, req_time, n=1): self.success += n self.succ_ps.put(time.time(), 1) self.succ_times.append(req_time) self.succ_time_ps.put(time.time(), req_time) def log_exception(self, group, msg, req_time, n=1): self.fail += n self.exec_ps.put(time.time(), 1) self.exec_times.append(req_time) self.exec_time_ps.put(time.time(), req_time) self.exceptions[group].append(msg) def print_step(self): now = time.time() headers = ( "Result", "Total", "Reqs/s", "Resp Time Avg", "Client Health %", ) r = ( ( "succ", f"{self.success}", f"{self.succ_ps.sum(now)}", f"{self.succ_time_ps.mean(now)}", f"{(1 - self.client_busy / max(self.req_total, 1)) * 100}", ), ( "fail", f"{self.fail}", f"{self.exec_ps.sum(now)}", f"{self.exec_time_ps.mean(now)}", "", ), ) print(tabulate(r, headers=headers, tablefmt="fancy_grid")) def print_sumup(self): ps = percentile(self.succ_times, [0.5, 0.95, 0.99]) ps_fail = percentile(self.exec_times, [0.5, 0.95, 0.99]) health = (1 - self.client_busy / max(self.req_total, 1)) * 100 headers = ( "Result", "Total", "Reqs/s", "Resp Time Avg", "P50", "P95", "P99", ) r = ( ( "succ", self.success, self.success / max(self.sess_time, 1), sum(self.succ_times) / max(self.success, 1), ps[0], ps[1], ps[2], ), ( "fail", self.fail, self.fail / max(self.sess_time, 1), sum(self.exec_times) / max(self.fail, 1), ps_fail[0], ps_fail[1], ps_fail[2], ), ) print(tabulate(r, headers=headers, tablefmt="fancy_grid")) print(f"------ Client Health {health:.1f}% ------") if health < 90: print( """ *** WARNING *** The client health rate is low. The benchmark result is not reliable. Possible solutions: * check the failure_rate and avoid request failures * Rewrite your request_producer to reduce the CPU cost * Run more instances with multiprocessing. (Multi-threading will not work because of the GIL) * Reduce the total_user of your session """ ) def print_exec(self): headers = ["exceptions", "count"] rs = [ ( wrap_line(str(v[0]), 50)[:1000], len(v), ) for k, v in self.exceptions.items() ] print(tabulate(rs, headers=headers, tablefmt="fancy_grid")) def default_verify_response(status, _): if status // 100 == 2: return True else: return False class BenchmarkClient: """ A locust-like benchmark tool with asyncio. Features: * Very efficient, low CPU cost * Could be embedded into other asyncio apps, like jupyter notebook Paras: * request_producer: The test case producer, a function with return value (url: str, method: str, headers: dict, data: str) * request_interval: intervals in seconds between each requests of the same user, lazy value supported. for eg: - 1 # for constant 1 sec - lambda: random.random() # for random wait time between 0 and 1 * url_override: override the url provided by request_producer Example usage ========= In a session of one minute, 100 users keep sending POST request with one seconds interval: ``` test.py def test_case_producer(): return ('http://localhost:3000', "POST", {"Content-Type": "application/json"}, '{"x": 1.0}') from bentoml.utils.benchmark import BenchmarkClient b = BenchmarkClient(test_case_producer, request_interval=1, timeout=10) b.start_session(session_time=60, total_user=100) ``` run command: > python test.py """ STATUS_STOPPED = 0 STATUS_SPAWNING = 1 STATUS_SPAWNED = 2 STATUS_STOPPING = 3 def __init__( self, request_producer: callable, request_interval, verify_response: callable = default_verify_response, url_override=None, timeout=10, ): self.request_interval = request_interval self.request_producer = request_producer self.verify_response = verify_response self.url_override = url_override self.user_pool = [] self.status = self.STATUS_STOPPED self.stat = Stat() self.timeout = timeout self._stop_loop_flag = False async def _start(self): from aiohttp import ClientSession from aiohttp.client_exceptions import ServerDisconnectedError wait_time_suffix = 0 url, method, headers, data = self.request_producer() async with ClientSession() as sess: while True: req_start = time.time() req_url = self.url_override or url err = "" group = "" # noinspection PyUnresolvedReferences try: async with sess.request( method, req_url, data=data, headers=headers, timeout=self.timeout, ) as r: msg = await r.text() if not self.verify_response(r.status, msg): group = f"{r.status}" err = f"<status: {r.status}>\n{msg}" except asyncio.CancelledError: # pylint: disable=try-except-raise raise except (ServerDisconnectedError, TimeoutError) as e: group = repr(e.__class__) err = repr(e) except Exception as e: # pylint: disable=broad-except group = repr(e.__class__) err = repr(e) req_stop = time.time() if err: self.stat.log_exception(group, err, req_stop - req_start) else: self.stat.log_succeed(req_stop - req_start) url, method, headers, data = self.request_producer() if callable(self.request_interval): request_interval = self.request_interval() else: request_interval = self.request_interval wait_time = request_interval + wait_time_suffix sleep_until = req_stop + wait_time await asyncio.sleep(sleep_until - time.time()) now = time.time() if (now - sleep_until) / wait_time > 0.5: self.stat.client_busy += 1 wait_time_suffix = sleep_until - now def spawn(self): self.user_pool.append(asyncio.get_event_loop().create_task(self._start())) async def _trigger_batch_spawn(self, total, speed): try: wait_time = 1 / speed while self.status == self.STATUS_SPAWNING and len(self.user_pool) < total: self.spawn() await asyncio.sleep(wait_time) finally: if self.status == self.STATUS_SPAWNING: print(f"------ {total} users spawned ------") self.status = self.STATUS_SPAWNED else: print(f"------ spawn canceled before {total} users ------") def kill(self): if self.user_pool: self.user_pool.pop().cancel() if not self.user_pool: self.status = self.STATUS_STOPPED return True else: return False def batch_spawn(self, total, speed): if self.status in {self.STATUS_STOPPED}: self.status = self.STATUS_SPAWNING asyncio.get_event_loop().create_task( self._trigger_batch_spawn(total, speed) ) else: print("The status must be STATUS_STOPPED before start_session/batch_spawn") def killall(self): if self.status in {self.STATUS_SPAWNING, self.STATUS_SPAWNED}: self.status = self.STATUS_STOPPING while self.kill(): pass async def _start_output(self): while self.status in {self.STATUS_SPAWNING, self.STATUS_SPAWNED}: print("") self.stat.print_step() await asyncio.sleep(2) async def _start_session(self, session_time, total_user, spawn_speed): try: print("======= Session started! =======") self.stat._sess_start_time = time.time() self.batch_spawn(total_user, spawn_speed) asyncio.get_event_loop().create_task(self._start_output()) await asyncio.sleep(session_time) finally: self.killall() self.stat._sess_stop_time = time.time() print("======= Session stopped! =======") if self.stat.exceptions: print("------ Exceptions happened ------") self.stat.print_exec() self.stat.print_sumup() if self._stop_loop_flag: loop = asyncio.get_event_loop() loop.stop() def start_session(self, session_time, total_user, spawn_speed=None): """ To start a benchmark session. If it's running It will return immediately. Paras: * session_time: session time in sec * total_user: user count need to be spawned * spawn_speed: user spawning speed, in user/sec """ if spawn_speed is None: spawn_speed = total_user loop = asyncio.get_event_loop() if not loop.is_running(): self._stop_loop_flag = True loop.create_task(self._start_session(session_time, total_user, spawn_speed)) if not loop.is_running(): loop.run_forever()
import os import json import time import shutil import logging import zipfile import platform import tempfile import subprocess from pathlib import Path from threading import Thread import requests from ...exceptions import BentoMLException logger = logging.getLogger(__name__) def get_command() -> str: """ ngrok command based on OS """ system = platform.system() if system == "Darwin": command = "ngrok" elif system == "Windows": command = "ngrok.exe" elif system == "Linux": command = "ngrok" else: raise BentoMLException(f"{system} is not supported") return command def log_url() -> None: localhost_url = "http://localhost:4040/api/tunnels" # Url with tunnel details while True: time.sleep(1) response = requests.get(localhost_url) if response.status_code == 200: data = json.loads(response.text) if data["tunnels"]: tunnel = data["tunnels"][0] logger.info( " Ngrok running at: %s", tunnel["public_url"].replace("https://", "http://"), ) logger.info(" Traffic stats available on http://127.0.0.1:4040") return else: logger.info("Waiting for ngrok to start...") def start_ngrok(port: int): """ Start ngrok server synchronously """ command = get_command() ngrok_path = str(Path(tempfile.gettempdir(), "ngrok")) download_ngrok(ngrok_path) executable = str(Path(ngrok_path, command)) os.chmod(executable, 0o777) Thread(target=log_url).start() with subprocess.Popen([executable, "http", str(port)]) as ngrok_process: ngrok_process.wait() def download_ngrok(ngrok_path: str) -> None: """ Check OS and decide on ngrok download URL """ if Path(ngrok_path).exists(): return system = platform.system() if system == "Darwin": url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip" elif system == "Windows": url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip" elif system == "Linux": url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip" else: raise Exception(f"{system} is not supported") download_path = download_file(url) with zipfile.ZipFile(download_path, "r") as zip_ref: zip_ref.extractall(ngrok_path) def download_file(url: str) -> str: """ Download ngrok binary file to local Args: url (:code:`str`): URL to download Returns: :code:`download_path`: str """ local_filename = url.split("/")[-1] r = requests.get(url, stream=True) download_path = str(Path(tempfile.gettempdir(), local_filename)) with open(download_path, "wb") as f: shutil.copyfileobj(r.raw, f) return download_path
import io import json import typing as t import itertools from typing import TYPE_CHECKING from . import catch_exceptions from .csv import csv_row from .csv import csv_quote from .csv import csv_split from .csv import csv_unquote from .csv import csv_splitlines from .lazy_loader import LazyLoader from ...exceptions import BadInput from ...exceptions import BentoMLException if TYPE_CHECKING: import pandas as pd else: pd = LazyLoader("pd", globals(), "pandas") def check_dataframe_column_contains( required_column_names: str, df: "pd.DataFrame" ) -> None: df_columns = set(map(str, df.columns)) for col in required_column_names: if col not in df_columns: raise BadInput( f"Missing columns: {','.join(set(required_column_names) - df_columns)}, required_column:{df_columns}" # noqa: E501 ) @catch_exceptions(Exception, BentoMLException, fallback=None) def guess_orient( table: t.Union[t.List[t.Mapping[str, t.Any]], t.Dict[str, t.Any]], strict: bool = False, ) -> t.Optional[t.Set[str]]: if isinstance(table, list): if not table: if strict: return {"records", "values"} else: return {"records"} if isinstance(table[0], dict): return {"records"} else: return {"values"} elif isinstance(table, dict): if set(table) == {"columns", "index", "data"}: return {"split"} if set(table) == {"schema", "data"} and "primaryKey" in table["schema"]: return {"table"} if strict: return {"columns", "index"} else: return {"columns"} else: return None class _DataFrameState(object): # fmt: off @t.overload def __init__(self, columns: t.Optional[t.Dict[str, int]]): ... # noqa: F811,E704 @t.overload # noqa: F811 def __init__(self, columns: t.Optional[t.Tuple[str, ...]]): ... # noqa: F811,E704 # fmt: on def __init__( # noqa: F811 self, columns: t.Optional[t.Union[t.Mapping[str, int], t.Tuple[str, ...]]] = None, ): self.columns = columns def _from_json_records(state: _DataFrameState, table: list) -> t.Iterator[str]: if state.columns is None: # make header state.columns = {k: i for i, k in enumerate(table[0].keys())} for tr in table: yield csv_row(tr[c] for c in state.columns) def _from_json_values(_: _DataFrameState, table: list) -> t.Iterator[str]: for tr in table: yield csv_row(tr) def _from_json_columns(state: _DataFrameState, table: dict) -> t.Iterator[str]: if state.columns is None: # make header state.columns = {k: i for i, k in enumerate(table.keys())} for row in next(iter(table.values())): yield csv_row(table[col][row] for col in state.columns) def _from_json_index(state: _DataFrameState, table: dict) -> t.Iterator[str]: if state.columns is None: # make header state.columns = {k: i for i, k in enumerate(next(iter(table.values())).keys())} for row in table.keys(): yield csv_row(td for td in table[row].values()) else: for row in table.keys(): yield csv_row(table[row][col] for col in state.columns) def _from_json_split(state: _DataFrameState, table: dict) -> t.Iterator[str]: table_columns = {k: i for i, k in enumerate(table["columns"])} if state.columns is None: # make header state.columns = table_columns for row in table["data"]: yield csv_row(row) else: idxs = [state.columns[k] for k in table_columns] for row in table["data"]: yield csv_row(row[idx] for idx in idxs) def _from_csv_without_index( state: _DataFrameState, table: t.Iterator[str] ) -> t.Iterator[str]: row_str = next(table) # skip column names table_columns = tuple(csv_unquote(s) for s in csv_split(row_str, ",")) if state.columns is None: state.columns = table_columns for row_str in table: if not row_str: # skip blank line continue if not row_str.strip(): yield csv_quote(row_str) else: yield row_str elif not all( c1 == c2 for c1, c2 in itertools.zip_longest(state.columns, table_columns) ): # TODO: check type hint for this case. Right now nothing breaks so :) idxs = [state.columns[k] for k in table_columns] # type: ignore[call-overload] for row_str in table: if not row_str: # skip blank line continue if not row_str.strip(): yield csv_quote(row_str) else: tr = tuple(s for s in csv_split(row_str, ",")) yield csv_row(tr[i] for i in idxs) else: for row_str in table: if not row_str: # skip blank line continue if not row_str.strip(): yield csv_quote(row_str) else: yield row_str _ORIENT_MAP: t.Dict[str, t.Callable[["_DataFrameState", str], t.Iterator[str]]] = { "records": _from_json_records, "columns": _from_json_columns, "values": _from_json_values, "split": _from_json_split, "index": _from_json_index, # 'table': _from_json_table, } PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS = {k for k in _ORIENT_MAP} def _dataframe_csv_from_input( table: str, fmt: str, orient: t.Optional[str], state: _DataFrameState, ) -> t.Optional[t.Tuple[str, ...]]: try: if not fmt or fmt == "json": table = json.loads(table) if not orient: orient = guess_orient(table, strict=False).pop() else: # TODO: this can be either a set or a string guessed_orient = guess_orient(table, strict=True) # type: t.Set[str] if set(orient) != guessed_orient and orient not in guessed_orient: return None if orient not in _ORIENT_MAP: return None _from_json = _ORIENT_MAP[orient] try: return tuple(_from_json(state, table)) except (TypeError, AttributeError, KeyError, IndexError): return None elif fmt == "csv": _table = csv_splitlines(table) return tuple(_from_csv_without_index(state, _table)) else: return None except json.JSONDecodeError: return None def from_json_or_csv( data: t.Iterable[str], formats: t.Iterable[str], orient: t.Optional[str] = None, columns: t.Optional[t.List[str]] = None, dtype: t.Optional[t.Union[bool, t.Dict[str, t.Any]]] = None, ) -> t.Tuple[t.Optional["pd.DataFrame"], t.Tuple[int, ...]]: """ Load DataFrames from multiple raw data sources in JSON or CSV format, efficiently Background: Each call of `pandas.read_csv()` or `pandas.read_json` takes about 100ms, no matter how many lines the read data contains. This function concats the ragged_tensor/csv before running `read_json`/`read_csv` to improve performance. Args: data (`Iterable[str]`): Data in either JSON or CSV format formats (`Iterable[str]`): List of formats, which are either `json` or `csv` orient (:code:`str`, `optional`, default `"records"`): Indication of expected JSON string format. Compatible JSON strings can be produced by `pandas.io.json.to_json()` with a corresponding orient value. Possible orients are: - `split` - :code:`Dict[str, Any]`: {idx -> [idx], columns -> [columns], data -> [values]} - `records` - `List[Any]`: [{column -> value}, ..., {column -> value}] - `index` - :code:`Dict[str, Any]`: {idx -> {column -> value}} - `columns` - :code:`Dict[str, Any]`: {column -> {index -> value}} - `values` - :code:`Dict[str, Any]`: Values arrays columns (`List[str]`, `optional`, default `None`): List of column names that users wish to update dtype (:code:`Union[bool, Dict[str, Any]]`, `optional`, default `None`): Data type to inputs/outputs to. If it is a boolean, then pandas will infer data types. Otherwise, if it is a dictionary of column to data type, then applies those to incoming dataframes. If False, then don't infer data types at all (only applies to the data). This is not applicable when `orient='table'`. Returns: A tuple containing a `pandas.DataFrame` and a tuple containing the length of all series in the returned DataFrame. Raises: pandas.errors.EmptyDataError: When data is not found or is empty. """ state = _DataFrameState( columns={k: i for i, k in enumerate(columns)} if columns else None ) trs_list = tuple( _dataframe_csv_from_input(_t, _fmt, orient, state) for _t, _fmt in zip(data, formats) ) header = ",".join(csv_quote(td) for td in state.columns) if state.columns else None lens = tuple(len(trs) if trs else 0 for trs in trs_list) table = "\n".join(tr for trs in trs_list if trs is not None for tr in trs) try: if not header: df = pd.read_csv( io.StringIO(table), dtype=dtype, index_col=None, header=None, ) else: df = pd.read_csv( io.StringIO("\n".join((header, table))), dtype=dtype, index_col=None, ) return df, lens except pd.errors.EmptyDataError: return None, lens
from __future__ import annotations import os import sys import uuid import random import socket import typing as t import functools import contextlib from typing import overload from typing import TYPE_CHECKING from pathlib import Path from datetime import date from datetime import time from datetime import datetime from datetime import timedelta import fs import attr import fs.copy if sys.version_info >= (3, 8): from functools import cached_property else: from backports.cached_property import cached_property from .cattr import bentoml_cattr from ..types import LazyType from ..types import PathType from ..types import MetadataDict from ..types import MetadataType from .lazy_loader import LazyLoader if TYPE_CHECKING: from fs.base import FS P = t.ParamSpec("P") GenericFunction = t.Callable[P, t.Any] C = t.TypeVar("C") T = t.TypeVar("T") _T_co = t.TypeVar("_T_co", covariant=True, bound=t.Any) __all__ = [ "bentoml_cattr", "cached_property", "cached_contextmanager", "reserve_free_port", "catch_exceptions", "LazyLoader", "validate_or_create_dir", "display_path_under_home", ] @overload def kwargs_transformers( func: GenericFunction[t.Concatenate[str, bool, t.Iterable[str], P]], *, transformer: GenericFunction[t.Any], ) -> GenericFunction[t.Concatenate[str, t.Iterable[str], bool, P]]: ... @overload def kwargs_transformers( func: None = None, *, transformer: GenericFunction[t.Any] ) -> GenericFunction[t.Any]: ... def kwargs_transformers( _func: t.Callable[..., t.Any] | None = None, *, transformer: GenericFunction[t.Any], ) -> GenericFunction[t.Any]: def decorator(func: GenericFunction[t.Any]) -> t.Callable[P, t.Any]: @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> t.Any: return func(*args, **{k: transformer(v) for k, v in kwargs.items()}) return wrapper if _func is None: return decorator return decorator(_func) @t.overload def first_not_none(*args: T | None, default: T) -> T: ... @t.overload def first_not_none(*args: T | None) -> T | None: ... def first_not_none(*args: T | None, default: None | T = None) -> T | None: """ Returns the first argument that is not None. """ return next((arg for arg in args if arg is not None), default) def randomize_runner_name(module_name: str): return f"{module_name.split('.')[-1]}_{uuid.uuid4().hex[:6].lower()}" def validate_or_create_dir(*path: PathType) -> None: for p in path: path_obj = Path(p) if path_obj.exists(): if not path_obj.is_dir(): raise OSError(20, f"{path_obj} is not a directory") else: path_obj.mkdir(parents=True) def calc_dir_size(path: PathType) -> int: return sum(f.stat().st_size for f in Path(path).glob("**/*") if f.is_file()) def display_path_under_home(path: str) -> str: # Shorten path under home directory with leading `~` # e.g. from `/Users/foo/bar` to just `~/bar` try: return str("~" / Path(path).relative_to(Path.home())) except ValueError: # when path is not under home directory, return original full path return path def human_readable_size(size: t.Union[int, float], decimal_places: int = 2) -> str: for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]: if size < 1024.0 or unit == "PiB": break size /= 1024.0 else: raise ValueError("size is too large") return f"{size:.{decimal_places}f} {unit}" class catch_exceptions(t.Generic[_T_co], object): def __init__( self, catch_exc: t.Union[t.Type[BaseException], t.Tuple[t.Type[BaseException], ...]], throw_exc: t.Callable[[str], BaseException], msg: str = "", fallback: t.Optional[_T_co] = None, raises: t.Optional[bool] = True, ) -> None: self._catch_exc = catch_exc self._throw_exc = throw_exc self._msg = msg self._fallback = fallback self._raises = raises def __call__(self, func: t.Callable[P, _T_co]) -> t.Callable[P, t.Optional[_T_co]]: @functools.wraps(func) def _(*args: P.args, **kwargs: P.kwargs) -> t.Optional[_T_co]: try: return func(*args, **kwargs) except self._catch_exc: if self._raises: raise self._throw_exc(self._msg) return self._fallback return _ @contextlib.contextmanager def reserve_free_port( host: str = "localhost", prefix: t.Optional[str] = None, max_retry: int = 50, ) -> t.Iterator[int]: """ detect free port and reserve until exit the context """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if prefix is not None: prefix_num = int(prefix) * 10 ** (5 - len(prefix)) suffix_range = min(65535 - prefix_num, 10 ** (5 - len(prefix))) for _ in range(max_retry): suffix = random.randint(0, suffix_range) port = int(f"{prefix_num + suffix}") try: sock.bind((host, port)) break except OSError: continue else: raise RuntimeError( f"cannot find free port with prefix {prefix} after {max_retry} retries" ) else: sock.bind((host, 0)) port = sock.getsockname()[1] yield port sock.close() def copy_file_to_fs_folder( src_path: str, dst_fs: FS, dst_folder_path: str = ".", dst_filename: t.Optional[str] = None, ): """Copy the given file at src_path to dst_fs filesystem, under its dst_folder_path folder with dst_filename as file name. When dst_filename is None, keep the original file name. """ src_path = os.path.realpath(os.path.expanduser(src_path)) dir_name, file_name = os.path.split(src_path) src_fs = fs.open_fs(dir_name) dst_filename = file_name if dst_filename is None else dst_filename dst_path = fs.path.join(dst_folder_path, dst_filename) fs.copy.copy_file(src_fs, file_name, dst_fs, dst_path) def resolve_user_filepath(filepath: str, ctx: t.Optional[str]) -> str: """Resolve the abspath of a filepath provided by user, which may contain "~" or may be a relative path base on ctx dir. """ # Return if filepath exist after expanduser _path = os.path.expanduser(filepath) if os.path.exists(_path): return os.path.realpath(_path) # Try finding file in ctx if provided if ctx: _path = os.path.expanduser(os.path.join(ctx, filepath)) if os.path.exists(_path): return os.path.realpath(_path) raise FileNotFoundError(f"file {filepath} not found") def label_validator( _: t.Any, _attr: attr.Attribute[dict[str, str]], labels: dict[str, str] ): validate_labels(labels) def validate_labels(labels: dict[str, str]): if not isinstance(labels, dict): raise ValueError("labels must be a dict!") for key, val in labels.items(): if not isinstance(key, str): raise ValueError("label keys must be strings") if not isinstance(val, str): raise ValueError("label values must be strings") def metadata_validator( _: t.Any, _attr: attr.Attribute[MetadataDict], metadata: MetadataDict ): validate_metadata(metadata) def validate_metadata(metadata: MetadataDict): if not isinstance(metadata, dict): raise ValueError("metadata must be a dict!") for key, val in metadata.items(): if not isinstance(key, (str, int, float)): raise ValueError("metadata keys must be strings") metadata[key] = _validate_metadata_entry(val) def _validate_metadata_entry(entry: MetadataType) -> MetadataType: if isinstance(entry, dict): validate_metadata(entry) elif isinstance(entry, list): for i, val in enumerate(entry): entry[i] = _validate_metadata_entry(val) elif isinstance(entry, tuple): entry = tuple((_validate_metadata_entry(x) for x in entry)) elif LazyType("numpy", "ndarray").isinstance(entry): entry = entry.tolist() # type: ignore (LazyType) _validate_metadata_entry(entry) elif LazyType("numpy", "generic").isinstance(entry): entry = entry.item() # type: ignore (LazyType) _validate_metadata_entry(entry) elif LazyType("scipy.sparse", "spmatrix").isinstance(entry): raise ValueError( "SciPy sparse matrices are currently not supported as metadata items; consider using a dictionary instead" ) elif LazyType("pandas", "Series").isinstance(entry): entry = {entry.name: entry.to_dict()} _validate_metadata_entry(entry) elif LazyType("pandas.api.extensions", "ExtensionArray").isinstance(entry): entry = entry.to_numpy().tolist() # type: ignore (LazyType) _validate_metadata_entry(entry) elif LazyType("pandas", "DataFrame").isinstance(entry): entry = entry.to_dict() # type: ignore (LazyType) validate_metadata(entry) # type: ignore (LazyType) elif LazyType("pandas", "Timestamp").isinstance(entry): entry = entry.to_pydatetime() # type: ignore (LazyType) elif LazyType("pandas", "Timedelta").isinstance(entry): entry = entry.to_pytimedelta() # type: ignore (LazyType) elif LazyType("pandas", "Period").isinstance(entry): entry = entry.to_timestamp().to_pydatetime() # type: ignore (LazyType) elif LazyType("pandas", "Interval").isinstance(entry): entry = (entry.left, entry.right) # type: ignore (LazyType) _validate_metadata_entry(entry) elif not isinstance( entry, (str, bytes, bool, int, float, complex, datetime, date, time, timedelta) ): raise ValueError( f"metadata entries must be basic python types like 'str', 'int', or 'complex', got '{type(entry).__name__}'" ) return entry VT = t.TypeVar("VT") class cached_contextmanager: """ Just like contextlib.contextmanager, but will cache the yield value for the same arguments. When all instances of the same contextmanager exits, the cache value will be dropped. Example Usage: (To reuse the container based on the same image) >>> @cached_contextmanager("{docker_image.id}") >>> def start_docker_container_from_image(docker_image, timeout=60): >>> container = ... >>> yield container >>> container.stop() """ def __init__(self, cache_key_template: t.Optional[str] = None): self._cache_key_template = cache_key_template self._cache: t.Dict[t.Any, t.Any] = {} def __call__( self, func: "t.Callable[P, t.Generator[VT, None, None]]" ) -> "t.Callable[P, t.ContextManager[VT]]": func_m = contextlib.contextmanager(func) @contextlib.contextmanager @functools.wraps(func) def _func(*args: "P.args", **kwargs: "P.kwargs") -> t.Any: import inspect bound_args = inspect.signature(func).bind(*args, **kwargs) bound_args.apply_defaults() if self._cache_key_template: cache_key = self._cache_key_template.format(**bound_args.arguments) else: cache_key = repr(tuple(bound_args.arguments.values())) if cache_key in self._cache: yield self._cache[cache_key] else: with func_m(*args, **kwargs) as value: self._cache[cache_key] = value yield value self._cache.pop(cache_key) return _func
# type: ignore[reportMissingTypeStubs] import typing as t from typing import TYPE_CHECKING from opentelemetry.trace import get_current_span from opentelemetry.sdk.trace.sampling import Decision from opentelemetry.sdk.trace.sampling import ALWAYS_ON from opentelemetry.sdk.trace.sampling import ParentBased from opentelemetry.sdk.trace.sampling import StaticSampler from opentelemetry.sdk.trace.sampling import SamplingResult from opentelemetry.sdk.trace.sampling import TraceIdRatioBased if TYPE_CHECKING: from opentelemetry.trace import Link from opentelemetry.trace import Context from opentelemetry.trace import SpanKind from opentelemetry.trace import TraceState from opentelemetry.util.types import Attributes def _get_parent_trace_state(parent_context: "Context") -> t.Optional["TraceState"]: parent_span_context = get_current_span(parent_context).get_span_context() if parent_span_context is None or not parent_span_context.is_valid: return None return parent_span_context.trace_state class TraceIdRatioBasedAlwaysRecording(TraceIdRatioBased): """ A trace Sampler that: * always recording (so that we can get the trace_id) * respect the parent's trace_state * ratio sampling """ def should_sample( self, parent_context: t.Optional["Context"], trace_id: int, name: str, kind: t.Optional["SpanKind"] = None, attributes: t.Optional["Attributes"] = None, links: t.Optional[t.Sequence["Link"]] = None, trace_state: t.Optional["TraceState"] = None, ) -> "SamplingResult": decision = Decision.RECORD_ONLY if trace_id & self.TRACE_ID_LIMIT < self.bound: decision = Decision.RECORD_AND_SAMPLE if decision is Decision.RECORD_ONLY: pass # attributes = None return SamplingResult( decision, attributes, _get_parent_trace_state(parent_context), # type: ignore[reportGeneralTypeIssues] ) class ParentBasedTraceIdRatio(ParentBased): """ Sampler that respects its parent span's sampling decision, but otherwise samples probabalistically based on `rate`. """ def __init__(self, rate: float): root = TraceIdRatioBasedAlwaysRecording(rate=rate) super().__init__( root=root, remote_parent_sampled=ALWAYS_ON, remote_parent_not_sampled=StaticSampler(Decision.RECORD_ONLY), local_parent_sampled=ALWAYS_ON, local_parent_not_sampled=StaticSampler(Decision.RECORD_ONLY), )
import re import typing as t import logging from typing import TYPE_CHECKING from ...exceptions import BentoMLException logger = logging.getLogger(__name__) if TYPE_CHECKING: import click def to_valid_docker_image_name(name: str) -> str: # https://docs.docker.com/engine/reference/commandline/tag/#extended-description return name.lower().strip("._-") def to_valid_docker_image_version(version: str) -> str: # https://docs.docker.com/engine/reference/commandline/tag/#extended-description return version.encode("ascii", errors="ignore").decode().lstrip(".-")[:128] def validate_tag( ctx: "click.Context", param: "click.Parameter", tag: t.Optional[str] ) -> t.Optional[str]: # noqa # pylint: disable=unused-argument if tag is None: return tag if ":" in tag: name, version = tag.split(":")[:2] else: name, version = tag, None valid_name_pattern = re.compile( r""" ^( [a-z0-9]+ # alphanumeric (.|_{1,2}|-+)? # seperators )*$ """, re.VERBOSE, ) valid_version_pattern = re.compile( r""" ^ [a-zA-Z0-9] # cant start with .- [ -~]{,127} # ascii match rest, cap at 128 $ """, re.VERBOSE, ) if not valid_name_pattern.match(name): raise BentoMLException( f"Provided Docker Image tag {tag} is invalid. " "Name components may contain lowercase letters, digits " "and separators. A separator is defined as a period, " "one or two underscores, or one or more dashes." ) if version and not valid_version_pattern.match(version): raise BentoMLException( f"Provided Docker Image tag {tag} is invalid. " "A tag name must be valid ASCII and may contain " "lowercase and uppercase letters, digits, underscores, " "periods and dashes. A tag name may not start with a period " "or a dash and may contain a maximum of 128 characters." ) return tag
import typing as t import logging import importlib.util from typing import TYPE_CHECKING from bentoml.exceptions import BentoMLException from ..types import LazyType from .lazy_loader import LazyLoader try: import importlib.metadata as importlib_metadata except ImportError: import importlib_metadata if TYPE_CHECKING: import tensorflow as tf from ..external_typing import tensorflow as tf_ext else: tf = LazyLoader( "tf", globals(), "tensorflow", exc_msg="`tensorflow` is required to use bentoml.tensorflow module.", ) logger = logging.getLogger(__name__) TF_KERAS_DEFAULT_FUNCTIONS = { "_default_save_signature", "call_and_return_all_conditional_losses", } TENSOR_CLASS_NAMES = ( "RaggedTensor", "SparseTensor", "TensorArray", "EagerTensor", "Tensor", ) __all__ = [ "get_tf_version", "tf_function_wrapper", "pretty_format_restored_model", "is_gpu_available", "hook_loaded_model", ] TF_FUNCTION_WARNING: str = """\ Due to TensorFlow's internal mechanism, only methods wrapped under `@tf.function` decorator and the Keras default function `__call__(inputs, training=False)` can be restored after a save & load.\n You can test the restored model object via `bentoml.tensorflow.load(path)` """ KERAS_MODEL_WARNING: str = """\ BentoML detected that {name} is being used to pack a Keras API based model. In order to get optimal serving performance, we recommend to wrap your keras model `call()` methods with `@tf.function` decorator. """ def hook_loaded_model( tf_model: "tf_ext.AutoTrackable", module_name: str ) -> "tf_ext.AutoTrackable": tf_function_wrapper.hook_loaded_model(tf_model) logger.warning(TF_FUNCTION_WARNING) # pretty format loaded model logger.info(pretty_format_restored_model(tf_model)) if hasattr(tf_model, "keras_api"): logger.warning(KERAS_MODEL_WARNING.format(name=module_name)) return tf_model def is_gpu_available() -> bool: try: return len(tf.config.list_physical_devices("GPU")) > 0 except AttributeError: return tf.test.is_gpu_available() def get_tf_version() -> str: # courtesy of huggingface/transformers _tf_version = "" _tf_available = importlib.util.find_spec("tensorflow") is not None if _tf_available: candidates = ( "tensorflow", "tensorflow-cpu", "tensorflow-gpu", "tf-nightly", "tf-nightly-cpu", "tf-nightly-gpu", "intel-tensorflow", "intel-tensorflow-avx512", "tensorflow-rocm", "tensorflow-macos", ) # For the metadata, we have to look for both tensorflow and tensorflow-cpu for pkg in candidates: try: _tf_version = importlib_metadata.version(pkg) break except importlib_metadata.PackageNotFoundError: pass return _tf_version def check_tensor_spec( tensor: "tf_ext.TensorLike", tensor_spec: t.Union[str, t.Tuple[str, ...], t.List[str], "tf_ext.UnionTensorSpec"], class_name: t.Optional[str] = None, ) -> bool: """ :code:`isinstance` wrapper to check spec for a given tensor. Args: tensor (:code:`Union[tf.Tensor, tf.EagerTensor, tf.SparseTensor, tf.RaggedTensor]`): tensor class to check. tensor_spec (:code:`Union[str, Tuple[str,...]]`): class used to check with :obj:`tensor`. Follows :obj:`TENSOR_CLASS_NAME` class_name (:code:`str`, `optional`, default to :code:`None`): Optional class name to pass for correct path of tensor spec. If none specified, then :code:`class_name` will be determined via given spec class. Returns: `bool` if given tensor match a given spec. """ if tensor_spec is None: raise BentoMLException("`tensor` should not be None") tensor_cls = type(tensor).__name__ if isinstance(tensor_spec, str): return tensor_cls == tensor_spec.split(".")[-1] elif isinstance(tensor_spec, (list, tuple, set)): return all(check_tensor_spec(tensor, k) for k in tensor_spec) else: if class_name is None: class_name = ( str(tensor_spec.__class__).replace("<class '", "").replace("'>", "") ) return LazyType["tf_ext.TensorSpec"](class_name).isinstance(tensor) def normalize_spec(value: t.Any) -> "tf_ext.TypeSpec": """normalize tensor spec""" if not check_tensor_spec(value, TENSOR_CLASS_NAMES): return value if check_tensor_spec(value, "RaggedTensor"): return tf.RaggedTensorSpec.from_value(value) if check_tensor_spec(value, "SparseTensor"): return tf.SparseTensorSpec.from_value(value) if check_tensor_spec(value, "TensorArray"): return tf.TensorArraySpec.from_value(value) if check_tensor_spec(value, ("Tensor", "EagerTensor")): return tf.TensorSpec.from_tensor(value) raise BentoMLException(f"Unknown type for tensor spec, got{type(value)}.") def get_input_signatures( func: "tf_ext.DecoratedFunction", ) -> t.Tuple["tf_ext.InputSignature"]: if hasattr(func, "function_spec"): # RestoredFunction func_spec: "tf_ext.FunctionSpec" = getattr(func, "function_spec") input_spec: "tf_ext.TensorSignature" = getattr(func_spec, "input_signature") if input_spec is not None: return ((input_spec, {}),) else: concrete_func: t.List["tf_ext.ConcreteFunction"] = getattr( func, "concrete_functions" ) return tuple( s for conc in concrete_func for s in get_input_signatures(conc) ) else: sis: "tf_ext.InputSignature" = getattr(func, "structured_input_signature") if sis is not None: return (sis,) # NOTE: we can use internal `_arg_keywords` here. # Seems that this is a attributes of all ConcreteFunction and # does seem safe to access and use externally. if getattr(func, "_arg_keywords") is not None: return ( ( tuple(), { k: normalize_spec(v) for k, v in zip( getattr(func, "_arg_keywords"), getattr(func, "inputs") ) }, ), ) return tuple() def get_output_signature( func: "tf_ext.DecoratedFunction", ) -> t.Union[ "tf_ext.ConcreteFunction", t.Tuple[t.Any, ...], t.Dict[str, "tf_ext.TypeSpec"] ]: if hasattr(func, "function_spec"): # for RestoredFunction # assume all concrete functions have same signature concrete_function_wrapper: "tf_ext.ConcreteFunction" = getattr( func, "concrete_functions" )[0] return get_output_signature(concrete_function_wrapper) if hasattr(func, "structured_input_signature"): # for ConcreteFunction if getattr(func, "structured_outputs") is not None: outputs = getattr(func, "structured_outputs") if LazyType[t.Dict[str, "tf_ext.TensorSpec"]](dict).isinstance(outputs): return {k: normalize_spec(v) for k, v in outputs.items()} return outputs else: outputs: t.Tuple["tf_ext.TensorSpec"] = getattr(func, "outputs") return tuple(normalize_spec(v) for v in outputs) return tuple() def get_arg_names(func: "tf_ext.DecoratedFunction") -> t.Optional[t.List[str]]: if hasattr(func, "function_spec"): # for RestoredFunction func_spec: "tf_ext.FunctionSpec" = getattr(func, "function_spec") return getattr(func_spec, "arg_names") if hasattr(func, "structured_input_signature"): # for ConcreteFunction return getattr(func, "_arg_keywords") return list() def get_restored_functions( m: "tf_ext.Trackable", ) -> t.Dict[str, "tf_ext.RestoredFunction"]: function_map = {k: getattr(m, k) for k in dir(m)} return { k: v for k, v in function_map.items() if k not in TF_KERAS_DEFAULT_FUNCTIONS and hasattr(v, "function_spec") } def get_serving_default_function(m: "tf_ext.Trackable") -> "tf_ext.ConcreteFunction": if not hasattr(m, "signatures"): raise EnvironmentError(f"{type(m)} is not a valid SavedModel format.") signatures: "tf_ext.SignatureMap" = getattr(m, "signatures") func = signatures.get(tf.compat.v2.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY) # type: ignore if func is not None: return func raise BentoMLException( "Given Trackable objects doesn't contain a" " default functions from SignatureMap." " Most likely Tensorflow internal error." ) def _pretty_format_function_call(base: str, name: str, arg_names: t.Tuple[t.Any]): if arg_names: part_sigs = ", ".join(f"{k}" for k in arg_names) else: part_sigs = "" if name == "__call__": return f"{base}({part_sigs})" return f"{base}.{name}({part_sigs})" def _pretty_format_positional(positional: t.Optional["tf_ext.TensorSignature"]) -> str: if positional is not None: return f'Positional arguments ({len(positional)} total):\n {" * ".join(str(a) for a in positional)}' # noqa return "No positional arguments.\n" def pretty_format_function( function: "tf_ext.DecoratedFunction", obj: str = "<object>", name: str = "<function>", ) -> str: ret = "" outs = get_output_signature(function) sigs = get_input_signatures(function) arg_names = get_arg_names(function) if hasattr(function, "function_spec"): arg_names = getattr(function, "function_spec").arg_names else: arg_names = getattr(function, "_arg_keywords") ret += _pretty_format_function_call(obj, name, arg_names) ret += "\n------------\n" signature_descriptions = [] # type: t.List[str] for index, sig in enumerate(sigs): positional, keyword = sig signature_descriptions.append( f"Arguments Option {index + 1}:\n {_pretty_format_positional(positional)}\n Keyword arguments:\n {keyword}" ) ret += "\n\n".join(signature_descriptions) ret += f"\n\nReturn:\n {outs}\n\n" return ret def pretty_format_restored_model(model: "tf_ext.AutoTrackable") -> str: part_functions = "" restored_functions = get_restored_functions(model) for name, func in restored_functions.items(): part_functions += pretty_format_function(func, "model", name) part_functions += "\n" if get_tf_version().startswith("1"): serving_default = get_serving_default_function(model) if serving_default: part_functions += pretty_format_function( serving_default, "model", "signatures['serving_default']" ) part_functions += "\n" return f"Found restored functions:\n{part_functions}" def cast_tensor_by_spec( _input: "tf_ext.TensorLike", spec: "tf_ext.TypeSpec" ) -> "tf_ext.TensorLike": """ transform dtype & shape following spec """ if not LazyType["tf_ext.TensorSpec"]( "tensorflow.python.framework.tensor_spec.TensorSpec" ).isinstance(spec): return _input if LazyType["tf_ext.CastableTensorType"]("tf.Tensor").isinstance( _input ) or LazyType["tf_ext.CastableTensorType"]( "tensorflow.python.framework.ops.EagerTensor" ).isinstance( _input ): # TensorFlow Issues #43038 # pylint: disable=unexpected-keyword-arg, no-value-for-parameter return t.cast( "tf_ext.TensorLike", tf.cast(_input, dtype=spec.dtype, name=spec.name) ) else: return t.cast( "tf_ext.TensorLike", tf.constant(_input, dtype=spec.dtype, name=spec.name) ) class tf_function_wrapper: # pragma: no cover def __init__( self, origin_func: t.Callable[..., t.Any], arg_names: t.Optional[t.List[str]] = None, arg_specs: t.Optional[t.Tuple["tf_ext.TensorSpec"]] = None, kwarg_specs: t.Optional[t.Dict[str, "tf_ext.TensorSpec"]] = None, ) -> None: self.origin_func = origin_func self.arg_names = arg_names self.arg_specs = arg_specs self.kwarg_specs = {k: v for k, v in zip(arg_names or [], arg_specs or [])} self.kwarg_specs.update(kwarg_specs or {}) def __call__( self, *args: "tf_ext.TensorLike", **kwargs: "tf_ext.TensorLike" ) -> t.Any: if self.arg_specs is None and self.kwarg_specs is None: return self.origin_func(*args, **kwargs) for k in kwargs: if k not in self.kwarg_specs: raise TypeError(f"Function got an unexpected keyword argument {k}") arg_keys = {k for k, _ in zip(self.arg_names, args)} # type: ignore[arg-type] _ambiguous_keys = arg_keys & set(kwargs) # type: t.Set[str] if _ambiguous_keys: raise TypeError(f"got two values for arguments '{_ambiguous_keys}'") # INFO: # how signature with kwargs works? # https://github.com/tensorflow/tensorflow/blob/v2.0.0/tensorflow/python/eager/function.py#L1519 transformed_args: t.Tuple[t.Any, ...] = tuple( cast_tensor_by_spec(arg, spec) for arg, spec in zip(args, self.arg_specs) # type: ignore[arg-type] ) transformed_kwargs = { k: cast_tensor_by_spec(arg, self.kwarg_specs[k]) for k, arg in kwargs.items() } return self.origin_func(*transformed_args, **transformed_kwargs) def __getattr__(self, k: t.Any) -> t.Any: return getattr(self.origin_func, k) @classmethod def hook_loaded_model(cls, loaded_model: t.Any) -> None: funcs = get_restored_functions(loaded_model) for k, func in funcs.items(): arg_names = get_arg_names(func) sigs = get_input_signatures(func) if not sigs: continue arg_specs, kwarg_specs = sigs[0] setattr( loaded_model, k, cls( func, arg_names=arg_names, arg_specs=arg_specs, # type: ignore kwarg_specs=kwarg_specs, # type: ignore ), )
import signal import subprocess from typing import TYPE_CHECKING import psutil if TYPE_CHECKING: import typing as t def kill_subprocess_tree(p: "subprocess.Popen[t.Any]") -> None: """ Tell the process to terminate and kill all of its children. Availabe both on Windows and Linux. Note: It will return immediately rather than wait for the process to terminate. Args: p: subprocess.Popen object """ if psutil.WINDOWS: subprocess.call(["taskkill", "/F", "/T", "/PID", str(p.pid)]) else: p.terminate() def cancel_subprocess(p: "subprocess.Popen[t.Any]") -> None: if psutil.WINDOWS: p.send_signal(signal.CTRL_C_EVENT) # type: ignore else: p.send_signal(signal.SIGINT)
from __future__ import annotations import io import uuid import typing as t from typing import TYPE_CHECKING import multipart.multipart as multipart from starlette.requests import Request from starlette.responses import Response from starlette.formparsers import MultiPartMessage from starlette.datastructures import Headers from starlette.datastructures import MutableHeaders from .http import set_cookies from ...exceptions import BentoMLException if TYPE_CHECKING: from ..context import InferenceApiContext as Context _ItemsBody = t.List[t.Tuple[str, t.List[t.Tuple[bytes, bytes]], bytes]] def user_safe_decode(src: bytes, codec: str) -> str: try: return src.decode(codec) except (UnicodeDecodeError, LookupError): return src.decode("latin-1") class MultiPartParser: """ An modified version of starlette MultiPartParser. """ def __init__(self, headers: Headers, stream: t.AsyncGenerator[bytes, None]) -> None: assert ( multipart is not None ), "The `python-multipart` library must be installed to use form parsing." self.headers: Headers = headers self.stream = stream self.messages: t.List[t.Tuple[MultiPartMessage, bytes]] = list() def on_part_begin(self) -> None: message = (MultiPartMessage.PART_BEGIN, b"") self.messages.append(message) def on_part_data(self, data: bytes, start: int, end: int) -> None: message = (MultiPartMessage.PART_DATA, data[start:end]) self.messages.append(message) def on_part_end(self) -> None: message = (MultiPartMessage.PART_END, b"") self.messages.append(message) def on_header_field(self, data: bytes, start: int, end: int) -> None: message = (MultiPartMessage.HEADER_FIELD, data[start:end]) self.messages.append(message) def on_header_value(self, data: bytes, start: int, end: int) -> None: message = (MultiPartMessage.HEADER_VALUE, data[start:end]) self.messages.append(message) def on_header_end(self) -> None: message = (MultiPartMessage.HEADER_END, b"") self.messages.append(message) def on_headers_finished(self) -> None: message = (MultiPartMessage.HEADERS_FINISHED, b"") self.messages.append(message) def on_end(self) -> None: message = (MultiPartMessage.END, b"") self.messages.append(message) async def parse(self) -> _ItemsBody: # Parse the Content-Type header to get the multipart boundary. _, params = multipart.parse_options_header(self.headers["Content-Type"]) params = t.cast(t.Dict[bytes, bytes], params) charset = params.get(b"charset", b"utf-8") charset = charset.decode("latin-1") boundary = params.get(b"boundary") # Callbacks dictionary. callbacks = { "on_part_begin": self.on_part_begin, "on_part_data": self.on_part_data, "on_part_end": self.on_part_end, "on_header_field": self.on_header_field, "on_header_value": self.on_header_value, "on_header_end": self.on_header_end, "on_headers_finished": self.on_headers_finished, "on_end": self.on_end, } # Create the parser. parser = multipart.MultipartParser(boundary, callbacks) header_field = b"" header_value = b"" field_name = "" data = b"" items: _ItemsBody = [] headers: t.List[t.Tuple[bytes, bytes]] = [] # Feed the parser with data from the request. async for chunk in self.stream: parser.write(chunk) messages = list(self.messages) self.messages.clear() for message_type, message_bytes in messages: if message_type == MultiPartMessage.PART_BEGIN: field_name = "" data = b"" headers = list() elif message_type == MultiPartMessage.HEADER_FIELD: # type: ignore header_field += message_bytes elif message_type == MultiPartMessage.HEADER_VALUE: # type: ignore header_value += message_bytes elif message_type == MultiPartMessage.HEADER_END: # type: ignore field = header_field.lower() if field == b"content-disposition": _, options = multipart.parse_options_header(header_value) options = t.cast(t.Dict[bytes, bytes], options) field_name = user_safe_decode(options[b"name"], charset) elif field == b"bentoml-payload-field": field_name = user_safe_decode(header_value, charset) else: headers.append((field, header_value)) header_field = b"" header_value = b"" elif message_type == MultiPartMessage.HEADERS_FINISHED: # type: ignore assert ( field_name ), "`Content-Disposition` is not available in headers" elif message_type == MultiPartMessage.PART_DATA: # type: ignore data += message_bytes elif message_type == MultiPartMessage.PART_END: # type: ignore items.append((field_name, headers, data)) parser.finalize() return items async def populate_multipart_requests(request: Request) -> t.Dict[str, Request]: content_type_header = request.headers.get("Content-Type") content_type, _ = multipart.parse_options_header(content_type_header) assert content_type in (b"multipart/form-data", b"multipart/mixed") stream = request.stream() multipart_parser = MultiPartParser(request.headers, stream) try: form = await multipart_parser.parse() except multipart.MultipartParseError: raise BentoMLException("Invalid multipart requests") reqs: dict[str, Request] = dict() for field_name, headers, data in form: scope = dict(request.scope) ori_headers = dict(scope.get("headers", dict())) ori_headers = t.cast(t.Dict[bytes, bytes], ori_headers) ori_headers.update(dict(headers)) scope["headers"] = list(ori_headers.items()) req = Request(scope) req._body = data reqs[field_name] = req return reqs def _get_disp_filename(headers: MutableHeaders) -> t.Optional[bytes]: if "content-disposition" in headers: _, options = multipart.parse_options_header(headers["content-disposition"]) if b"filename" in options: return t.cast(bytes, options[b"filename"]) return None async def concat_to_multipart_response( responses: t.Mapping[str, Response], ctx: Context | None ) -> Response: boundary = uuid.uuid4().hex boundary_bytes = boundary.encode("latin1") writer = io.BytesIO() for field_name, resp in responses.items(): writer.write(b"--%b\r\n" % boundary_bytes) # headers filename = _get_disp_filename(resp.headers) if filename: writer.write( b'Content-Disposition: form-data; name="%b"; filename="%b"\r\n' % (field_name.encode("latin1"), filename) ) else: writer.write( b'Content-Disposition: form-data; name="%b"\r\n' % field_name.encode("latin1") ) for header_key, header_value in resp.raw_headers: if header_key == b"content-disposition": continue writer.write(b"%b: %b\r\n" % (header_key, header_value)) writer.write(b"\r\n") # body writer.write(resp.body) writer.write(b"\r\n") writer.write(b"--%b--\r\n" % boundary_bytes) if ctx is not None: res = Response( writer.getvalue(), headers=ctx.response.metadata, # type: ignore (pyright thinks the type is dict[Unknown, Unknown]) media_type=f"multipart/form-data; boundary={boundary}", status_code=ctx.response.status_code, ) set_cookies(res, ctx.response.cookies) return res else: return Response( writer.getvalue(), media_type=f"multipart/form-data; boundary={boundary}" )
import os import pathlib from urllib.parse import unquote from urllib.parse import urlparse from urllib.request import url2pathname import psutil def path_to_uri(path: str) -> str: """ Convert a path to a URI. Args: path: Path to convert to URI. Returns: URI string. (quoted, absolute) """ path = os.path.abspath(path) if psutil.WINDOWS: return pathlib.PureWindowsPath(path).as_uri() if psutil.POSIX: return pathlib.PurePosixPath(path).as_uri() raise ValueError("Unsupported OS") def uri_to_path(uri: str) -> str: """ Convert a file URI to a path. Args: uri: URI to convert to path. Returns: Path string. (unquoted) """ parsed = urlparse(uri) if parsed.scheme not in ("file", "filesystem", "unix"): raise ValueError("Unsupported URI scheme") host = "{0}{0}{mnt}{0}".format(os.path.sep, mnt=parsed.netloc) return os.path.normpath(os.path.join(host, url2pathname(unquote(parsed.path))))
from __future__ import annotations from typing import TYPE_CHECKING import attr if TYPE_CHECKING: import starlette.responses @attr.define class Cookie: key: str value: str max_age: int | None expires: int | None path: str domain: str | None secure: bool httponly: bool samesite: str def set_cookies(response: starlette.responses.Response, cookies: list[Cookie]): for cookie in cookies: response.set_cookie( cookie.key, cookie.value, max_age=cookie.max_age, # type: ignore (bad starlette types) expires=cookie.expires, # type: ignore (bad starlette types) path=cookie.path, domain=cookie.domain, # type: ignore (bad starlette types) secure=cookie.secure, httponly=cookie.httponly, samesite=cookie.samesite, )
# CSV utils following https://tools.ietf.org/html/rfc4180 import typing as t def csv_splitlines(string: str) -> t.Iterator[str]: if '"' in string: def _iter_line(line: str) -> t.Iterator[str]: quoted = False last_cur = 0 for i, c in enumerate(line): if c == '"': quoted = not quoted if not quoted and string[i : i + 1] == "\n": if i == 0 or string[i - 1] != "\r": yield line[last_cur:i] last_cur = i + 1 else: yield line[last_cur : i - 1] last_cur = i + 1 yield line[last_cur:] return _iter_line(string) return iter(string.splitlines()) def csv_split(string: str, delimiter: str) -> t.Iterator[str]: if '"' in string: d_len = len(delimiter) def _iter_line(line: str) -> t.Iterator[str]: quoted = False last_cur = 0 for i, c in enumerate(line): if c == '"': quoted = not quoted if not quoted and string[i : i + d_len] == delimiter: yield line[last_cur:i] last_cur = i + d_len yield line[last_cur:] return _iter_line(string) else: return iter(string.split(delimiter)) def csv_row(tds: t.Iterable) -> str: return ",".join(csv_quote(td) for td in tds) def csv_unquote(string: str) -> str: if '"' in string: string = string.strip() assert string[0] == '"' and string[-1] == '"' return string[1:-1].replace('""', '"') return string def csv_quote(td: t.Union[int, str]) -> str: """ >>> csv_quote(1) '1' >>> csv_quote('string') 'string' >>> csv_quote('a,b"c') '"a,b""c"' >>> csv_quote(' ') '" "' """ if td is None: td = "" elif not isinstance(td, str): td = str(td) if "\n" in td or '"' in td or "," in td or not td.strip(): return td.replace('"', '""').join('""') return td
try: import importlib.metadata as importlib_metadata except ImportError: import importlib_metadata get_pkg_version = importlib_metadata.version
import json import typing as t from dataclasses import asdict from dataclasses import fields as get_fields from dataclasses import is_dataclass class DataclassJsonEncoder(json.JSONEncoder): """Special json encoder for numpy types""" def default(self, o: t.Any): # pylint: disable=method-hidden if is_dataclass(o): if hasattr(o, "to_json"): return o.to_json() else: return asdict(o) return super().default(o) class json_serializer: def __init__(self, fields: t.Optional[t.List[str]] = None, compat: bool = False): self.fields = fields self.compat = compat @staticmethod def _extract_nested(obj: t.Any): if hasattr(obj, "to_json"): return obj.to_json() return obj T = t.TypeVar( "T", ) def __call__(self, klass: t.Type[T]) -> t.Type[T]: if not is_dataclass(klass): raise TypeError( f"{self.__class__.__name__} only accepts dataclasses, " f"got {klass.__name__}" ) default_map = { f.name: f.default_factory() if callable(f.default_factory) else f.default for f in get_fields(klass) } if self.fields is None: _fields = tuple(k for k in default_map.keys() if not k.startswith("_")) else: _fields = self.fields if self.compat: def to_json_compat(data_obj: t.Any): return { k: self._extract_nested(getattr(data_obj, k)) for k in _fields if default_map[k] != getattr(data_obj, k) } klass.to_json = to_json_compat # type: ignore else: def to_json(data_obj: t.Any): return {k: self._extract_nested(getattr(data_obj, k)) for k in _fields} klass.to_json = to_json # type: ignore return klass
from __future__ import annotations import typing as t import logging import pathlib from typing import TYPE_CHECKING from urllib.parse import urlparse from circus.plugins import CircusPlugin # type: ignore[reportMissingTypeStubs] if TYPE_CHECKING: from circus.arbiter import Arbiter # type: ignore[reportMissingTypeStubs] from circus.sockets import CircusSocket # type: ignore[reportMissingTypeStubs] from circus.watcher import Watcher # type: ignore[reportMissingTypeStubs] logger = logging.getLogger(__name__) def create_circus_socket_from_uri( uri: str, *args: t.Any, name: str = "", **kwargs: t.Any, ) -> CircusSocket: from circus.sockets import CircusSocket # type: ignore[reportMissingTypeStubs] from bentoml._internal.utils.uri import uri_to_path parsed = urlparse(uri) if parsed.scheme in ("file", "unix"): return CircusSocket( name=name, path=uri_to_path(uri), *args, **kwargs, ) elif parsed.scheme == "tcp": return CircusSocket( name=name, host=parsed.hostname, port=parsed.port, *args, **kwargs, ) else: raise ValueError(f"Unsupported URI scheme: {parsed.scheme}") def create_standalone_arbiter(watchers: list[Watcher], **kwargs: t.Any) -> Arbiter: from circus.arbiter import Arbiter # type: ignore[reportMissingTypeStubs] from . import reserve_free_port with reserve_free_port() as endpoint_port: with reserve_free_port() as pubsub_port: return Arbiter( watchers, endpoint=f"tcp://127.0.0.1:{endpoint_port}", pubsub_endpoint=f"tcp://127.0.0.1:{pubsub_port}", **kwargs, ) # TODO: use svc.build_args.include/exclude as default files to watch # TODO: watch changes in model store when "latest" model tag is used class BentoChangeReloader(CircusPlugin): """ A circus plugin that reloads the BentoService when the service code changes. Args: working_dir: The directory of the bento service. reload_delay: The delay in seconds between checking for changes. """ name = "bento_change_reloader" config: dict[str, t.Any] def __init__(self, *args: t.Any, **config: t.Any): assert "bento_identifier" in config, "`bento_identifier` is required" assert "working_dir" in config, "`working_dir` is required" super().__init__(*args, **config) # type: ignore (unfinished types for circus) self.name = self.config.get("name") working_dir: str = self.config["working_dir"] # circus/plugins/__init__.py:282 -> converts all given configs to dict[str, str] self.reload_delay: float = float(self.config.get("reload_delay", 1)) self.file_watcher = PyFileChangeWatcher([working_dir]) def look_after(self): if self.file_watcher.is_file_changed(): logger.info("Restarting...") self.call("restart", name="*") # type: ignore self.file_watcher.reset() def handle_init(self): from tornado import ioloop self.period = ioloop.PeriodicCallback(self.look_after, self.reload_delay * 1000) self.period.start() def handle_stop(self): self.period.stop() def handle_recv(self, data: t.Any): pass class PyFileChangeWatcher: def __init__( self, watch_dirs: list[pathlib.Path] | list[str] | None = None, ) -> None: self.mtimes: dict[pathlib.Path, float] = {} if not watch_dirs: watch_dirs = [pathlib.Path.cwd()] self.watch_dirs = [ pathlib.Path(d) if isinstance(d, str) else d for d in watch_dirs ] logger.info(f"Watching directories: {', '.join(map(str, self.watch_dirs))}") def is_file_changed(self) -> bool: for file in self.iter_files(): try: mtime = file.stat().st_mtime except OSError: # pragma: nocover continue old_time = self.mtimes.get(file) if old_time is None: self.mtimes[file] = mtime continue elif mtime > old_time: display_path = str(file) try: display_path = str(file.relative_to(pathlib.Path.cwd())) except ValueError: pass message = "Detected file change in '%s'" logger.warning(message, display_path) return True return False def reset(self) -> None: self.mtimes = {} def iter_files(self) -> t.Iterator[pathlib.Path]: for reload_dir in self.watch_dirs: for path in list(reload_dir.rglob("*.py")): yield path.resolve()
import typing as t from typing import TYPE_CHECKING from .. import calc_dir_size from .schemas import BentoBuildEvent if TYPE_CHECKING: from ...bento.bento import Bento def _cli_bentoml_build_event( cmd_group: str, cmd_name: str, return_value: "t.Optional[Bento]", ) -> BentoBuildEvent: # pragma: no cover if return_value is not None: bento = return_value return BentoBuildEvent( cmd_group=cmd_group, cmd_name=cmd_name, bento_creation_timestamp=bento.info.creation_time, bento_size_in_kb=calc_dir_size(bento.path_of("/")) / 1024, model_size_in_kb=calc_dir_size(bento.path_of("/models")) / 1024, num_of_models=len(bento.info.models), num_of_runners=len(bento.info.runners), model_types=[m.module for m in bento.info.models], runnable_types=[r.runnable_type for r in bento.info.runners], ) else: return BentoBuildEvent( cmd_group=cmd_group, cmd_name=cmd_name, ) cli_events_map = {"cli": {"build": _cli_bentoml_build_event}}
import os import typing as t import logging import secrets import threading import contextlib from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone from functools import wraps from functools import lru_cache import attr import requests from simple_di import inject from simple_di import Provide from .schemas import EventMeta from .schemas import ServeInitEvent from .schemas import TrackingPayload from .schemas import CommonProperties from .schemas import ServeUpdateEvent from ...configuration.containers import BentoMLContainer from ...configuration.containers import DeploymentContainer if TYPE_CHECKING: P = t.ParamSpec("P") T = t.TypeVar("T") AsyncFunc = t.Callable[P, t.Coroutine[t.Any, t.Any, t.Any]] from bentoml import Service from ...server.metrics.prometheus import PrometheusClient logger = logging.getLogger(__name__) BENTOML_DO_NOT_TRACK = "BENTOML_DO_NOT_TRACK" USAGE_TRACKING_URL = "https://t.bentoml.com" SERVE_USAGE_TRACKING_INTERVAL_SECONDS = int(12 * 60 * 60) # every 12 hours USAGE_REQUEST_TIMEOUT_SECONDS = 1 @lru_cache(maxsize=1) def do_not_track() -> bool: # Returns True if and only if the environment variable is defined and has value True. # The function is cached for better performance. return os.environ.get(BENTOML_DO_NOT_TRACK, str(False)).lower() == "true" @lru_cache(maxsize=1) def _usage_event_debugging() -> bool: # For BentoML developers only - debug and print event payload if turned on return os.environ.get("__BENTOML_DEBUG_USAGE", str(False)).lower() == "true" def slient(func: "t.Callable[P, T]") -> "t.Callable[P, T]": # pragma: no cover # Slient errors when tracking @wraps(func) def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Any: try: return func(*args, **kwargs) except Exception as err: # pylint: disable=broad-except if _usage_event_debugging(): logger.info(f"Tracking Error: {err}") else: logger.debug(f"Tracking Error: {err}") return wrapper @attr.define class ServeInfo: serve_id: str serve_started_timestamp: datetime def get_serve_info() -> ServeInfo: # pragma: no cover # Returns a safe token for serve as well as timestamp of creating this token return ServeInfo( serve_id=secrets.token_urlsafe(32), serve_started_timestamp=datetime.now(timezone.utc), ) @inject def get_payload( event_properties: EventMeta, session_id: str = Provide[BentoMLContainer.session_id], ) -> t.Dict[str, t.Any]: return TrackingPayload( session_id=session_id, common_properties=CommonProperties(), event_properties=event_properties, event_type=event_properties.event_name, ).to_dict() @slient def track( event_properties: EventMeta, ): if do_not_track(): return payload = get_payload(event_properties=event_properties) if _usage_event_debugging(): # For internal debugging purpose global SERVE_USAGE_TRACKING_INTERVAL_SECONDS # pylint: disable=global-statement SERVE_USAGE_TRACKING_INTERVAL_SECONDS = 5 logger.info("Tracking Payload: %s", payload) return requests.post( USAGE_TRACKING_URL, json=payload, timeout=USAGE_REQUEST_TIMEOUT_SECONDS ) @inject def _track_serve_init( svc: "t.Optional[Service]", production: bool, serve_info: ServeInfo = Provide[DeploymentContainer.serve_info], ): if svc.bento is not None: bento = svc.bento event_properties = ServeInitEvent( serve_id=serve_info.serve_id, serve_from_bento=True, production=production, bento_creation_timestamp=bento.info.creation_time, num_of_models=len(bento.info.models), num_of_runners=len(svc.runners), num_of_apis=len(bento.info.apis), model_types=[m.module for m in bento.info.models], runnable_types=[r.runnable_type for r in bento.info.runners], api_input_types=[api.input_type for api in bento.info.apis], api_output_types=[api.output_type for api in bento.info.apis], ) else: event_properties = ServeInitEvent( serve_id=serve_info.serve_id, serve_from_bento=False, production=production, bento_creation_timestamp=None, num_of_models=len( set( svc.models + [model for runner in svc.runners for model in runner.models] ) ), num_of_runners=len(svc.runners), num_of_apis=len(svc.apis.keys()), runnable_types=[r.runnable_class.__name__ for r in svc.runners], api_input_types=[api.input.__class__.__name__ for api in svc.apis.values()], api_output_types=[ api.output.__class__.__name__ for api in svc.apis.values() ], ) track(event_properties) EXCLUDE_PATHS = {"/docs.json", "/livez", "/healthz", "/readyz"} def get_metrics_report( metrics_client, ) -> t.List[t.Dict[str, t.Union[str, float]]]: metrics_text = metrics_client.generate_latest().decode() if not metrics_text: return [] from prometheus_client.parser import text_string_to_metric_families for metric in text_string_to_metric_families(metrics_text): # Searching for the metric BENTOML_{service_name}_request of type Counter if ( metric.type == "counter" and metric.name.startswith("BENTOML_") and metric.name.endswith("_request") ): return [ {**sample.labels, "value": sample.value} for sample in metric.samples if "endpoint" in sample.labels # exclude common infra paths and sample.labels["endpoint"] not in EXCLUDE_PATHS # exclude static_content prefix and not sample.labels["endpoint"].startswith("/static_content/") ] return [] @inject @contextlib.contextmanager def track_serve( svc: "t.Optional[Service]", production: bool, metrics_client: "PrometheusClient" = Provide[DeploymentContainer.metrics_client], serve_info: ServeInfo = Provide[DeploymentContainer.serve_info], ): # pragma: no cover if do_not_track(): yield return _track_serve_init(svc, production) stop_event = threading.Event() @slient def loop() -> t.NoReturn: # type: ignore while not stop_event.wait(SERVE_USAGE_TRACKING_INTERVAL_SECONDS): now = datetime.now(timezone.utc) event_properties = ServeUpdateEvent( serve_id=serve_info.serve_id, production=production, triggered_at=now, duration_in_seconds=(now - serve_info.serve_started_timestamp).seconds, metrics=get_metrics_report(metrics_client), ) track(event_properties) tracking_thread = threading.Thread(target=loop, daemon=True) try: tracking_thread.start() yield finally: stop_event.set() tracking_thread.join()
from .schemas import CliEvent from .schemas import ModelSaveEvent from .schemas import BentoBuildEvent from .schemas import ServeUpdateEvent from .cli_events import cli_events_map from .usage_stats import track from .usage_stats import ServeInfo from .usage_stats import track_serve from .usage_stats import get_serve_info from .usage_stats import BENTOML_DO_NOT_TRACK __all__ = [ "track", "track_serve", "get_serve_info", "ServeInfo", "BENTOML_DO_NOT_TRACK", "CliEvent", "ModelSaveEvent", "BentoBuildEvent", "ServeUpdateEvent", "cli_events_map", ]
import os import re import uuid import typing as t from abc import ABC from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone from platform import platform from platform import python_version from functools import lru_cache import attr import yaml import psutil import attr.converters from simple_di import inject from simple_di import Provide from ...utils import bentoml_cattr from ...configuration import BENTOML_VERSION from ...configuration.containers import BentoMLContainer from ...yatai_rest_api_client.config import get_config_path from ...yatai_rest_api_client.config import get_current_context if TYPE_CHECKING: P = t.ParamSpec("P") GenericFunction = t.Callable[P, t.Any] # Refers to bentoml/yatai-deployment-operator/common/consts/consts.go ENV_YATAI_VERSION = "YATAI_T_VERSION" ENV_YATAI_ORG_UID = "YATAI_T_ORG_UID" ENV_YATAI_DEPLOYMENT_UID = "YATAI_T_DEPLOYMENT_UID" ENV_YATAI_CLUSTER_UID = "YATAI_T_CLUSTER_UID" @lru_cache(maxsize=1) def get_platform() -> str: return platform(aliased=True) @lru_cache(maxsize=1) def get_python_version() -> str: return python_version() @attr.define class ClientInfo: id: str creation_timestamp: datetime @inject @lru_cache(maxsize=1) def get_client_info( bentoml_home: str = Provide[BentoMLContainer.bentoml_home], ) -> t.Optional[ClientInfo]: CLIENT_INFO_FILE_PATH = os.path.join(bentoml_home, "client_id") if os.path.exists(CLIENT_INFO_FILE_PATH): with open(CLIENT_INFO_FILE_PATH, "r", encoding="utf-8") as f: client_info = yaml.safe_load(f) return bentoml_cattr.structure(client_info, ClientInfo) else: # Create new client id new_client_info = ClientInfo( id=str(uuid.uuid4()), creation_timestamp=datetime.now(timezone.utc), ) # write client info to ~/bentoml/client_id with open(CLIENT_INFO_FILE_PATH, "w", encoding="utf-8") as f: yaml.dump(attr.asdict(new_client_info), stream=f) return new_client_info @lru_cache(maxsize=1) def get_yatai_user_email() -> t.Optional[str]: if os.path.exists(get_config_path()): return get_current_context().email @lru_cache(maxsize=1) def is_interactive() -> bool: import __main__ as main return not hasattr(main, "__file__") @lru_cache(maxsize=1) def in_notebook() -> bool: try: from IPython import get_ipython if "IPKernelApp" not in get_ipython().config: # pragma: no cover return False except ImportError: return False except AttributeError: return False return True @attr.define class CommonProperties: # when the event is triggered timestamp: datetime = attr.field(factory=lambda: datetime.now(timezone.utc)) # environment related platform: str = attr.field(factory=get_platform) bentoml_version: str = attr.field(default=BENTOML_VERSION) python_version: str = attr.field(factory=get_python_version) is_interactive: bool = attr.field(factory=is_interactive) in_notebook: bool = attr.field(factory=in_notebook) # resource related memory_usage_percent: float = attr.field(init=False) total_memory_in_mb: float = attr.field(init=False) # client related client: ClientInfo = attr.field(factory=get_client_info) yatai_user_email: t.Optional[str] = attr.field(factory=get_yatai_user_email) yatai_version: t.Optional[str] = attr.field( default=os.environ.get(ENV_YATAI_VERSION, None) ) yatai_org_uid: t.Optional[str] = attr.field( default=os.environ.get(ENV_YATAI_ORG_UID, None) ) yatai_cluster_uid: t.Optional[str] = attr.field( default=os.environ.get(ENV_YATAI_CLUSTER_UID, None) ) yatai_deployment_uid: t.Optional[str] = attr.field( default=os.environ.get(ENV_YATAI_DEPLOYMENT_UID, None) ) def __attrs_post_init__(self): self.total_memory_in_mb = int(psutil.virtual_memory().total / 1024.0 / 1024.0) proc = psutil.Process(os.getpid()) with proc.oneshot(): self.memory_usage_percent = proc.memory_percent() class EventMeta(ABC): @property def event_name(self): # camel case to snake case event_name = re.sub(r"(?<!^)(?=[A-Z])", "_", self.__class__.__name__).lower() # remove "_event" suffix suffix_to_remove = "_event" if event_name.endswith(suffix_to_remove): event_name = event_name[: -len(suffix_to_remove)] return event_name @attr.define class CliEvent(EventMeta): cmd_group: str cmd_name: str duration_in_ms: float = attr.field(default=0) error_type: t.Optional[str] = attr.field(default=None) return_code: t.Optional[int] = attr.field(default=None) @attr.define class BentoBuildEvent(CliEvent): bento_creation_timestamp: t.Optional[datetime] = attr.field(default=None) bento_size_in_kb: float = attr.field(default=0) model_size_in_kb: float = attr.field(default=0) num_of_models: int = attr.field(default=0) num_of_runners: int = attr.field(default=0) model_types: t.List[str] = attr.field(factory=list) runnable_types: t.List[str] = attr.field(factory=list) @attr.define class ModelSaveEvent(EventMeta): module: str model_size_in_kb: float @attr.define class ServeInitEvent(EventMeta): serve_id: str production: bool serve_from_bento: bool bento_creation_timestamp: t.Optional[datetime] num_of_models: int = attr.field(default=0) num_of_runners: int = attr.field(default=0) num_of_apis: int = attr.field(default=0) model_types: t.List[str] = attr.field(factory=list) runnable_types: t.List[str] = attr.field(factory=list) api_input_types: t.List[str] = attr.field(factory=list) api_output_types: t.List[str] = attr.field(factory=list) @attr.define class ServeUpdateEvent(EventMeta): serve_id: str production: bool triggered_at: datetime duration_in_seconds: int metrics: t.List[str] = attr.field(factory=list) ALL_EVENT_TYPES = t.Union[ CliEvent, ModelSaveEvent, BentoBuildEvent, ServeInitEvent, ServeUpdateEvent, EventMeta, ] @attr.define class TrackingPayload: session_id: str event_properties: ALL_EVENT_TYPES common_properties: CommonProperties event_type: str def to_dict(self): return bentoml_cattr.unstructure(self)
from .model import Model from .model import copy_model from .model import ModelStore from .model import ModelContext from .model import ModelOptions # Deprecated. Use framework module local constants and name the saved files with API # Version in mind. E.g.: # api_v1_model_file_name = "saved_model.pkl" # api_v2_model_file_name = "torch_model.pth" SAVE_NAMESPACE = "saved_model" JSON_EXT = ".json" PKL_EXT = ".pkl" PTH_EXT = ".pth" TXT_EXT = ".txt" YAML_EXT = ".yaml" __all__ = ["Model", "ModelStore", "ModelContext", "ModelOptions", "copy_model"]
from __future__ import annotations import io import typing as t import logging import importlib from sys import version_info as pyver from typing import overload from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone import fs import attr import yaml import fs.errors import fs.mirror import cloudpickle from fs.base import FS from cattr.gen import override from cattr.gen import make_dict_unstructure_fn from simple_di import inject from simple_di import Provide from ..tag import Tag from ..store import Store from ..store import StoreItem from ..types import MetadataDict from ..utils import bentoml_cattr from ..utils import label_validator from ..utils import metadata_validator from ..runner import Runner from ..runner import Runnable from ...exceptions import NotFound from ...exceptions import BentoMLException from ..configuration import BENTOML_VERSION from ..configuration.containers import BentoMLContainer if TYPE_CHECKING: from ..types import AnyType from ..types import PathType class ModelSignatureDict(t.TypedDict, total=False): batch_dim: tuple[int, int] | int batchable: bool input_spec: tuple[AnyType] | AnyType | None output_spec: AnyType | None T = t.TypeVar("T") logger = logging.getLogger(__name__) PYTHON_VERSION: str = f"{pyver.major}.{pyver.minor}.{pyver.micro}" MODEL_YAML_FILENAME = "model.yaml" CUSTOM_OBJECTS_FILENAME = "custom_objects.pkl" @attr.define class ModelOptions: def with_options(self, **kwargs: t.Any) -> ModelOptions: return attr.evolve(self, **kwargs) def to_dict(self: ModelOptions) -> dict[str, t.Any]: return attr.asdict(self) bentoml_cattr.register_structure_hook(ModelOptions, lambda d, cls: cls(**d)) bentoml_cattr.register_unstructure_hook(ModelOptions, lambda v: v.to_dict()) # type: ignore # pylint: disable=unnecessary-lambda # lambda required @attr.define(repr=False, eq=False, init=False) class Model(StoreItem): _tag: Tag __fs: FS _info: ModelInfo _custom_objects: dict[str, t.Any] | None = None _runnable: t.Type[Runnable] | None = attr.field(init=False, default=None) def __init__( self, tag: Tag, model_fs: FS, info: ModelInfo, custom_objects: dict[str, t.Any] | None = None, *, _internal: bool = False, ): if not _internal: raise BentoMLException( "Model cannot be instantiated directly directly; use bentoml.<framework>.save or bentoml.models.get instead" ) self.__attrs_init__(tag, model_fs, info, custom_objects) # type: ignore (no types for attrs init) @staticmethod def _export_ext() -> str: return "bentomodel" @property def tag(self) -> Tag: return self._tag @property def _fs(self) -> FS: return self.__fs @property def info(self) -> ModelInfo: return self._info @property def custom_objects(self) -> t.Dict[str, t.Any]: if self._custom_objects is None: if self._fs.isfile(CUSTOM_OBJECTS_FILENAME): with self._fs.open(CUSTOM_OBJECTS_FILENAME, "rb") as cofile: self._custom_objects: dict[str, t.Any] | None = cloudpickle.load( cofile ) if not isinstance(self._custom_objects, dict): raise ValueError("Invalid custom objects found.") else: self._custom_objects: dict[str, t.Any] | None = {} return self._custom_objects def __eq__(self, other: object) -> bool: return isinstance(other, Model) and self._tag == other._tag def __hash__(self) -> int: return hash(self._tag) @staticmethod def create( name: str, *, module: str, api_version: str, signatures: ModelSignaturesType, labels: dict[str, str] | None = None, options: ModelOptions | None = None, custom_objects: dict[str, t.Any] | None = None, metadata: dict[str, t.Any] | None = None, context: ModelContext, ) -> Model: """Create a new Model instance in temporary filesystem used for serializing model artifacts and save to model store Args: name: model name in target model store, model version will be automatically generated module: import path of module used for saving/loading this model, e.g. "bentoml.tensorflow" labels: user-defined labels for managing models, e.g. team=nlp, stage=dev options: default options for loading this model, defined by runner implementation, e.g. xgboost booster_params custom_objects: user-defined additional python objects to be saved alongside the model, e.g. a tokenizer instance, preprocessor function, model configuration json metadata: user-defined metadata for storing model training context information or model evaluation metrics, e.g. dataset version, training parameters, model scores context: Environment context managed by BentoML for loading model, e.g. {"framework:" "tensorflow", "framework_version": _tf_version} Returns: object: Model instance created in temporary filesystem """ tag = Tag(name).make_new_version() labels = {} if labels is None else labels metadata = {} if metadata is None else metadata options = ModelOptions() if options is None else options model_fs = fs.open_fs(f"temp://bentoml_model_{name}") res = Model( tag, model_fs, ModelInfo( tag=tag, module=module, api_version=api_version, signatures=signatures, labels=labels, options=options, metadata=metadata, context=context, ), custom_objects=custom_objects, _internal=True, ) return res @inject def save( self, model_store: ModelStore = Provide[BentoMLContainer.model_store] ) -> Model: self._save(model_store) return self def _save(self, model_store: ModelStore) -> Model: if not self.validate(): logger.warning(f"Failed to create Model for {self.tag}, not saving.") raise BentoMLException("Failed to save Model because it was invalid") with model_store.register(self.tag) as model_path: out_fs = fs.open_fs(model_path, create=True, writeable=True) fs.mirror.mirror(self._fs, out_fs, copy_if_newer=False) self._fs.close() self.__fs = out_fs logger.info(f"Successfully saved {self}") return self @classmethod def from_fs(cls: t.Type[Model], item_fs: FS) -> Model: try: with item_fs.open(MODEL_YAML_FILENAME, "r") as model_yaml: info = ModelInfo.from_yaml_file(model_yaml) except fs.errors.ResourceNotFound: raise BentoMLException( f"Failed to load bento model because it does not contain a '{MODEL_YAML_FILENAME}'" ) res = Model(tag=info.tag, model_fs=item_fs, info=info, _internal=True) if not res.validate(): raise BentoMLException( f"Failed to load bento model because it contains an invalid '{MODEL_YAML_FILENAME}'" ) return res @property def path(self) -> str: return self.path_of("/") def path_of(self, item: str) -> str: return self._fs.getsyspath(item) def flush(self): self._write_info() self._write_custom_objects() def _write_info(self): with self._fs.open(MODEL_YAML_FILENAME, "w", encoding="utf-8") as model_yaml: self.info.dump(t.cast(io.StringIO, model_yaml)) def _write_custom_objects(self): # pickle custom_objects if it is not None and not empty if self.custom_objects: with self._fs.open(CUSTOM_OBJECTS_FILENAME, "wb") as cofile: cloudpickle.dump(self.custom_objects, cofile) # type: ignore (incomplete cloudpickle types) @property def creation_time(self) -> datetime: return self.info.creation_time def validate(self): return self._fs.isfile(MODEL_YAML_FILENAME) def __str__(self): return f'Model(tag="{self.tag}")' def __repr__(self): return f'Model(tag="{self.tag}", path="{self.path}")' def to_runner( self, name: str = "", cpu: int | None = None, nvidia_gpu: int | None = None, custom_resources: dict[str, float] | None = None, max_batch_size: int | None = None, max_latency_ms: int | None = None, method_configs: dict[str, dict[str, int]] | None = None, ) -> Runner: """ TODO(chaoyu): add docstring Args: name: cpu: nvidia_gpu: custom_resources: max_batch_size: max_latency_ms: runnable_method_configs: Returns: """ return Runner( self.to_runnable(), name=name if name != "" else self.tag.name, models=[self], cpu=cpu, nvidia_gpu=nvidia_gpu, custom_resources=custom_resources, max_batch_size=max_batch_size, max_latency_ms=max_latency_ms, method_configs=method_configs, ) def to_runnable(self) -> t.Type[Runnable]: if self._runnable is None: module = importlib.import_module(self.info.module) self._runnable = module.get_runnable(self) return self._runnable def with_options(self, **kwargs: t.Any) -> Model: res = Model( self._tag, self._fs, self.info.with_options(**kwargs), self._custom_objects, _internal=True, ) return res class ModelStore(Store[Model]): def __init__(self, base_path: "t.Union[PathType, FS]"): super().__init__(base_path, Model) @attr.frozen class ModelContext: framework_name: str framework_versions: t.Dict[str, str] bentoml_version: str = attr.field(default=BENTOML_VERSION) python_version: str = attr.field(default=PYTHON_VERSION) @staticmethod def from_dict(data: dict[str, str | dict[str, str]] | ModelContext) -> ModelContext: if isinstance(data, ModelContext): return data return bentoml_cattr.structure(data, ModelContext) def to_dict(self: ModelContext) -> dict[str, str | dict[str, str]]: return bentoml_cattr.unstructure(self) # type: ignore (incomplete cattr types) # Remove after attrs support ForwardRef natively attr.resolve_types(ModelContext, globals(), locals()) @attr.frozen class ModelSignature: """ A model signature represents a method on a model object that can be called. This information is used when creating BentoML runners for this model. Note that anywhere a ``ModelSignature`` is used, a ``dict`` with keys corresponding to the fields can be used instead. For example, instead of ``{"predict": ModelSignature(batchable=True)}``, one can pass ``{"predict": {"batchable": True}}``. Fields: batchable: Whether multiple API calls to this predict method should be batched by the BentoML runner. batch_dim: The dimension(s) that contain multiple data when passing to this prediction method. For example, if you have two inputs you want to run prediction on, ``[1, 2]`` and ``[3, 4]``, if the array you would pass to the predict method would be ``[[1, 2], [3, 4]]``, then the batch dimension would be ``0``. If the array you would pass to the predict method would be ``[[1, 3], [2, 4]]``, then the batch dimension would be ``1``. If there are multiple arguments to the predict method and there is only one batch dimension supplied, all arguments will use that batch dimension. Example: .. code-block:: python # Save two models with `predict` method that supports taking input batches on the dimension 0 and the other on dimension 1: bentoml.pytorch.save_model("demo0", model_0, signatures={"predict": {"batchable": True, "batch_dim": 0}}) bentoml.pytorch.save_model("demo1", model_1, signatures={"predict": {"batchable": True, "batch_dim": 1}}) # if the following calls are batched, the input to the actual predict method on the # model.predict method would be [[1, 2], [3, 4], [5, 6]] runner0 = bentoml.pytorch.get("demo0:latest").to_runner() runner0.init_local() runner0.predict.run(np.array([[1, 2], [3, 4]])) runner0.predict.run(np.array([[5, 6]])) # if the following calls are batched, the input to the actual predict method on the # model.predict would be [[1, 2, 5], [3, 4, 6]] runner1 = bentoml.pytorch.get("demo1:latest").to_runner() runner1.init_local() runner1.predict.run(np.array([[1, 2], [3, 4]])) runner1.predict.run(np.array([[5], [6]])) Expert API: The batch dimension can also be a tuple of (input batch dimension, output batch dimension). For example, if the predict method should have its input batched along the first axis and its output batched along the zeroth axis, ``batch_dim`` can be set to ``(1, 0)``. input_spec: Reserved for future use. output_spec: Reserved for future use. """ batchable: bool = False batch_dim: t.Tuple[int, int] = (0, 0) # TODO: define input/output spec struct input_spec: t.Any = None output_spec: t.Any = None @staticmethod def from_dict(data: ModelSignatureDict) -> ModelSignature: if "batch_dim" in data and isinstance(data["batch_dim"], int): formated_data = dict(data, batch_dim=(data["batch_dim"], data["batch_dim"])) else: formated_data = data return bentoml_cattr.structure(formated_data, ModelSignature) @staticmethod def convert_signatures_dict( data: dict[str, ModelSignatureDict | ModelSignature] ) -> dict[str, ModelSignature]: return { k: ModelSignature.from_dict(v) if isinstance(v, dict) else v for k, v in data.items() } # Remove after attrs support ForwardRef natively attr.resolve_types(ModelSignature, globals(), locals()) if TYPE_CHECKING: ModelSignaturesType: t.TypeAlias = ( dict[str, ModelSignature] | dict[str, ModelSignatureDict] ) def model_signature_encoder(model_signature: ModelSignature) -> dict[str, t.Any]: encoded: dict[str, t.Any] = { "batchable": model_signature.batchable, } # ignore batch_dim if batchable is False if model_signature.batchable: encoded["batch_dim"] = model_signature.batch_dim if model_signature.input_spec is not None: encoded["input_spec"] = model_signature.input_spec if model_signature.output_spec is not None: encoded["output_spec"] = model_signature.output_spec return encoded bentoml_cattr.register_unstructure_hook(ModelSignature, model_signature_encoder) @attr.define(repr=False, eq=False, frozen=True) class ModelInfo: tag: Tag name: str version: str module: str labels: t.Dict[str, str] = attr.field(validator=label_validator) options: ModelOptions # TODO: make metadata a MetadataDict; this works around a bug in attrs metadata: t.Dict[str, t.Any] = attr.field( validator=metadata_validator, converter=dict ) context: ModelContext = attr.field() signatures: t.Dict[str, ModelSignature] = attr.field( converter=ModelSignature.convert_signatures_dict ) api_version: str creation_time: datetime def __init__( self, tag: Tag, module: str, labels: dict[str, str], options: ModelOptions, metadata: MetadataDict, context: ModelContext, signatures: ModelSignaturesType, api_version: str, creation_time: datetime | None = None, ): self.__attrs_init__( # type: ignore tag=tag, name=tag.name, version=tag.version, module=module, labels=labels, options=options, metadata=metadata, context=context, signatures=signatures, api_version=api_version, creation_time=creation_time or datetime.now(timezone.utc), ) self.validate() def __eq__(self, other: object) -> bool: if not isinstance(other, ModelInfo): return False return ( self.tag == other.tag and self.module == other.module and self.signatures == other.signatures and self.labels == other.labels and self.options == other.options and self.metadata == other.metadata and self.context == other.context and self.signatures == other.signatures and self.api_version == other.api_version and self.creation_time == other.creation_time ) def with_options(self, **kwargs: t.Any) -> ModelInfo: return ModelInfo( tag=self.tag, module=self.module, signatures=self.signatures, labels=self.labels, options=self.options.with_options(**kwargs), metadata=self.metadata, context=self.context, api_version=self.api_version, creation_time=self.creation_time, ) def to_dict(self) -> t.Dict[str, t.Any]: return bentoml_cattr.unstructure(self) # type: ignore (incomplete cattr types) @overload def dump(self, stream: io.StringIO) -> io.BytesIO: ... @overload def dump(self, stream: None = None) -> None: ... def dump(self, stream: io.StringIO | None = None) -> io.BytesIO | None: return yaml.safe_dump(self.to_dict(), stream=stream, sort_keys=False) # type: ignore (bad yaml types) @staticmethod def from_yaml_file(stream: t.IO[t.Any]): try: yaml_content = yaml.safe_load(stream) except yaml.YAMLError as exc: # pragma: no cover - simple error handling logger.error(exc) raise if not isinstance(yaml_content, dict): raise BentoMLException(f"malformed {MODEL_YAML_FILENAME}") yaml_content["tag"] = str( Tag( t.cast(str, yaml_content["name"]), t.cast(str, yaml_content["version"]), ) ) del yaml_content["name"] del yaml_content["version"] # For backwards compatibility for bentos created prior to version 1.0.0rc1 if "bentoml_version" in yaml_content: del yaml_content["bentoml_version"] if "signatures" not in yaml_content: yaml_content["signatures"] = {} if "context" in yaml_content and "pip_dependencies" in yaml_content["context"]: del yaml_content["context"]["pip_dependencies"] yaml_content["context"]["framework_versions"] = {} # register hook for model options module_name: str = yaml_content["module"] try: module = importlib.import_module(module_name) except (ValueError, ModuleNotFoundError) as e: raise BentoMLException( f"Module '{module_name}' defined in {MODEL_YAML_FILENAME} is not found." ) from e if hasattr(module, "ModelOptions"): bentoml_cattr.register_structure_hook( ModelOptions, lambda d, _: module.ModelOptions(**d), ) try: model_info = bentoml_cattr.structure(yaml_content, ModelInfo) except TypeError as e: # pragma: no cover - simple error handling raise BentoMLException(f"unexpected field in {MODEL_YAML_FILENAME}: {e}") return model_info def validate(self): # Validate model.yml file schema, content, bentoml version, etc # add tests when implemented ... # Remove after attrs support ForwardRef natively attr.resolve_types(ModelInfo, globals(), locals()) bentoml_cattr.register_unstructure_hook_func( lambda cls: issubclass(cls, ModelInfo), # Ignore tag, tag is saved via the name and version field make_dict_unstructure_fn(ModelInfo, bentoml_cattr, tag=override(omit=True)), # type: ignore (incomplete types) ) def copy_model( model_tag: t.Union[Tag, str], *, src_model_store: ModelStore, target_model_store: ModelStore, ): """copy a model from src model store to target modelstore, and do nothing if the model tag already exist in target model store """ try: target_model_store.get(model_tag) # if model tag already found in target return except NotFound: pass model = src_model_store.get(model_tag) model.save(target_model_store) def _ModelInfo_dumper(dumper: yaml.Dumper, info: ModelInfo) -> yaml.Node: return dumper.represent_dict(info.to_dict()) yaml.add_representer(ModelInfo, _ModelInfo_dumper) # type: ignore (incomplete yaml types)
# type: ignore[reportUnusedFunction] import sys import typing as t import logging import click from ..log import configure_server_logging from ..configuration.containers import DeploymentContainer logger = logging.getLogger(__name__) DEFAULT_DEV_SERVER_HOST = "127.0.0.1" DEFAULT_RELOAD_DELAY = 0.25 def add_serve_command(cli: click.Group) -> None: @cli.command() @click.argument("bento", type=click.STRING, default=".") @click.option( "--production", type=click.BOOL, help="Run the BentoServer in production mode", is_flag=True, default=False, show_default=True, ) @click.option( "--port", type=click.INT, default=DeploymentContainer.service_port.get(), help="The port to listen on for the REST api server", envvar="BENTOML_PORT", show_default=True, ) @click.option( "--host", type=click.STRING, default=None, help="The host to bind for the REST api server [defaults: 127.0.0.1(dev), 0.0.0.0(production)]", envvar="BENTOML_HOST", ) @click.option( "--api-workers", type=click.INT, default=None, help="Specify the number of API server workers to start. Default to number of available CPU cores in production mode", envvar="BENTOML_API_WORKERS", ) @click.option( "--backlog", type=click.INT, default=DeploymentContainer.api_server_config.backlog.get(), help="The maximum number of pending connections.", show_default=True, ) @click.option( "--reload", type=click.BOOL, is_flag=True, help="Reload Service when code changes detected, this is only available in development mode", default=False, show_default=True, ) @click.option( "--reload-delay", type=click.FLOAT, help="Delay in seconds between each check if the Service needs to be reloaded", show_default=True, default=DEFAULT_RELOAD_DELAY, ) @click.option( "--working-dir", type=click.Path(), help="When loading from source code, specify the directory to find the Service instance", default=".", show_default=True, ) @click.option( "--run-with-ngrok", # legacy option "--ngrok", is_flag=True, default=False, help="Use ngrok to relay traffic on a public endpoint to the local BentoServer, only available in dev mode", show_default=True, ) def serve( bento: str, production: bool, port: int, host: t.Optional[str], api_workers: t.Optional[int], backlog: int, reload: bool, reload_delay: float, working_dir: str, run_with_ngrok: bool, ) -> None: """Start BentoServer from BENTO BENTO is the serving target: it can be the import path of a bentoml.Service instance; a tag to a Bento in local Bento store; or a file path to a Bento directory, e.g.: \b Serve from a bentoml.Service instance source code(for development use only): bentoml serve fraud_detector.py:svc \b Serve from a Bento built in local store: bentoml serve fraud_detector:4tht2icroji6zput3suqi5nl2 bentoml serve fraud_detector:latest \b Serve from a Bento directory: bentoml serve ./fraud_detector_bento """ configure_server_logging() if sys.path[0] != working_dir: sys.path.insert(0, working_dir) if production: if run_with_ngrok: logger.warning( "'--run-with-ngrok' is not supported with '--production; ignoring" ) if reload: logger.warning( "'--reload' is not supported with '--production'; ignoring" ) from ..server import serve_production serve_production( bento, working_dir=working_dir, port=port, host=DeploymentContainer.service_host.get() if host is None else host, backlog=backlog, api_workers=api_workers, ) else: from ..server import serve_development serve_development( bento, working_dir=working_dir, with_ngrok=run_with_ngrok, port=port, host=DEFAULT_DEV_SERVER_HOST if host is None else host, reload=reload, reload_delay=reload_delay, )
from __future__ import annotations import sys import typing as t import logging import click from bentoml.bentos import containerize as containerize_bento from ..utils import kwargs_transformers from ..utils.docker import validate_tag logger = logging.getLogger("bentoml") def containerize_transformer( value: t.Iterable[str] | str | bool | None, ) -> t.Iterable[str] | str | bool | None: if value is None: return if isinstance(value, tuple) and not value: return return value def add_containerize_command(cli: click.Group) -> None: @cli.command() @click.argument("bento_tag", type=click.STRING) @click.option( "-t", "--docker-image-tag", help="Name and optionally a tag (format: 'name:tag'), defaults to bento tag.", required=False, callback=validate_tag, ) @click.option( "--add-host", multiple=True, help="Add a custom host-to-IP mapping (format: 'host:ip').", ) @click.option( "--allow", multiple=True, default=None, help="Allow extra privileged entitlement (e.g., 'network.host', 'security.insecure').", ) @click.option("--build-arg", multiple=True, help="Set build-time variables.") @click.option( "--build-context", multiple=True, help="Additional build contexts (e.g., name=path).", ) @click.option( "--builder", type=click.STRING, default=None, help="Override the configured builder instance.", ) @click.option( "--cache-from", multiple=True, default=None, help="External cache sources (e.g., 'user/app:cache', 'type=local,src=path/to/dir').", ) @click.option( "--cache-to", multiple=True, default=None, help="Cache export destinations (e.g., 'user/app:cache', 'type=local,dest=path/to/dir').", ) @click.option( "--cgroup-parent", type=click.STRING, default=None, help="Optional parent cgroup for the container.", ) @click.option( "--iidfile", type=click.STRING, default=None, help="Write the image ID to the file.", ) @click.option("--label", multiple=True, help="Set metadata for an image.") @click.option( "--load", is_flag=True, default=False, help="Shorthand for '--output=type=docker'.", ) @click.option( "--metadata-file", type=click.STRING, default=None, help="Write build result metadata to the file.", ) @click.option( "--network", type=click.STRING, default=None, help="Set the networking mode for the 'RUN' instructions during build (default 'default').", ) @click.option( "--no-cache", is_flag=True, default=False, help="Do not use cache when building the image.", ) @click.option( "--no-cache-filter", multiple=True, help="Do not cache specified stages.", ) @click.option( "--output", multiple=True, default=None, help="Output destination (format: 'type=local,dest=path').", ) @click.option( "--platform", default=None, multiple=True, help="Set target platform for build." ) @click.option( "--progress", default="auto", type=click.Choice(["auto", "tty", "plain"]), help="Set type of progress output ('auto', 'plain', 'tty'). Use plain to show container output.", ) @click.option( "--pull", is_flag=True, default=False, help="Always attempt to pull all referenced images.", ) @click.option( "--push", is_flag=True, default=False, help="Shorthand for '--output=type=registry'.", ) @click.option( "--secret", multiple=True, default=None, help="Secret to expose to the build (format: 'id=mysecret[,src=/local/secret]').", ) @click.option("--shm-size", default=None, help="Size of '/dev/shm'.") @click.option( "--ssh", type=click.STRING, default=None, help="SSH agent socket or keys to expose to the build (format: 'default|<id>[=<socket>|<key>[,<key>]]').", ) @click.option( "--target", type=click.STRING, default=None, help="Set the target build stage to build.", ) @click.option( "--ulimit", type=click.STRING, default=None, help="Ulimit options (default [])." ) @kwargs_transformers(transformer=containerize_transformer) def containerize( # type: ignore bento_tag: str, docker_image_tag: str, add_host: t.Iterable[str], allow: t.Iterable[str], build_arg: t.List[str], build_context: t.List[str], builder: str, cache_from: t.List[str], cache_to: t.List[str], cgroup_parent: str, iidfile: str, label: t.List[str], load: bool, network: str, metadata_file: str, no_cache: bool, no_cache_filter: t.List[str], output: t.List[str], platform: t.List[str], progress: t.Literal["auto", "tty", "plain"], pull: bool, push: bool, secret: t.List[str], shm_size: str, ssh: str, target: str, ulimit: str, ) -> None: """Containerizes given Bento into a ready-to-use Docker image. \b BENTO is the target BentoService to be containerized, referenced by its name and version in format of name:version. For example: "iris_classifier:v1.2.0" `bentoml containerize` command also supports the use of the `latest` tag which will automatically use the last built version of your Bento. You can provide a tag for the image built by Bento using the `--tag` flag. Additionally, you can provide a `--push` flag, which will push the built image to the Docker repository specified by the image tag. You can also prefixing the tag with a hostname for the repository you wish to push to. e.g. `bentoml containerize IrisClassifier:latest --push --tag repo-address.com:username/iris` would build a Docker image called `username/iris:latest` and push that to docker repository at repo-address.com. By default, the `containerize` command will use the current credentials provided by Docker daemon. `bentoml containerize` also uses Docker Buildx as backend, in place for normal `docker build`. By doing so, BentoML will leverage Docker Buildx features such as multi-node builds for cross-platform images, Full BuildKit capabilities with all of the familiar UI from `docker build`. We also pass all given args for `docker buildx` through `bentoml containerize` with ease. """ add_hosts = {} if add_host: for host in add_host: host_name, ip = host.split(":") add_hosts[host_name] = ip allow_ = [] if allow: allow_ = list(allow) build_args = {} if build_arg: for build_arg_str in build_arg: key, value = build_arg_str.split("=") build_args[key] = value build_context_ = {} if build_context: for build_context_str in build_context: key, value = build_context_str.split("=") build_context_[key] = value labels = {} if label: for label_str in label: key, value = label_str.split("=") labels[key] = value if output: output_ = {} for arg in output: if "," in arg: for val in arg.split(","): k, v = val.split("=") output_[k] = v key, value = arg.split("=") output_[key] = value else: output_ = None if not platform: load = True else: if len(platform) > 1: logger.warning( "Multiple `--platform` arguments were found. Make sure to also use `--push` to push images to a repository or generated images will not be saved. For more information, see https://docs.docker.com/engine/reference/commandline/buildx_build/#load." ) else: load = True exit_code = not containerize_bento( bento_tag, docker_image_tag=docker_image_tag, add_host=add_hosts, allow=allow_, build_args=build_args, build_context=build_context_, builder=builder, cache_from=cache_from, cache_to=cache_to, cgroup_parent=cgroup_parent, iidfile=iidfile, labels=labels, load=load, metadata_file=metadata_file, network=network, no_cache=no_cache, no_cache_filter=no_cache_filter, output=output_, # type: ignore platform=platform, progress=progress, pull=pull, push=push, quiet=logger.getEffectiveLevel() == logging.ERROR, secrets=secret, shm_size=shm_size, ssh=ssh, target=target, ulimit=ulimit, ) sys.exit(exit_code)
# type: ignore[reportUnusedFunction] import sys import json import typing as t import logging from typing import TYPE_CHECKING import yaml import click from simple_di import inject from simple_di import Provide from rich.table import Table from rich.syntax import Syntax from rich.console import Console from bentoml import Tag from bentoml.bentos import import_bento from bentoml.bentos import build_bentofile from ..utils import calc_dir_size from ..utils import human_readable_size from ..utils import display_path_under_home from .click_utils import is_valid_bento_tag from .click_utils import is_valid_bento_name from ..bento.bento import DEFAULT_BENTO_BUILD_FILE from ..yatai_client import yatai_client from ..configuration.containers import BentoMLContainer if TYPE_CHECKING: from ..bento import BentoStore logger = logging.getLogger(__name__) def parse_delete_targets_argument_callback( ctx: "click.Context", params: "click.Parameter", value: t.Any ) -> t.List[str]: # pylint: disable=unused-argument if value is None: return value delete_targets = value.split(",") delete_targets = list(map(str.strip, delete_targets)) for delete_target in delete_targets: if not ( is_valid_bento_tag(delete_target) or is_valid_bento_name(delete_target) ): raise click.BadParameter( "Bad formatting. Please present a valid bento bundle name or " '"name:version" tag. For list of bento bundles, separate delete ' 'targets by ",", for example: "my_service:v1,my_service:v2,' 'classifier"' ) return delete_targets @inject def add_bento_management_commands( cli: "click.Group", bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ): @cli.command() @click.argument("bento_tag", type=click.STRING) @click.option( "-o", "--output", type=click.Choice(["json", "yaml", "path"]), default="yaml", ) def get(bento_tag: str, output: str) -> None: """Print Bento details by providing the bento_tag \b bentoml get FraudDetector:latest bentoml get --output=json FraudDetector:20210709_DE14C9 """ bento = bento_store.get(bento_tag) console = Console() if output == "path": console.print(bento.path) elif output == "json": info = json.dumps(bento.info.to_dict(), indent=2, default=str) console.print_json(info) else: info = yaml.dump(bento.info, indent=2, sort_keys=False) console.print(Syntax(info, "yaml")) @cli.command(name="list") @click.argument("bento_name", type=click.STRING, required=False) @click.option( "-o", "--output", type=click.Choice(["json", "yaml", "table"]), default="table", ) @click.option( "--no-trunc", is_flag=False, help="Don't truncate the output", ) def list_bentos(bento_name: str, output: str, no_trunc: bool) -> None: """List Bentos in local store \b # show all bentos saved > bentoml list \b # show all verions of bento with the name FraudDetector > bentoml list FraudDetector """ bentos = bento_store.list(bento_name) res = [ { "tag": str(bento.tag), "path": display_path_under_home(bento.path), "size": human_readable_size(calc_dir_size(bento.path)), "creation_time": bento.info.creation_time.astimezone().strftime( "%Y-%m-%d %H:%M:%S" ), } for bento in sorted( bentos, key=lambda x: x.info.creation_time, reverse=True ) ] console = Console() if output == "json": info = json.dumps(res, indent=2) console.print(info) elif output == "yaml": info = yaml.safe_dump(res, indent=2) console.print(Syntax(info, "yaml")) else: table = Table(box=None) table.add_column("Tag") table.add_column("Size") table.add_column("Creation Time") table.add_column("Path") for bento in res: table.add_row( bento["tag"], bento["size"], bento["creation_time"], bento["path"], ) console.print(table) @cli.command() @click.argument( "delete_targets", type=click.STRING, callback=parse_delete_targets_argument_callback, required=True, ) @click.option( "-y", "--yes", "--assume-yes", is_flag=True, help="Skip confirmation when deleting a specific bento bundle", ) def delete( delete_targets: t.List[str], yes: bool, ) -> None: """Delete Bento in local bento store. \b Examples: * Delete single bento bundle by "name:version", e.g: `bentoml delete IrisClassifier:v1` * Bulk delete all bento bundles with a specific name, e.g.: `bentoml delete IrisClassifier` * Bulk delete multiple bento bundles by name and version, separated by ",", e.g.: `benotml delete Irisclassifier:v1,MyPredictService:v2` * Bulk delete without confirmation, e.g.: `bentoml delete IrisClassifier --yes` """ # noqa def delete_target(target: str) -> None: tag = Tag.from_str(target) if tag.version is None: to_delete_bentos = bento_store.list(target) else: to_delete_bentos = [bento_store.get(tag)] for bento in to_delete_bentos: if yes: delete_confirmed = True else: delete_confirmed = click.confirm(f"delete bento {bento.tag}?") if delete_confirmed: bento_store.delete(bento.tag) logger.info(f"{bento} deleted") for target in delete_targets: delete_target(target) @cli.command() @click.argument("bento_tag", type=click.STRING) @click.argument( "out_path", type=click.STRING, default="", required=False, ) def export(bento_tag: str, out_path: str) -> None: """Export a Bento to an external file archive \b Arguments: BENTO_TAG: bento identifier OUT_PATH: output path of exported bento. If out_path argument is not provided, bento is exported to name-version.bento in the current directory. Beside the native .bento format, we also support ('tar'), tar.gz ('gz'), tar.xz ('xz'), tar.bz2 ('bz2'), and zip. \b Examples: bentoml export FraudDetector:20210709_DE14C9 bentoml export FraudDetector:20210709_DE14C9 ./my_bento.bento bentoml export FraudDetector:latest ./my_bento.bento bentoml export FraudDetector:latest s3://mybucket/bentos/my_bento.bento """ bento = bento_store.get(bento_tag) out_path = bento.export(out_path) logger.info(f"{bento} exported to {out_path}") @cli.command(name="import") @click.argument("bento_path", type=click.STRING) def import_bento_(bento_path: str) -> None: """Import a previously exported Bento archive file \b Arguments: BENTO_PATH: path of Bento archive file \b Examples: bentoml import ./my_bento.bento bentoml import s3://mybucket/bentos/my_bento.bento """ bento = import_bento(bento_path) logger.info(f"{bento} imported") @cli.command( help="Pull Bento from a yatai server", ) @click.argument("bento_tag", type=click.STRING) @click.option( "-f", "--force", is_flag=True, default=False, help="Force pull from yatai to local and overwrite even if it already exists in local", ) def pull(bento_tag: str, force: bool) -> None: yatai_client.pull_bento(bento_tag, force=force) @cli.command(help="Push Bento to a yatai server") @click.argument("bento_tag", type=click.STRING) @click.option( "-f", "--force", is_flag=True, default=False, help="Forced push to yatai even if it exists in yatai", ) def push(bento_tag: str, force: bool) -> None: bento_obj = bento_store.get(bento_tag) if not bento_obj: raise click.ClickException(f"Bento {bento_tag} not found in local store") yatai_client.push_bento(bento_obj, force=force) @cli.command(help="Build a new Bento from current directory") @click.argument("build_ctx", type=click.Path(), default=".") @click.option( "-f", "--bentofile", type=click.STRING, default=DEFAULT_BENTO_BUILD_FILE ) @click.option("--version", type=click.STRING, default=None) def build(build_ctx: str, bentofile: str, version: str) -> None: if sys.path[0] != build_ctx: sys.path.insert(0, build_ctx) return build_bentofile(bentofile, build_ctx=build_ctx, version=version)
import click import psutil from bentoml import __version__ as BENTOML_VERSION from .yatai import add_login_command from .click_utils import BentoMLCommandGroup from .bento_server import add_serve_command from .containerize import add_containerize_command from .bento_management import add_bento_management_commands from .model_management import add_model_management_commands def create_bentoml_cli(): # exclude traceback from the click library from rich.traceback import install install(suppress=[click]) CONTEXT_SETTINGS = {"help_option_names": ("-h", "--help")} @click.group(cls=BentoMLCommandGroup, context_settings=CONTEXT_SETTINGS) @click.version_option(BENTOML_VERSION, "-v", "--version") # type: ignore def cli(): """BentoML CLI""" # Add top-level CLI commands add_login_command(cli) add_bento_management_commands(cli) add_model_management_commands(cli) add_serve_command(cli) add_containerize_command(cli) if psutil.WINDOWS: import sys sys.stdout.reconfigure(encoding="utf-8") # type: ignore return cli cli = create_bentoml_cli() if __name__ == "__main__": cli()
import os import re import time import typing as t import difflib import logging import functools from typing import TYPE_CHECKING import click from click import ClickException from click.exceptions import UsageError from ..log import configure_logging from ...exceptions import BentoMLException from ..configuration import CONFIG_ENV_VAR from ..configuration import set_debug_mode from ..configuration import set_quiet_mode from ..configuration import load_global_config from ..utils.analytics import track from ..utils.analytics import CliEvent from ..utils.analytics import cli_events_map from ..utils.analytics import BENTOML_DO_NOT_TRACK if TYPE_CHECKING: P = t.ParamSpec("P") class ClickFunctionWrapper(t.Protocol[P]): __name__: str __click_params__: t.List[click.Option] def __call__(*args: P.args, **kwargs: P.kwargs) -> t.Callable[P, t.Any]: ... WrappedCLI = t.Callable[P, ClickFunctionWrapper[t.Any]] logger = logging.getLogger(__name__) class BentoMLCommandGroup(click.Group): """Click command class customized for BentoML CLI, allow specifying a default command for each group defined """ NUMBER_OF_COMMON_PARAMS = 4 @staticmethod def bentoml_common_params( func: "t.Callable[P, t.Any]", ) -> "WrappedCLI[bool, bool, t.Optional[str]]": # NOTE: update NUMBER_OF_COMMON_PARAMS when adding option. @click.option( "-q", "--quiet", is_flag=True, default=False, help="Suppress all warnings and info logs", ) @click.option( "--verbose", "--debug", is_flag=True, default=False, help="Generate debug information", ) @click.option( "--do-not-track", is_flag=True, default=False, envvar=BENTOML_DO_NOT_TRACK, help="Do not send usage info", ) @click.option( "--config", type=click.Path(exists=True), envvar=CONFIG_ENV_VAR, help="BentoML configuration YAML file to apply", ) @functools.wraps(func) def wrapper( quiet: bool, verbose: bool, config: t.Optional[str], *args: "P.args", **kwargs: "P.kwargs", ) -> t.Any: if config: load_global_config(config) if quiet: set_quiet_mode(True) if verbose: logger.warning("'--quiet' passed; ignoring '--verbose/--debug'") elif verbose: set_debug_mode(True) configure_logging() return func(*args, **kwargs) return wrapper @staticmethod def bentoml_track_usage( func: t.Union["t.Callable[P, t.Any]", "ClickFunctionWrapper[t.Any]"], cmd_group: click.Group, **kwargs: t.Any, ): command_name = kwargs.get("name", func.__name__) @functools.wraps(func) def wrapper(do_not_track: bool, *args: "P.args", **kwargs: "P.kwargs") -> t.Any: if do_not_track: os.environ[BENTOML_DO_NOT_TRACK] = str(True) return func(*args, **kwargs) start_time = time.time_ns() if ( cmd_group.name in cli_events_map and command_name in cli_events_map[cmd_group.name] ): get_tracking_event = functools.partial( cli_events_map[cmd_group.name][command_name], cmd_group.name, command_name, ) else: def get_tracking_event(ret: t.Any) -> CliEvent: return CliEvent( cmd_group=cmd_group.name, cmd_name=command_name, ) try: return_value = func(*args, **kwargs) event = get_tracking_event(return_value) duration_in_ns = time.time_ns() - start_time event.duration_in_ms = duration_in_ns / 1e6 track(event) return return_value except BaseException as e: event = get_tracking_event(None) duration_in_ns = time.time_ns() - start_time event.duration_in_ms = duration_in_ns / 1e6 event.error_type = type(e).__name__ event.return_code = 2 if isinstance(e, KeyboardInterrupt) else 1 track(event) raise return wrapper @staticmethod def raise_click_exception( func: t.Union["t.Callable[P, t.Any]", "ClickFunctionWrapper[t.Any]"], cmd_group: click.Group, **kwargs: t.Any, ) -> "ClickFunctionWrapper[t.Any]": command_name = kwargs.get("name", func.__name__) @functools.wraps(func) def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Any: try: return func(*args, **kwargs) except BentoMLException as err: msg = f"[{cmd_group.name}] `{command_name}` failed: {str(err)}" raise ClickException(click.style(msg, fg="red")) from err return t.cast("ClickFunctionWrapper[t.Any]", wrapper) def command( self, *args: t.Any, **kwargs: t.Any ) -> "t.Callable[[t.Callable[P, t.Any]], click.Command]": if "context_settings" not in kwargs: kwargs["context_settings"] = {} kwargs["context_settings"]["max_content_width"] = 120 def wrapper(func: "t.Callable[P, t.Any]") -> click.Command: # add common parameters to command. func = BentoMLCommandGroup.bentoml_common_params(func) # Send tracking events before command finish. func = BentoMLCommandGroup.bentoml_track_usage(func, self, **kwargs) # If BentoMLException raise ClickException instead before exit. func = BentoMLCommandGroup.raise_click_exception(func, self, **kwargs) # move common parameters to end of the parameters list func.__click_params__ = ( func.__click_params__[-self.NUMBER_OF_COMMON_PARAMS :] + func.__click_params__[: -self.NUMBER_OF_COMMON_PARAMS] ) return super(BentoMLCommandGroup, self).command(*args, **kwargs)(func) return wrapper def resolve_command( self, ctx: click.Context, args: t.List[str] ) -> t.Tuple[str, click.Command, t.List[str]]: try: return super(BentoMLCommandGroup, self).resolve_command(ctx, args) except UsageError as e: error_msg = str(e) original_cmd_name = click.utils.make_str(args[0]) matches = difflib.get_close_matches( original_cmd_name, self.list_commands(ctx), 3, 0.5 ) if matches: fmt_matches = "\n ".join(matches) error_msg += "\n\n" error_msg += f"Did you mean?\n {fmt_matches}" raise UsageError(error_msg, e.ctx) def is_valid_bento_tag(value: str) -> bool: return re.match(r"^[A-Za-z_][A-Za-z_0-9]*:[A-Za-z0-9.+-_]*$", value) is not None def is_valid_bento_name(value: str) -> bool: return re.match(r"^[A-Za-z_0-9]*$", value) is not None
# type: ignore[reportUnusedFunction] import logging import click from bentoml.exceptions import CLIException from ..cli.click_utils import BentoMLCommandGroup from ..yatai_rest_api_client.yatai import YataiRESTApiClient from ..yatai_rest_api_client.config import add_context from ..yatai_rest_api_client.config import YataiClientContext from ..yatai_rest_api_client.config import default_context_name logger = logging.getLogger(__name__) def add_login_command(cli: click.Group) -> None: @cli.group(name="yatai", cls=BentoMLCommandGroup) def yatai_cli(): """Yatai Subcommands Groups""" @yatai_cli.command(help="Login to Yatai server") @click.option( "--endpoint", type=click.STRING, help="Yatai endpoint, i.e: https://yatai.com" ) @click.option("--api-token", type=click.STRING, help="Yatai user API token") def login(endpoint: str, api_token: str) -> None: if not endpoint: raise CLIException("need --endpoint") if not api_token: raise CLIException("need --api-token") yatai_rest_client = YataiRESTApiClient(endpoint, api_token) user = yatai_rest_client.get_current_user() if user is None: raise CLIException("current user is not found") org = yatai_rest_client.get_current_organization() if org is None: raise CLIException("current organization is not found") ctx = YataiClientContext( name=default_context_name, endpoint=endpoint, api_token=api_token, email=user.email, ) add_context(ctx) logger.info( f"login successfully! user: {user.name}, organization: {org.name}", )
# type: ignore[reportUnusedFunction] import json import typing as t import logging from typing import TYPE_CHECKING import yaml import click from simple_di import inject from simple_di import Provide from rich.table import Table from rich.syntax import Syntax from rich.console import Console from bentoml import Tag from bentoml.models import import_model from ..utils import calc_dir_size from ..utils import human_readable_size from ..utils import display_path_under_home from .click_utils import is_valid_bento_tag from .click_utils import BentoMLCommandGroup from .click_utils import is_valid_bento_name from ..yatai_client import yatai_client from ..configuration.containers import BentoMLContainer if TYPE_CHECKING: from ..models import ModelStore logger = logging.getLogger(__name__) def parse_delete_targets_argument_callback( ctx: "click.Context", params: "click.Parameter", value: t.Any ) -> t.Any: # pylint: disable=unused-argument if value is None: return value delete_targets = value.split(",") delete_targets = list(map(str.strip, delete_targets)) for delete_target in delete_targets: if not ( is_valid_bento_tag(delete_target) or is_valid_bento_name(delete_target) ): raise click.BadParameter( "Bad formatting. Please present a valid bento bundle name or " '"name:version" tag. For list of bento bundles, separate delete ' 'targets by ",", for example: "my_service:v1,my_service:v2,' 'classifier"' ) return delete_targets @inject def add_model_management_commands( cli: "click.Group", model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> None: @cli.group(name="models", cls=BentoMLCommandGroup) def model_cli(): """Model Subcommands Groups""" @model_cli.command() @click.argument("model_tag", type=click.STRING) @click.option( "-o", "--output", type=click.Choice(["json", "yaml", "path"]), default="yaml", ) def get(model_tag: str, output: str) -> None: """Print Model details by providing the model_tag \b bentoml models get FraudDetector:latest bentoml models get --output=json FraudDetector:20210709_DE14C9 """ model = model_store.get(model_tag) console = Console() if output == "path": console.print(model.path) elif output == "json": info = json.dumps(model.info.to_dict(), indent=2, default=str) console.print_json(info) else: console.print(Syntax(model.info.dump(), "yaml")) @model_cli.command(name="list") @click.argument("model_name", type=click.STRING, required=False) @click.option( "-o", "--output", type=click.Choice(["json", "yaml", "table"]), default="table", ) @click.option( "--no-trunc", is_flag=False, help="Don't truncate the output", ) def list_models(model_name: str, output: str, no_trunc: bool) -> None: """List Models in local store \b # show all models saved > bentoml models list \b # show all verions of bento with the name FraudDetector > bentoml models list FraudDetector """ console = Console() models = model_store.list(model_name) res = [ { "tag": str(model.tag), "module": model.info.module, "size": human_readable_size(calc_dir_size(model.path)), "creation_time": model.info.creation_time.astimezone().strftime( "%Y-%m-%d %H:%M:%S" ), } for model in sorted( models, key=lambda x: x.info.creation_time, reverse=True ) ] if output == "json": info = json.dumps(res, indent=2) console.print_json(info) elif output == "yaml": info = yaml.safe_dump(res, indent=2) console.print(Syntax(info, "yaml")) else: table = Table(box=None) table.add_column("Tag") table.add_column("Module") table.add_column("Size") table.add_column("Creation Time") for model in res: table.add_row( model["tag"], model["module"], model["size"], model["creation_time"], ) console.print(table) @model_cli.command() @click.argument( "delete_targets", type=click.STRING, callback=parse_delete_targets_argument_callback, required=True, ) @click.option( "-y", "--yes", "--assume-yes", is_flag=True, help="Skip confirmation when deleting a specific model", ) def delete( delete_targets: str, yes: bool, ) -> None: """Delete Model in local model store. \b Examples: * Delete single model by "name:version", e.g: `bentoml models delete iris_clf:v1` * Bulk delete all models with a specific name, e.g.: `bentoml models delete iris_clf` * Bulk delete multiple models by name and version, separated by ",", e.g.: `benotml models delete iris_clf:v1,iris_clf:v2` * Bulk delete without confirmation, e.g.: `bentoml models delete IrisClassifier --yes` """ # noqa def delete_target(target: str) -> None: tag = Tag.from_str(target) if tag.version is None: to_delete_models = model_store.list(target) else: to_delete_models = [model_store.get(tag)] for model in to_delete_models: if yes: delete_confirmed = True else: delete_confirmed = click.confirm(f"delete model {model.tag}?") if delete_confirmed: model_store.delete(model.tag) logger.info(f"{model} deleted") for target in delete_targets: delete_target(target) @model_cli.command() @click.argument("model_tag", type=click.STRING) @click.argument("out_path", type=click.STRING, default="", required=False) def export(model_tag: str, out_path: str) -> None: """Export a Model to an external archive file arguments: \b MODEL_TAG: model identifier OUT_PATH: output path of exported model. If this argument is not provided, model is exported to name-version.bentomodel in the current directory. Besides native .bentomodel format, we also support formats like tar('tar'), tar.gz ('gz'), tar.xz ('xz'), tar.bz2 ('bz2'), and zip. examples: \b bentoml models export FraudDetector:latest bentoml models export FraudDetector:latest ./my_model.bentomodel bentoml models export FraudDetector:20210709_DE14C9 ./my_model.bentomodel bentoml models export FraudDetector:20210709_DE14C9 s3://mybucket/models/my_model.bentomodel """ bentomodel = model_store.get(model_tag) out_path = bentomodel.export(out_path) logger.info(f"{bentomodel} exported to {out_path}") @model_cli.command(name="import") @click.argument("model_path", type=click.STRING) def import_from(model_path: str) -> None: """Import a previously exported Model archive file bentoml models import ./my_model.bentomodel bentoml models import s3://mybucket/models/my_model.bentomodel """ bentomodel = import_model(model_path) logger.info(f"{bentomodel} imported") @model_cli.command( help="Pull Model from a yatai server", ) @click.argument("model_tag", type=click.STRING) @click.option( "-f", "--force", is_flag=True, default=False, help="Force pull from yatai to local and overwrite even if it already exists in local", ) def pull(model_tag: str, force: bool): yatai_client.pull_model(model_tag, force=force) @model_cli.command(help="Push Model to a yatai server") @click.argument("model_tag", type=click.STRING) @click.option( "-f", "--force", is_flag=True, default=False, help="Forced push to yatai even if it exists in yatai", ) def push(model_tag: str, force: bool): model_obj = model_store.get(model_tag) if not model_obj: raise click.ClickException(f"Model {model_tag} not found in local store") yatai_client.push_model(model_obj, force=force)
import os import logging from typing import List from typing import Optional from pathlib import Path import attr import yaml import cattr from bentoml.exceptions import YataiRESTApiClientError from .yatai import YataiRESTApiClient from ..configuration.containers import BENTOML_HOME logger = logging.getLogger(__name__) default_context_name = "default" def get_config_path() -> Path: return Path(BENTOML_HOME) / ".yatai.yaml" @attr.define class YataiClientContext: name: str endpoint: str api_token: str email: Optional[str] = attr.field(default=None) def get_yatai_rest_api_client(self) -> YataiRESTApiClient: return YataiRESTApiClient(self.endpoint, self.api_token) def get_email(self) -> str: if not self.email: cli = self.get_yatai_rest_api_client() user = cli.get_current_user() if user is None: raise YataiRESTApiClientError( "Unable to get current user from yatai server" ) self.email = user.email add_context(self, ignore_warning=True) return self.email @attr.define class YataiClientConfig: contexts: List[YataiClientContext] = attr.field(factory=list) current_context_name: str = attr.field(default=default_context_name) def get_current_context(self) -> YataiClientContext: for ctx in self.contexts: if ctx.name == self.current_context_name: return ctx raise YataiRESTApiClientError( f"Not found {self.current_context_name} yatai context, please login!" ) _config: YataiClientConfig = YataiClientConfig() def store_config(config: YataiClientConfig) -> None: with open(get_config_path(), "w") as f: dct = cattr.unstructure(config) yaml.dump(dct, stream=f) def init_config() -> YataiClientConfig: config = YataiClientConfig(contexts=[], current_context_name=default_context_name) store_config(config) return config def get_config() -> YataiClientConfig: if not os.path.exists(get_config_path()): return init_config() with open(get_config_path(), "r") as f: dct = yaml.safe_load(f) if not dct: return init_config() return cattr.structure(dct, YataiClientConfig) def add_context(context: YataiClientContext, *, ignore_warning: bool = False) -> None: config = get_config() for idx, ctx in enumerate(config.contexts): if ctx.name == context.name: if not ignore_warning: logger.warning("Overriding existing Yatai context config: %s", ctx.name) config.contexts[idx] = context break else: config.contexts.append(context) store_config(config) def get_current_context() -> YataiClientContext: config = get_config() return config.get_current_context() def get_current_yatai_rest_api_client() -> YataiRESTApiClient: ctx = get_current_context() return ctx.get_yatai_rest_api_client()
import json from enum import Enum from typing import Any from typing import Dict from typing import List from typing import Type from typing import TypeVar from typing import Optional from datetime import datetime import attr import cattr from dateutil.parser import parse time_format = "%Y-%m-%d %H:%M:%S.%f" def datetime_encoder(time_obj: Optional[datetime]) -> Optional[str]: if not time_obj: return None return time_obj.strftime(time_format) def datetime_decoder(datetime_str: Optional[str], _) -> Optional[datetime]: if not datetime_str: return None return parse(datetime_str) converter = cattr.Converter() converter.register_unstructure_hook(datetime, datetime_encoder) converter.register_structure_hook(datetime, datetime_decoder) T = TypeVar("T") def schema_from_json(json_content: str, cls: Type[T]) -> T: dct = json.loads(json_content) return converter.structure(dct, cls) def schema_to_json(obj: T) -> str: res = converter.unstructure(obj, obj.__class__) return json.dumps(res) @attr.define class BaseSchema: uid: str created_at: datetime updated_at: Optional[datetime] deleted_at: Optional[datetime] @attr.define class BaseListSchema: start: int count: int total: int class ResourceType(Enum): USER = "user" ORG = "organization" CLUSTER = "cluster" BENTO_REPOSITORY = "bento_repository" BENTO = "bento" MODEL_REPOSITORY = "model_repository" MODEL = "model" @attr.define class ResourceSchema(BaseSchema): name: str resource_type: ResourceType @attr.define class LabelItemSchema: key: str value: str @attr.define class UserSchema: name: str email: str first_name: str last_name: str def get_name(self) -> str: if not self.first_name and not self.last_name: return self.name return f"{self.first_name} {self.last_name}".strip() @attr.define class OrganizationSchema(ResourceSchema): description: str @attr.define class OrganizationListSchema(BaseListSchema): items: List[OrganizationSchema] @attr.define class ClusterSchema(ResourceSchema): description: str @attr.define class CreateBentoRepositorySchema: name: str description: str class BentoImageBuildStatus(Enum): PENDING = "pending" BUILDING = "building" SUCCESS = "success" FAILED = "failed" class BentoUploadStatus(Enum): PENDING = "pending" BUILDING = "uploading" SUCCESS = "success" FAILED = "failed" @attr.define class BentoApiSchema: route: str doc: str input: str output: str @attr.define class BentoRunnerResourceSchema: cpu: Optional[float] nvidia_gpu: Optional[float] custom_resources: Dict[str, float] @attr.define class BentoRunnerSchema: name: str runnable_type: Optional[str] models: Optional[List[str]] resource_config: Optional[BentoRunnerResourceSchema] @attr.define class BentoManifestSchema: service: str bentoml_version: str size_bytes: int apis: Dict[str, BentoApiSchema] = attr.field(factory=dict) models: List[str] = attr.field(factory=list) runners: Optional[List[BentoRunnerSchema]] = attr.field(factory=list) @attr.define class BentoSchema(ResourceSchema): description: str version: str image_build_status: BentoImageBuildStatus upload_status: BentoUploadStatus upload_finished_reason: str presigned_upload_url: str presigned_download_url: str manifest: BentoManifestSchema upload_started_at: Optional[datetime] = attr.field(default=None) upload_finished_at: Optional[datetime] = attr.field(default=None) build_at: datetime = attr.field(factory=datetime.now) @attr.define class BentoRepositorySchema(ResourceSchema): description: str latest_bento: Optional[BentoSchema] @attr.define class CreateBentoSchema: description: str version: str manifest: BentoManifestSchema build_at: datetime = attr.field(factory=datetime.now) labels: List[LabelItemSchema] = attr.field(factory=list) @attr.define class UpdateBentoSchema: manifest: Optional[BentoManifestSchema] = attr.field(default=None) labels: Optional[List[LabelItemSchema]] = attr.field(default=None) @attr.define class FinishUploadBentoSchema: status: Optional[BentoUploadStatus] reason: Optional[str] @attr.define class CreateModelRepositorySchema: name: str description: str class ModelImageBuildStatus(Enum): PENDING = "pending" BUILDING = "building" SUCCESS = "success" FAILED = "failed" class ModelUploadStatus(Enum): PENDING = "pending" BUILDING = "uploading" SUCCESS = "success" FAILED = "failed" @attr.define class ModelManifestSchema: module: str api_version: str bentoml_version: str size_bytes: int metadata: Dict[str, Any] = attr.field(factory=dict) context: Dict[str, Any] = attr.field(factory=dict) options: Dict[str, Any] = attr.field(factory=dict) @attr.define class ModelSchema(ResourceSchema): description: str version: str image_build_status: ModelImageBuildStatus upload_status: ModelUploadStatus upload_finished_reason: str presigned_upload_url: str presigned_download_url: str manifest: ModelManifestSchema upload_started_at: Optional[datetime] = attr.field(default=None) upload_finished_at: Optional[datetime] = attr.field(default=None) build_at: datetime = attr.field(factory=datetime.now) @attr.define class ModelRepositorySchema(ResourceSchema): description: str latest_model: Optional[ModelSchema] @attr.define class CreateModelSchema: description: str version: str manifest: ModelManifestSchema build_at: datetime = attr.field(factory=datetime.now) labels: List[LabelItemSchema] = attr.field(factory=list) @attr.define class FinishUploadModelSchema: status: Optional[ModelUploadStatus] reason: Optional[str]
import logging from typing import Optional from urllib.parse import urljoin import requests from .schemas import UserSchema from .schemas import BentoSchema from .schemas import ModelSchema from .schemas import schema_to_json from .schemas import schema_from_json from .schemas import CreateBentoSchema from .schemas import CreateModelSchema from .schemas import UpdateBentoSchema from .schemas import OrganizationSchema from .schemas import BentoRepositorySchema from .schemas import ModelRepositorySchema from .schemas import FinishUploadBentoSchema from .schemas import FinishUploadModelSchema from .schemas import CreateBentoRepositorySchema from .schemas import CreateModelRepositorySchema from ...exceptions import YataiRESTApiClientError logger = logging.getLogger(__name__) class YataiRESTApiClient: def __init__(self, endpoint: str, api_token: str) -> None: self.endpoint = endpoint self.session = requests.Session() self.session.headers.update( { "X-YATAI-API-TOKEN": api_token, "Content-Type": "application/json", } ) def _is_not_found(self, resp: requests.Response) -> bool: # Forgive me, I don't know how to map the error returned by gorm to juju/errors return resp.status_code == 400 and "record not found" in resp.text def _check_resp(self, resp: requests.Response) -> None: if resp.status_code != 200: raise YataiRESTApiClientError( f"request failed with status code {resp.status_code}: {resp.text}" ) def get_current_user(self) -> Optional[UserSchema]: url = urljoin(self.endpoint, "/api/v1/auth/current") resp = self.session.get(url) if self._is_not_found(resp): return None self._check_resp(resp) return schema_from_json(resp.text, UserSchema) def get_current_organization(self) -> Optional[OrganizationSchema]: url = urljoin(self.endpoint, "/api/v1/current_org") resp = self.session.get(url) if self._is_not_found(resp): return None self._check_resp(resp) return schema_from_json(resp.text, OrganizationSchema) def get_bento_repository( self, bento_repository_name: str ) -> Optional[BentoRepositorySchema]: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}" ) resp = self.session.get(url) if self._is_not_found(resp): return None self._check_resp(resp) return schema_from_json(resp.text, BentoRepositorySchema) def create_bento_repository( self, req: CreateBentoRepositorySchema ) -> BentoRepositorySchema: url = urljoin(self.endpoint, "/api/v1/bento_repositories") resp = self.session.post(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, BentoRepositorySchema) def get_bento( self, bento_repository_name: str, version: str ) -> Optional[BentoSchema]: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos/{version}", ) resp = self.session.get(url) if self._is_not_found(resp): return None self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def create_bento( self, bento_repository_name: str, req: CreateBentoSchema ) -> BentoSchema: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos" ) resp = self.session.post(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def update_bento( self, bento_repository_name: str, version: str, req: UpdateBentoSchema ) -> BentoSchema: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos/{version}", ) resp = self.session.patch(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def presign_bento_upload_url( self, bento_repository_name: str, version: str ) -> BentoSchema: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos/{version}/presign_upload_url", ) resp = self.session.patch(url) self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def presign_bento_download_url( self, bento_repository_name: str, version: str ) -> BentoSchema: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos/{version}/presign_download_url", ) resp = self.session.patch(url) self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def start_upload_bento( self, bento_repository_name: str, version: str ) -> BentoSchema: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos/{version}/start_upload", ) resp = self.session.patch(url) self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def finish_upload_bento( self, bento_repository_name: str, version: str, req: FinishUploadBentoSchema ) -> BentoSchema: url = urljoin( self.endpoint, f"/api/v1/bento_repositories/{bento_repository_name}/bentos/{version}/finish_upload", ) resp = self.session.patch(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, BentoSchema) def get_model_repository( self, model_repository_name: str ) -> Optional[ModelRepositorySchema]: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}" ) resp = self.session.get(url) if self._is_not_found(resp): return None self._check_resp(resp) return schema_from_json(resp.text, ModelRepositorySchema) def create_model_repository( self, req: CreateModelRepositorySchema ) -> ModelRepositorySchema: url = urljoin(self.endpoint, "/api/v1/model_repositories") resp = self.session.post(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, ModelRepositorySchema) def get_model( self, model_repository_name: str, version: str ) -> Optional[ModelSchema]: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}/models/{version}", ) resp = self.session.get(url) if self._is_not_found(resp): return None self._check_resp(resp) return schema_from_json(resp.text, ModelSchema) def create_model( self, model_repository_name: str, req: CreateModelSchema ) -> ModelSchema: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}/models" ) resp = self.session.post(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, ModelSchema) def presign_model_upload_url( self, model_repository_name: str, version: str ) -> ModelSchema: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}/models/{version}/presign_upload_url", ) resp = self.session.patch(url) self._check_resp(resp) return schema_from_json(resp.text, ModelSchema) def presign_model_download_url( self, model_repository_name: str, version: str ) -> ModelSchema: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}/models/{version}/presign_download_url", ) resp = self.session.patch(url) self._check_resp(resp) return schema_from_json(resp.text, ModelSchema) def start_upload_model( self, model_repository_name: str, version: str ) -> ModelSchema: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}/models/{version}/start_upload", ) resp = self.session.patch(url) self._check_resp(resp) return schema_from_json(resp.text, ModelSchema) def finish_upload_model( self, model_repository_name: str, version: str, req: FinishUploadModelSchema ) -> ModelSchema: url = urljoin( self.endpoint, f"/api/v1/model_repositories/{model_repository_name}/models/{version}/finish_upload", ) resp = self.session.patch(url, data=schema_to_json(req)) self._check_resp(resp) return schema_from_json(resp.text, ModelSchema)
import io import typing as t import tarfile from pathlib import Path from tempfile import NamedTemporaryFile from functools import wraps from contextlib import contextmanager from concurrent.futures import ThreadPoolExecutor import fs import requests from rich.live import Live from simple_di import inject from simple_di import Provide from rich.panel import Panel from rich.console import Group from rich.console import ConsoleRenderable from rich.progress import TaskID from rich.progress import Progress from rich.progress import BarColumn from rich.progress import TextColumn from rich.progress import SpinnerColumn from rich.progress import DownloadColumn from rich.progress import TimeElapsedColumn from rich.progress import TimeRemainingColumn from rich.progress import TransferSpeedColumn from ..tag import Tag from ..bento import Bento from ..bento import BentoStore from ..utils import calc_dir_size from ..models import Model from ..models import copy_model from ..models import ModelStore from ...exceptions import NotFound from ...exceptions import BentoMLException from ..configuration.containers import BentoMLContainer from ..yatai_rest_api_client.config import get_current_yatai_rest_api_client from ..yatai_rest_api_client.schemas import BentoApiSchema from ..yatai_rest_api_client.schemas import LabelItemSchema from ..yatai_rest_api_client.schemas import BentoRunnerSchema from ..yatai_rest_api_client.schemas import BentoUploadStatus from ..yatai_rest_api_client.schemas import CreateBentoSchema from ..yatai_rest_api_client.schemas import CreateModelSchema from ..yatai_rest_api_client.schemas import ModelUploadStatus from ..yatai_rest_api_client.schemas import UpdateBentoSchema from ..yatai_rest_api_client.schemas import BentoManifestSchema from ..yatai_rest_api_client.schemas import ModelManifestSchema from ..yatai_rest_api_client.schemas import FinishUploadBentoSchema from ..yatai_rest_api_client.schemas import FinishUploadModelSchema from ..yatai_rest_api_client.schemas import BentoRunnerResourceSchema from ..yatai_rest_api_client.schemas import CreateBentoRepositorySchema from ..yatai_rest_api_client.schemas import CreateModelRepositorySchema class ObjectWrapper(object): def __getattr__(self, name: str) -> t.Any: return getattr(self._wrapped, name) def __setattr__(self, name: str, value: t.Any) -> None: return setattr(self._wrapped, name, value) def wrapper_getattr(self, name: str): """Actual `self.getattr` rather than self._wrapped.getattr""" return getattr(self, name) def wrapper_setattr(self, name: str, value: t.Any) -> None: """Actual `self.setattr` rather than self._wrapped.setattr""" return object.__setattr__(self, name, value) def __init__(self, wrapped: t.Any): """ Thin wrapper around a given object """ self.wrapper_setattr("_wrapped", wrapped) class _CallbackIOWrapper(ObjectWrapper): def __init__( self, callback: t.Callable[[int], None], stream: t.BinaryIO, method: "t.Literal['read', 'write']" = "read", ): """ Wrap a given `file`-like object's `read()` or `write()` to report lengths to the given `callback` """ super().__init__(stream) func = getattr(stream, method) if method == "write": @wraps(func) def write(data: t.Union[bytes, bytearray], *args: t.Any, **kwargs: t.Any): res = func(data, *args, **kwargs) callback(len(data)) return res self.wrapper_setattr("write", write) elif method == "read": @wraps(func) def read(*args: t.Any, **kwargs: t.Any): data = func(*args, **kwargs) callback(len(data)) return data self.wrapper_setattr("read", read) else: raise KeyError("Can only wrap read/write methods") # Just make type checker happy class BinaryIOCast(io.BytesIO): def __init__( # pylint: disable=useless-super-delegation self, *args: t.Any, **kwargs: t.Any ) -> None: super().__init__(*args, **kwargs) CallbackIOWrapper: t.Type[BinaryIOCast] = t.cast( t.Type[BinaryIOCast], _CallbackIOWrapper ) # Just make type checker happy class ProgressCast(Progress): def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: super().__init__(*args, **kwargs) def __rich__(self) -> t.Union[ConsoleRenderable, str]: # pragma: no cover ... ProgressWrapper: t.Type[ProgressCast] = t.cast(t.Type[ProgressCast], ObjectWrapper) class YataiClient: log_progress = ProgressWrapper( Progress( TextColumn("{task.description}"), ) ) spinner_progress = ProgressWrapper( Progress( TextColumn(" "), TimeElapsedColumn(), TextColumn("[bold purple]{task.fields[action]}"), SpinnerColumn("simpleDots"), ) ) transmission_progress = ProgressWrapper( Progress( TextColumn("[bold blue]{task.description}", justify="right"), BarColumn(bar_width=None), "[progress.percentage]{task.percentage:>3.1f}%", "•", DownloadColumn(), "•", TransferSpeedColumn(), "•", TimeRemainingColumn(), ) ) progress_group = Group( Panel(Group(log_progress, spinner_progress)), transmission_progress ) @contextmanager def spin(self, *, text: str): task_id = self.spinner_progress.add_task("", action=text) try: yield finally: self.spinner_progress.stop_task(task_id) self.spinner_progress.update(task_id, visible=False) @inject def push_bento( self, bento: "Bento", *, force: bool = False, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ): with Live(self.progress_group): upload_task_id = self.transmission_progress.add_task( f'Pushing Bento "{bento.tag}"', start=False, visible=False ) self._do_push_bento( bento, upload_task_id, force=force, model_store=model_store ) @inject def _do_push_bento( self, bento: "Bento", upload_task_id: TaskID, *, force: bool = False, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ): yatai_rest_client = get_current_yatai_rest_api_client() name = bento.tag.name version = bento.tag.version if version is None: raise BentoMLException(f"Bento {bento.tag} version cannot be None") info = bento.info model_tags = [m.tag for m in info.models] with ThreadPoolExecutor(max_workers=max(len(model_tags), 1)) as executor: def push_model(model: "Model"): model_upload_task_id = self.transmission_progress.add_task( f'Pushing model "{model.tag}"', start=False, visible=False ) self._do_push_model(model, model_upload_task_id, force=force) futures = executor.map( push_model, (model_store.get(name) for name in model_tags) ) list(futures) with self.spin(text=f'Fetching Bento repository "{name}"'): bento_repository = yatai_rest_client.get_bento_repository( bento_repository_name=name ) if not bento_repository: with self.spin(text=f'Bento repository "{name}" not found, creating now..'): bento_repository = yatai_rest_client.create_bento_repository( req=CreateBentoRepositorySchema(name=name, description="") ) with self.spin(text=f'Try fetching Bento "{bento.tag}" from Yatai..'): remote_bento = yatai_rest_client.get_bento( bento_repository_name=name, version=version ) if ( not force and remote_bento and remote_bento.upload_status == BentoUploadStatus.SUCCESS ): self.log_progress.add_task( f'[bold blue]Push failed: Bento "{bento.tag}" already exists in Yatai' ) return labels: t.List[LabelItemSchema] = [ LabelItemSchema(key=key, value=value) for key, value in info.labels.items() ] apis: t.Dict[str, BentoApiSchema] = {} models = [str(m.tag) for m in info.models] runners = [ BentoRunnerSchema( name=r.name, runnable_type=r.runnable_type, models=r.models, resource_config=BentoRunnerResourceSchema( cpu=r.resource_config.cpu, nvidia_gpu=r.resource_config.nvidia_gpu, custom_resources=r.resource_config.custom_resources, ) if r.resource_config else None, ) for r in info.runners ] manifest = BentoManifestSchema( service=info.service, bentoml_version=info.bentoml_version, apis=apis, models=models, runners=runners, size_bytes=calc_dir_size(bento.path), ) if not remote_bento: with self.spin(text=f'Registering Bento "{bento.tag}" with Yatai..'): yatai_rest_client.create_bento( bento_repository_name=bento_repository.name, req=CreateBentoSchema( description="", version=version, build_at=info.creation_time, manifest=manifest, labels=labels, ), ) else: with self.spin(text=f'Updating Bento "{bento.tag}"..'): yatai_rest_client.update_bento( bento_repository_name=bento_repository.name, version=version, req=UpdateBentoSchema( manifest=manifest, labels=labels, ), ) with self.spin(text=f'Getting a presigned upload url for "{bento.tag}" ..'): remote_bento = yatai_rest_client.presign_bento_upload_url( bento_repository_name=bento_repository.name, version=version ) with io.BytesIO() as tar_io: bento_dir_path = bento.path if bento_dir_path is None: raise BentoMLException(f'Bento "{bento}" path cannot be None') with self.spin(text=f'Creating tar archive for Bento "{bento.tag}"..'): with tarfile.open(fileobj=tar_io, mode="w:gz") as tar: def filter_( tar_info: tarfile.TarInfo, ) -> t.Optional[tarfile.TarInfo]: if tar_info.path == "./models" or tar_info.path.startswith( "./models/" ): return None return tar_info tar.add(bento_dir_path, arcname="./", filter=filter_) tar_io.seek(0, 0) with self.spin(text=f'Start uploading Bento "{bento.tag}"..'): yatai_rest_client.start_upload_bento( bento_repository_name=bento_repository.name, version=version ) file_size = tar_io.getbuffer().nbytes self.transmission_progress.update( upload_task_id, completed=0, total=file_size, visible=True ) self.transmission_progress.start_task(upload_task_id) def io_cb(x: int): self.transmission_progress.update(upload_task_id, advance=x) wrapped_file = CallbackIOWrapper( io_cb, tar_io, "read", ) finish_req = FinishUploadBentoSchema( status=BentoUploadStatus.SUCCESS, reason="", ) try: resp = requests.put( remote_bento.presigned_upload_url, data=wrapped_file ) if resp.status_code != 200: finish_req = FinishUploadBentoSchema( status=BentoUploadStatus.FAILED, reason=resp.text, ) except Exception as e: # pylint: disable=broad-except finish_req = FinishUploadBentoSchema( status=BentoUploadStatus.FAILED, reason=str(e), ) if finish_req.status is BentoUploadStatus.FAILED: self.log_progress.add_task( f'[bold red]Failed to upload Bento "{bento.tag}"' ) with self.spin(text="Submitting upload status to Yatai"): yatai_rest_client.finish_upload_bento( bento_repository_name=bento_repository.name, version=version, req=finish_req, ) if finish_req.status != BentoUploadStatus.SUCCESS: self.log_progress.add_task( f'[bold red]Failed pushing Bento "{bento.tag}": {finish_req.reason}' ) else: self.log_progress.add_task( f'[bold green]Successfully pushed Bento "{bento.tag}"' ) @inject def pull_bento( self, tag: t.Union[str, Tag], *, force: bool = False, bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Bento": with Live(self.progress_group): download_task_id = self.transmission_progress.add_task( f'Pulling bento "{tag}"', start=False, visible=False ) return self._do_pull_bento( tag, download_task_id, force=force, bento_store=bento_store, model_store=model_store, ) @inject def _do_pull_bento( self, tag: t.Union[str, Tag], download_task_id: TaskID, *, force: bool = False, bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Bento": try: bento = bento_store.get(tag) if not force: self.log_progress.add_task( f'[bold blue]Bento "{tag}" exists in local model store' ) return bento bento_store.delete(tag) except NotFound: pass _tag = Tag.from_taglike(tag) name = _tag.name version = _tag.version if version is None: raise BentoMLException(f'Bento "{_tag}" version can not be None') yatai_rest_client = get_current_yatai_rest_api_client() with self.spin(text=f'Fetching bento "{_tag}"'): remote_bento = yatai_rest_client.get_bento( bento_repository_name=name, version=version ) if not remote_bento: raise BentoMLException(f'Bento "{_tag}" not found on Yatai') with ThreadPoolExecutor( max_workers=max(len(remote_bento.manifest.models), 1) ) as executor: def pull_model(model_tag: Tag): model_download_task_id = self.transmission_progress.add_task( f'Pulling model "{model_tag}"', start=False, visible=False ) self._do_pull_model( model_tag, model_download_task_id, force=force, model_store=model_store, ) futures = executor.map(pull_model, remote_bento.manifest.models) list(futures) with self.spin(text=f'Getting a presigned download url for bento "{_tag}"'): remote_bento = yatai_rest_client.presign_bento_download_url(name, version) url = remote_bento.presigned_download_url response = requests.get(url, stream=True) if response.status_code != 200: raise BentoMLException( f'Failed to download bento "{_tag}": {response.text}' ) total_size_in_bytes = int(response.headers.get("content-length", 0)) block_size = 1024 # 1 Kibibyte with NamedTemporaryFile() as tar_file: self.transmission_progress.update( download_task_id, completed=0, total=total_size_in_bytes, visible=True ) self.transmission_progress.start_task(download_task_id) for data in response.iter_content(block_size): self.transmission_progress.update(download_task_id, advance=len(data)) tar_file.write(data) self.log_progress.add_task( f'[bold green]Finished downloading all bento "{_tag}" files' ) tar_file.seek(0, 0) tar = tarfile.open(fileobj=tar_file, mode="r:gz") with fs.open_fs("temp://") as temp_fs: for member in tar.getmembers(): f = tar.extractfile(member) if f is None: continue p = Path(member.name) if p.parent != Path("."): temp_fs.makedirs(str(p.parent), recreate=True) temp_fs.writebytes(member.name, f.read()) bento = Bento.from_fs(temp_fs) for model_tag in remote_bento.manifest.models: with self.spin(text=f'Copying model "{model_tag}" to bento'): copy_model( model_tag, src_model_store=model_store, target_model_store=bento._model_store, # type: ignore ) bento = bento.save(bento_store) self.log_progress.add_task( f'[bold green]Successfully pulled bento "{_tag}"' ) return bento def push_model(self, model: "Model", *, force: bool = False): with Live(self.progress_group): upload_task_id = self.transmission_progress.add_task( f'Pushing model "{model.tag}"', start=False, visible=False ) self._do_push_model(model, upload_task_id, force=force) def _do_push_model( self, model: "Model", upload_task_id: TaskID, *, force: bool = False ): yatai_rest_client = get_current_yatai_rest_api_client() name = model.tag.name version = model.tag.version if version is None: raise BentoMLException(f'Model "{model.tag}" version cannot be None') info = model.info with self.spin(text=f'Fetching model repository "{name}"'): model_repository = yatai_rest_client.get_model_repository( model_repository_name=name ) if not model_repository: with self.spin(text=f'Model repository "{name}" not found, creating now..'): model_repository = yatai_rest_client.create_model_repository( req=CreateModelRepositorySchema(name=name, description="") ) with self.spin(text=f'Try fetching model "{model.tag}" from Yatai..'): remote_model = yatai_rest_client.get_model( model_repository_name=name, version=version ) if ( not force and remote_model and remote_model.upload_status == ModelUploadStatus.SUCCESS ): self.log_progress.add_task( f'[bold blue]Model "{model.tag}" already exists in Yatai, skipping' ) return if not remote_model: labels: t.List[LabelItemSchema] = [ LabelItemSchema(key=key, value=value) for key, value in info.labels.items() ] with self.spin(text=f'Registering model "{model.tag}" with Yatai..'): yatai_rest_client.create_model( model_repository_name=model_repository.name, req=CreateModelSchema( description="", version=version, build_at=info.creation_time, manifest=ModelManifestSchema( module=info.module, metadata=info.metadata, context=info.context.to_dict(), options=info.options.to_dict(), api_version=info.api_version, bentoml_version=info.context.bentoml_version, size_bytes=calc_dir_size(model.path), ), labels=labels, ), ) with self.spin( text=f'Getting a presigned upload url for model "{model.tag}"..' ): remote_model = yatai_rest_client.presign_model_upload_url( model_repository_name=model_repository.name, version=version ) with io.BytesIO() as tar_io: bento_dir_path = model.path with self.spin(text=f'Creating tar archive for model "{model.tag}"..'): with tarfile.open(fileobj=tar_io, mode="w:gz") as tar: tar.add(bento_dir_path, arcname="./") tar_io.seek(0, 0) with self.spin(text=f'Start uploading model "{model.tag}"..'): yatai_rest_client.start_upload_model( model_repository_name=model_repository.name, version=version ) file_size = tar_io.getbuffer().nbytes self.transmission_progress.update( upload_task_id, description=f'Uploading model "{model.tag}"', total=file_size, visible=True, ) self.transmission_progress.start_task(upload_task_id) def io_cb(x: int): self.transmission_progress.update(upload_task_id, advance=x) wrapped_file = CallbackIOWrapper( io_cb, tar_io, "read", ) finish_req = FinishUploadModelSchema( status=ModelUploadStatus.SUCCESS, reason="", ) try: resp = requests.put( remote_model.presigned_upload_url, data=wrapped_file ) if resp.status_code != 200: finish_req = FinishUploadModelSchema( status=ModelUploadStatus.FAILED, reason=resp.text, ) except Exception as e: # pylint: disable=broad-except finish_req = FinishUploadModelSchema( status=ModelUploadStatus.FAILED, reason=str(e), ) if finish_req.status is ModelUploadStatus.FAILED: self.log_progress.add_task( f'[bold red]Failed to upload model "{model.tag}"' ) with self.spin(text="Submitting upload status to Yatai"): yatai_rest_client.finish_upload_model( model_repository_name=model_repository.name, version=version, req=finish_req, ) if finish_req.status != ModelUploadStatus.SUCCESS: self.log_progress.add_task( f'[bold red]Failed pushing model "{model.tag}" : {finish_req.reason}' ) else: self.log_progress.add_task( f'[bold green]Successfully pushed model "{model.tag}"' ) @inject def pull_model( self, tag: t.Union[str, Tag], *, force: bool = False, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Model": with Live(self.progress_group): download_task_id = self.transmission_progress.add_task( f'Pulling model "{tag}"', start=False, visible=False ) return self._do_pull_model( tag, download_task_id, force=force, model_store=model_store ) @inject def _do_pull_model( self, tag: t.Union[str, Tag], download_task_id: TaskID, *, force: bool = False, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "Model": try: model = model_store.get(tag) if not force: self.log_progress.add_task( f'[bold blue]Model "{tag}" already exists locally, skipping' ) return model else: model_store.delete(tag) except NotFound: pass yatai_rest_client = get_current_yatai_rest_api_client() _tag = Tag.from_taglike(tag) name = _tag.name version = _tag.version if version is None: raise BentoMLException(f'Model "{_tag}" version cannot be None') with self.spin(text=f'Getting a presigned download url for model "{_tag}"..'): remote_model = yatai_rest_client.presign_model_download_url(name, version) if not remote_model: raise BentoMLException(f'Model "{_tag}" not found on Yatai') url = remote_model.presigned_download_url response = requests.get(url, stream=True) if response.status_code != 200: raise BentoMLException( f'Failed to download model "{_tag}": {response.text}' ) total_size_in_bytes = int(response.headers.get("content-length", 0)) block_size = 1024 # 1 Kibibyte with NamedTemporaryFile() as tar_file: self.transmission_progress.update( download_task_id, description=f'Downloading model "{_tag}"', total=total_size_in_bytes, visible=True, ) self.transmission_progress.start_task(download_task_id) for data in response.iter_content(block_size): self.transmission_progress.update(download_task_id, advance=len(data)) tar_file.write(data) self.log_progress.add_task( f'[bold green]Finished downloading model "{_tag}" files' ) tar_file.seek(0, 0) tar = tarfile.open(fileobj=tar_file, mode="r:gz") with fs.open_fs("temp://") as temp_fs: for member in tar.getmembers(): f = tar.extractfile(member) if f is None: continue p = Path(member.name) if p.parent != Path("."): temp_fs.makedirs(str(p.parent), recreate=True) temp_fs.writebytes(member.name, f.read()) model = Model.from_fs(temp_fs).save(model_store) self.log_progress.add_task( f'[bold green]Successfully pulled model "{_tag}"' ) return model yatai_client = YataiClient()
import os import uuid import shutil import logging import importlib import importlib.util from ..configuration import is_pypi_installed_bentoml from ..utils.tempdir import TempDirectory logger = logging.getLogger(__name__) BENTOML_DEV_BUILD = "BENTOML_BUNDLE_LOCAL_BUILD" def build_bentoml_editable_wheel(target_path: str) -> None: """This is for BentoML developers to create Bentos that contains their local bentoml build base on their development branch. To enable this behavior, the developer must set env var BENTOML_BUNDLE_LOCAL_BUILD=True before building a Bento. If bentoml is installed in editor mode(pip install -e), this will build a wheel distribution with the local bentoml source and add it to saved bento directory under {bento_path}/env/python/wheels/ """ if str(os.environ.get(BENTOML_DEV_BUILD, False)).lower() != "true": return if is_pypi_installed_bentoml(): # skip this entirely if BentoML is installed from PyPI return # Find bentoml module path (module_location,) = importlib.util.find_spec("bentoml").submodule_search_locations # type: ignore # noqa bentoml_setup_py = os.path.abspath(os.path.join(module_location, "..", "setup.py")) # type: ignore # this is for BentoML developer to create Service containing custom development # branches of BentoML library, it is True only when BentoML module is installed # in development mode via "pip install --editable ." if os.path.isfile(bentoml_setup_py): logger.info( "BentoML is installed in `editable` mode; building BentoML distribution with the local BentoML code base. The built wheel file will be included in the target bento." ) # temp dir for creating the distribution with TempDirectory() as dist_dir: # Assuming developer has setuptools installed from dev-requirements.txt from setuptools import sandbox bdist_dir = os.path.join("build", str(uuid.uuid4())[0:8]) sandbox.run_setup( # type: ignore bentoml_setup_py, [ "--quiet", "bdist_wheel", "--dist-dir", dist_dir, "--bdist-dir", bdist_dir, ], ) # copy the built wheel file to target directory shutil.copytree(dist_dir, target_path) # type: ignore else: logger.info( "Custom BentoML build is detected. For a Bento to use the same build at serving time, add your custom BentoML build to the pip packages list, e.g. `packages=['git+https://github.com/bentoml/bentoml.git@13dfb36']`" )
from __future__ import annotations import os import re import typing as t import logging from sys import version_info from typing import TYPE_CHECKING import attr from jinja2 import Environment from jinja2.loaders import FileSystemLoader from ..utils import resolve_user_filepath from .docker import DistroSpec from ...exceptions import BentoMLException from ..configuration import BENTOML_VERSION logger = logging.getLogger(__name__) if TYPE_CHECKING: P = t.ParamSpec("P") from .build_config import DockerOptions TemplateFunc = t.Callable[[DockerOptions], t.Dict[str, t.Any]] GenericFunc = t.Callable[P, t.Any] BENTO_UID_GID = 1034 BENTO_USER = "bentoml" BENTO_HOME = f"/home/{BENTO_USER}/" BENTO_PATH = f"{BENTO_HOME}bento" BLOCKS = { "SETUP_BENTO_BASE_IMAGE", "SETUP_BENTO_USER", "SETUP_BENTO_ENVARS", "SETUP_BENTO_COMPONENTS", "SETUP_BENTO_ENTRYPOINT", } def clean_bentoml_version(bentoml_version: str) -> str: post_version = bentoml_version.split("+")[0] match = re.match(r"^(\d+).(\d+).(\d+)(?:(a|rc)\d)*", post_version) if match is None: raise BentoMLException("Errors while parsing BentoML version.") return match.group() def expands_bento_path(*path: str, bento_path: str = BENTO_PATH) -> str: """ Expand a given paths with respect to :code:`BENTO_PATH`. Note on using "/": the returned path is meant to be used in the generated Dockerfile. """ return "/".join([bento_path, *path]) J2_FUNCTION: dict[str, GenericFunc[t.Any]] = { "clean_bentoml_version": clean_bentoml_version, "expands_bento_path": expands_bento_path, } @attr.frozen(on_setattr=None, eq=False, repr=False) class ReservedEnv: base_image: str supported_architectures: list[str] bentoml_version: str = attr.field( default=BENTOML_VERSION, converter=clean_bentoml_version ) python_version_full: str = attr.field( default=f"{version_info.major}.{version_info.minor}.{version_info.micro}" ) def todict(self): return {f"__{k}__": v for k, v in attr.asdict(self).items()} @attr.frozen(on_setattr=None, eq=False, repr=False) class CustomizableEnv: uid_gid: int = attr.field(default=BENTO_UID_GID) user: str = attr.field(default=BENTO_USER) home: str = attr.field(default=BENTO_HOME) path: str = attr.field(default=BENTO_PATH) def todict(self) -> dict[str, str]: return {f"bento__{k}": v for k, v in attr.asdict(self).items()} def get_templates_variables( options: DockerOptions, use_conda: bool ) -> dict[str, t.Any]: """ Returns a dictionary of variables to be used in BentoML base templates. """ distro = options.distro cuda_version = options.cuda_version python_version = options.python_version if options.base_image is None: spec = DistroSpec.from_distro( distro, cuda=cuda_version is not None, conda=use_conda ) if cuda_version is not None: base_image = spec.image.format(spec_version=cuda_version) else: if distro in ["ubi8"]: python_version = python_version.replace(".", "") else: python_version = python_version base_image = spec.image.format(spec_version=python_version) supported_architecture = spec.supported_architectures else: base_image = options.base_image supported_architecture = ["amd64"] logger.info( f"BentoML will not install Python to custom base images; ensure the base image '{base_image}' has Python installed." ) # environment returns are # __base_image__, __supported_architectures__, __bentoml_version__, __python_version_full__ # bento__uid_gid, bento__user, bento__home, bento__path # __options__distros, __options__base_image, __options_env, __options_system_packages, __options_setup_script return { **{f"__options__{k}": v for k, v in attr.asdict(options).items()}, **CustomizableEnv().todict(), **ReservedEnv(base_image, supported_architecture).todict(), } def generate_dockerfile( options: DockerOptions, build_ctx: str, *, use_conda: bool ) -> str: """ Generate a Dockerfile that containerize a Bento. Args: docker_options (:class:`DockerOptions`): Docker Options class parsed from :code:`bentofile.yaml` or any arbitrary Docker options class. use_conda (:code:`bool`, `required`): Whether to use conda in the given Dockerfile. Returns: str: The rendered Dockerfile string. .. dropdown:: Implementation Notes The coresponding Dockerfile template will be determined automatically based on given :class:`DockerOptions`. The templates are located `here <https://github.com/bentoml/BentoML/tree/main/bentoml/_internal/bento/docker/templates>`_ As one can see, the Dockerfile templates are organized with the format :code:`<release_type>_<distro>.j2` with: +---------------+------------------------------------------+ | Release type | Description | +===============+==========================================+ | base | A base setup for all supported distros. | +---------------+------------------------------------------+ | cuda | CUDA-supported templates. | +---------------+------------------------------------------+ | miniconda | Conda-supported templates. | +---------------+------------------------------------------+ | python | Python releases. | +---------------+------------------------------------------+ Each of the templates will be validated correctly before being rendered. This will also include the user-defined custom templates if :code:`dockerfile_template` is specified. .. code-block:: python from bentoml._internal.bento.gen import generate_dockerfile from bentoml._internal.bento.bento import BentoInfo docker_options = BentoInfo.from_yaml_file("{bento_path}/bento.yaml").docker docker_options.docker_template = "./override_template.j2" dockerfile = generate_dockerfile(docker_options, use_conda=False) """ distro = options.distro use_cuda = options.cuda_version is not None user_templates = options.dockerfile_template TEMPLATES_PATH = [os.path.join(os.path.dirname(__file__), "docker", "templates")] ENVIRONMENT = Environment( extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols", "jinja2.ext.debug"], trim_blocks=True, lstrip_blocks=True, loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True), ) if options.base_image is not None: base = "base.j2" else: spec = DistroSpec.from_distro(distro, cuda=use_cuda, conda=use_conda) base = f"{spec.release_type}_{distro}.j2" template = ENVIRONMENT.get_template(base, globals=J2_FUNCTION) logger.debug( f"Using base Dockerfile template: {base}, and their path: {os.path.join(TEMPLATES_PATH[0], base)}" ) if user_templates is not None: dir_path = os.path.dirname(resolve_user_filepath(user_templates, build_ctx)) user_templates = os.path.basename(user_templates) TEMPLATES_PATH.append(dir_path) new_loader = FileSystemLoader(TEMPLATES_PATH, followlinks=True) environment = ENVIRONMENT.overlay(loader=new_loader) template = environment.get_template( user_templates, globals={"bento_base_template": template, **J2_FUNCTION}, ) return template.render(**get_templates_variables(options, use_conda=use_conda))
from .bento import Bento from .bento import BentoStore __all__ = ["Bento", "BentoStore"]
from __future__ import annotations import os import typing as t import logging from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone import fs import attr import yaml import fs.osfs import pathspec import fs.errors import fs.mirror from fs.copy import copy_file from cattr.gen import override # type: ignore (incomplete cattr types) from cattr.gen import make_dict_unstructure_fn # type: ignore (incomplete cattr types) from simple_di import inject from simple_di import Provide from ..tag import Tag from ..store import Store from ..store import StoreItem from ..types import PathType from ..utils import bentoml_cattr from ..utils import copy_file_to_fs_folder from ..models import ModelStore from ..runner import Runner from ...exceptions import InvalidArgument from ...exceptions import BentoMLException from .build_config import CondaOptions from .build_config import DockerOptions from .build_config import PythonOptions from .build_config import BentoBuildConfig from ..configuration import BENTOML_VERSION from ..runner.resource import Resource from ..configuration.containers import BentoMLContainer if TYPE_CHECKING: from fs.base import FS from ..models import Model from ..service import Service from ..service.inference_api import InferenceAPI logger = logging.getLogger(__name__) BENTO_YAML_FILENAME = "bento.yaml" BENTO_PROJECT_DIR_NAME = "src" BENTO_README_FILENAME = "README.md" DEFAULT_BENTO_BUILD_FILE = "bentofile.yaml" def get_default_bento_readme(svc: "Service"): doc = f'# BentoML Service "{svc.name}"\n\n' doc += "This is a Machine Learning Service created with BentoML. \n\n" if svc.apis: doc += "## Inference APIs:\n\nIt contains the following inference APIs:\n\n" for api in svc.apis.values(): doc += f"### /{api.name}\n\n" doc += f"* Input: {api.input.__class__.__name__}\n" doc += f"* Output: {api.output.__class__.__name__}\n\n" doc += """ ## Customize This Message This is the default generated `bentoml.Service` doc. You may customize it in your Bento build file, e.g.: ```yaml service: "image_classifier.py:svc" description: "file: ./readme.md" labels: foo: bar team: abc docker: distro: debian gpu: True python: packages: - tensorflow - numpy ``` """ # TODO: add links to documentation that may help with API client development return doc @attr.define(repr=False, auto_attribs=False) class Bento(StoreItem): _tag: Tag = attr.field() __fs: "FS" = attr.field() _info: "BentoInfo" _model_store: ModelStore _doc: t.Optional[str] = None @staticmethod def _export_ext() -> str: return "bento" @__fs.validator # type:ignore # attrs validators not supported by pyright def check_fs(self, _attr: t.Any, new_fs: "FS"): try: new_fs.makedir("models", recreate=True) except fs.errors.ResourceReadOnly: # when we import a tarfile, it will be read-only, so just skip the step where we create # the models folder. pass self._model_store = ModelStore(new_fs.opendir("models")) def __init__(self, tag: Tag, bento_fs: "FS", info: "BentoInfo"): self._tag = tag self.__fs = bento_fs self.check_fs(None, bento_fs) self._info = info self.validate() @property def tag(self) -> Tag: return self._tag @property def _fs(self) -> "FS": return self.__fs @property def info(self) -> "BentoInfo": return self._info @classmethod @inject def create( cls, build_config: BentoBuildConfig, version: t.Optional[str] = None, build_ctx: t.Optional[str] = None, ) -> Bento: from ..service.loader import import_service build_ctx = ( os.getcwd() if build_ctx is None else os.path.realpath(os.path.expanduser(build_ctx)) ) assert os.path.isdir(build_ctx), f"build ctx {build_ctx} does not exist" # This also verifies that svc can be imported correctly svc = import_service( build_config.service, working_dir=build_ctx, change_global_cwd=True ) # Apply default build options build_config = build_config.with_defaults() tag = Tag(svc.name, version) if version is None: tag = tag.make_new_version() logger.info( f'Building BentoML service "{tag}" from build context "{build_ctx}"' ) bento_fs = fs.open_fs(f"temp://bentoml_bento_{svc.name}") ctx_fs = fs.open_fs(build_ctx) models: t.Set[Model] = set() # Add all models required by the service for model in svc.models: models.add(model) # Add all models required by service runners for runner in svc.runners: for model in runner.models: models.add(model) bento_fs.makedir("models", recreate=True) bento_model_store = ModelStore(bento_fs.opendir("models")) for model in models: logger.info(f'Packing model "{model.tag}"') model._save(bento_model_store) # type: ignore[reportPrivateUsage] # Copy all files base on include and exclude, into `src` directory relpaths = [s for s in build_config.include if s.startswith("../")] if len(relpaths) != 0: raise InvalidArgument( "Paths outside of the build context directory cannot be included; use a symlink or copy those files into the working directory manually." ) spec = pathspec.PathSpec.from_lines("gitwildmatch", build_config.include) exclude_spec = pathspec.PathSpec.from_lines( "gitwildmatch", build_config.exclude ) exclude_specs: t.List[t.Tuple[str, pathspec.PathSpec]] = [] bento_fs.makedir(BENTO_PROJECT_DIR_NAME) target_fs = bento_fs.opendir(BENTO_PROJECT_DIR_NAME) for dir_path, _, files in ctx_fs.walk(): for ignore_file in [f for f in files if f.name == ".bentoignore"]: exclude_specs.append( ( dir_path, pathspec.PathSpec.from_lines( "gitwildmatch", ctx_fs.open(ignore_file.make_path(dir_path)) ), ) ) cur_exclude_specs: t.List[t.Tuple[str, pathspec.PathSpec]] = [] for ignore_path, _spec in exclude_specs: if fs.path.isparent(ignore_path, dir_path): cur_exclude_specs.append((ignore_path, _spec)) for f in files: _path = fs.path.combine(dir_path, f.name).lstrip("/") if spec.match_file(_path) and not exclude_spec.match_file(_path): if not any( _spec.match_file(fs.path.relativefrom(ignore_path, _path)) for ignore_path, _spec in cur_exclude_specs ): target_fs.makedirs(dir_path, recreate=True) copy_file(ctx_fs, _path, target_fs, _path) build_config.docker.write_to_bento(bento_fs, build_ctx, build_config.conda) build_config.python.write_to_bento(bento_fs, build_ctx) build_config.conda.write_to_bento(bento_fs, build_ctx) # Create `readme.md` file if build_config.description is None: with bento_fs.open(BENTO_README_FILENAME, "w", encoding="utf-8") as f: f.write(get_default_bento_readme(svc)) else: if build_config.description.startswith("file:"): file_name = build_config.description[5:].strip() copy_file_to_fs_folder( file_name, bento_fs, dst_filename=BENTO_README_FILENAME ) else: with bento_fs.open(BENTO_README_FILENAME, "w") as f: f.write(build_config.description) # Create 'apis/openapi.yaml' file bento_fs.makedir("apis") with bento_fs.open(fs.path.combine("apis", "openapi.yaml"), "w") as f: yaml.dump(svc.openapi_doc(), f) res = Bento( tag, bento_fs, BentoInfo( tag=tag, service=svc, # type: ignore # attrs converters do not typecheck labels=build_config.labels, models=[BentoModelInfo.from_bento_model(m) for m in models], runners=[BentoRunnerInfo.from_runner(r) for r in svc.runners], apis=[ BentoApiInfo.from_inference_api(api) for api in svc.apis.values() ], docker=build_config.docker, python=build_config.python, conda=build_config.conda, ), ) # Create bento.yaml res.flush_info() return res @classmethod def from_fs(cls, item_fs: "FS") -> "Bento": try: with item_fs.open(BENTO_YAML_FILENAME, "r", encoding="utf-8") as bento_yaml: info = BentoInfo.from_yaml_file(bento_yaml) except fs.errors.ResourceNotFound: raise BentoMLException( f"Failed to load bento because it does not contain a '{BENTO_YAML_FILENAME}'" ) res = cls(info.tag, item_fs, info) if not res.validate(): raise BentoMLException( f"Failed to create bento because it contains an invalid '{BENTO_YAML_FILENAME}'" ) return res @property def path(self) -> str: return self.path_of("/") def path_of(self, item: str) -> str: return self._fs.getsyspath(item) def flush_info(self): with self._fs.open(BENTO_YAML_FILENAME, "w") as bento_yaml: self.info.dump(bento_yaml) @property def doc(self) -> str: if self._doc is not None: return self._doc with self._fs.open(BENTO_README_FILENAME, "r") as readme_md: self._doc = str(readme_md.read()) return self._doc @property def creation_time(self) -> datetime: return self.info.creation_time @inject def save( self, bento_store: "BentoStore" = Provide[BentoMLContainer.bento_store], ) -> "Bento": if not self.validate(): logger.warning(f"Failed to create Bento for {self.tag}, not saving.") raise BentoMLException("Failed to save Bento because it was invalid.") with bento_store.register(self.tag) as bento_path: out_fs = fs.open_fs(bento_path, create=True, writeable=True) fs.mirror.mirror(self._fs, out_fs, copy_if_newer=False) self._fs.close() self.__fs = out_fs return self def validate(self): return self._fs.isfile(BENTO_YAML_FILENAME) def __str__(self): return f'Bento(tag="{self.tag}")' class BentoStore(Store[Bento]): def __init__(self, base_path: t.Union[PathType, "FS"]): super().__init__(base_path, Bento) @attr.define(frozen=True, on_setattr=None) class BentoRunnerInfo: name: str runnable_type: str models: t.List[str] = attr.field(factory=list) resource_config: t.Optional[Resource] = attr.field(default=None) @classmethod def from_runner(cls, r: Runner) -> "BentoRunnerInfo": # Add runner default resource quota and batching config here return cls( name=r.name, # type: ignore runnable_type=r.runnable_class.__name__, # type: ignore models=[str(model.tag) for model in r.models], # type: ignore resource_config=r.resource_config, # type: ignore ) # Remove after attrs support ForwardRef natively attr.resolve_types(BentoRunnerInfo, globals(), locals()) @attr.define(frozen=True, on_setattr=None) class BentoApiInfo: name: str input_type: str output_type: str @classmethod def from_inference_api(cls, api: "InferenceAPI") -> "BentoApiInfo": return cls( name=api.name, # type: ignore input_type=api.input.__class__.__name__, # type: ignore output_type=api.output.__class__.__name__, # type: ignore ) # Remove after attrs support ForwardRef natively attr.resolve_types(BentoApiInfo, globals(), locals()) @attr.define(frozen=True, on_setattr=None) class BentoModelInfo: tag: Tag = attr.field(converter=Tag.from_taglike) module: str creation_time: datetime @classmethod def from_bento_model(cls, bento_model: "Model") -> "BentoModelInfo": return cls( tag=bento_model.tag, module=bento_model.info.module, creation_time=bento_model.info.creation_time, ) # Remove after attrs support ForwardRef natively attr.resolve_types(BentoModelInfo, globals(), locals()) @attr.define(repr=False, frozen=True, on_setattr=None) class BentoInfo: tag: Tag service: str = attr.field( converter=lambda svc: svc if isinstance(svc, str) else svc._import_str ) # type: ignore[reportPrivateUsage] name: str = attr.field(init=False) # converted from tag in __attrs_post_init__ version: str = attr.field(init=False) # converted from tag in __attrs_post_init__ bentoml_version: str = attr.field(default=BENTOML_VERSION) creation_time: datetime = attr.field(factory=lambda: datetime.now(timezone.utc)) labels: t.Dict[str, t.Any] = attr.field(factory=dict) models: t.List[BentoModelInfo] = attr.field(factory=list) runners: t.List[BentoRunnerInfo] = attr.field(factory=list) apis: t.List[BentoApiInfo] = attr.field(factory=list) docker: DockerOptions = attr.field(factory=lambda: DockerOptions().with_defaults()) python: PythonOptions = attr.field(factory=lambda: PythonOptions().with_defaults()) conda: CondaOptions = attr.field(factory=lambda: CondaOptions().with_defaults()) def __attrs_post_init__(self): # Direct set is not available when frozen=True object.__setattr__(self, "name", self.tag.name) object.__setattr__(self, "version", self.tag.version) self.validate() def to_dict(self) -> t.Dict[str, t.Any]: return bentoml_cattr.unstructure(self) # type: ignore (incomplete cattr types) def dump(self, stream: t.IO[t.Any]): return yaml.dump(self, stream, sort_keys=False) @classmethod def from_yaml_file(cls, stream: t.IO[t.Any]) -> "BentoInfo": try: yaml_content = yaml.safe_load(stream) except yaml.YAMLError as exc: logger.error(exc) raise assert yaml_content is not None yaml_content["tag"] = Tag(yaml_content["name"], yaml_content["version"]) del yaml_content["name"] del yaml_content["version"] # For backwards compatibility for bentos created prior to version 1.0.0rc1 if "runners" in yaml_content: runners = yaml_content["runners"] for r in runners: if "runner_type" in r: # BentoRunnerInfo prior to 1.0.0rc1 release r["runnable_type"] = r["runner_type"] del r["runner_type"] if "model_runner_module" in r: del r["model_runner_module"] if "models" in yaml_content: # For backwards compatibility for bentos created prior to version 1.0.0a7 models = yaml_content["models"] if models and len(models) > 0 and isinstance(models[0], str): yaml_content["models"] = list( map( lambda model_tag: { "tag": model_tag, "module": "unknown", "creation_time": datetime.fromordinal(1), }, models, ) ) try: # type: ignore[attr-defined] return bentoml_cattr.structure(yaml_content, cls) except KeyError as e: raise BentoMLException(f"Missing field {e} in {BENTO_YAML_FILENAME}") def validate(self): # Validate bento.yml file schema, content, bentoml version, etc ... # Remove after attrs support ForwardRef natively attr.resolve_types(BentoInfo, globals(), locals()) bentoml_cattr.register_unstructure_hook( BentoInfo, # Ignore tag, tag is saved via the name and version field make_dict_unstructure_fn(BentoInfo, bentoml_cattr, tag=override(omit=True)), # type: ignore ) def _BentoInfo_dumper(dumper: yaml.Dumper, info: BentoInfo) -> yaml.Node: return dumper.represent_dict(info.to_dict()) yaml.add_representer(BentoInfo, _BentoInfo_dumper) # type: ignore (incomplete yaml types)
from __future__ import annotations import typing as t import logging from typing import TYPE_CHECKING import attr from ...exceptions import InvalidArgument from ...exceptions import BentoMLException if TYPE_CHECKING: P = t.ParamSpec("P") logger = logging.getLogger(__name__) # Python supported versions SUPPORTED_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] # CUDA supported versions SUPPORTED_CUDA_VERSIONS = {"11": "11.6.2"} # Supported supported_architectures SUPPORTED_ARCHITECTURES = ["amd64", "arm64", "ppc64le", "s390x"] # Supported release types SUPPORTED_RELEASE_TYPES = ["python", "miniconda", "cuda"] # BentoML supported distros mapping spec with # keys represents distros, and value is a tuple of list for supported python # versions and list of supported CUDA versions. DOCKER_METADATA: dict[str, dict[str, t.Any]] = { "amazonlinux": { "supported_python_versions": ["3.7", "3.8"], "supported_cuda_versions": None, "python": { "image": "amazonlinux:2", "supported_architectures": ["amd64", "arm64"], }, }, "ubi8": { "supported_python_versions": ["3.8", "3.9"], "supported_cuda_versions": list(SUPPORTED_CUDA_VERSIONS.values()), "python": { "image": "registry.access.redhat.com/ubi8/python-{spec_version}:1", "supported_architectures": ["amd64", "arm64"], }, "cuda": { "image": "nvidia/cuda:{spec_version}-cudnn8-runtime-ubi8", "supported_architectures": ["amd64", "arm64", "ppc64le"], }, }, "debian": { "supported_python_versions": SUPPORTED_PYTHON_VERSIONS, "supported_cuda_versions": list(SUPPORTED_CUDA_VERSIONS.values()), "python": { "image": "python:{spec_version}-slim", "supported_architectures": SUPPORTED_ARCHITECTURES, }, "cuda": { "image": "nvidia/cuda:{spec_version}-cudnn8-runtime-ubuntu20.04", "supported_architectures": ["amd64", "arm64"], }, "miniconda": { "image": "continuumio/miniconda3:latest", "supported_architectures": SUPPORTED_ARCHITECTURES, }, }, "alpine": { "supported_python_versions": SUPPORTED_PYTHON_VERSIONS, "supported_cuda_versions": None, "python": { "image": "python:{spec_version}-alpine", "supported_architectures": SUPPORTED_ARCHITECTURES, }, "miniconda": { "image": "continuumio/miniconda3:4.10.3p0-alpine", "supported_architectures": ["amd64"], }, }, } DOCKER_SUPPORTED_DISTROS = list(DOCKER_METADATA.keys()) def get_supported_spec(spec: t.Literal["python", "miniconda", "cuda"]) -> list[str]: if spec not in SUPPORTED_RELEASE_TYPES: raise InvalidArgument( f"Unknown release type: {spec}, supported spec: {SUPPORTED_RELEASE_TYPES}" ) return [v for v in DOCKER_METADATA if spec in DOCKER_METADATA[v]] @attr.define(slots=True, frozen=True) class DistroSpec: name: str = attr.field() image: str = attr.field(kw_only=True) release_type: str = attr.field(kw_only=True) supported_python_versions: t.List[str] = attr.field( validator=attr.validators.deep_iterable( lambda _, __, value: value in SUPPORTED_PYTHON_VERSIONS, iterable_validator=attr.validators.instance_of(list), ), ) supported_cuda_versions: t.List[str] = attr.field( default=None, validator=attr.validators.optional( attr.validators.deep_iterable( lambda _, __, value: value in SUPPORTED_CUDA_VERSIONS.values(), ) ), ) supported_architectures: t.List[str] = attr.field( default=SUPPORTED_ARCHITECTURES, validator=attr.validators.deep_iterable( lambda _, __, value: value in SUPPORTED_ARCHITECTURES, ), ) @classmethod def from_distro( cls, value: str, *, cuda: bool = False, conda: bool = False, ) -> DistroSpec: if not value: raise BentoMLException("Distro name is required, got None instead.") if value not in DOCKER_METADATA: raise BentoMLException( f"{value} is not supported. " f"Supported distros are: {', '.join(DOCKER_METADATA.keys())}." ) if cuda: release_type = "cuda" elif conda: release_type = "miniconda" else: release_type = "python" meta = DOCKER_METADATA[value] python_version = meta["supported_python_versions"] cuda_version = ( meta["supported_cuda_versions"] if release_type == "cuda" else None ) return cls( **meta[release_type], name=value, release_type=release_type, supported_python_versions=python_version, supported_cuda_versions=cuda_version, )
import os import re import sys import typing as t import logging import subprocess from sys import version_info as pyver from typing import TYPE_CHECKING import fs import attr import yaml import fs.copy from dotenv import dotenv_values # type: ignore from .gen import generate_dockerfile from ..utils import bentoml_cattr from ..utils import resolve_user_filepath from ..utils import copy_file_to_fs_folder from .docker import DistroSpec from .docker import get_supported_spec from .docker import SUPPORTED_CUDA_VERSIONS from .docker import DOCKER_SUPPORTED_DISTROS from .docker import SUPPORTED_PYTHON_VERSIONS from ...exceptions import InvalidArgument from ...exceptions import BentoMLException from .build_dev_bentoml_whl import build_bentoml_editable_wheel if pyver >= (3, 8): from typing import Literal else: from typing_extensions import Literal if TYPE_CHECKING: from attr import Attribute from fs.base import FS if pyver >= (3, 10): from typing import TypeAlias else: from typing_extensions import TypeAlias logger = logging.getLogger(__name__) PYTHON_VERSION = f"{pyver.major}.{pyver.minor}" PYTHON_FULL_VERSION = f"{pyver.major}.{pyver.minor}.{pyver.micro}" # Docker defaults DEFAULT_CUDA_VERSION = "11.6.2" DEFAULT_DOCKER_DISTRO = "debian" CONDA_ENV_YAML_FILE_NAME = "environment.yml" if PYTHON_VERSION not in SUPPORTED_PYTHON_VERSIONS: logger.warning( f"BentoML may not work well with current python version: {PYTHON_VERSION}, " f"supported python versions are: {', '.join(SUPPORTED_PYTHON_VERSIONS)}" ) def _convert_python_version(py_version: t.Optional[str]) -> t.Optional[str]: if py_version is None: return None if not isinstance(py_version, str): py_version = str(py_version) match = re.match(r"^(\d+).(\d+)", py_version) if match is None: raise InvalidArgument( f'Invalid build option: docker.python_version="{py_version}", python ' f"version must follow standard python semver format, e.g. 3.7.10 ", ) major, minor = match.groups() return f"{major}.{minor}" def _convert_cuda_version(cuda_version: t.Optional[str]) -> t.Optional[str]: if cuda_version is None or cuda_version == "": return None if isinstance(cuda_version, int): cuda_version = str(cuda_version) if cuda_version == "default": cuda_version = DEFAULT_CUDA_VERSION match = re.match(r"^(\d+)$", cuda_version) if match is not None: cuda_version = SUPPORTED_CUDA_VERSIONS[cuda_version] return cuda_version def _convert_user_envars( envars: t.Optional[t.Union[t.List[str], t.Dict[str, t.Any]]] ) -> t.Optional[t.Dict[str, t.Any]]: if envars is None: return None if isinstance(envars, list): return {k: v for e in envars for k, v in e.split("=")} else: return envars def _envars_validator( _: t.Any, attribute: "Attribute[t.Union[str, t.List[str], t.Dict[str, t.Any]]]", value: t.Union[str, t.List[str], t.Dict[str, t.Any]], ) -> None: if isinstance(value, str): if not os.path.exists(value) and os.path.isfile(value): raise InvalidArgument( f'`env="{value}"` is not a valid path. if `env` is parsed as a string, it should be a path to an ".env" file.' ) envars_rgx = re.compile(r"(^[A-Z0-9_]+)(\=)(.*\n)") if isinstance(value, list): for envar in value: match = envars_rgx.match(envar) if match is None: raise InvalidArgument(f"{envar} doesn't follow format ENVAR=value") k, _ = envar.split("=") if not k.isupper(): raise InvalidArgument( f'Invalid env var defined, key "{k}" should be in uppercase.' ) elif isinstance(value, dict): if not all(k.isupper() for k in value): raise InvalidArgument("All envars should be in UPPERCASE.") else: raise InvalidArgument( f"`env` must be either a list or a dict, got type {attribute.type} instead." ) @attr.frozen class DockerOptions: distro: str = attr.field( default=None, validator=attr.validators.optional( attr.validators.in_(DOCKER_SUPPORTED_DISTROS) ), ) python_version: str = attr.field( converter=_convert_python_version, default=None, validator=attr.validators.optional( attr.validators.in_(SUPPORTED_PYTHON_VERSIONS) ), ) cuda_version: t.Union[str, Literal["default"]] = attr.field( default=None, converter=_convert_cuda_version, validator=attr.validators.optional( attr.validators.in_(SUPPORTED_CUDA_VERSIONS.values()) ), ) # A user-provided environment variable to be passed to a given bento # accepts the following format: # # env: # - ENVAR=value1 # - FOO=value2 # # env: # ENVAR: value1"Options" # FOO: value2 # # env: /path/to/.env env: t.Dict[str, t.Any] = attr.field( default=None, converter=_convert_user_envars, validator=attr.validators.optional(_envars_validator), ) # A user-provided system packages that can be installed for a given bento # using distro package manager. system_packages: t.Optional[t.List[str]] = None # A python or sh script that executes during docker build time setup_script: t.Optional[str] = None # A user-provided custom docker image base_image: t.Optional[str] = None # A user-provided dockerfile jinja2 template dockerfile_template: str = attr.field( default=None, validator=attr.validators.optional( lambda _, __, value: os.path.exists(value) and os.path.isfile(value) ), ) def __attrs_post_init__(self): if self.base_image is not None: if self.distro is not None: logger.warning( f"docker base_image {self.base_image} is used, " f"'distro={self.distro}' option is ignored.", ) if self.python_version is not None: logger.warning( f"docker base_image {self.base_image} is used, " f"'python={self.python_version}' option is ignored.", ) if self.cuda_version is not None: logger.warning( f"docker base_image {self.base_image} is used, " f"'cuda_version={self.cuda_version}' option is ignored.", ) if self.system_packages: logger.warning( f"docker base_image {self.base_image} is used, " f"'system_packages={self.system_packages}' option is ignored.", ) if self.distro is not None and self.cuda_version is not None: supports_cuda = get_supported_spec("cuda") if self.distro not in supports_cuda: raise BentoMLException( f'Distro "{self.distro}" does not support CUDA. Distros that support CUDA are: {supports_cuda}.' ) def with_defaults(self) -> "DockerOptions": # Convert from user provided options to actual build options with default values defaults: t.Dict[str, t.Any] = {} if self.base_image is None: if self.distro is None: defaults["distro"] = DEFAULT_DOCKER_DISTRO if self.python_version is None: defaults["python_version"] = PYTHON_VERSION if self.system_packages is None: defaults["system_packages"] = [] if self.env is None: defaults["env"] = {} if self.cuda_version is None: defaults["cuda_version"] = None if self.dockerfile_template is None: defaults["dockerfile_template"] = None return attr.evolve(self, **defaults) def write_to_bento( self, bento_fs: "FS", build_ctx: str, conda_options: "CondaOptions" ) -> None: use_conda = any( val is not None for _, val in bentoml_cattr.unstructure(conda_options).items() ) docker_folder = fs.path.combine("env", "docker") bento_fs.makedirs(docker_folder, recreate=True) dockerfile = fs.path.combine(docker_folder, "Dockerfile") with bento_fs.open(dockerfile, "w") as dockerfile: dockerfile.write( generate_dockerfile(self, build_ctx=build_ctx, use_conda=use_conda) ) copy_file_to_fs_folder( fs.path.join(os.path.dirname(__file__), "docker", "entrypoint.sh"), bento_fs, docker_folder, ) if self.setup_script: try: setup_script = resolve_user_filepath(self.setup_script, build_ctx) except FileNotFoundError as e: raise InvalidArgument(f"Invalid setup_script file: {e}") copy_file_to_fs_folder( setup_script, bento_fs, docker_folder, "setup_script" ) def _docker_options_structure_hook(d: t.Any, _: t.Type[DockerOptions]) -> DockerOptions: # Allow bentofile yaml to have either a str or list of str for these options if "env" in d and isinstance(d["env"], str): try: d["env"] = dotenv_values(d["env"]) except FileNotFoundError: raise BentoMLException(f"Invalid env file path: {d['env']}") return DockerOptions(**d) bentoml_cattr.register_structure_hook(DockerOptions, _docker_options_structure_hook) @attr.frozen class CondaOptions: environment_yml: t.Optional[str] = None channels: t.Optional[t.List[str]] = None dependencies: t.Optional[t.List[str]] = None pip: t.Optional[t.List[str]] = None # list of pip packages to install via conda def __attrs_post_init__(self): if self.environment_yml is not None: if self.channels is not None: logger.warning( "conda environment_yml %s is used, 'channels=%s' option is ignored", self.environment_yml, self.channels, ) if self.dependencies is not None: logger.warning( "conda environment_yml %s is used, 'dependencies=%s' option is ignored", self.environment_yml, self.dependencies, ) if self.pip is not None: logger.warning( "conda environment_yml %s is used, 'pip=%s' option is ignored", self.environment_yml, self.pip, ) def write_to_bento(self, bento_fs: "FS", build_ctx: str) -> None: conda_folder = fs.path.join("env", "conda") bento_fs.makedirs(conda_folder, recreate=True) if self.environment_yml is not None: environment_yml_file = resolve_user_filepath( self.environment_yml, build_ctx ) copy_file_to_fs_folder( environment_yml_file, bento_fs, conda_folder, dst_filename=CONDA_ENV_YAML_FILE_NAME, ) else: deps_list = [] if self.dependencies is None else self.dependencies if self.pip is not None: deps_list.append(dict(pip=self.pip)) # type: ignore if not deps_list: return yaml_content = dict(dependencies=deps_list) yaml_content["channels"] = self.channels with bento_fs.open( fs.path.join(conda_folder, CONDA_ENV_YAML_FILE_NAME), "w" ) as f: yaml.dump(yaml_content, f) def with_defaults(self) -> "CondaOptions": # Convert from user provided options to actual build options with default values defaults: t.Dict[str, t.Any] = {} # When `channels` field was left empty, apply the community maintained # channel `conda-forge` as default if ( (self.dependencies or self.pip) and not self.channels and not self.environment_yml ): defaults["channels"] = ["conda-forge"] return attr.evolve(self, **defaults) @attr.frozen class PythonOptions: requirements_txt: t.Optional[str] = None packages: t.Optional[t.List[str]] = None lock_packages: t.Optional[bool] = None index_url: t.Optional[str] = None no_index: t.Optional[bool] = None trusted_host: t.Optional[t.List[str]] = None find_links: t.Optional[t.List[str]] = None extra_index_url: t.Optional[t.List[str]] = None pip_args: t.Optional[str] = None wheels: t.Optional[t.List[str]] = None def __attrs_post_init__(self): if self.requirements_txt and self.packages: logger.warning( f'Build option python: requirements_txt="{self.requirements_txt}" found,' f' this will ignore the option: packages="{self.packages}"' ) if self.no_index and (self.index_url or self.extra_index_url): logger.warning( "Build option python.no_index=True found, this will ignore index_url" " and extra_index_url option when installing PyPI packages" ) def write_to_bento(self, bento_fs: "FS", build_ctx: str) -> None: py_folder = fs.path.join("env", "python") wheels_folder = fs.path.join(py_folder, "wheels") bento_fs.makedirs(py_folder, recreate=True) # Save the python version of current build environment with bento_fs.open(fs.path.join(py_folder, "version.txt"), "w") as f: f.write(PYTHON_FULL_VERSION) # Move over required wheel files # Note: although wheel files outside of build_ctx will also work, we should # discourage users from doing that if self.wheels is not None: for whl_file in self.wheels: # pylint: disable=not-an-iterable whl_file = resolve_user_filepath(whl_file, build_ctx) copy_file_to_fs_folder(whl_file, bento_fs, wheels_folder) build_bentoml_editable_wheel(bento_fs.getsyspath(wheels_folder)) if self.requirements_txt is not None: requirements_txt_file = resolve_user_filepath( self.requirements_txt, build_ctx ) copy_file_to_fs_folder( requirements_txt_file, bento_fs, py_folder, dst_filename="requirements.txt", ) elif self.packages is not None: with bento_fs.open(fs.path.join(py_folder, "requirements.txt"), "w") as f: f.write("\n".join(self.packages)) else: # Return early if no python packages were specified return pip_args: t.List[str] = [] if self.no_index: pip_args.append("--no-index") if self.index_url: pip_args.append(f"--index-url={self.index_url}") if self.trusted_host: for item in self.trusted_host: # pylint: disable=not-an-iterable pip_args.append(f"--trusted-host={item}") if self.find_links: for item in self.find_links: # pylint: disable=not-an-iterable pip_args.append(f"--find-links={item}") if self.extra_index_url: for item in self.extra_index_url: # pylint: disable=not-an-iterable pip_args.append(f"--extra-index-url={item}") if self.pip_args: # Additional user provided pip_args pip_args.append(self.pip_args) # write pip install args to a text file if applicable if pip_args: with bento_fs.open(fs.path.join(py_folder, "pip_args.txt"), "w") as f: f.write(" ".join(pip_args)) if self.lock_packages: # Note: "--allow-unsafe" is required for including setuptools in the # generated requirements.lock.txt file, and setuptool is required by # pyfilesystem2. Once pyfilesystem2 drop setuptools as dependency, we can # remove the "--allow-unsafe" flag here. # Note: "--generate-hashes" is purposefully not used here because it will # break if user includes PyPI package from version control system pip_compile_in = bento_fs.getsyspath( fs.path.join(py_folder, "requirements.txt") ) pip_compile_out = bento_fs.getsyspath( fs.path.join(py_folder, "requirements.lock.txt") ) pip_compile_args = ( [pip_compile_in] + pip_args + [ "--quiet", "--allow-unsafe", "--no-header", f"--output-file={pip_compile_out}", ] ) logger.info("Locking PyPI package versions..") cmd = [sys.executable, "-m", "piptools", "compile"] cmd.extend(pip_compile_args) try: subprocess.check_call(cmd) except subprocess.CalledProcessError as e: logger.error(f"Failed locking PyPI packages: {e}") logger.error( "Falling back to using user-provided package requirement specifier, equivalent to `lock_packages=False`" ) def with_defaults(self) -> "PythonOptions": # Convert from user provided options to actual build options with default values defaults: t.Dict[str, t.Any] = {} if self.requirements_txt is None: if self.lock_packages is None: defaults["lock_packages"] = True return attr.evolve(self, **defaults) def _python_options_structure_hook(d: t.Any, _: t.Type[PythonOptions]) -> PythonOptions: # Allow bentofile yaml to have either a str or list of str for these options for field in ["trusted_host", "find_links", "extra_index_url"]: if field in d and isinstance(d[field], str): d[field] = [d[field]] return PythonOptions(**d) bentoml_cattr.register_structure_hook(PythonOptions, _python_options_structure_hook) OptionsCls: TypeAlias = t.Union[DockerOptions, CondaOptions, PythonOptions] def dict_options_converter( options_type: t.Type[OptionsCls], ) -> t.Callable[[t.Union[OptionsCls, t.Dict[str, t.Any]]], t.Any]: def _converter(value: t.Union[OptionsCls, t.Dict[str, t.Any]]) -> options_type: if isinstance(value, dict): return options_type(**value) return value return _converter @attr.define(frozen=True, on_setattr=None) class BentoBuildConfig: """This class is intended for modeling the bentofile.yaml file where user will provide all the options for building a Bento. All optional build options should be default to None so it knows which fields are NOT SET by the user provided config, which makes it possible to omitted unset fields when writing a BentoBuildOptions to a yaml file for future use. This also applies to nested options such as the DockerOptions class and the PythonOptions class. """ service: str # Import Str of target service to build description: t.Optional[str] = None labels: t.Optional[t.Dict[str, t.Any]] = None include: t.Optional[t.List[str]] = None exclude: t.Optional[t.List[str]] = None docker: DockerOptions = attr.field( factory=DockerOptions, converter=dict_options_converter(DockerOptions), ) python: PythonOptions = attr.field( factory=PythonOptions, converter=dict_options_converter(PythonOptions), ) conda: CondaOptions = attr.field( factory=CondaOptions, converter=dict_options_converter(CondaOptions), ) def __attrs_post_init__(self) -> None: use_conda = any( val is not None for _, val in bentoml_cattr.unstructure(self.conda).items() ) use_cuda = self.docker.cuda_version is not None if use_cuda and use_conda: logger.warning( f'Conda will be ignored and will not be available inside bento container when "cuda={self.docker.cuda_version}" is set.' ) if self.docker.distro is not None: if use_conda and self.docker.distro not in get_supported_spec("miniconda"): raise BentoMLException( f"{self.docker.distro} does not supports conda. BentoML will only support conda with the following distros: {get_supported_spec('miniconda')}." ) if use_cuda and self.docker.distro not in get_supported_spec("cuda"): raise BentoMLException( f"{self.docker.distro} does not supports cuda. BentoML will only support cuda with the following distros: {get_supported_spec('cuda')}." ) _spec = DistroSpec.from_distro( self.docker.distro, cuda=use_cuda, conda=use_conda ) if _spec is not None: if self.docker.python_version is not None: if ( self.docker.python_version not in _spec.supported_python_versions ): raise BentoMLException( f"{self.docker.python_version} is not supported for {self.docker.distro}. Supported python versions are: {', '.join(_spec.supported_python_versions)}." ) if self.docker.cuda_version is not None: if self.docker.cuda_version != "default" and ( self.docker.cuda_version not in _spec.supported_cuda_versions ): raise BentoMLException( f"{self.docker.cuda_version} is not supported for {self.docker.distro}. Supported cuda versions are: {', '.join(_spec.supported_cuda_versions)}." ) def with_defaults(self) -> "FilledBentoBuildConfig": """ Convert from user provided options to actual build options with defaults values filled in. Returns: BentoBuildConfig: a new copy of self, with default values filled """ return FilledBentoBuildConfig( self.service, self.description, {} if self.labels is None else self.labels, ["*"] if self.include is None else self.include, [] if self.exclude is None else self.exclude, self.docker.with_defaults(), self.python.with_defaults(), self.conda.with_defaults(), ) @classmethod def from_yaml(cls, stream: t.TextIO) -> "BentoBuildConfig": try: yaml_content = yaml.safe_load(stream) except yaml.YAMLError as exc: logger.error(exc) raise try: return bentoml_cattr.structure(yaml_content, cls) except KeyError as e: if str(e) == "'service'": raise InvalidArgument( 'Missing required build config field "service", which' " indicates import path of target bentoml.Service instance." ' e.g.: "service: fraud_detector.py:svc"' ) else: raise def to_yaml(self, stream: t.TextIO) -> None: # TODO: Save BentoBuildOptions to a yaml file # This is reserved for building interactive build file creation CLI raise NotImplementedError class FilledBentoBuildConfig(BentoBuildConfig): service: str description: t.Optional[str] labels: t.Dict[str, t.Any] include: t.List[str] exclude: t.List[str] docker: DockerOptions python: PythonOptions conda: CondaOptions
import os import re import sys import inspect import logging import importlib import modulefinder from typing import List from typing import Tuple from unittest.mock import patch from ..types import PathType from .pip_pkg import get_all_pip_installed_modules from ...exceptions import BentoMLException logger = logging.getLogger(__name__) def _get_module_src_file(module): """ Return module.__file__, change extension to '.py' if __file__ is ending with '.pyc' """ return module.__file__[:-1] if module.__file__.endswith(".pyc") else module.__file__ def _is_valid_py_identifier(s): """ Return true if string is in a valid python identifier format: https://docs.python.org/2/reference/lexical_analysis.html#identifiers """ return re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", s) is not None def _get_module_relative_file_path(module_name, module_file): if not os.path.isabs(module_file): # For modules within current top level package, module_file here should # already be a relative path to the src file relative_path = module_file elif os.path.split(module_file)[1] == "__init__.py": # for module a.b.c in 'some_path/a/b/c/__init__.py', copy file to # 'destination/a/b/c/__init__.py' relative_path = os.path.join(module_name.replace(".", os.sep), "__init__.py") else: # for module a.b.c in 'some_path/a/b/c.py', copy file to 'destination/a/b/c.py' relative_path = os.path.join(module_name.replace(".", os.sep) + ".py") return relative_path def _get_module(target_module): # When target_module is a string, try import it if isinstance(target_module, str): try: target_module = importlib.import_module(target_module) except ImportError: pass return inspect.getmodule(target_module) def _import_module_from_file(path): module_name = path.replace(os.sep, ".")[:-3] spec = importlib.util.spec_from_file_location(module_name, path) m = importlib.util.module_from_spec(spec) return m # TODO: change this to find_local_py_modules_used(svc: Service) def find_local_py_modules_used(target_module_file: PathType) -> List[Tuple[str, str]]: """Find all local python module dependencies of target_module, and list all the local module python files to the destination directory while maintaining the module structure unchanged to ensure all imports in target_module still works when loading from the destination directory again Args: path (`Union[str, bytes, os.PathLike]`): Path to a python source file Returns: list of (source file path, target file path) pairs """ target_module = _import_module_from_file(target_module_file) try: target_module_name = target_module.__spec__.name except AttributeError: target_module_name = target_module.__name__ # Find all non pip installed modules must be packaged for target module to run exclude_modules = ["bentoml"] + get_all_pip_installed_modules() finder = modulefinder.ModuleFinder(excludes=exclude_modules) try: logger.debug( "Searching for local dependant modules of %s:%s", target_module_name, target_module_file, ) if sys.version_info[0] == 3 and sys.version_info[1] >= 8: _find_module = modulefinder._find_module _PKG_DIRECTORY = modulefinder._PKG_DIRECTORY def _patch_find_module(name, path=None): """ref issue: https://bugs.python.org/issue40350""" importlib.machinery.PathFinder.invalidate_caches() spec = importlib.machinery.PathFinder.find_spec(name, path) if spec is not None and spec.loader is None: return None, None, ("", "", _PKG_DIRECTORY) return _find_module(name, path) with patch.object(modulefinder, "_find_module", _patch_find_module): finder.run_script(target_module_file) else: finder.run_script(target_module_file) except SyntaxError: # For package with conditional import that may only work with py2 # or py3, ModuleFinder#run_script will try to compile the source # with current python version. And that may result in SyntaxError. pass if finder.badmodules: logger.debug( "Find bad module imports that can not be parsed properly: %s", finder.badmodules.keys(), ) # Look for dependencies that are not distributed python package, but users' # local python code, all other dependencies must be defined with @env # decorator when creating a new BentoService class user_packages_and_modules = {} for name, module in finder.modules.items(): if hasattr(module, "__file__") and module.__file__ is not None: user_packages_and_modules[name] = module # Lastly, add target module itself user_packages_and_modules[target_module_name] = target_module file_list = [] for module_name, module in user_packages_and_modules.items(): module_file = _get_module_src_file(module) relative_path = _get_module_relative_file_path(module_name, module_file) file_list.append((module_file, relative_path)) return file_list def copy_local_py_modules(target_module, destination): """Find all local python module dependencies of target_module, and copy all the local module python files to the destination directory while maintaining the module structure unchanged to ensure all imports in target_module still works when loading from the destination directory again """ target_module = _get_module(target_module) # When target module is defined in interactive session, we can not easily # get the class definition into a python module file and distribute it if target_module.__name__ == "__main__" and not hasattr(target_module, "__file__"): raise BentoMLException( "Custom BentoModel class can not be defined in Python interactive REPL, try" " writing the class definition to a file and import it." ) try: target_module_name = target_module.__spec__.name except AttributeError: target_module_name = target_module.__name__ target_module_file = _get_module_src_file(target_module) logger.debug( "copy_local_py_modules target_module_name: %s, target_module_file: %s", target_module_name, target_module_file, ) if target_module_name == "__main__": # Assuming no relative import in this case target_module_file_name = os.path.split(target_module_file)[1] target_module_name = target_module_file_name[:-3] # remove '.py' logger.debug( "Updating for __main__ module, target_module_name: %s, " "target_module_file: %s", target_module_name, target_module_file, ) # Find all non pip installed modules must be packaged for target module to run # exclude_modules = ['bentoml'] + get_all_pip_installed_modules() # finder = modulefinder.ModuleFinder(excludes=exclude_modules) # # try: # logger.debug( # "Searching for local dependant modules of %s:%s", # target_module_name, # target_module_file, # ) # if sys.version_info[0] == 3 and sys.version_info[1] >= 8: # _find_module = modulefinder._find_module # _PKG_DIRECTORY = modulefinder._PKG_DIRECTORY # # def _patch_find_module(name, path=None): # """ref issue: https://bugs.python.org/issue40350""" # # importlib.machinery.PathFinder.invalidate_caches() # # spec = importlib.machinery.PathFinder.find_spec(name, path) # # if spec is not None and spec.loader is None: # return None, None, ("", "", _PKG_DIRECTORY) # # return _find_module(name, path) # # with patch.object(modulefinder, '_find_module', _patch_find_module): # finder.run_script(target_module_file) # else: # finder.run_script(target_module_file) # except SyntaxError: # # For package with conditional import that may only work with py2 # # or py3, ModuleFinder#run_script will try to compile the source # # with current python version. And that may result in SyntaxError. # pass # # if finder.badmodules: # logger.debug( # "Find bad module imports that can not be parsed properly: %s", # finder.badmodules.keys(), # ) # # # Look for dependencies that are not distributed python package, but users' # # local python code, all other dependencies must be defined with @env # # decorator when creating a new BentoService class # user_packages_and_modules = {} # for name, module in finder.modules.items(): # if hasattr(module, "__file__") and module.__file__ is not None: # user_packages_and_modules[name] = module # # Remove "__main__" module, if target module is loaded as __main__, it should # # be in module_files as (module_name, module_file) in current context # if "__main__" in user_packages_and_modules: # del user_packages_and_modules["__main__"] # # # Lastly, add target module itself # user_packages_and_modules[target_module_name] = target_module # logger.debug( # "Copying user local python dependencies: %s", user_packages_and_modules # ) # # for module_name, module in user_packages_and_modules.items(): # module_file = _get_module_src_file(module) # relative_path = _get_module_relative_file_path(module_name, module_file) # target_file = os.path.join(destination, relative_path) # # # Create target directory if not exist # Path(os.path.dirname(target_file)).mkdir(parents=True, exist_ok=True) # # # Copy module file to BentoArchive for distribution # logger.debug("Copying local python module '%s'", module_file) # copyfile(module_file, target_file) # # for root, _, files in os.walk(destination): # if "__init__.py" not in files: # logger.debug("Creating empty __init__.py under folder:'%s'", root) # Path(os.path.join(root, "__init__.py")).touch() # # target_module_relative_path = _get_module_relative_file_path( # target_module_name, target_module_file # ) # logger.debug("Done copying local python dependant modules") # # return target_module_name, target_module_relative_path
import os import ast import sys import typing as t import logging import pkgutil import zipfile import zipimport from typing import TYPE_CHECKING from collections import defaultdict try: import importlib.metadata as importlib_metadata except ImportError: import importlib_metadata from packaging.requirements import Requirement if TYPE_CHECKING: from ..service import Service EPP_NO_ERROR = 0 EPP_PKG_NOT_EXIST = 1 EPP_PKG_VERSION_MISMATCH = 2 __mm = None logger = logging.getLogger(__name__) def split_requirement(requirement: str) -> t.Tuple[str, str]: """ Split requirements. 'bentoml>=1.0.0' -> ['bentoml', '>=1.0.0'] """ req = Requirement(requirement) name = req.name.replace("-", "_") return name, str(req.specifier) def packages_distributions() -> t.Dict[str, t.List[str]]: """Return a mapping of top-level packages to their distributions. We're inlining this helper from the importlib_metadata "backport" here, since it's not available in the builtin importlib.metadata. """ pkg_to_dist = defaultdict(list) for dist in importlib_metadata.distributions(): for pkg in (dist.read_text("top_level.txt") or "").split(): pkg_to_dist[pkg].append(dist.metadata["Name"]) return dict(pkg_to_dist) def parse_requirement_string(rs): name, _, version = rs.partition("==") return name, version def verify_pkg(pkg_req): global __mm # pylint: disable=global-statement if __mm is None: __mm = ModuleManager() return __mm.verify_pkg(pkg_req) def seek_pip_packages(target_py_file_path): global __mm # pylint: disable=global-statement if __mm is None: __mm = ModuleManager() return __mm.seek_pip_packages(target_py_file_path) def get_pkg_version(pkg_name): global __mm # pylint: disable=global-statement if __mm is None: __mm = ModuleManager() return __mm.pip_pkg_map.get(pkg_name, None) def get_zipmodules(): global __mm # pylint: disable=global-statement if __mm is None: __mm = ModuleManager() return __mm.zip_modules def get_all_pip_installed_modules(): global __mm # pylint: disable=global-statement if __mm is None: __mm = ModuleManager() installed_modules = list( # local modules are the ones imported from current directory, either from a # module.py file or a module directory that contains a `__init__.py` file filter(lambda m: not m.is_local, __mm.searched_modules.values()) ) return list(map(lambda m: m.name, installed_modules)) class ModuleInfo(object): def __init__(self, name, path, is_local, is_pkg): super(ModuleInfo, self).__init__() self.name = name self.path = path self.is_local = is_local self.is_pkg = is_pkg class ModuleManager(object): def __init__(self): super(ModuleManager, self).__init__() self.pip_pkg_map = {} self.pip_module_map = {} self.setuptools_module_set = set() self.nonlocal_package_path = set() import pkg_resources for dist in pkg_resources.working_set: # pylint: disable=not-an-iterable module_path = dist.module_path or dist.location if not module_path: # Skip if no module path was found for pkg distribution continue if os.path.realpath(module_path) != os.getcwd(): # add to nonlocal_package path only if it's not current directory self.nonlocal_package_path.add(module_path) self.pip_pkg_map[dist._key] = dist._version for mn in dist._get_metadata("top_level.txt"): if dist._key != "setuptools": self.pip_module_map.setdefault(mn, []).append( (dist._key, dist._version) ) else: self.setuptools_module_set.add(mn) self.searched_modules = {} self.zip_modules: t.Dict[str, zipimport.zipimporter] = {} for m in pkgutil.iter_modules(): if m.name not in self.searched_modules: if isinstance(m.module_finder, zipimport.zipimporter): logger.info(f"Detected zipimporter {m.module_finder}") path = m.module_finder.archive self.zip_modules[path] = m.module_finder else: path = m.module_finder.path is_local = self.is_local_path(path) self.searched_modules[m.name] = ModuleInfo( m.name, path, is_local, m.ispkg ) def verify_pkg(self, pkg_req): if pkg_req.name not in self.pip_pkg_map: # package does not exist in the current python session return EPP_PKG_NOT_EXIST if self.pip_pkg_map[pkg_req.name] not in pkg_req.specifier: # package version being used in the current python session does not meet # the specified package version requirement return EPP_PKG_VERSION_MISMATCH return EPP_NO_ERROR def seek_pip_packages(self, target_py_file_path): logger.debug("target py file path: %s", target_py_file_path) work = DepSeekWork(self, target_py_file_path) work.do() requirements = {} for _, pkg_info_list in work.dependencies.items(): for pkg_name, pkg_version in pkg_info_list: requirements[pkg_name] = pkg_version return requirements, work.unknown_module_set def is_local_path(self, path): if path in self.nonlocal_package_path: return False dir_name = os.path.split(path)[1] if ( "site-packages" in path or "anaconda" in path or path.endswith("packages") or dir_name == "bin" or dir_name.startswith("lib") or dir_name.startswith("python") or dir_name.startswith("plat") ): self.nonlocal_package_path.add(path) return False return True class DepSeekWork(object): def __init__(self, module_manager, target_py_file_path): super(DepSeekWork, self).__init__() self.module_manager = module_manager self.target_py_file_path = target_py_file_path self.dependencies = {} self.unknown_module_set = set() self.parsed_module_set = set() def do(self): self.seek_in_file(self.target_py_file_path) def seek_in_file(self, file_path): try: with open(file_path) as f: content = f.read() except UnicodeDecodeError: with open(file_path, encoding="utf-8") as f: content = f.read() self.seek_in_source(content) def seek_in_source(self, content): # Extract all dependency modules by searching through the trees of the Python # abstract syntax grammar with Python's built-in ast module tree = ast.parse(content) import_set = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for name in node.names: import_set.add(name.name.partition(".")[0]) elif isinstance(node, ast.ImportFrom): if node.module is not None and node.level == 0: import_set.add(node.module.partition(".")[0]) logger.debug("import set: %s", import_set) for module_name in import_set: # Avoid parsing BentoML when BentoML is imported from local source code repo if module_name == "bentoml": continue if module_name in self.parsed_module_set: continue self.parsed_module_set.add(module_name) if module_name in self.module_manager.searched_modules: m = self.module_manager.searched_modules[module_name] if m.is_local: # Recursively search dependencies in sub-modules if m.path in self.module_manager.zip_modules: self.seek_in_zip(m.path) elif m.is_pkg: self.seek_in_dir(os.path.join(m.path, m.name)) else: self.seek_in_file(os.path.join(m.path, "{}.py".format(m.name))) else: # check if the package has already been added to the list if ( module_name in self.module_manager.pip_module_map and module_name not in self.dependencies and module_name not in self.module_manager.setuptools_module_set ): self.dependencies[ module_name ] = self.module_manager.pip_module_map[module_name] else: if module_name in self.module_manager.pip_module_map: if module_name not in self.dependencies: # In some special cases, the pip-installed module can not # be located in the searched_modules self.dependencies[ module_name ] = self.module_manager.pip_module_map[module_name] else: if module_name not in sys.builtin_module_names: self.unknown_module_set.add(module_name) def seek_in_dir(self, dir_path): for path, dir_list, file_list in os.walk(dir_path): for file_name in file_list: if not file_name.endswith(".py"): continue self.seek_in_file(os.path.join(path, file_name)) for dir_name in dir_list: if dir_name in ["__pycache__", ".ipynb_checkpoints"]: continue self.seek_in_dir(os.path.join(path, dir_name)) def seek_in_zip(self, zip_path): with zipfile.ZipFile(zip_path) as zf: for module_path in zf.infolist(): filename = module_path.filename if filename.endswith(".py"): logger.debug("Seeking modules in zip %s", filename) content = self.module_manager.zip_modules[zip_path].get_source( filename.replace(".py", "") ) self.seek_in_source(content) def lock_pypi_versions(package_list: t.List[str]) -> t.List[str]: """ Lock versions of pypi packages in current virtualenv Args: package_list List[str]: List contains package names Raises: ValueError: if one package in `package_list` is not available in current virtualenv Returns: list of lines for requirements.txt Example Results: * ['numpy==1.20.3', 'pandas==1.2.4', 'scipy==1.4.1'] """ pkgs_with_version = [] for pkg in package_list: version = get_pkg_version(pkg) print(pkg, version) if version: pkg_line = f"{pkg}=={version}" pkgs_with_version.append(pkg_line) else: # better warning or throw an exception? raise ValueError(f"package {pkg} is not available in current virtualenv") return pkgs_with_version def with_pip_install_options( package_lines: t.List[str], index_url: t.Optional[str] = None, extra_index_url: t.Optional[str] = None, find_links: t.Optional[str] = None, ) -> t.List[str]: """ Lock versions of pypi packages in current virtualenv Args: package_lines List[str]: List contains items each representing one line of requirements.txt index_url Optional[str]: value of --index-url extra_index_url Optional[str]: value of --extra_index-url find_links Optional[str]: value of --find-links Returns: list of lines for requirements.txt Example Results: * ['pandas==1.2.4 --index-url=https://mirror.baidu.com/pypi/simple', 'numpy==1.20.3 --index-url=https://mirror.baidu.com/pypi/simple'] """ options = [] if index_url: options.append(f"--index-url={index_url}") if extra_index_url: options.append(f"--extra-index-url={extra_index_url}") if find_links: options.append(f"--find-links={find_links}") if not options: return package_lines option_str = " ".join(options) pkgs_with_options = [pkg + " " + option_str for pkg in package_lines] return pkgs_with_options def find_required_pypi_packages( svc: "Service", lock_versions: bool = True ) -> t.List[str]: """ Find required pypi packages in a python source file Args: path (`Union[str, bytes, os.PathLike]`): Path to a python source file lock_versions bool: if the versions of packages should be locked Returns: list of lines for requirements.txt Example Results: * ['numpy==1.20.3', 'pandas==1.2.4'] * ['numpy', 'pandas'] """ module_name = svc.__module__ module = sys.modules[module_name] reqs, unknown_modules = seek_pip_packages(module.__file__) for module_name in unknown_modules: logger.warning("unknown package dependency for module: %s", module_name) if lock_versions: pkg_lines = ["%s==%s" % pkg for pkg in reqs.items()] else: pkg_lines = list(reqs.keys()) return pkg_lines
from __future__ import annotations import typing as t import logging from typing import TYPE_CHECKING import attr from bentoml.exceptions import BentoMLException from ..tag import Tag from ..models import Model from ..runner import Runner from ..bento.bento import get_default_bento_readme from .inference_api import InferenceAPI from ..io_descriptors import IODescriptor if TYPE_CHECKING: from .. import external_typing as ext from ..bento import Bento WSGI_APP = t.Callable[ [t.Callable[..., t.Any], t.Mapping[str, t.Any]], t.Iterable[bytes] ] logger = logging.getLogger(__name__) def add_inference_api( svc: Service, func: t.Callable[..., t.Any], input: IODescriptor[t.Any], # pylint: disable=redefined-builtin output: IODescriptor[t.Any], name: t.Optional[str], doc: t.Optional[str], route: t.Optional[str], ) -> None: api = InferenceAPI( name=name if name is not None else func.__name__, user_defined_callback=func, input_descriptor=input, output_descriptor=output, doc=doc, route=route, ) if api.name in svc.apis: raise BentoMLException( f"API {api.name} is already defined in Service {svc.name}" ) from ..io_descriptors import Multipart if isinstance(output, Multipart): logger.warning( f"Found Multipart as the output of API '{api.name}'. Multipart responses are rarely used in the real world, and few clients/browsers support it. Make sure you know what you are doing." ) svc.apis[api.name] = api def get_valid_service_name(user_provided_svc_name: str) -> str: lower_name = user_provided_svc_name.lower() if user_provided_svc_name != lower_name: logger.warning( f"converting {user_provided_svc_name} to lowercase: {lower_name}" ) # Service name must be a valid Tag name; create a dummy tag to use its validation Tag(lower_name) return lower_name @attr.define(frozen=True) class Service: """The service definition is the manifestation of the Service Oriented Architecture and the core building block in BentoML where users define the service runtime architecture and model serving logic. A BentoML service is defined via instantiate this Service class. When creating a Service instance, user must provide a Service name and list of runners that are required by this Service. The instance can then be used to define InferenceAPIs via the `api` decorator. """ name: str runners: t.List[Runner] models: t.List[Model] mount_apps: t.List[t.Tuple[ext.ASGIApp, str, str]] = attr.field( init=False, factory=list ) middlewares: t.List[ t.Tuple[t.Type[ext.AsgiMiddleware], t.Dict[str, t.Any]] ] = attr.field(init=False, factory=list) apis: t.Dict[str, InferenceAPI] = attr.field(init=False, factory=dict) # Tag/Bento are only set when the service was loaded from a bento tag: Tag | None = attr.field(init=False, default=None) bento: Bento | None = attr.field(init=False, default=None) # Working dir and Import path of the service, set when the service was imported _working_dir: str | None = attr.field(init=False, default=None) _import_str: str | None = attr.field(init=False, default=None) def __init__( self, name: str, *, runners: t.List[Runner] | None = None, models: t.List[Model] | None = None, ): """ Args: name: runners: models: """ name = get_valid_service_name(name) # validate runners list contains Runner instances and runner names are unique if runners is not None: runner_names: t.Set[str] = set() for r in runners: assert isinstance( r, Runner ), f'Service runners list can only contain bentoml.Runner instances, type "{type(r)}" found.' if r.name in runner_names: raise ValueError( f"Found duplicate name `{r.name}` in service runners." ) runner_names.add(r.name) # validate models list contains Model instances if models is not None: for model in models: assert isinstance( model, Model ), f'Service models list can only contain bentoml.Model instances, type "{type(model)}" found.' self.__attrs_init__( # type: ignore name=name, runners=[] if runners is None else runners, models=[] if models is None else models, ) def api( self, input: IODescriptor[t.Any], # pylint: disable=redefined-builtin output: IODescriptor[t.Any], name: t.Optional[str] = None, doc: t.Optional[str] = None, route: t.Optional[str] = None, ) -> t.Callable[[t.Callable[..., t.Any]], t.Callable[..., t.Any]]: """Decorator for adding InferenceAPI to this service""" D = t.TypeVar("D", bound=t.Callable[..., t.Any]) def decorator(func: D) -> D: add_inference_api(self, func, input, output, name, doc, route) return func return decorator def __str__(self): if self.bento: return f'bentoml.Service(tag="{self.tag}", ' f'path="{self.bento.path}")' elif self._import_str and self._working_dir: return ( f'bentoml.Service(name="{self.name}", ' f'import_str="{self._import_str}", ' f'working_dir="{self._working_dir}")' ) else: return ( f'bentoml.Service(name="{self.name}", ' f'runners=[{",".join([r.name for r in self.runners])}])' ) def __repr__(self): return self.__str__() @property def doc(self) -> str: if self.bento is not None: return self.bento.doc return get_default_bento_readme(self) def openapi_doc(self): from .openapi import get_service_openapi_doc return get_service_openapi_doc(self) def on_asgi_app_startup(self) -> None: pass def on_asgi_app_shutdown(self) -> None: pass @property def asgi_app(self) -> "ext.ASGIApp": from ..server.service_app import ServiceAppFactory return ServiceAppFactory(self)() def mount_asgi_app( self, app: "ext.ASGIApp", path: str = "/", name: t.Optional[str] = None ) -> None: self.mount_apps.append((app, path, name)) # type: ignore def mount_wsgi_app( self, app: WSGI_APP, path: str = "/", name: t.Optional[str] = None ) -> None: # TODO: Migrate to a2wsgi from starlette.middleware.wsgi import WSGIMiddleware self.mount_apps.append((WSGIMiddleware(app), path, name)) # type: ignore def add_asgi_middleware( self, middleware_cls: t.Type["ext.AsgiMiddleware"], **options: t.Any ) -> None: self.middlewares.append((middleware_cls, options)) def on_load_bento(svc: Service, bento: Bento): object.__setattr__(svc, "bento", bento) object.__setattr__(svc, "tag", bento.info.tag) def on_import_svc(svc: Service, working_dir: str, import_str: str): object.__setattr__(svc, "_working_dir", working_dir) object.__setattr__(svc, "_import_str", import_str)
import typing as t from typing import TYPE_CHECKING if TYPE_CHECKING: from . import Service from ..io_descriptors import IODescriptor HEALTHZ_DESC = ( "Health check endpoint. Expecting an empty response with status code" " <code>200</code> when the service is in health state. The <code>/healthz</code>" " endpoint is <b>deprecated</b> (since Kubernetes v1.16)" ) LIVEZ_DESC = ( "Health check endpoint for Kubernetes. Healthy endpoint responses with a" " <code>200</code> OK status." ) READYZ_DESC = ( "A <code>200</code> OK status from <code>/readyz</code> endpoint indicated" " the service is ready to accept traffic. From that point and onward, Kubernetes" " will use <code>/livez</code> endpoint to perform periodic health checks." ) METRICS_DESC = "Prometheus metrics endpoint" def _generate_responses_schema( output: "IODescriptor[t.Any]", ) -> t.Dict[str, t.Dict[str, t.Any]]: resp = { "200": dict( description="success", content=output.openapi_responses_schema(), ), "400": dict(description="Bad Request"), "404": dict(description="Not Found"), "500": dict(description="Internal Server Error"), } return resp def get_service_openapi_doc(svc: "Service"): info = { "title": svc.name, "description": "A Prediction Service built with BentoML", "contact": {"email": "[email protected]"}, "version": svc.tag.version if svc.tag is not None else "0.0.0", } docs: t.Dict[str, t.Any] = { "openapi": "3.0.0", "info": info, "tags": [ { "name": "infra", "description": "Infrastructure endpoints", }, { "name": "app", "description": "Inference endpoints", }, ], } paths = {} default_response = {"200": {"description": "success"}} paths["/healthz"] = { "get": { "tags": ["infra"], "description": HEALTHZ_DESC, "responses": default_response, } } paths["/livez"] = { "get": { "tags": ["infra"], "description": LIVEZ_DESC, "responses": default_response, } } paths["/readyz"] = { "get": { "tags": ["infra"], "description": READYZ_DESC, "responses": default_response, } } paths["/metrics"] = { "get": { "tags": ["infra"], "description": METRICS_DESC, "responses": default_response, } } for api in svc.apis.values(): api_path = api.route if api.route.startswith("/") else f"/{api.route}" paths[api_path] = { "post": dict( tags=["app"], summary=f"{api}", description=api.doc or "", operationId=f"{svc.name}__{api.name}", requestBody=dict(content=api.input.openapi_request_schema()), responses=_generate_responses_schema(api.output), # examples=None, # headers=None, ) } docs["paths"] = paths return docs