[pySpark, 파이썬 spark] Best Practices Writing Production-Grade PySpark Jobs

How to Structure Your PySpark Job Repository and Code

Using PySpark to process large amounts of data in a distributed fashion is a great way to manage large-scale data-heavy tasks and gain business insights while not sacrificing on developer efficiency.

In short, PySpark is awesome.
However, while there are a lot of code examples out there, there’s isn’t a lot of information out there (that I could find) on how to build a PySpark codebase— writing modular jobs, building, packaging, handling dependencies, testing, etc. — that could scale to a larger development team.

So, following a year+ working with PySpark I decided to collect all the know-hows and conventions we’ve gathered into this post (and accompanying boilerplate project)

In this post we’ll cover:

  • Structuring PySpark Jobs
  • Handling 3rd-party dependencies
  • Writing a PySpark Job
  • Unit Testing

Structuring our Jobs Repository

First, let’s go over how submitting a job to PySpark works:
spark-submit --py-files pyfile.py,zipfile.zip main.py --arg1 val1

When we submit a job to PySpark we submit the main Python file to run — main.py — and we can also add a list of dependent files that will be located together with our main file during execution.
These dependency files can be .py code files we can import from, but can also be any other kind of files. For example, .zip packages.

One of the cool features in Python is that it can treat a zip file as a directory as import modules and functions from just as any other directory.
All that is needed is to add the zip file to its search path.

import sys
sys.path.insert(0, jobs.zip)

now (assuming jobs.zip contains a python module called jobs) we can import that module and whatever that’s in it. For example:

from jobs.wordcount import run_job
run_job()

This will allow us to build our PySpark job like we’d build any Python project — using multiple modules and files — rather than one bigass myjob.py (or several such files)

Armed with this knowledge let’s structure out PySpark project…

Jobs as Modules

We’ll define each job as a Python module where it can define its code and transformation in whatever way it likes (multiple files, multiple sub modules…).

.
├── README.md
├── src
│   ├── main.py
│   ├── jobs
│   │   └── wordcount
│   │       └── __init__.py

The job itself has to expose an analyze function:

def analyze(sc, **kwargs):
   ...

and a main.py which is the entry point to our job — it parses command line arguments and dynamically loads the requested job module and runs it:

import pysparkif os.path.exists('jobs.zip'):
    sys.path.insert(0, 'jobs.zip')
else:
    sys.path.insert(0, './jobs')parser = argparse.ArgumentParser()
parser.add_argument('--job', type=str, required=True)
parser.add_argument('--job-args', nargs='*')
args = parser.parse_args()sc = pyspark.SparkContext(appName=args.job_name)
job_module = importlib.import_module('jobs.%s' % args.job)
job_module.analyze(sc, job_args)

To run this job on Spark we’ll need to package it so we can submit it via spark-submit …

Packaging

As we previously showed, when we submit the job to Spark we want to submit main.py as our job file and the rest of the code as a --py-files extra dependency jobs.zipfile.
So, out packaging script (we’ll add it as a command to our Makefile) is:

build:
    mkdir ./dist
    cp ./src/main.py ./dist
    cd ./src && zip -x main.py -r ../dist/jobs.zip .

Now we can submit our job to Spark:

make build
cd dist && spark-submit --py-files jobs.zip main.py --job wordcount

