모듈 개발 가이드
사바쨩에 새로운 게임을 추가하는 Python 모듈을 만드는 방법. module.toml 스키마와 lifecycle.py의 실제 함수 계약·프로토콜을 다룹니다.
모듈 개발 가이드 (Python)
사바쨩 데몬은 게임별 세부 동작을 알지 못합니다. 대신 각 게임을 Python 모듈이 설명하는 구조로 짜여 있습니다. 모듈 하나를 추가하면 새 게임을 사바쨩에서 관리할 수 있습니다.
이 문서는 saba-chan-modules 저장소의 실제 모듈(minecraft, palworld, zomboid)과 주석이 달린 빈 틀 __example, 그리고 데몬 코드를 기준으로 작성되었습니다.
1. 모듈 파일 구조
- module.toml필수. 선언 (스키마 v1)필수. 선언 (스키마 v1)
- lifecycle.py필수. [module].entry 가 가리키는 진입 파일필수. [module].entry 가 가리키는 진입 파일
- icon.png선택. [module].icon 으로 지정선택. [module].icon 으로 지정
- locales/
- en.json기준 언어기준 언어
- ko.json
- ...화면 문구화면 문구
- test_lifecycle.py선택. pytest 단위 테스트 (권장)선택. pytest 단위 테스트 (권장)
- 폴더 이름은
module.toml의[module].name과 같게, 영문 소문자로 짓습니다. - 데몬은 모듈 루트의 1단계 폴더 중
module.toml이 있는 것만 읽고,[module].entry파일이 없으면 모듈을 로드하지 않습니다. - 처음 시작할 때는
__example/__example__module.toml을module.toml로,__example/__example__lifecycle.py를lifecycle.py로 복사해 필요 없는 부분을 지우는 것을 권장합니다.
2. module.toml 스펙
실제 minecraft/module.toml의 앞부분을 요약한 예:
[module]
schema_version = 1 # 필수. 모르는 키나 잘못된 값이 있으면 로드 실패
name = "minecraft" # 폴더명과 동일
version = "0.1.0"
display_name = "Minecraft"
game_name = "Minecraft"
entry = "lifecycle.py" # 데몬이 실행할 Python 파일
icon = "icon.png"
log_pattern = '^\[\d{2}:\d{2}:\d{2}(?:\] \[[^\]]*/| )(?P<level>INFO|WARN|ERROR|DEBUG|FATAL)\]'
[module.dependencies]
saba-core = ">=0.1.5" # 컴포넌트 → 최소 버전 (">=" 만)
[permissions]
network = true # 코드가 쓰는 능력 선언
spawn_process = true
[protocols]
supported = ["stdin"] # "stdin" / "rest" 중에서
default = "stdin"
interaction_mode = "console" # "console" 또는 "commands"
[config]
server_executable = "server.jar"
process_name = "java.exe"
default_port = 25565
announce_command = "say" # 공지에 쓰는 [[commands.fields]] 이름
# stop_command 를 생략하면 "stop"
[backup]
paths = ["{level_name}", "{level_name}_nether", "{level_name}_the_end"]
save_command = "save-all"
[install]
method = "download" # "manual"(기본) / "download" / 익스텐션 id (예: "steamcmd")
[detection]
dir_signatures = ["server.jar"]
graceful_exit_patterns = ["Stopping the server"]
crash_artifacts = ["crash-reports/*.txt", "hs_err_pid*.log"]
섹션별 의미:
[module]: 메타데이터.name·version·entry는 필수입니다.log_pattern은(?P<level>…)그룹으로 콘솔 줄의 로그 레벨을 뽑습니다.[module.dependencies]의 키는saba-core,ext-<익스텐션 id>등입니다.[permissions]: 코드가 쓰는 위험한 능력(network,spawn_process,native_code,dynamic_code,env_secrets,fs_outside_instance) 선언.[protocols]:supported에는"stdin","rest","rcon"을 씁니다. 명령 경로는 stdin, REST, RCON 순서입니다. RCON은 콘솔도 REST API도 없는 게임에만 씁니다. 그런 게임은rcon_port도 선언해야 하고, 데몬이 인스턴스마다 포트와 무작위 비밀번호를 정합니다. 콘솔이나 REST가 있는 게임은 모듈이 RCON 설정을 끕니다.interaction_mode는 콘솔 화면(console)을 보일지, 명령 버튼만(commands) 보일지 정합니다.[config]:server_executable,executable_path,process_name,default_port,stop_command(콘솔로 보낼 정지 명령, 기본stop),stop_timeout(초, 기본 30),announce_command. 게임 설정 값은 여기가 아니라[[settings.fields]]에 둡니다.[[settings.fields]]: 인스턴스 설정 화면 항목(name,type,label,default,options,group등). 사용자가 바꾼 값은 인스턴스 설정으로 저장되고 함수 호출 때 config로 들어옵니다.install = true인 항목은 새 서버를 만들 때 고르는 값(서버 종류, 새 월드 설정 등)으로, 만들기 화면·웹·CLIserver add가 묻습니다. select 항목의install_options는 사바쨩이 새로 설치할 수 있는 값만 고릅니다(나머지options는 가져온 서버를 판정할 때만 씁니다).[[commands.fields]]: 게임 명령.method가"console"(+console_template)이면 콘솔(stdin)로,"rest"면 게임 REST API로,"module"(기본)이면lifecycle.py의command()로 보냅니다.risk(safe/caution/danger)와description은 AI 명령 해석이 읽습니다.[install]: 설치 방식과app_id,requires_extensions(필요한 익스텐션 id 목록) 등. Palworld는["steamcmd", "ue4-ini"]를 요구합니다.[detection]: 기존 서버 폴더 인식(dir_signatures), 프로세스 찾기(process_patterns,cmd_patterns), 크래시 판정(graceful_exit_patterns,crash_artifacts). 크래시로 판정된 종료만 자동 재시작됩니다.[backup]: 백업에 묶을 경로(paths), 백업 직전 실행할 명령(save_command), 경로를 코드로 계산할 때hook = true.[credential_map]: 데몬 표준 키 → 게임 설정 키 매핑. Palworld 예:rest_password = "AdminPassword".- 그 밖에
[launch],[[agreements]],[[presets]],[[queries]],[aliases],[errors],[[syntax_highlight.rules]],[extensions.<id>]가 있습니다. 전체 키 목록은saba-chan-modules저장소의docs/module-spec.md를 참고하세요.
3. lifecycle.py 함수 계약
데몬은 필요할 때마다 새 Python 프로세스를 띄워이 파일의 함수 하나를 호출합니다. 모든 함수는 config: dict 하나를 받아 dict를 돌려주고, 파일 끝의 FUNCTIONS 표에 등록되어 있어야 합니다. 모듈에는 start 함수가 없습니다. 서버는 데몬이 get_launch_command의 결과로 직접 띄웁니다.
3.1 필수 함수
필수는 get_launch_command 하나입니다.
import os
from daemon_rcon import config_value, run_lifecycle
def get_launch_command(config: dict) -> dict:
"""서버를 띄울 실행 정보를 돌려준다. 프로세스는 데몬이 띄운다."""
exe = config.get("server_executable", "")
if not exe or not os.path.exists(exe):
return {"success": False, "message": f"Server executable not found: {exe}"}
port = config_value(config, "port", 7777)
return {
"success": True,
"program": exe,
"args": [f"-port={port}"],
"working_dir": config.get("working_dir") or os.path.dirname(exe),
"env_vars": {},
}
FUNCTIONS = {"get_launch_command": get_launch_command}
if __name__ == "__main__":
run_lifecycle(FUNCTIONS)
- 데몬은 인스턴스 설정(
module_settings)을 config 최상위에 펼쳐 넣습니다.config_value(config, key, default)로 읽으면 안전합니다. - config에
extra_args(사용자가 더한 실행 인자)가 오면, 알맞은 자리에 넣고extra_args_placed: true를 돌려줍니다. 없으면 데몬이args끝에 붙입니다. preview: true가 오면 실행 인자 미리보기입니다. 설정 파일을 쓰지 말고 실행 정보만 돌려주세요.
3.2 선택 함수
지원할 기능만 만들고, 만들었다면 반드시 FUNCTIONS 표에 넣습니다.
| 함수 | 데몬이 부르는 때 | 돌려줄 것 |
|---|---|---|
validate | 서버 시작 전 점검 | success, issues[] (severity: "critical"이 있으면 시작하지 않음) |
stop | 콘솔이 없는 서버·non-managed 서버 정지 | success |
status | non-managed 상태 조회 | status, pid |
command | method = "module" 명령 | success, message |
get_credentials | REST 접속 정보가 필요할 때 | rest_username, rest_password |
configure / read_properties / reset_properties / reset_server | 설정 화면 저장·읽기·초기화 | success (+ 읽은 값) |
import_settings | 기존 서버 가져오기, 설정 읽기 | settings{} |
list_versions / get_version_details | 버전 목록·상세 | 버전 정보 |
install_server | 설치·업데이트 | success, executable_path, install_path |
get_installed_version | 설치된 버전 조회 | version |
accept_agreements | 사용자가 [[agreements]]에 동의한 뒤 | success |
diagnose_log | 로그 진단 | success |
backup_paths | 백업 ([backup] hook = true 일 때) | success, paths[] |
instance_commands | 명령 목록 ([commands] hook = true 일 때) | success, commands[] |
공통 규칙:
- 모든 응답은
success: bool과message: str을 넣습니다. 사용자 조치가 필요하면action_required: "<코드>"를 넣습니다. - 필요한 익스텐션이 없으면
error_code: "extension_required",missing_extensions: [...]로 답합니다. - 모르는 함수 이름에는
{"success": false, "message": "Unknown function: X"}로 답합니다(run_lifecycle()이 처리).
콘솔이 있는 managed 서버의 정지는 데몬이
[config].stop_command를 콘솔(stdin)로 보내고 기다립니다. 모듈의stop()은 콘솔이 없을 때만 불리며, 정상 종료 요청 → 대기 → 강제 종료 순서를 지키고 데몬이 넘긴pid만 다뤄야 합니다.
4. 서브프로세스 프로토콜
데몬이 모듈 함수를 호출하는 방식은 사바쨩 저장소의 src/plugin/mod.rs에 구현되어 있습니다. 요약하면:
python lifecycle.py <함수 이름>형태로 프로세스를 띄웁니다. Python은 데몬이 관리하는 환경을 씁니다.- 환경변수 주입:
PYTHONIOENCODING=utf-8,PYTHONUNBUFFERED=1PYTHONPATH: 공용 파일(i18n.py,daemon_rcon.py)이 있는 modules 폴더와 익스텐션 폴더의 부모SABA_IPC_URL,SABA_IPC_PORT: 데몬 API 주소SABA_TOKEN_PATH: 데몬 API 토큰이 든 파일 경로SABA_LANG: GUI 언어SABA_ENABLED_EXTENSIONS: 활성 익스텐션 id를 콤마로 이은 목록 (예:steamcmd,ue4-ini)
- stdin으로 config JSON 하나를 쓰고 닫습니다.
- stdout 전체를 JSON으로 읽고, 전체가 JSON이 아니면 비어 있지 않은 마지막 줄을 결과로 씁니다.
- stderr는 로그입니다.
PROGRESS:로 시작하는 줄은 진행률 이벤트로 파싱되어 설치 진행 표시에 쓰입니다. - 종료 코드는 0이어야 합니다. 0이 아니면 stdout이
success: false를 담고 있어도 데몬은 일반 오류로 처리합니다. - 프로세스는 호출마다 끝납니다. 기본 제한 시간은 120초이고, 프로비저닝·업데이트 때의
install_server만 더 길게(1800초) 기다립니다.
확인되지 않은 모듈: 사바쨩의 서명된 카탈로그에서 받지 않았거나 받은 뒤 바뀐 모듈은 Windows는 AppContainer, 리눅스는 bubblewrap 안에서 실행합니다. 백신 검사는 하지 않습니다. 격리할 수 없는 환경(bubblewrap이 없거나 쓸 수 없는 리눅스, macOS)에서는 지금 파일에 사용자가 동의한 뒤에만 실행합니다. 격리 실행에서는 루프백에 직접 연결할 수 없고(공용 도우미를 쓰면 데몬이 중계합니다),
SABA_TOKEN_PATH가 주어지지 않으며, 인스턴스·작업·설치 폴더와data_roots에 선언한 폴더에만 쓸 수 있습니다.msiexec와tempfile.mkdtemp이 만든 폴더도 쓸 수 없습니다. 전체 목록은 모듈 만들기: 조사부터 발행까지을 보세요.
4.1 진행률 보고 예시
# install_server 내부에서
import json, sys
def report(step, total, percent, msg):
sys.stderr.write("PROGRESS:" + json.dumps({
"step": step, "total": total, "percent": percent, "message": msg
}) + "\n")
sys.stderr.flush()
report(1, 3, 10, "다운로드 시작")
# … 실제 다운로드 …
report(2, 3, 70, "압축 해제 중")
# …
report(3, 3, 100, "설치 완료")
인식하는 필드는 percent, message, step, total, label 입니다.
5. 공용 유틸리티
데몬은 공용 파일 i18n.py와 daemon_rcon.py를 modules 폴더에 두고 PYTHONPATH에 넣습니다. 모듈 폴더에 복사하지 마세요.
import os
from i18n import I18n
from daemon_rcon import daemon_stdin_command, wait_for_exit, force_kill
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
i18n = I18n(MODULE_DIR) # MODULE_DIR/locales/<SABA_LANG>.json
msg = i18n.t("errors.failed_to_stop", error="…") # 문구 안의 {{error}} 를 바꿈
daemon_stdin_command(config["instance_id"], "save-all") # 서버 콘솔에 한 줄 보내기
daemon_rcon.py는 이름만 남은 것으로, RCON 소켓을 열지 않습니다. 주요 도우미:
| 함수 | 용도 |
|---|---|
daemon_stdin_command(instance_id, line) | 데몬이 관리하는 서버 콘솔에 명령 보내기 |
daemon_post(path, payload) | 그 밖의 데몬 API 호출 (토큰 자동) |
is_process_alive, wait_for_exit, force_kill | PID 단위 확인·대기·강제 종료 |
config_value(config, key, default) | config에서 설정 값 찾기 |
run_lifecycle(FUNCTIONS) | python lifecycle.py <함수> 진입점 |
활성화된 익스텐션은 from extensions.steamcmd import SteamCMD, import extensions.ue4_ini처럼 불러 쓸 수 있습니다. 비활성 익스텐션은 import 가드가 막으므로(ModuleNotFoundError), 함수 안에서 import 하고 실패하면 extension_required로 답하세요.
6. 기본 제공 모듈 참고
| 모듈 | 기본 포트 | 프로토콜 | 의존 익스텐션 | 참고 |
|---|---|---|---|---|
minecraft | 25565 | stdin (콘솔) | 없음 | download 설치, Java 자동 감지·다운로드, RCON 강제 비활성 |
palworld | 8211 | REST API | steamcmd, ue4-ini | 콘솔이 없는 게임. credential_map으로 rest_password ↔ AdminPassword 매핑 |
zomboid | 16261 | stdin (콘솔) | steamcmd | stop_command = "quit", [backup] hook = true |
terraria | 7777 | stdin (의사 콘솔 pty) | xna (Windows) | download 설치, Windows·리눅스 서버, [backup] hook = true |
모두 module.toml과 lifecycle.py를 중심으로 구성됩니다. 새 모듈을 만들 때는 __example 이나 이 넷 중 가장 비슷한 구조에서 출발하는 것을 권장합니다.
7. 개발 규칙 (필수 준수)
모듈 PR은 다음을 지켜야 합니다.
- 데몬 코드에 의존 금지. 데몬이 넘겨주는 config·환경변수·API만 사용합니다.
- 모든 실패도 JSON + 종료 코드 0.
success: false와 이유를 담아 답합니다. - 로그는 stderr로. stdout은 결과 JSON 용입니다. 예외 traceback도 stderr로 출력하고 삼키지 않습니다.
- stdin을 먼저, 다음으로 REST를 씁니다. RCON은 둘 다 없는 게임에만 씁니다. 콘솔이나 REST가 있는 게임은 RCON 설정을 끄고
supported에"rcon"을 넣지 않습니다. - 프로세스는 데몬이 준
pid로만 다룹니다. 실행 파일 이름으로 찾아 죽이면 같은 게임의 다른 인스턴스까지 끝납니다. - **경로는
os.path.join**으로 만들고 하드코딩하지 않습니다. - 필드명 매핑 검증.
[[settings.fields]]의 이름이 게임 설정 파일의 어떤 키로 가는지configure와import_settings양쪽에서 대조합니다. - 테스트.
test_lifecycle.py에 단위 테스트를 두고, 적합성 키트를 통과해야 합니다(아래 8절).
8. 디버깅 팁
- 결과는 stdout의 마지막 줄로 읽히므로, 디버그 출력은 stderr로 보내세요. 결과 JSON 뒤에 무언가를 출력하면 파싱이 깨집니다.
- 데몬 없이 함수를 직접 돌려 볼 수 있습니다.
daemon_rcon을 찾도록PYTHONPATH에 사바쨩 저장소의modules/를 넣으세요.echo '{"server_executable": "C:/Games/MyGame/GameServer.exe", "port": 7777}' | python lifecycle.py get_launch_command module.toml은 데몬과 같은 파서로 검사합니다:saba-core module validate <모듈 폴더>- 적합성 키트:
pytest conformance --module path/to/mygame --shared-libs path/to/saba-chan/modules(saba-chan-modules저장소) - 진행률이 GUI에 반영되지 않는다면, stderr 줄이 정확히
PROGRESS:로 시작하는지, 뒤의 JSON이 유효한지 확인하세요. - 모듈을 수정한 뒤에는 데이터 폴더의
modules\<name>\에도 반영해야 데몬이 최신 코드를 씁니다. 데몬은 모듈 목록을 캐시하므로module.toml을 바꿨다면POST /api/modules/refresh로 다시 읽게 하세요.