Microsoft MVP성태의 닷넷 이야기
스크립트: 43. uwsgi의 --processes와 --threads 옵션 [링크 복사], [링크+제목 복사],
조회: 12078
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

uwsgi의 --processes와 --threads 옵션

지난 글에서,

파이썬 - uwsgi의 --enable-threads 옵션
; https://www.sysnet.pe.kr/2/0/12886

uwsgi의 prefork/worker 방식에 대해 언급했하면서 테스트를 했는데, 뭘 좀 몰랐던 시기라 테스트가 제대로 안 되었습니다. ^^; 그래서 이참에 다시 정리해 봅니다.




uwsgi 테스트를 위해 최소 구현 코드만을 만족하는 다음의 파이썬 코드로,

import os
import time
from datetime import datetime

HELLO_WORLD = b"Hello world!\n"


def simple_app(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    print(os.getpid(), os.getppid(), environ['REQUEST_URI'], "called", datetime.now().strftime("%H:%M:%S"))
    time.sleep(10)
    start_response(status, response_headers)
    return [HELLO_WORLD]


application = simple_app

uwsgi를 기본 옵션만을 사용해 호스팅해보겠습니다.

$ uwsgi --http :18000  --wsgi-file ./main.py

이 상태에서 웹 브라우저를 통해 (식별을 위해 sleep1, sleep2를 경로에 추가해) 2번 동시에 방문해 보면 화면에 다음과 같은 출력을 볼 수 있습니다.

// 2개의 동시 요청, http://localhost:18000/sleep1, http://localhost:18000/sleep2

22053 19712 /sleep1 called 11:38:46
22053 19712 /sleep2 called 11:38:56

즉, 2개의 요청이 직렬화돼 하나의 프로세스(22053)에서 차례대로 실행되었습니다. 이때의 uwsgi 프로세스 구조를 보면,

├─init(19710)───init(19711)───bash(19712)───uwsgi(22053)

단일하게 실행 중인 1개의 uwsgi를 볼 수 있습니다. 그러니까, uwsgi 프로세스 한 개당 1개의 동시 요청만 처리하고 있는 것입니다. 이러한 동시성을 개선하기 위해 줄 수 있는 옵션이 prefork/worker 프로세스 방식일 텐데요, 재미있게도 uwsgi의 경우 이 옵션이 각각 --processes, --workers로 나뉘어 있지만 정작 약식 옵션으로는 "-p"로 통일이 되므로,

    -p|--processes                          spawn the specified number of workers/processes
    -p|--workers                            spawn the specified number of workers/processes

사실상 2개의 옵션은 완전히 같은 역할을 합니다. 또한, 기본값은 모두 1인데요, 즉 기본적으로 떠 있는 uwsgi 프로세스가 하나의 worker/process에 해당합니다. 따라서 다음과 같이 workers/processes를 3으로 주면,

$ uwsgi --http-socket :18000 --wsgi-file ./main.py --workers 3
...[생략]...
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (pid: 22079, cores: 1)
spawned uWSGI worker 2 (pid: 22080, cores: 1)
spawned uWSGI worker 3 (pid: 22081, cores: 1)

$ uwsgi --http-socket :18000 --wsgi-file ./main.py --processes 3
...[생략]...
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (pid: 22081, cores: 1)
spawned uWSGI worker 2 (pid: 22082, cores: 1)
spawned uWSGI worker 3 (pid: 22083, cores: 1)

예상할 수 있듯이 프로세스의 구조도 같습니다.

// worker/processes 총 3개: 22081, 22082, 22083

 ├─init(19710)───init(19711)───bash(19712)───uwsgi(22081)─┬─uwsgi(22082)
 │                                                        └─uwsgi(22083)

더욱 재미있는 건, uwsgi에도 --threads 옵션이 있다는 점입니다. 실제로 다음과 같은 식으로 실행해 보면,

$ uwsgi --http :18000  --wsgi-file ./main.py --processes 3 --threads 4

이때의 프로세스 결과는 이렇게 나옵니다.

// processes 3개 == 22111, 22112, 22113

// 프로세스 당 threads 4개
// 22111(프로세스이면서 스레드), 22116, 22119, 22122
// 22112(프로세스이면서 스레드), 22114, 22117, 22121
// 22113(프로세스이면서 스레드), 22115, 22118, 22120

├─init(19710)───init(19711)───bash(19712)───uwsgi(22111)─┬─uwsgi(22112)─┬─{uwsgi}(22114)
│                                                        │              ├─{uwsgi}(22117)
│                                                        │              └─{uwsgi}(22121)
│                                                        ├─uwsgi(22113)─┬─{uwsgi}(22115)
│                                                        │              ├─{uwsgi}(22118)
│                                                        │              └─{uwsgi}(22120)
│                                                        ├─{uwsgi}(22116)
│                                                        ├─{uwsgi}(22119)
│                                                        └─{uwsgi}(22122)

출력 결과를 보면, "uwsgi"라고 나오는 것과 "{uwsgi}"라고 나오는 것이 있습니다. 중괄호가 없는 것이 프로세스이고, 있는 것이 스레드입니다.

당연히, 이런 경우 동시 처리가 됩니다. 위의 예제 코드에 대한 요청을 다시 재현해 보면,

$ uwsgi --http-socket :18000 --wsgi-file ./main.py --processes 3

// 2개 동시 요청: http://localhost:18000/sleep1, http://localhost:18000/sleep2

22126 22124 /sleep1 called 13:51:20
22125 22124 /sleep2 called 13:51:21
22124 19712 /favicon.ico called 13:51:30
22126 22124 /favicon.ico called 13:51:41

// 프로세스 구조
├─init(19710)───init(19711)───bash(19712)───uwsgi(22124)─┬─uwsgi(22125)
│                                                        └─uwsgi(22126)

/sleep1과 /sleep2가 함께 처리되고 있는 것을 볼 수 있고, (웹 브라우저로 인해 부가적으로 발생한) favicon.ico 요청까지 처리하는 프로세스 ID까지 고려하면 3개의 uwsgi 프로세스가 요청을 협업해서 처리하고 있습니다.

--processes와 --threads의 또 다른 차이점은, --enable-threads의 활성 유무입니다. 단순히 --processes로만 fork를 한 경우에는 해당 옵션이 활성화되지 않습니다. 따라서 사용자 스레드의 활동이 필요하다면 --processes와 함께 --enable-threads도 명시해야 합니다.




아마도, uwsgi의 prefork와 worker가 사실상 fork 방식으로만 처리하는 데에는 GIL의 영향으로 인해 프로세스를 나누는 것이 최선의 방식이라고 생각했던 것 같습니다.

참고로, uwsgi로 호스팅하면 app framework에 따라 초기 프로세스의 상태가 다릅니다.

// 이 글의 예제를 호스팅한 경우
├─init(19710)───init(19711)───bash(19712)───uwsgi(22053)

// Django를 호스팅한 경우
├─init(19710)───init(19711)───bash(19712)───uwsgi(22067)───uwsgi(22068)

아마도 Django 내부에서 fork를 하는 프로세스가 하나 있는 듯한데 저 프로세스가 요청을 처리하는 uwsgi 프로세스 역할은 하지 않습니다. 또한, 이 상태에서 --py-autoreload=3 옵션을 넣으면 다시 이렇게 바뀝니다.

// 이 글의 예제를 호스팅한 경우
├─init(19710)───init(19711)───bash(19712)───uwsgi(22061)───uwsgi(22062)───{uwsgi}(22063) // --py-autoreload 옵션으로 자식 프로세스 1개와 그것에서 다시 스레드 1개

// Django를 호스팅한 경우
├─init(19710)───init(19711)───bash(19712)───uwsgi(22070)─┬─uwsgi(22071)───{uwsgi}(22072) // --py-autoreload 옵션으로 자식 프로세스 1개와 그것에서 다시 스레드 1개
│                                                        └─uwsgi(22073) // Django로 인한 1개의 자식 프로세스




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/9/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12209정성태4/13/202017399오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/202015960Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015782스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018419오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015091스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015086스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017920오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021182개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018424오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018517VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016166오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019527오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018805VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015939오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018261.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020991오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017899개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019912개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021037개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015613오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021200개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202026016Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015559오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017397오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202017983오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202019907오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...