/
management.py
executable file
·1184 lines (908 loc) · 35.2 KB
/
management.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# LSDA Management Daemon.
"""
Running on every worker node, this script manages a persistent connection to
AMQP and ZooKeeper for the duration of each job.
Author: Jeremy Archer <jarcher@uchicago.edu>
Date: 10 December 2013
"""
# Import the Python green threading library.
from gevent import monkey
monkey.patch_all()
from gevent.coros import Semaphore
from gevent.pywsgi import WSGIServer
from gevent import subprocess
import gevent
# Import the pure-Python ZooKeeper implementation.
from kazoo.client import KazooClient
from kazoo.exceptions import NoNodeError, NodeExistsError
from kazoo.handlers.gevent import SequentialGeventHandler
# Import the pure-Python AMQP client libraries.
import pika
# Allow putting data to S3.
import boto.s3
import boto.ec2
# Allow adjusting the size of the worker pool.
from boto.ec2.autoscale import AutoScaleConnection
# Track subsystem statistics in ZooKeeper.
from linux_metrics import mem_stat, disk_stat, cpu_stat, net_stat
# Finally, import the stdlib.
import socket
import argparse
import sys
import logging
import time
import uuid
import json
import random
import tempfile
import os
import urllib
import zipfile
from functools import wraps, partial
from collections import namedtuple
import os.path
def forever(func):
"""
Returns a modified version of the given function with the code wrapped in
a while-loop. This function is meant to be used as an annotation, like so:
>>> @forever
... def test(x = [ 0 ]):
... x[0] += 1
... if x[0] == 10:
... raise Exception("test is now complete")
...
>>> test()
Traceback (most recent call last):
...
Exception: test is now complete
"""
@wraps(func)
def inner(*vargs, **dargs):
"""
A wrapper for +func+.
"""
while True:
func(*vargs, **dargs)
return inner
class DeepBreakException(Exception):
"""
An exception to allows breaking out of multiply-nested code.
"""
class Interruptable(object):
"""
This context manager allows a user to break out of code by calling the given
function.
"""
def __init__(self, description=None, owner=None):
self.exception = DeepBreakException()
self.active = True
self.thread = gevent.getcurrent()
self.description = description
self.owner = owner
def __enter__(self):
self.active = True
if self.owner:
self.owner.enter_state(self)
return self
def __exit__(self, kind, instance, traceback):
self.active = False
if self.owner:
self.owner.exit_state(self)
return instance is self.exception
def interrupt(self, *vargs, **dargs):
"""
Jumps to the end of this block.
"""
if self.active:
self.thread.kill(self.exception)
def wait_forever():
"""
Waits indefinitely.
"""
while True:
gevent.sleep(60)
def _get_ip_address():
"""
Determines the current instance IP address by attempting to connect to
Google Public DNS.
"""
connection = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connection.connect(("8.8.8.8", 1337))
try:
return connection.getsockname()[0]
finally:
connection.close()
def _get_public_ip_address():
"""
Determines the publicly-routable instance IP address using Amazon magics.
"""
return urllib.urlopen("http://169.254.169.254/latest/"
"meta-data/public-ipv4").read()
def _is_up_to_date():
"""
Returns True if this instance is up to date.
"""
# Retrieve instance information.
conn = AutoScaleConnection()
pool = conn.get_all_groups(["LSDA Worker Pool"])[0]
config = conn.get_all_launch_configurations(
names=[pool.launch_config_name])[0]
# Retrive the AMI for this instance and for others.
config_ami = config.image_id
my_ami = urllib.urlopen("http://169.254.169.254/latest/"
"meta-data/ami-id").read()
return config_ami == my_ami
def _watchdog_timer(delay_in_seconds = 30 * 60):
"""
Waits the given amount of time before shutting down this instance.
"""
# Wait a random amount of time.
seconds = delay_in_seconds + random.uniform(-300, 300)
logging.info("About to wait for {}s before shutting down.".format(seconds))
gevent.sleep(seconds)
# Remove this node from the rotation.
_remove_from_worker_pool()
_shutdown_instance()
def _remove_from_worker_pool():
"""
Ensures that this instance is shut down, and unregisted from the worker
pool.
"""
# Retrieve the current state of the pool.
pool = AutoScaleConnection().get_all_groups(["LSDA Worker Pool"])[0]
if pool.desired_capacity <= pool.min_size:
return
# Reduce the pool size and shut ourself down.
pool.desired_capacity -= 1
pool.update()
def _shutdown_instance():
"""
Shuts down this instance and removes it from the worker pool.
"""
# Trigger immediate shutdown.
subprocess.check_call(["/usr/bin/sudo", "/sbin/shutdown", "-h", "now"])
# Wait for shutdown.
while True:
gevent.sleep(3600)
Task = namedtuple('Task', ['kind', 'from_user', 'task_id', 'sha1', 'file_name',
'owner'])
class AMQPLoggingHandler(logging.Handler):
"""
A Python logging handler to send logging results to AMQP for distribution
and archival.
"""
def __init__(self, amqp_channel, exchange_name):
super(AMQPLoggingHandler, self).__init__()
# Set up local state.
self.amqp_channel = amqp_channel
self.exchange = exchange_name
self.disable = False
self.task_id = None
self.owner = None
self.sha1 = None
self.task_type = None
self.my_uuid = str(uuid.uuid4())
self.ip_address = _get_public_ip_address()
self.setFormatter(logging.Formatter(
"%(asctime)s [%(levelname)-8s] %(message)s"
))
self.semaphore = Semaphore()
# Initialize the AMQP exchange.
self.amqp_channel.exchange_declare(
exchange=exchange_name,
type="topic")
def emit_amqp(self, message):
"""
Emit a message to this stream's STDERR.
"""
# Ensure that we don't send crazy packets to AMQP.
with self.semaphore:
# Publish this message over AMQP.
self.amqp_channel.basic_publish(
exchange=self.exchange,
routing_key="stderr.{0}".format(self.task_id),
# Pack the current worker and task IDs into the message.
body=json.dumps(message)
)
def emit_close(self):
"""
Closes the other end of this pipe.
"""
self.emit_amqp(dict(
worker_uuid=self.my_uuid,
task_id=self.task_id,
owner=self.owner,
sha1=self.sha1,
task_type=self.task_type,
ip_address=self.ip_address,
type='close'
))
def emit_unformatted(self, message, level=None):
"""
Emit an unformatted (string) logging message to AMQP.
"""
# Bounce most logs to syslog.
sys.stderr.write("{0}\n".format(message))
sys.stderr.flush()
# Ensure that generic messages are shown to the user.
if level is None:
level = logging.WARN
# Ensure that we don't create log loops.
if self.disable:
return
self.disable = True
try:
self.emit_amqp(dict(
type='data',
worker_uuid=self.my_uuid,
task_id=self.task_id,
owner=self.owner,
sha1=self.sha1,
task_type=self.task_type,
ip_address=self.ip_address,
message=message,
level=level,
))
except pika.exceptions.ChannelClosed:
print "Channel closed!"
self.disable = False
def emit(self, record):
"""
Emits a logging message to AMQP.
"""
return self.emit_unformatted(self.format(record), level=record.levelno)
class ZooKeeperAgent(object):
"""
This class records any daemon that relies on a ZooKeeper connection
to function.
"""
def __init__(self, zookeeper):
"""
Initialize this agent given the connection to ZooKeeper. This class
automatically spawns a new greenlet to manage state.
"""
self.zookeeper = zookeeper
self.state_values = dict()
self.agent_identifier = "/nodes/{}".format(_get_public_ip_address())
self["state_stack"] = []
self.warnings = dict()
self.thread = gevent.spawn(self._on_currently_running)
self.update_thread = gevent.spawn(self._state_updater)
self.web_server = WSGIServer(('', 1337), self._state_server)
self.web_server_thread = gevent.spawn(self.web_server.serve_forever)
self.metrics_threads = []
self.metrics = {
"mem_usage": (mem_stat.mem_stats,),
"cpu_usage": (cpu_stat.cpu_percents, 1),
"disk_throughput": (disk_stat.disk_reads_writes_persec, "xvdb", 1),
"spindles": (disk_stat.disk_busy, "xvdb", 5),
"disk_usage": (disk_stat.disk_usage, "/mnt"),
"net_throughput": (self._netstat, "eth0"),
"warnings": (self._compute_warnings,),
}
self.update_metric_collection()
def update_state(self):
"""
Tells ZooKeeper of our current state, if we are connected.
"""
if self.zookeeper.state == 'CONNECTED':
value = json.dumps(self.state_values)
# Create the given nameserver record, if possible.
try:
self.zookeeper.set(self.agent_identifier, value)
except NoNodeError:
try:
self.zookeeper.create(self.agent_identifier, value,
makepath=True, ephemeral=True)
except NodeExistsError:
pass
def __delitem__(self, name):
"""
Deletes the given state variable from this agent.
"""
del self.state_values[name]
def __setitem__(self, name, value):
"""
Stores a globally-visible state variable.
"""
self.state_values[name] = value
def __getitem__(self, name):
"""
Retrieves the value of the given state variable.
"""
return self.state_values[name]
def _compute_warnings(self):
"""
Marks the current set of warnings in ZooKeeper.
"""
# Provide notification of this error.
right_now = time.time()
all_warnings = []
# Check for high memory usage.
if "mem_usage" in self.state_values:
mactive, mtotal, mcached, mfree, stotal, sfree = self["mem_usage"]
usage_percent = 1 - (mfree + mcached) / float(mtotal)
if usage_percent > 0.90:
self.apply_warning("OutOfRAM")
# Check for high disk usage.
if "disk_usage" in self.state_values:
disk_usage = float(self["disk_usage"][4][:-1]) / 100
if disk_usage > 0.90:
self.apply_warning("OutOfSSD")
# Find those warnings that have occured in the last five minutes.
for warning, last_notified in self.warnings.items():
if (right_now - last_notified) < 5:
all_warnings.append(warning)
return all_warnings
def apply_warning(self, warning_name):
"""
Makes a note of something that could cause a task to fail.
"""
self.warnings[warning_name] = time.time()
def enter_state(self, state):
"""
Tracks when this Agent enters a given state.
"""
logging.info("Enter state={!r}".format(state.description))
# Send an update to ZooKeeper.
self["state_stack"].append(state.description)
def exit_state(self, state):
"""
Tracks when this Agent leaves a given state.
"""
logging.info("Exit state={!r}".format(state.description))
# Send an update to ZooKeeper.
self["state_stack"].pop()
def _state_server(self, environ, start_response):
"""
A small WSGI server to stream data from this server.
"""
# Prepare a HTTP response.
start_response("200 Okay", [("Content-type", "text/json")])
if environ['PATH_INFO'] == '/stream':
# Continuously stream data out of this server.
while True:
yield json.dumps(self.state_values)
gevent.sleep(2)
elif environ['PATH_INFO'] == '/state':
# Allow one-shot metrics collection.
yield json.dumps(self.state_values)
elif (environ['PATH_INFO'] == '/exit' and
environ['REQUEST_METHOD'] == 'POST'):
# Kills this instance.
_shutdown_instance()
yield json.dumps(dict(status="okay"))
@forever
def _state_updater(self):
"""
Triggers a 0.5 Hz flush to ZooKeeper to track statistics about this
worker."""
self.update_state()
gevent.sleep(2)
def _netstat(self, interface):
"""
Calculate the latest network status information.
"""
irx, itx = net_stat.rx_tx_bytes(interface)
gevent.sleep(1)
frx, ftx = net_stat.rx_tx_bytes(interface)
return dict(transmitted=(ftx - itx), received=(frx - irx))
@forever
def _metrics_thread(self, name, metric):
"""
Update the server with the current value of the given metric.
"""
function = metric[0]
args = metric[1:]
try:
self[name] = function(*args)
except Exception:
logging.exception("Unable to read metric {}.".format(name))
gevent.sleep(1)
def update_metric_collection(self):
"""
Update the background metrics threads given the values in self.metrics.
"""
for thread in self.metrics_threads:
thread.kill()
for name, metric in self.metrics.items():
self.metrics_threads.append(gevent.spawn(self._metrics_thread,
name, metric))
@forever
def _on_currently_running(self):
"""
The first level of processing. It simply ensures that we remain
connected to ZooKeeper. When active, it calls
+_on_connected_to_zookeeper()+, a method meant to be overriden.
"""
def trigger_on_states(action, states):
"""
Helper function to trigger the given +action+ when the connection is
in one of +states+."""
def inner(state):
"""
Handler function for the state change listener.
"""
if state in states:
gevent.spawn(action)
self.zookeeper.remove_listener(inner)
# Actually hook into the ZooKeeper connection.
self.zookeeper.add_listener(inner)
# Skip ahead if we're already connected.
if self.zookeeper.state != 'CONNECTED':
with Interruptable("Disconnected from ZooKeeper") as disconnected:
trigger_on_states(disconnected.interrupt, ('CONNECTED'))
# Wake up when we are connected.
wait_forever()
# Block until this occurs.
# Mark ourselves as present in ZooKeeper.
self.update_state()
with Interruptable("Connected to ZooKeeper", self) as connected:
trigger_on_states(connected.interrupt, ('SUSPENDED', 'LOST'))
# Wake up If we reach the given state.
self._on_connected_to_zookeeper()
# Process events until this occurs.
def _on_connected_to_zookeeper(self):
"""
Override this function to customize the behavior of this class.
"""
def join(self):
"""
Block until this daemon has completed.
"""
# Wait until this thread completes or raise the exception it terminated
# with.
try:
self.thread.get()
finally:
for thread in self.metrics_threads:
thread.kill()
thread.get()
class EngineOrControllerRunner(ZooKeeperAgent):
"""
This task initializes an agent that could run either an IPython
controller or IPython engine task.
"""
STUPID_JSON = (
'/home/lsda/.ipython/profile_default/' +
'security/ipcontroller-engine.json'
)
def __init__(self, zookeeper, amqp_channel, queue_name, logs_handler):
# Initialize the connection to ZooKeeper.
super(EngineOrControllerRunner, self).__init__(zookeeper)
# Save local state.
self.amqp_channel = amqp_channel
self.queue_name = queue_name
self.logs_handler = logs_handler
self.watchdog = None
self.dequeue_this_task = False
self.time = 0
# Broadcast the current Git revision and AMQP channel.
self["release"] = subprocess.check_output(
["/usr/bin/env", "git", "rev-parse", "HEAD"],
env={"GIT_DIR": os.path.join(os.path.dirname(__file__), ".git")})
self["queue_name"] = queue_name
@forever
def _on_connected_to_zookeeper(self):
"""
This function manages the daemon to pull tasks from AMQP.
"""
# Ensure that the node eventually shuts down.
self.watchdog = gevent.spawn(_watchdog_timer)
while True:
# Rate-limit polling from AMQP.
gevent.sleep(1)
# Ensure that we remain up-to-date.
if self.time % 600 == 0:
if not _is_up_to_date():
_shutdown_instance()
self.time += 1
# Consume the next event.
with self.logs_handler.semaphore:
method_frame, _, body = (
self.amqp_channel.basic_get(self.queue_name))
# Break out of this loop if not an event.
if method_frame:
break
# Parse the incoming message.
data = json.loads(body)
# Keep this node alive for another 30m.
if self.watchdog:
self.watchdog.kill()
self.watchdog = None
# Ensure that all fields are defined.
for key in data.keys():
if key not in Task._fields:
del data[key]
for key in Task._fields:
if key not in data:
data[key] = None
logging.warn("Data is {!r}".format(data))
# Allow in-task cancellation.
self.dequeue_this_task = False
# Process the task.
self._has_task_available(Task(**data))
# ACK the AMQP task, if it is marked as having completed.
with self.logs_handler.semaphore:
if (self.zookeeper.exists('/done/{0}'.format(data["task_id"])) or
self.dequeue_this_task):
self.amqp_channel.basic_ack(method_frame.delivery_tag)
else:
self.amqp_channel.basic_reject(method_frame.delivery_tag,
requeue=True)
def _has_task_available(self, task):
"""
Processes a task from AMQP.
"""
with Interruptable("AMQP Task available", self) as task_available:
# Ensure that this task has not already finished.
if not self.zookeeper.exists(
'/done/{0}'.format(task.task_id),
partial(gevent.spawn, task_available.interrupt
)):
# Log the start of execution.
logging.info('Got task={!r}'.format(task))
# Associate logs with this task.
self.logs_handler.task_id = task.task_id
self.logs_handler.sha1 = task.sha1
self.logs_handler.owner = task.owner
self.logs_handler.task_type = task.kind
# Report the current state in ZooKeeper.
self["task"] = task._asdict()
self["flag"] = ""
try:
with Interruptable("Processing task", self) as working:
# Launch the correct type of worker.
if task.kind == 'engine':
self._has_engine_task_to_perform(task)
elif task.kind == 'controller':
result = self._has_controller_task_to_perform(task)
# Tell ZooKeeper that we have finished.
try:
self.zookeeper.create(
'/done/{0}'.format(task.task_id),
result, makepath=True)
except NodeExistsError:
pass
else:
logging.warn(
"Received task of unknown type {0!r}"
.format(task.kind)
)
except Exception:
logging.exception(
'Unhandled exception in daemon')
finally:
# Emitting a closing handler.
if task.kind == 'controller':
self.logs_handler.emit_close()
# Clean up logging.
self.logs_handler.task_id = None
self.logs_handler.owner = None
self.logs_handler.task_type = None
self.logs_handler.branch_name = None
# Clean up ZooKeeper state.
del self["task"]
del self["flag"]
self.update_state()
# Log completion.
logging.info('Completed task={0!r}'.format(task))
else:
logging.warn("Removed task {0!r} that has already been run."
.format(task.task_id))
def _has_engine_task_to_perform(self, task):
"""
This function waits until a controller is ready to handle this engine
task.
"""
# Wait until the controller is ready.
for i in xrange(15):
try:
controller_info = self.zookeeper.get(
'/controller/{}'.format(task.task_id))[0]
except NoNodeError:
time.sleep(1)
else:
break
else: # reschedule after 15s
return
self._has_controller(task, controller_info)
def _has_controller(self, task, controller_info):
"""
This function ensures that the engine remains running while the
controller is active.
"""
# Create the parent directory for the IPython configuration file.
try:
os.makedirs(os.path.dirname(self.__class__.STUPID_JSON))
except OSError:
pass
# Save the stupid IPython profile configuration file.
with open(self.__class__.STUPID_JSON, 'w+') as output_file:
output_file.write(controller_info)
# Run the two engines in separate sandboxes.
engines = []
for i in xrange(2):
engines.append(gevent.spawn(self._run_in_sandbox, task,
["ipengine"]))
# Wait for completion.
try:
for engine in engines:
engine.get()
finally:
for engine in engines:
engine.kill()
def _has_controller_task_to_perform(self, task):
"""
This function manages the IPython controller subprocess.
"""
# Rate limit controller launches to avoid hammering Git.
gevent.sleep(1)
# Start the local IPython controller.
command = ["/usr/bin/env", "ipcontroller", "--init", "--ip=*"]
# Record the arguments.
logging.info("Starting ipcontroller cmd={0!r}".format(command))
controller_job = subprocess.Popen(command, stderr=subprocess.PIPE)
try:
# Keep reading until there's output suggesting that we are
# available for connections.
while True:
line = controller_job.stderr.readline()
if 'scheduler started' in line.lower():
controller_info = open(self.__class__.STUPID_JSON).read()
break
# Start a local IPython engine.
local_engine = gevent.spawn(self._has_controller,
task, controller_info)
# Notify ZooKeeper that we've started.
try:
self.zookeeper.create(
'/controller/{0}'.format(task.task_id),
ephemeral=True,
value=controller_info,
makepath=True
)
except NodeExistsError:
self.zookeeper.set(
'/controller/{0}'.format(task.task_id),
value=controller_info
)
logging.warn(
'Potential race condition in task_id or done/task_id.')
@gevent.spawn
def copy_output_from_controller():
"""
Copies output from ipcontroller to AMQP.
"""
while True:
line = controller_job.stderr.readline()
if line == '':
break
self.logs_handler.emit_unformatted("ipcontroller says {:}"
.format(line.strip()))
try:
# Run the main script in the sandbox.
return self._run_in_sandbox(task, ["main"])
finally:
# Delete the controller job.
try:
self.zookeeper.delete('/controller/{0}'.format(
task.task_id))
except NoNodeError:
pass
# Ensure that the output copier is shut down properly.
copy_output_from_controller.kill()
finally:
# Ensure that we don't run a subprocess without ZooKeeper's
# permission.
try:
controller_job.terminate()
controller_job.wait()
except OSError:
pass
# Kill the local instance.
local_engine.kill()
def _notebook_copier(self, code_directory, task):
"""
Copies main.ipynb to the S3 bucket for the given +task_id+.
"""
previous_time = 0
path = os.path.join(code_directory, "__saved.ipynb")
while True:
# Ensure that we've actually changed since the last time.
if os.path.exists(path) and os.path.getmtime(path) > previous_time:
# Log the current state.
logging.info("Pushing notebook file to S3.")
# Upload the ipynb file to S3.
try:
connection = boto.connect_s3()
bucket = connection.get_bucket('ml-submissions')
key = bucket.new_key('results/{}.ipynb'.
format(task.task_id))
key.content_type = "text/json"
# Upload the resulting notebook.
key.set_contents_from_filename(path)
# Generate a rendered version of this notebook.
with tempfile.TemporaryFile() as fp:
# Convert notebook to an HTML file.
subprocess.check_call(["/usr/bin/env",
"ipython", "nbconvert",
"--to=html", "--stdout", path], stdout = fp)
# Construct a rendered URL.
render_url = urllib.urlencode(task.__dict__)
fp.write((
'<script type="script/javascript" src="https://lsda.c'
's.uchicago.edu/render.js?{}"></script>'
).format(render_url))
fp.seek(0)
# Upload the HTML version of the notebook.
key = bucket.new_key('results/{}.html'.
format(task.task_id))
key.content_type = "text/html"
key.set_contents_from_file(fp)
except Exception:
logging.exception("Unable to upload notebook.")
else:
previous_time = os.path.getmtime(path)
gevent.sleep(3)
def _stderr_copier(self, main_job, task):
"""
Copies data from stdout/stderr to the main logging output, pushing
some data values to S3.
"""
while True:
line = main_job.stdout.readline(65536)
# Allow reporting of "flag" values for running jobs.
if line.startswith("REPORTING_SEMAPHORE "):
self["flag"] = line.split(" ", 1)[1]
# Allow the task to cancel itself.
elif line.startswith("DEQUEUE_THIS_TASK"):
self.dequeue_this_task = True
main_job.kill()
# Allow the task to create more copies of itself.
elif line.startswith("SPAWN_NEW_COPY"):