22
33# python2 or python3 compatible
44
5+ import datetime
6+ import logging
7+ import logging .config
58import os
9+ import sched
10+ import shutil
11+ import signal
612import sys
13+ import threading
14+ import time
15+
716import yaml
8- import signal
9- import logging
10- import logging .config
1117
1218import runner_service .configuration as configuration
19+ from runner_service .app import create_app
1320from runner_service .utils import (fread ,
1421 create_self_signed_cert ,
1522 ssh_create_key ,
1623 RunnerServiceError )
17- from runner_service .app import create_app
18-
1924
2025def signal_stop (* args ):
2126 '''
@@ -141,8 +146,40 @@ def setup_common_environment():
141146 setup_localhost_ssh ()
142147
143148
144- def main (test_mode = False ):
149+ def remove_artifacts (scheduler , frequency ):
150+ # Clean artifacts older than artifacts_remove_age days.
151+ artifacts_dir = os .path .join (configuration .settings .playbooks_root_dir , "artifacts" )
152+ if os .path .exists (artifacts_dir ):
153+ dir_list = os .listdir (artifacts_dir )
154+ time_now = time .mktime (time .localtime ())
155+ for artifacts in dir_list :
156+ mtime = os .path .getmtime (os .path .join (artifacts_dir , artifacts ))
157+ time_difference = datetime .timedelta (seconds = time_now - mtime )
158+ if time_difference .days >= configuration .settings .artifacts_remove_age :
159+ shutil .rmtree (os .path .join (artifacts_dir , artifacts ))
160+
161+ # Reschedule next self-execution:
162+ scheduler .enter (frequency , 0 , remove_artifacts , (scheduler , frequency ))
163+ scheduler .run ()
164+
165+
166+ def remove_artifacts_thread_proc (frequency ):
167+ scheduler = sched .scheduler ()
168+ # Schedule first execution immediately.
169+ scheduler .enter (0 , 0 , remove_artifacts , (scheduler , frequency ))
170+ scheduler .run ()
171+
145172
173+ def remove_artifacts_init ():
174+ remove_artifacts_thread = threading .Thread (
175+ target = remove_artifacts_thread_proc ,
176+ args = (datetime .timedelta (days = configuration .settings .artifacts_remove_frequency ).total_seconds (),),
177+ daemon = True
178+ )
179+ remove_artifacts_thread .start ()
180+
181+
182+ def main (test_mode = False ):
146183 # Setup log and ssh and other things present in all the environments
147184 setup_common_environment ()
148185
@@ -156,6 +193,9 @@ def main(test_mode=False):
156193 app .config ['WTF_CSRF_ENABLED' ] = False
157194 return app .test_client ()
158195
196+ if configuration .settings .mode == 'prod' and configuration .settings .artifacts_remove_age > 0 :
197+ remove_artifacts_init ()
198+
159199 # Start the API server
160200 app .run (host = configuration .settings .ip_address ,
161201 port = configuration .settings .port ,
0 commit comments