Skip to content

Commit 31173d5

Browse files
committed
Added contrib.simulate.RunAnywayTarget with test in test/simulate_test.py
RunAnywayTarget: added new test, checking tasks output RunAnywayTarget: added test and a reset function called in each test Fixed coding style and documentation errors RunAnywayTarget: Made some changes to the custom temp directory and fixed some problems related to travis' tests RunAnywayTarget: complied with the sphinx documentation syntax Fixed unused import and used absolute paths for custom temp dirs in simulate_test RunAnywayTarget: changed the way it works, now deleting files at the end of the execution Removed a test than made no sense with the new changes, and adapted the other ones Revamped luigi.contrib.simulate module using a shared value containing a PID as an unique identifier Changed tests for luigi.contrib.simulate and removed the inconsistent ones Fixed test_output in simulate_test, and removed Travis specific file removal Potentially bypassed tests for environments that don't allow file creation in a temporary directory Fixed coding style and added is_writable decorator in simulate_test Fixed is_writable decorator, now creating parent directories and handling exceptions Made changes to the RunAnywayTarget (changed comments, used task_id) and added a test ran in another process
1 parent d2dac79 commit 31173d5

2 files changed

Lines changed: 222 additions & 0 deletions

File tree

luigi/contrib/simulate.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# Copyright 2012-2015 Spotify AB
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
"""
18+
A module containing classes used to simulate certain behaviors
19+
"""
20+
21+
from multiprocessing import Value
22+
import tempfile
23+
import hashlib
24+
import logging
25+
import os
26+
27+
import luigi
28+
29+
logger = logging.getLogger('luigi-interface')
30+
31+
32+
class RunAnywayTarget(luigi.Target):
33+
"""
34+
A target used to make a task run everytime it is called.
35+
36+
Usage:
37+
38+
Pass `self` as the first argument in your task's `output`:
39+
40+
.. code-block: python
41+
42+
def output(self):
43+
return RunAnywayTarget(self)
44+
45+
And then mark it as `done` in your task's `run`:
46+
47+
.. code-block: python
48+
49+
def run(self):
50+
# Your task execution
51+
# ...
52+
self.output().done() # will then be considered as "existing"
53+
"""
54+
55+
# Specify the location of the temporary folder storing the state files. Subclass to change this value
56+
temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-simulate')
57+
temp_time = 24 * 3600 # seconds
58+
59+
# Unique value (PID of the first encountered target) to separate temporary files between executions and
60+
# avoid deletion collision
61+
unique = Value('i', 0)
62+
63+
def __init__(self, task_obj):
64+
self.task_id = task_obj.task_id
65+
66+
if self.unique.value == 0:
67+
with self.unique.get_lock():
68+
if self.unique.value == 0:
69+
self.unique.value = os.getpid() # The PID will be unique for every execution of the pipeline
70+
71+
# Deleting old files > temp_time
72+
if os.path.isdir(self.temp_dir):
73+
import shutil
74+
import time
75+
limit = time.time() - self.temp_time
76+
for fn in os.listdir(self.temp_dir):
77+
path = os.path.join(self.temp_dir, fn)
78+
if os.path.isdir(path) and os.stat(path).st_mtime < limit:
79+
shutil.rmtree(path)
80+
logger.debug('Deleted temporary directory %s', path)
81+
82+
def get_path(self):
83+
"""
84+
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
85+
"""
86+
md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()
87+
logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)
88+
89+
return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)
90+
91+
def exists(self):
92+
"""
93+
Checks if the file exists
94+
"""
95+
return os.path.isfile(self.get_path())
96+
97+
def done(self):
98+
"""
99+
Creates temporary file to mark the task as `done`
100+
"""
101+
logger.info('Marking %s as done', self.task_id)
102+
103+
fn = self.get_path()
104+
os.makedirs(os.path.dirname(fn), exist_ok=True)
105+
open(fn, 'w').close()

test/simulate_test.py

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# Copyright 2012-2015 Spotify AB
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
18+
from helpers import unittest
19+
import luigi
20+
from luigi.contrib.simulate import RunAnywayTarget
21+
22+
from multiprocessing import Process
23+
import os
24+
import tempfile
25+
26+
27+
def temp_dir():
28+
if os.getenv('TRAVIS') == 'true':
29+
return os.path.abspath(os.path.join(os.path.dirname(__file__), 'simulate-tmp'))
30+
return os.path.join(tempfile.gettempdir(), 'luigi-simulate')
31+
32+
33+
def is_writable():
34+
d = temp_dir()
35+
fn = os.path.join(d, 'luigi-simulate-write-test')
36+
exists = True
37+
try:
38+
os.makedirs(d, exist_ok=True)
39+
open(fn, 'w').close()
40+
os.remove(fn)
41+
except:
42+
exists = False
43+
44+
return unittest.skipIf(not exists, 'Can\'t write to temporary directory')
45+
46+
47+
class PathRunAnywayTarget(RunAnywayTarget):
48+
temp_dir = temp_dir()
49+
50+
51+
class TaskA(luigi.Task):
52+
i = luigi.IntParameter(default=0)
53+
54+
def output(self):
55+
return PathRunAnywayTarget(self)
56+
57+
def run(self):
58+
fn = os.path.join(temp_dir(), 'luigi-simulate-test.tmp')
59+
os.makedirs(os.path.dirname(fn), exist_ok=True)
60+
61+
with open(fn, 'a') as f:
62+
f.write('{0}={1}\n'.format(self.__class__.__name__, self.i))
63+
64+
self.output().done()
65+
66+
67+
class TaskB(TaskA):
68+
def requires(self):
69+
return TaskA(i=10)
70+
71+
72+
class TaskC(TaskA):
73+
def requires(self):
74+
return TaskA(i=5)
75+
76+
77+
class TaskD(TaskA):
78+
def requires(self):
79+
return [TaskB(), TaskC(), TaskA(i=20)]
80+
81+
82+
class TaskWrap(luigi.WrapperTask):
83+
def requires(self):
84+
return [TaskA(), TaskD()]
85+
86+
87+
def reset():
88+
# Force tasks to be executed again (because multiple pipelines are executed inside of the same process)
89+
t = TaskA().output()
90+
with t.unique.get_lock():
91+
t.unique.value = 0
92+
93+
94+
class RunAnywayTargetTest(unittest.TestCase):
95+
@is_writable()
96+
def test_output(self):
97+
reset()
98+
99+
fn = os.path.join(temp_dir(), 'luigi-simulate-test.tmp')
100+
101+
luigi.build([TaskWrap()], local_scheduler=True)
102+
with open(fn, 'r') as f:
103+
data = f.read().strip().split('\n')
104+
105+
data.sort()
106+
reference = ['TaskA=0', 'TaskA=10', 'TaskA=20', 'TaskA=5', 'TaskB=0', 'TaskC=0', 'TaskD=0']
107+
reference.sort()
108+
109+
os.remove(fn)
110+
self.assertEqual(data, reference)
111+
112+
@is_writable()
113+
def test_output_again(self):
114+
# Running the test in another process because the PID is used to determine if the target exists
115+
p = Process(target=self.test_output)
116+
p.start()
117+
p.join()

0 commit comments

Comments
 (0)