If you noticed before, out main.py code runs
sys.path.insert(0, 'jobs.zip)
making all the modules inside it available for import.
Right now we only have one such module we need to import — jobs — which contains our job logic.

We can also add a shared module for writing logic that is used by multiple jobs. That module we’ll simply get zipped into jobs.zip too and become available for import.

.
├── Makefile
├── README.md
├── src
│   ├── main.py
│   ├── jobs
│   │   └── wordcount
│   │       └── __init__.py
│   └── shared
│       └── __init__.py

Handling 3rd Party Dependencies

One of the requirements anyone who’s writing a job bigger the the “hello world” probably needs to depend on some external python pip packages.

To use external libraries, we’ll simply have to pack their code and ship it to spark the same way we pack and ship our jobs code.
pip allows installing dependencies into a folder using its -t ./some_folder options.

The same way we defined the shared module we can simply install all our dependencies into the src folder and they’ll be packages and be available for import the same way our jobs and shared modules are:

pip install -r requirements.txt -t ./src

However, this will create an ugly folder structure where all our requirement’s code will sit in source, overshadowing the 2 modules we really care about: shared and jobs

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

That’s why I find it useful to add a special folder — libs — where I install requirements to:

.
├── Makefile
├── README.md
├── requirements.txt
├── src
│   ├── main.py
│   ├── jobs
│   │   └── wordcount
│   │       └── __init__.py
│   └── libs
│   │   └── requests
│   │   └── ...
│   └── shared
│       └── __init__.py

With our current packaging system will break imports as import some_package will now have to be written as import libs.some_package.
To solve that we’ll simply package our libs folder into a separate zip package who’s root older is libs.

build: clean
 mkdir ./dist
 cp ./src/main.py ./dist
 cd ./src && zip -x main.py -x \*libs\* -r ../dist/jobs.zip .
 cd ./src/libs && zip -r ../../dist/libs.zip .

Now we can import our 3rd party dependencies without a libs. prefix, and run our job on PySpark using:

cd dist
spark-submit --py-files jobs.zip,libs.zip main.py --job wordcount

The only caveat with this approach is that it can only work for pure-Python dependencies. For libraries that require C++ compilation, there’s no other choice but to make sure they’re pre-installed on all nodes before the job runs which is a bit harder to manage. Fortunately, most libraries do not require compilation which makes most dependencies easy to manage,

Writing a PySpark Job

The next section is how to write a jobs’s code so that it’s nice, tidy and easy to test.

Providing a Shared Context

When writing a job, there’s usually some sort of global context we want to make available to the different transformation functions.
Spark broadcast variables, counters, and misc configuration data coming from command-line are the common examples for such job context data.

For this case we’ll define a JobContext class that handles all our broadcast variables and counters:

from collections import OrderedDict
from tabulate import tabulateclass JobContext(object):
  def __init__(self, sc):
    self.counters = OrderedDict()
    self._init_accumulators(sc)
    self._init_shared_data(sc)  def _init_accumulators(self, sc):
    pass  def _init_shared_data(self, sc):
    pass  def initalize_counter(self, sc, name):
    self.counters[name] = sc.accumulator(0)  def inc_counter(self, name, value=1):
    if name not in self.counters:
      raise ValueError("%s counter was not initialized. (%s)" % (name, self.counters.keys()))    self.counters[name] += value  def print_accumulators(self):
    print 'aa\n' * 2
    print tabulate(self.counters.items(), 
                   self.counters.keys(), 
                   tablefmt="simple")

We’ll create an instance of it on our job’s code and pass it to our transformations.
For example, let’s say we want to test the number of words on our wordcount job:

class WordCountJobContext(JobContext):
  def _init_accumulators(self, sc):
    self.initalize_counter(sc, 'words')def to_pairs(context, word):
  context.inc_counter('words')
  return word, 1def analyze(sc):
  print "Running wordcount"
  context = WordCountJobContext(sc)
  text = " ...  some text ..."  words = sc.parallelize(text.split())
  pairs = words.map(lambda word: to_pairs(context, word))
  ordered = counts.sortBy(lambda pair: pair[1], ascending=False)
  print ordered.collect()
  context.print_accumulators()

Besides sorting the words by occurrence, we’ll now also keep a distributed counter on our context that counts the number of words we processed in total. We can then nicely print it at the end by calling `context.print_accumulators()` or access it via context.counters['words']

Writing Transformations

The code above is pretty cumbersome to write instead of simple transformations that look like pairs = words.map(to_pairs) we now have this extra context parameter requiring us to write a lambda expression: pairs = words.map(lambda word: to_pairs(context, word)

So we’ll use functools.partial to make our code nicer:

def analyze(sc):
  print "Running wordcount"
  context = WordCountJobContext(sc)
  text = " ...  some text ..."  to_pairs_step = partial(to_pairs, context)  words = sc.parallelize(text.split())
  pairs = words.map(to_pairs_step)
  ordered = counts.sortBy(lambda pair: pair[1], ascending=False)
  print ordered.collect()
  context.print_accumulators()

Unit Testing

When looking at PySpark code, there are few ways we can (should) test our code:

Transformation Tests — since transformations (like our to_pairs above) are just regular Python functions, we can simply test them the same way we’d test any other python Function

from mock import MagicMock
from jobs.wordcount import to_pairsdef test_to_pairs():
  context_mock = MagicMock()
  result = to_pairs(context_mock, 'foo')
  assert result[0] == 'foo'
  assert result[1] == 1
  context_mock.inc_counter.assert_called_with('words')

These tests cover 99% of our code, so if we just test our transformations we’re mostly covered.

Entire Flow Tests — testing the entire PySpark flow is a bit tricky because Spark runs in JAVA and as a separate process.
The best way to test the flow is to fake the spark functionality.
The PySparking is a pure-Python implementation of the PySpark RDD interface.
It acts like a real Spark cluster would, but implemented Python so we can simple send our job’s analyze function a pysparking.Contextinstead of the real SparkContext to make our job run the same way it would run in Spark.
Since we’re running on pure Python we can easily mock things like external http requests, DB access etc. which is necessary for writing good unit tests.

import pysparkling
from mock import patch
from jobs.wordcount import analyze@patch('jobs.wordcount.get_text')
def test_wordcount(get_text_mock):
  get_text_mock.return_value = "foo bar foo"
  sc = pysparkling.Context()
  result = analyze(sc)
  assert result[0] == ('foo', 2)
  assert result[1] == ('bar', 1)

Testing the entire job flow requires refactoring the job’s code a bit so that analyze returns a value to be tested and that the input is configurable so that we could mock it.

Where to go from here…

You can find the full source code for a PySpark starter boilerplate implementing the concepts described above on https://github.com/ekampf/PySpark-Boilerplate

 

[출처] https://developerzen.com/best-practices-writing-production-grade-pyspark-jobs-cb688ac4d20f#.wg3iv4kie

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86143
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78639
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95367
27 [java dbms][database] [컴] Apache Derby 사용하기 - 4 - in-memory DB 졸리운_곰 2021.04.15 1560
26 [java dbms][database] [컴] Apache Derby 사용하기 - 3 - Apache Derby Network Server 졸리운_곰 2021.04.15 1634
25 [java dbms][database] [컴] Apache Derby 사용하기 - 2 - sql script tool ij 사용하기 졸리운_곰 2021.04.15 1823
24 [java dbms][database] [컴] Apache Derby 사용하기 - 1 - Derby 설치 file 졸리운_곰 2021.04.15 1153
23 실습 2 - GROUP 졸리운_곰 2020.09.30 1550
22 [SQL 가이드] 데이터베이스 모델의 이해 (Understanding Database model) file 졸리운_곰 2020.06.13 2483
21 [SQL 가이드] 식별자(Identification)의 개념 file 졸리운_곰 2020.06.13 2060
20 [SQL 가이드] 관계(relationship)의 개념 file 졸리운_곰 2020.06.13 1556
19 [SQL 가이드] 속성(attribute)의 개념 file 졸리운_곰 2020.06.13 1703
18 [SQL 가이드] 엔티티의 개념 file 졸리운_곰 2020.06.13 2201
17 [SQL] join의 on절과 where절 차이 졸리운_곰 2020.05.16 1303
16 JOIN*(3개 테이블) and GROUP BY*(보이지않더라도 key칼럼으로) and ORDER BY 졸리운_곰 2020.05.16 1224
15 다중 테이블에서 데이터 검색 - JOIN file 졸리운_곰 2020.05.16 1594
14 IFNULL(MYSQL), ISNULL(MSSQL), NVL(ORACLE) 졸리운_곰 2018.07.24 1778
13 4 Ways to Join Only The First Row in SQL file 졸리운_곰 2018.07.03 1637
12 DBMS별 기존테이블 SELECT해서 새 테이블에 INSERT하여 데이터 ... file 졸리운_곰 2018.01.22 1592
11 SOL 개발자의 현주소 : 개발자가 SQL 작성시 고쳐야 하는 태도 file 졸리운_곰 2018.01.01 2159
10 오라클 운반 최소 단위 BLOCK file 졸리운_곰 2017.07.15 2035
9 재미있는 DB 이야기 ‘놀라운 마방진의 세계’ file 졸리운_곰 2017.07.15 2394
8 재미있는 DB 이야기 ‘사라진 날짜를 찾아라’ file 졸리운_곰 2017.07.15 2224
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED