Python 함수 패키징하기

Python 함수 패키징하기

Python 함수는 다음 세 가지 포맷으로 패키징할 수 있어요. 첫째는 하나의 Python 파일로, 둘째는 ZIP 파일로, 셋째는 PIP(whl) 방식이에요. 각 방식은 준비물과 실행 방법이 조금씩 다르니 목적에 맞게 고르면 돼요.

가장 간단한 단일 파일 방식부터 시작해서, 의존성이 많아질수록 ZIP이나 PIP 방식을 사용하게 돼요. 특히 PIP 방식은 Kubernetes 런타임에서만 지원된다는 점을 기억해 두세요.

출처: 문서

본문

하나의 Python 파일 (One Python file)

Python 함수를 하나의 Python 파일로 패키징하려면 다음 단계를 완료해요.

  1. Python 함수를 작성해요.
from pulsar import Function #  import the Function module from Pulsar

# The classic ExclamationFunction that appends an exclamation at the end
# of the input
class ExclamationFunction(Function):
    def __init__(self):
        pass

    def process(self, input, context):
        return input + '!'

이 예시에서 Python 함수를 작성할 때는 Function 클래스를 상속하고 process() 메서드를 구현해야 해요.

process()는 주로 두 매개변수를 가져요.

  • input은 입력 데이터를 나타내요.
  • context는 Pulsar Function이 노출하는 인터페이스를 나타내요. 제공된 context 객체를 바탕으로 Python 함수 안의 속성들을 가져올 수 있어요.
  1. Python 클라이언트를 설치해요. Python 함수의 구현은 Python 클라이언트에 의존해요.
pip install pulsar-client==2.10.0

그리고 proto 파일을 생성하기 위한 protobuf 도구도 설치해요.

pip install 'protobuf==3.20.*'
  1. Python 함수 파일을 Pulsar 이미지에 복사해요.
docker exec -it [CONTAINER ID] /bin/bash
docker cp <path of Python function file>  CONTAINER ID:/pulsar
  1. 다음 명령으로 Python 함수를 실행해요.
./bin/pulsar-admin functions localrun \
    --classname <Python Function file name>.<Python Function class name> \
    --py <absolute path of Python Function file> \
    --inputs persistent://public/default/my-topic-1 \
    --output persistent://public/default/test-1 \
    --tenant public \
    --namespace default \
    --name PythonFunction

다음 로그는 Python 함수가 성공적으로 시작되었음을 나타내요.

 ...
 07:55:03.724 [main] INFO  org.apache.pulsar.functions.runtime.ProcessRuntime - Started process successfully
 ...

ZIP 파일 (ZIP file)

Python 함수를 ZIP 파일로 패키징하려면 다음 단계를 완료해요.

  1. ZIP 파일을 준비해요.

func.zip라는 이름의 zip 파일이 있다고 가정하면, func.zip 폴더의 압축을 풀면 이렇게 돼요.

    "func/src"
    "func/requirements.txt"
    "func/deps"

exclamation.zip 파일을 예로 들면, 예시의 내부 구조는 다음과 같아요.

 .
 ├── deps
 │   └── sh-1.12.14-py2.py3-none-any.whl
 └── src
     └── exclamation.py
  1. ZIP 파일을 Pulsar 이미지에 복사해요.
 docker exec -it [CONTAINER ID] /bin/bash
 docker cp <path of ZIP file>  CONTAINER ID:/pulsar
  1. 다음 명령으로 Python 함수를 실행해요.
./bin/pulsar-admin functions localrun \
    --classname exclamation \
    --py <absolute path of ZIP file> \
    --inputs persistent://public/default/in-topic \
    --output persistent://public/default/out-topic \
    --tenant public \
    --namespace default \
    --name PythonFunction

다음 로그는 Python 함수가 성공적으로 시작되었음을 나타내요.

 ...
 07:55:03.724 [main] INFO  org.apache.pulsar.functions.runtime.ProcessRuntime - Started process successfully
 ...

PIP (PIP)

알아두기: PIP 방식은 Kubernetes 런타임에서만 지원돼요.

PIP로 Python 함수를 패키징하려면 다음 단계를 완료해요.

  1. functions_worker.yml 파일을 구성해요.
 #### Kubernetes Runtime ####
 installUserCodeDependencies: true
  1. Python 함수를 작성해요.
from pulsar import Function
import js2xml

# The classic ExclamationFunction that appends an exclamation at the end
# of the input
class ExclamationFunction(Function):
    def __init__(self):
        pass

    def process(self, input, context):
        # add your logic
        return input + '!'

추가 의존성을 도입할 수 있어요. Python 함수가 현재 사용 중인 파일이 whl이고 installUserCodeDependencies 매개변수가 지정된 것을 감지하면, 시스템은 pip install 명령을 사용해 Python 함수에 필요한 의존성을 설치해요.

  1. whl 파일을 생성해요.
cd $PULSAR_HOME/pulsar-functions/scripts/python
chmod +x generate.sh
./generate.sh <path of your Python Function> <path of the whl output dir> <the version of whl>
# e.g: ./generate.sh /path/to/python /path/to/python/output 1.0.0

출력은 /path/to/python/output에 작성돼요.

 -rw-r--r--  1 root  staff   1.8K  8 27 14:29 pulsarfunction-1.0.0-py2-none-any.whl
 -rw-r--r--  1 root  staff   1.4K  8 27 14:29 pulsarfunction-1.0.0.tar.gz
 -rw-r--r--  1 root  staff     0B  8 27 14:29 pulsarfunction.whl

더 알아보기 (Learn more)

  • 함수 패키징의 전체 흐름이 궁금하다면 함수 패키징 문서를 참고해요.
  • 클러스터 모드로 함수를 배포하는 방법은 함수 배포 문서를 살펴보세요.
  • Kubernetes 런타임에서 함수를 실행하는 방법은 Kubernetes 런타임 문서를 참고해요.