55# Apache License, Version 2.0 (see LICENSE or https://www.apache.org/licenses/LICENSE-2.0)
66# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
77
8- from __future__ import annotations
8+ from __future__ import absolute_import , division , print_function
99
10+ __metaclass__ = type
1011
1112DOCUMENTATION = r'''
1213---
@@ -105,10 +106,11 @@ def amq_argument_spec():
105106
106107
107108# from https://stackoverflow.com/a/54263201/389099
108- def follow (file , sleep_sec = 0.1 ):
109+ def follow (file , sleep_sec = 0.1 , timeout_sec = 60 ):
109110 """ Yield each line from a file as they are written.
110111 `sleep_sec` is the time to sleep after empty reads. """
111112 line = ''
113+ ts = time .time ()
112114 while True :
113115 tmp = file .readline ()
114116 if tmp is not None and tmp != "" :
@@ -118,22 +120,24 @@ def follow(file, sleep_sec=0.1):
118120 line = ''
119121 elif sleep_sec :
120122 time .sleep (sleep_sec )
123+ if (time .time () >= (ts + timeout_sec )):
124+ raise Exception ("timeout reached without finding search string in file" )
121125
122126
123127def main ():
124128 module = AnsibleModule (argument_spec = amq_argument_spec (), supports_check_mode = False )
125129
126130 source = module .params ['path' ]
131+ regex = module .params ['regex' ]
132+ timeout = module .params ['timeout' ]
133+ delay = module .params ['delay' ]
127134
128135 try :
129136 with open (source , 'r' ) as source_fh :
130- ts = time .time ( )
131- for line in follow (file , 0.25 ):
137+ time .sleep ( delay )
138+ for line in follow (source_fh , 0.25 , timeout ):
132139 if re .match (regex , line ):
133140 break
134- if (time .time () >= ts + timeout ):
135- msg = "timeout reached without finding search string in file"
136- module .fail_json (msg )
137141 except (IOError , OSError ) as e :
138142 if e .errno == errno .ENOENT :
139143 msg = "file not found: %s" % source
@@ -142,10 +146,13 @@ def main():
142146 elif e .errno == errno .EISDIR :
143147 msg = "source is a directory and must be a file: %s" % source
144148 else :
145- msg = "unable to slurp file: %s" % to_native (e , errors = 'surrogate_then_replace' )
149+ msg = "unable to read file: %s" % to_native (e , errors = 'surrogate_then_replace' )
146150
147151 module .fail_json (msg )
148152
153+ except (Exception ) as e :
154+ module .fail_json (e .args )
155+
149156 module .exit_json (content = line , source = source )
150157
151158
0 commit comments