2012-09-06 20:45:48 +02:00
|
|
|
#!/usr/bin/python
|
2012-11-02 15:40:13 +01:00
|
|
|
# Copyright (C) 2012 Humbug, Inc. All rights reserved.
|
2012-09-13 02:29:26 +02:00
|
|
|
import sys
|
|
|
|
import traceback
|
|
|
|
import simplejson
|
|
|
|
import re
|
|
|
|
import time
|
2012-09-13 03:41:52 +02:00
|
|
|
import subprocess
|
2012-09-21 21:17:25 +02:00
|
|
|
import optparse
|
2012-09-26 16:44:42 +02:00
|
|
|
import os
|
2012-09-27 22:14:14 +02:00
|
|
|
import datetime
|
2012-09-28 20:29:23 +02:00
|
|
|
import textwrap
|
2012-10-12 23:19:49 +02:00
|
|
|
import signal
|
2012-11-09 23:23:42 +01:00
|
|
|
import logging
|
2012-09-26 22:46:23 +02:00
|
|
|
|
2012-11-14 00:02:35 +01:00
|
|
|
DEFAULT_SITE = "https://humbughq.com"
|
|
|
|
|
2012-11-02 21:41:04 +01:00
|
|
|
def to_humbug_username(zephyr_username):
|
2012-11-02 21:38:00 +01:00
|
|
|
if "@" in zephyr_username:
|
|
|
|
(user, realm) = zephyr_username.split("@")
|
|
|
|
else:
|
2012-11-05 19:10:41 +01:00
|
|
|
(user, realm) = (zephyr_username, "ATHENA.MIT.EDU")
|
2012-11-02 21:38:00 +01:00
|
|
|
if realm.upper() == "ATHENA.MIT.EDU":
|
|
|
|
return user.lower() + "@mit.edu"
|
2012-11-03 01:55:07 +01:00
|
|
|
return user.lower() + "|" + realm.upper() + "@mit.edu"
|
2012-10-01 20:36:08 +02:00
|
|
|
|
2012-11-02 20:46:50 +01:00
|
|
|
def to_zephyr_username(humbug_username):
|
2012-11-02 21:38:00 +01:00
|
|
|
(user, realm) = humbug_username.split("@")
|
|
|
|
if "|" not in user:
|
|
|
|
return user.lower() + "@ATHENA.MIT.EDU"
|
2012-11-09 21:25:54 +01:00
|
|
|
match_user = re.match(r'([a-zA-Z0-9_]+)\|(.+)', user)
|
2012-11-02 21:38:00 +01:00
|
|
|
if not match_user:
|
|
|
|
raise Exception("Could not parse Zephyr realm for cross-realm user %s" % (humbug_username,))
|
|
|
|
return match_user.group(1).lower() + "@" + match_user.group(2).upper()
|
2012-11-02 20:46:50 +01:00
|
|
|
|
2012-11-05 21:39:09 +01:00
|
|
|
# Checks whether the pair of adjacent lines would have been
|
|
|
|
# linewrapped together, had they been intended to be parts of the same
|
|
|
|
# paragraph. Our check is whether if you move the first word on the
|
|
|
|
# 2nd line onto the first line, the resulting line is either (1)
|
|
|
|
# significantly shorter than the following line (which, if they were
|
|
|
|
# in the same paragraph, should have been wrapped in a way consistent
|
|
|
|
# with how the previous line was wrapped) or (2) shorter than 60
|
|
|
|
# characters (our assumed minimum linewrapping threshhold for Zephyr)
|
2012-11-05 21:44:08 +01:00
|
|
|
# or (3) the first word of the next line is longer than this entire
|
|
|
|
# line.
|
2012-11-05 21:39:09 +01:00
|
|
|
def different_paragraph(line, next_line):
|
2012-11-05 18:46:16 +01:00
|
|
|
words = next_line.split()
|
2012-11-05 21:39:09 +01:00
|
|
|
return (len(line + " " + words[0]) < len(next_line) * 0.8 or
|
2012-11-10 00:04:37 +01:00
|
|
|
len(line + " " + words[0]) < 50 or
|
2012-11-05 21:44:08 +01:00
|
|
|
len(line) < len(words[0]))
|
2012-11-05 18:46:16 +01:00
|
|
|
|
|
|
|
# Linewrapping algorithm based on:
|
|
|
|
# http://gcbenison.wordpress.com/2011/07/03/a-program-to-intelligently-remove-carriage-returns-so-you-can-paste-text-without-having-it-look-awful/
|
2012-10-23 17:22:51 +02:00
|
|
|
def unwrap_lines(body):
|
2012-11-05 18:46:16 +01:00
|
|
|
lines = body.split("\n")
|
|
|
|
result = ""
|
|
|
|
previous_line = lines[0]
|
|
|
|
for line in lines[1:]:
|
2012-11-05 21:39:27 +01:00
|
|
|
line = line.rstrip()
|
2012-11-06 16:40:08 +01:00
|
|
|
if (re.match(r'^\W', line, flags=re.UNICODE)
|
|
|
|
and re.match(r'^\W', previous_line, flags=re.UNICODE)):
|
|
|
|
result += previous_line + "\n"
|
|
|
|
elif (line == "" or
|
2012-11-05 18:46:16 +01:00
|
|
|
previous_line == "" or
|
2012-11-06 16:40:08 +01:00
|
|
|
re.match(r'^\W', line, flags=re.UNICODE) or
|
2012-11-05 21:39:09 +01:00
|
|
|
different_paragraph(previous_line, line)):
|
2012-11-05 18:46:16 +01:00
|
|
|
# Use 2 newlines to separate sections so that we
|
|
|
|
# trigger proper Markdown processing on things like
|
|
|
|
# bulleted lists
|
|
|
|
result += previous_line + "\n\n"
|
|
|
|
else:
|
|
|
|
result += previous_line + " "
|
|
|
|
previous_line = line
|
|
|
|
result += previous_line
|
|
|
|
return result
|
2012-10-23 17:22:51 +02:00
|
|
|
|
2012-09-26 16:43:53 +02:00
|
|
|
def send_humbug(zeph):
|
2012-11-02 21:58:18 +01:00
|
|
|
message = {}
|
2012-10-18 17:14:03 +02:00
|
|
|
if options.forward_class_messages:
|
2012-11-02 21:58:18 +01:00
|
|
|
message["forged"] = "yes"
|
|
|
|
message['type'] = zeph['type']
|
|
|
|
message['time'] = zeph['time']
|
|
|
|
message['sender'] = to_humbug_username(zeph['sender'])
|
2012-10-11 00:01:39 +02:00
|
|
|
if "subject" in zeph:
|
2012-11-03 01:55:07 +01:00
|
|
|
# Truncate the subject to the current limit in Humbug. No
|
|
|
|
# need to do this for stream names, since we're only
|
|
|
|
# subscribed to valid stream names.
|
2012-11-02 21:58:18 +01:00
|
|
|
message["subject"] = zeph["subject"][:60]
|
2012-10-16 20:57:42 +02:00
|
|
|
if zeph['type'] == 'stream':
|
|
|
|
# Forward messages sent to -c foo -i bar to stream bar subject "instance"
|
|
|
|
if zeph["stream"] == "message":
|
2012-11-14 23:21:46 +01:00
|
|
|
message['to'] = zeph['subject'].lower()
|
2012-11-01 22:31:21 +01:00
|
|
|
message['subject'] = "instance %s" % (zeph['subject'],)
|
2012-10-16 20:57:42 +02:00
|
|
|
elif zeph["stream"] == "tabbott-test5":
|
2012-11-14 23:21:46 +01:00
|
|
|
message['to'] = zeph['subject'].lower()
|
2012-11-01 22:31:21 +01:00
|
|
|
message['subject'] = "test instance %s" % (zeph['subject'],)
|
2012-11-02 21:58:18 +01:00
|
|
|
else:
|
2012-11-14 23:21:46 +01:00
|
|
|
message["to"] = zeph["stream"]
|
2012-11-02 21:58:18 +01:00
|
|
|
else:
|
2012-11-14 23:21:46 +01:00
|
|
|
message["to"] = zeph["recipient"]
|
2012-11-02 21:58:18 +01:00
|
|
|
message['content'] = unwrap_lines(zeph['content'])
|
2012-09-26 21:23:52 +02:00
|
|
|
|
2012-11-14 00:02:35 +01:00
|
|
|
if options.test_mode and options.site == DEFAULT_SITE:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.debug("Message is: %s" % (str(message),))
|
2012-11-08 19:49:03 +01:00
|
|
|
return {'result': "success"}
|
|
|
|
|
2012-11-02 21:58:18 +01:00
|
|
|
return humbug_client.send_message(message)
|
2012-09-06 22:10:48 +02:00
|
|
|
|
2012-11-12 17:25:56 +01:00
|
|
|
def send_error_humbug(error_msg):
|
|
|
|
humbug = {"type": "private",
|
|
|
|
"sender": options.user + "@mit.edu",
|
2012-11-14 23:21:46 +01:00
|
|
|
"to": options.user + "@mit.edu",
|
2012-11-12 17:25:56 +01:00
|
|
|
"content": error_msg,
|
|
|
|
}
|
|
|
|
humbug_client.send_message(humbug)
|
|
|
|
|
2012-10-30 02:32:59 +01:00
|
|
|
current_zephyr_subs = set()
|
2012-11-07 20:32:02 +01:00
|
|
|
def zephyr_bulk_subscribe(subs):
|
2012-11-07 17:44:45 +01:00
|
|
|
try:
|
2012-11-07 20:32:02 +01:00
|
|
|
zephyr._z.subAll(subs)
|
2012-11-07 17:44:45 +01:00
|
|
|
except IOError:
|
|
|
|
# Since we haven't added the subscription to
|
|
|
|
# current_zephyr_subs yet, we can just return (so that we'll
|
|
|
|
# continue processing normal messages) and we'll end up
|
|
|
|
# retrying the next time the bot checks its subscriptions are
|
|
|
|
# up to date.
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Error subscribing to streams (will retry automatically):")
|
2012-11-13 18:47:59 +01:00
|
|
|
logging.debug("Streams were: %s" % ((cls for cls, instance, recipient in subs),))
|
2012-11-07 17:44:45 +01:00
|
|
|
return
|
2012-11-07 20:32:02 +01:00
|
|
|
for (cls, instance, recipient) in subs:
|
|
|
|
current_zephyr_subs.add(cls)
|
2012-10-11 20:39:52 +02:00
|
|
|
|
|
|
|
def update_subscriptions_from_humbug():
|
|
|
|
try:
|
|
|
|
res = humbug_client.get_public_streams()
|
2012-11-14 22:07:48 +01:00
|
|
|
if res.get("result") == "success":
|
|
|
|
streams = res["streams"]
|
|
|
|
else:
|
|
|
|
logger.error("Error getting public streams:\n%s" % res)
|
|
|
|
return
|
2012-10-11 20:39:52 +02:00
|
|
|
except:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Error getting public streams:")
|
2012-10-11 20:39:52 +02:00
|
|
|
return
|
2012-11-07 20:32:02 +01:00
|
|
|
streams_to_subscribe = []
|
2012-10-11 20:39:52 +02:00
|
|
|
for stream in streams:
|
2012-11-07 20:32:02 +01:00
|
|
|
if stream in current_zephyr_subs:
|
|
|
|
continue
|
2012-11-07 22:36:54 +01:00
|
|
|
streams_to_subscribe.append((stream.encode("utf-8"), "*", "*"))
|
2012-11-14 17:26:16 +01:00
|
|
|
if len(streams_to_subscribe) > 0:
|
|
|
|
zephyr_bulk_subscribe(streams_to_subscribe)
|
2012-09-07 17:45:09 +02:00
|
|
|
|
2012-10-12 20:51:57 +02:00
|
|
|
def maybe_restart_mirroring_script():
|
2012-11-07 21:37:46 +01:00
|
|
|
if os.stat(os.path.join(options.root_path, "stamps", "restart_stamp")).st_mtime > start_time or \
|
2012-10-29 19:34:24 +01:00
|
|
|
((options.user == "tabbott" or options.user == "tabbott/extra") and
|
2012-11-07 21:37:46 +01:00
|
|
|
os.stat(os.path.join(options.root_path, "stamps", "tabbott_stamp")).st_mtime > start_time):
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.warning("")
|
|
|
|
logger.warning("zephyr mirroring script has been updated; restarting...")
|
2012-11-19 17:46:05 +01:00
|
|
|
try:
|
|
|
|
os.kill(child_pid, signal.SIGTERM)
|
|
|
|
except OSError:
|
|
|
|
# We don't care if the child process no longer exists, so just print the error
|
|
|
|
logging.exception("")
|
2012-10-12 21:13:14 +02:00
|
|
|
while True:
|
|
|
|
try:
|
2012-11-07 21:37:46 +01:00
|
|
|
os.execvp(os.path.join(options.root_path, "user_root", "zephyr_mirror.py"), sys.argv)
|
2012-10-12 21:13:14 +02:00
|
|
|
except:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Error restarting mirroring script; trying again... Traceback:")
|
2012-11-05 22:44:04 +01:00
|
|
|
time.sleep(1)
|
2012-10-12 20:51:57 +02:00
|
|
|
|
2012-09-24 20:29:33 +02:00
|
|
|
def process_loop(log):
|
2012-10-11 20:39:52 +02:00
|
|
|
sleep_count = 0
|
|
|
|
sleep_time = 0.1
|
2012-09-13 02:29:26 +02:00
|
|
|
while True:
|
2012-10-11 20:39:52 +02:00
|
|
|
notice = zephyr.receive(block=False)
|
2012-10-12 20:51:28 +02:00
|
|
|
if notice is not None:
|
|
|
|
try:
|
|
|
|
process_notice(notice, log)
|
2012-11-14 22:02:56 +01:00
|
|
|
except Exception:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Error relaying zephyr:")
|
2012-10-12 20:51:28 +02:00
|
|
|
time.sleep(2)
|
|
|
|
|
2012-10-12 20:51:57 +02:00
|
|
|
maybe_restart_mirroring_script()
|
|
|
|
|
2012-10-12 20:51:28 +02:00
|
|
|
time.sleep(sleep_time)
|
|
|
|
sleep_count += sleep_time
|
|
|
|
if sleep_count > 15:
|
|
|
|
sleep_count = 0
|
|
|
|
if options.forward_class_messages:
|
|
|
|
# Ask the Humbug server about any new classes to subscribe to
|
|
|
|
update_subscriptions_from_humbug()
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-11-02 22:16:19 +01:00
|
|
|
def parse_zephyr_body(zephyr_data):
|
2012-10-19 19:13:52 +02:00
|
|
|
try:
|
2012-11-02 22:16:19 +01:00
|
|
|
(zsig, body) = zephyr_data.split("\x00", 1)
|
2012-10-19 19:13:52 +02:00
|
|
|
except ValueError:
|
2012-11-02 22:16:19 +01:00
|
|
|
(zsig, body) = ("", zephyr_data)
|
|
|
|
return (zsig, body)
|
|
|
|
|
|
|
|
def process_notice(notice, log):
|
|
|
|
(zsig, body) = parse_zephyr_body(notice.message)
|
2012-10-12 20:39:47 +02:00
|
|
|
is_personal = False
|
|
|
|
is_huddle = False
|
|
|
|
|
|
|
|
if notice.opcode == "PING":
|
|
|
|
# skip PING messages
|
|
|
|
return
|
|
|
|
|
2012-11-02 22:16:31 +01:00
|
|
|
if zsig.endswith("@(@color(blue))"):
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.debug("Skipping message we got from Humbug!")
|
2012-11-02 22:16:31 +01:00
|
|
|
return
|
2012-10-12 20:39:47 +02:00
|
|
|
|
2012-10-16 20:39:53 +02:00
|
|
|
zephyr_class = notice.cls.lower()
|
2012-10-12 20:39:47 +02:00
|
|
|
|
2012-11-02 21:48:39 +01:00
|
|
|
if (zephyr_class == "message" and notice.recipient != ""):
|
2012-10-12 20:39:47 +02:00
|
|
|
is_personal = True
|
|
|
|
if body.startswith("CC:"):
|
|
|
|
is_huddle = True
|
|
|
|
# Map "CC: sipbtest espuser" => "starnine@mit.edu,espuser@mit.edu"
|
2012-11-07 17:53:58 +01:00
|
|
|
huddle_recipients = [to_humbug_username(x.strip()) for x in
|
|
|
|
body.split("\n")[0][4:].split()]
|
|
|
|
if notice.sender not in huddle_recipients:
|
|
|
|
huddle_recipients.append(to_humbug_username(notice.sender))
|
2012-11-02 22:06:59 +01:00
|
|
|
body = body.split("\n", 1)[1]
|
|
|
|
if (zephyr_class == "mail" and notice.instance.lower() == "inbox"):
|
2012-10-12 20:39:47 +02:00
|
|
|
is_personal = True
|
|
|
|
|
|
|
|
# Drop messages not to the listed subscriptions
|
2012-10-16 20:39:53 +02:00
|
|
|
if (zephyr_class not in current_zephyr_subs) and not \
|
2012-10-12 20:39:47 +02:00
|
|
|
(is_personal and options.forward_personals):
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.debug("Skipping ... %s/%s/%s" %
|
|
|
|
(zephyr_class, notice.instance, is_personal))
|
2012-10-12 20:39:47 +02:00
|
|
|
return
|
|
|
|
|
2012-11-02 22:06:59 +01:00
|
|
|
zeph = { 'time' : str(notice.time),
|
|
|
|
'sender' : notice.sender,
|
|
|
|
'zsig' : zsig, # logged here but not used by app
|
|
|
|
'content' : body }
|
2012-10-12 20:39:47 +02:00
|
|
|
if is_huddle:
|
2012-11-08 00:38:21 +01:00
|
|
|
zeph['type'] = 'private'
|
2012-11-02 22:06:59 +01:00
|
|
|
zeph['recipient'] = huddle_recipients
|
2012-10-12 20:39:47 +02:00
|
|
|
elif is_personal:
|
2012-11-08 00:38:21 +01:00
|
|
|
zeph['type'] = 'private'
|
2012-11-02 22:06:59 +01:00
|
|
|
zeph['recipient'] = to_humbug_username(notice.recipient)
|
2012-10-12 20:39:47 +02:00
|
|
|
else:
|
2012-11-02 22:06:59 +01:00
|
|
|
zeph['type'] = 'stream'
|
|
|
|
zeph['stream'] = zephyr_class
|
2012-11-09 22:36:57 +01:00
|
|
|
if notice.instance.strip() != "":
|
2012-11-02 22:07:20 +01:00
|
|
|
zeph['subject'] = notice.instance
|
2012-11-02 22:06:59 +01:00
|
|
|
else:
|
2012-11-09 22:36:57 +01:00
|
|
|
zeph["subject"] = '(instance "%s")' % (notice.instance,)
|
2012-10-12 20:39:47 +02:00
|
|
|
|
2012-10-17 17:20:52 +02:00
|
|
|
# Add instances in for instanced personals
|
2012-11-08 00:38:21 +01:00
|
|
|
if zeph['type'] == "private" and notice.instance.lower() != "personal":
|
2012-11-02 22:06:59 +01:00
|
|
|
zeph["content"] = "[-i %s]" % (notice.instance,) + "\n" + zeph["content"]
|
2012-10-17 17:20:52 +02:00
|
|
|
|
2012-10-29 23:53:36 +01:00
|
|
|
zeph = decode_unicode_byte_strings(zeph)
|
2012-10-29 22:10:56 +01:00
|
|
|
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.info("Received a message on %s/%s from %s..." %
|
|
|
|
(zephyr_class, notice.instance, notice.sender))
|
2012-11-01 22:38:31 +01:00
|
|
|
if log is not None:
|
|
|
|
log.write(simplejson.dumps(zeph) + '\n')
|
|
|
|
log.flush()
|
2012-10-12 20:39:47 +02:00
|
|
|
|
2012-11-14 22:02:56 +01:00
|
|
|
if os.fork() == 0:
|
|
|
|
# Actually send the message in a child process, to avoid blocking.
|
|
|
|
res = send_humbug(zeph)
|
|
|
|
if res.get("result") != "success":
|
|
|
|
logger.error("Error relaying zephyr:\n%s\n%s" % (zeph, res))
|
|
|
|
sys.exit(0)
|
2012-10-12 20:39:47 +02:00
|
|
|
|
2012-10-29 23:53:36 +01:00
|
|
|
def decode_unicode_byte_strings(zeph):
|
|
|
|
for field in zeph.keys():
|
|
|
|
if isinstance(zeph[field], str):
|
|
|
|
try:
|
|
|
|
decoded = zeph[field].decode("utf-8")
|
|
|
|
except:
|
|
|
|
decoded = zeph[field].decode("iso-8859-1")
|
|
|
|
zeph[field] = decoded
|
|
|
|
return zeph
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-11-07 17:44:45 +01:00
|
|
|
def zephyr_subscribe_autoretry(sub):
|
|
|
|
while True:
|
|
|
|
try:
|
2012-11-07 20:55:30 +01:00
|
|
|
zephyr.Subscriptions().add(sub)
|
2012-11-07 17:44:45 +01:00
|
|
|
return
|
|
|
|
except IOError:
|
|
|
|
# Probably a SERVNAK from the zephyr server, but print the
|
|
|
|
# traceback just in case it's something else
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Error subscribing to personals (retrying). Traceback:")
|
2012-11-07 17:44:45 +01:00
|
|
|
time.sleep(1)
|
|
|
|
|
2012-09-24 20:29:33 +02:00
|
|
|
def zephyr_to_humbug(options):
|
|
|
|
if options.forward_class_messages:
|
2012-10-15 19:13:57 +02:00
|
|
|
update_subscriptions_from_humbug()
|
2012-09-24 20:29:33 +02:00
|
|
|
if options.forward_personals:
|
2012-11-07 17:44:45 +01:00
|
|
|
# Subscribe to personals; we really can't operate without
|
|
|
|
# those subscriptions, so just retry until it works.
|
|
|
|
zephyr_subscribe_autoretry(("message", "*", "%me%"))
|
2012-10-12 19:40:57 +02:00
|
|
|
if subscribed_to_mail_messages():
|
2012-11-07 17:44:45 +01:00
|
|
|
zephyr_subscribe_autoretry(("mail", "inbox", "%me%"))
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-11-07 20:11:33 +01:00
|
|
|
if options.resend_log_path is not None:
|
|
|
|
with open(options.resend_log_path, 'r') as log:
|
2012-09-26 21:23:52 +02:00
|
|
|
for ln in log:
|
|
|
|
try:
|
2012-09-24 20:29:33 +02:00
|
|
|
zeph = simplejson.loads(ln)
|
2012-10-29 22:10:56 +01:00
|
|
|
# New messages added to the log shouldn't have any
|
|
|
|
# elements of type str (they should already all be
|
|
|
|
# unicode), but older messages in the log are
|
|
|
|
# still of type str, so convert them before we
|
|
|
|
# send the message
|
2012-10-29 23:53:36 +01:00
|
|
|
zeph = decode_unicode_byte_strings(zeph)
|
|
|
|
# Handle importing older zephyrs in the logs
|
|
|
|
# where it isn't called a "stream" yet
|
|
|
|
if "class" in zeph:
|
|
|
|
zeph["stream"] = zeph["class"]
|
|
|
|
if "instance" in zeph:
|
|
|
|
zeph["subject"] = zeph["instance"]
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.info("sending saved message to %s from %s..." %
|
|
|
|
(zeph.get('stream', zeph.get('recipient')),
|
|
|
|
zeph['sender']))
|
2012-09-26 16:43:53 +02:00
|
|
|
send_humbug(zeph)
|
2012-09-26 21:23:52 +02:00
|
|
|
except:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Could not send saved zephyr:")
|
2012-09-26 21:23:52 +02:00
|
|
|
time.sleep(2)
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.info("Starting receive loop.")
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-11-07 20:11:33 +01:00
|
|
|
if options.log_path is not None:
|
2012-11-01 22:38:31 +01:00
|
|
|
with open(options.log_path, 'a') as log:
|
|
|
|
process_loop(log)
|
2012-09-28 23:37:10 +02:00
|
|
|
else:
|
2012-11-01 22:38:31 +01:00
|
|
|
process_loop(None)
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-11-12 17:25:56 +01:00
|
|
|
def send_zephyr(zwrite_args, content):
|
|
|
|
p = subprocess.Popen(zwrite_args, stdin=subprocess.PIPE,
|
|
|
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
|
|
stdout, stderr = p.communicate(input=content.encode("utf-8"))
|
|
|
|
if p.returncode:
|
|
|
|
print "zwrite command '%s' failed with return code %d:" % (
|
|
|
|
" ".join(zwrite_args), p.returncode,)
|
2012-11-16 19:07:54 +01:00
|
|
|
if stdout:
|
|
|
|
print stdout
|
|
|
|
elif stderr:
|
|
|
|
print "zwrite command '%s' printed the following warning:" % (
|
|
|
|
" ".join(zwrite_args),)
|
|
|
|
if stderr:
|
2012-11-12 17:25:56 +01:00
|
|
|
print stderr
|
2012-11-16 19:07:54 +01:00
|
|
|
return (p.returncode, stderr)
|
2012-11-12 17:25:56 +01:00
|
|
|
|
|
|
|
def send_authed_zephyr(zwrite_args, content):
|
|
|
|
return send_zephyr(zwrite_args, content)
|
|
|
|
|
|
|
|
def send_unauthed_zephyr(zwrite_args, content):
|
|
|
|
return send_zephyr(zwrite_args + ["-d"], content)
|
|
|
|
|
2012-10-02 21:47:59 +02:00
|
|
|
def forward_to_zephyr(message):
|
2012-11-13 22:30:39 +01:00
|
|
|
zsig = u"%s@(@color(blue))" % (zsig_fullname,)
|
2012-09-28 21:29:44 +02:00
|
|
|
if ' dot ' in zsig:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.error("Error computing zsig for %s!" % (message["sender_email"],))
|
2012-09-28 21:29:44 +02:00
|
|
|
return
|
2012-10-02 21:20:09 +02:00
|
|
|
|
2012-10-02 20:18:53 +02:00
|
|
|
wrapped_content = "\n".join("\n".join(textwrap.wrap(line))
|
2012-10-11 19:34:30 +02:00
|
|
|
for line in message["content"].split("\n"))
|
2012-10-02 21:20:09 +02:00
|
|
|
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.info("Forwarding message from %s" % (message["sender_email"],))
|
2012-10-10 22:57:21 +02:00
|
|
|
if message['type'] == "stream":
|
2012-10-16 20:57:42 +02:00
|
|
|
zephyr_class = message["display_recipient"]
|
|
|
|
instance = message["subject"]
|
2012-11-09 22:36:57 +01:00
|
|
|
|
|
|
|
match_whitespace_instance = re.match(r'^\(instance "(\s*)"\)$', instance)
|
|
|
|
if match_whitespace_instance:
|
|
|
|
# Forward messages sent to '(instance "WHITESPACE")' back to the
|
|
|
|
# appropriate WHITESPACE instance for bidirectional mirroring
|
|
|
|
instance = match_whitespace_instance.group(1)
|
|
|
|
elif (instance == "instance %s" % (zephyr_class,) or
|
2012-10-16 20:57:42 +02:00
|
|
|
instance == "test instance %s" % (zephyr_class,)):
|
|
|
|
# Forward messages to e.g. -c -i white-magic back from the
|
|
|
|
# place we forward them to
|
|
|
|
if instance.startswith("test"):
|
|
|
|
instance = zephyr_class
|
|
|
|
zephyr_class = "tabbott-test5"
|
|
|
|
else:
|
|
|
|
instance = zephyr_class
|
|
|
|
zephyr_class = "message"
|
2012-11-02 16:30:22 +01:00
|
|
|
zwrite_args = ["zwrite", "-s", zsig, "-c", zephyr_class, "-i", instance]
|
2012-09-26 16:44:42 +02:00
|
|
|
elif message['type'] == "personal":
|
2012-11-02 20:46:50 +01:00
|
|
|
recipient = to_zephyr_username(message["display_recipient"]["email"])
|
2012-11-02 16:30:22 +01:00
|
|
|
zwrite_args = ["zwrite", "-s", zsig, recipient]
|
2012-09-26 16:44:42 +02:00
|
|
|
elif message['type'] == "huddle":
|
2012-11-02 16:30:22 +01:00
|
|
|
zwrite_args = ["zwrite", "-s", zsig, "-C"]
|
2012-11-02 20:46:50 +01:00
|
|
|
zwrite_args.extend([to_zephyr_username(user["email"]).replace("@ATHENA.MIT.EDU", "")
|
2012-11-02 16:30:22 +01:00
|
|
|
for user in message["display_recipient"]])
|
|
|
|
|
2012-11-08 19:49:03 +01:00
|
|
|
if options.test_mode:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.debug("Would have forwarded: %s\n%s" %
|
|
|
|
(zwrite_args, wrapped_content.encode("utf-8")))
|
2012-11-08 19:49:03 +01:00
|
|
|
return
|
|
|
|
|
2012-11-16 19:07:54 +01:00
|
|
|
heading = "Hi there! This is an automated message from Humbug."
|
|
|
|
support_closing = """If you have any questions, please be in touch through the \
|
|
|
|
Feedback tab or at support@humbughq.com."""
|
|
|
|
|
|
|
|
(code, stderr) = send_authed_zephyr(zwrite_args, wrapped_content)
|
|
|
|
if code == 0 and stderr == "":
|
|
|
|
return
|
|
|
|
elif code == 0:
|
|
|
|
return send_error_humbug("""%s
|
|
|
|
|
|
|
|
Your last message was successfully mirrored to zephyr, but zwrite \
|
|
|
|
returned the following warning:
|
2012-11-12 17:25:56 +01:00
|
|
|
|
|
|
|
%s
|
|
|
|
|
2012-11-16 19:07:54 +01:00
|
|
|
%s""" % (heading, stderr, support_closing))
|
|
|
|
elif code != 0 and (stderr.startswith("zwrite: Ticket expired while sending notice to ") or
|
|
|
|
stderr.startswith("zwrite: No credentials cache found while sending notice to ")):
|
|
|
|
# Retry sending the message unauthenticated; if that works,
|
|
|
|
# just notify the user that they need to renew their tickets
|
|
|
|
(code, stderr) = send_unauthed_zephyr(zwrite_args, wrapped_content)
|
|
|
|
if code == 0:
|
|
|
|
return send_error_humbug("""%s
|
2012-11-12 17:25:56 +01:00
|
|
|
|
|
|
|
Your last message was forwarded from Humbug to Zephyr unauthenticated, \
|
|
|
|
because your Kerberos tickets have expired. It was sent successfully, \
|
|
|
|
but please renew your Kerberos tickets in the screen session where you \
|
|
|
|
are running the Humbug-Zephyr mirroring bot, so we can send \
|
2012-11-16 19:07:54 +01:00
|
|
|
authenticated Zephyr messages for you again.
|
|
|
|
|
|
|
|
%s""" % (heading, support_closing))
|
|
|
|
|
|
|
|
# zwrite failed and it wasn't because of expired tickets: This is
|
|
|
|
# probably because the recipient isn't subscribed to personals,
|
|
|
|
# but regardless, we should just notify the user.
|
|
|
|
return send_error_humbug("""%s
|
|
|
|
|
|
|
|
Your Humbug-Zephyr mirror bot was unable to forward that last message \
|
|
|
|
from Humbug to Zephyr. That means that while Humbug users (like you) \
|
|
|
|
received it, Zephyr users did not. The error message from zwrite was:
|
|
|
|
|
|
|
|
%s
|
|
|
|
|
|
|
|
%s""" % (heading, stderr, support_closing))
|
2012-09-26 16:44:42 +02:00
|
|
|
|
2012-10-02 21:47:59 +02:00
|
|
|
def maybe_forward_to_zephyr(message):
|
2012-11-02 23:13:48 +01:00
|
|
|
if (message["sender_email"] == options.user + "@mit.edu"):
|
|
|
|
if not ((message["type"] == "stream") or
|
|
|
|
(message["type"] == "personal" and
|
|
|
|
message["display_recipient"]["email"].lower().endswith("mit.edu")) or
|
|
|
|
(message["type"] == "huddle" and
|
|
|
|
False not in [u["email"].lower().endswith("mit.edu") for u in
|
|
|
|
message["display_recipient"]])):
|
|
|
|
# Don't try forward personals/huddles with non-MIT users
|
|
|
|
# to MIT Zephyr.
|
|
|
|
return
|
2012-10-12 19:53:29 +02:00
|
|
|
timestamp_now = datetime.datetime.now().strftime("%s")
|
|
|
|
if float(message["timestamp"]) < float(timestamp_now) - 15:
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.warning("Skipping out of order message: %s < %s" %
|
|
|
|
(message["timestamp"], timestamp_now))
|
2012-10-02 21:47:59 +02:00
|
|
|
return
|
2012-11-02 18:53:29 +01:00
|
|
|
try:
|
|
|
|
forward_to_zephyr(message)
|
|
|
|
except:
|
|
|
|
# Don't let an exception forwarding one message crash the
|
|
|
|
# whole process
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.exception("Error forwarding message:")
|
2012-10-02 21:47:59 +02:00
|
|
|
|
2012-09-24 20:29:33 +02:00
|
|
|
def humbug_to_zephyr(options):
|
|
|
|
# Sync messages from zephyr to humbug
|
2012-11-09 23:23:42 +01:00
|
|
|
logger.info("Starting syncing messages.")
|
2012-10-02 21:47:59 +02:00
|
|
|
humbug_client.call_on_each_message(maybe_forward_to_zephyr,
|
2012-10-19 21:37:37 +02:00
|
|
|
options={"mirror": 'zephyr_mirror'})
|
2012-09-24 20:29:33 +02:00
|
|
|
|
2012-10-12 19:40:57 +02:00
|
|
|
def subscribed_to_mail_messages():
|
2012-11-06 19:58:22 +01:00
|
|
|
# In case we have lost our AFS tokens and those won't be able to
|
|
|
|
# parse the Zephyr subs file, first try reading in result of this
|
|
|
|
# query from the environment so we can avoid the filesystem read.
|
|
|
|
stored_result = os.environ.get("HUMBUG_FORWARD_MAIL_ZEPHYRS")
|
|
|
|
if stored_result is not None:
|
|
|
|
return stored_result == "True"
|
2012-10-12 19:40:57 +02:00
|
|
|
for (cls, instance, recipient) in parse_zephyr_subs(verbose=False):
|
|
|
|
if (cls.lower() == "mail" and instance.lower() == "inbox"):
|
2012-11-06 19:58:22 +01:00
|
|
|
os.environ["HUMBUG_FORWARD_MAIL_ZEPHYRS"] = "True"
|
2012-10-12 19:40:57 +02:00
|
|
|
return True
|
2012-11-06 19:58:22 +01:00
|
|
|
os.environ["HUMBUG_FORWARD_MAIL_ZEPHYRS"] = "False"
|
2012-10-12 19:40:57 +02:00
|
|
|
return False
|
|
|
|
|
2012-10-29 17:51:44 +01:00
|
|
|
def add_humbug_subscriptions(verbose):
|
2012-10-12 19:40:57 +02:00
|
|
|
zephyr_subscriptions = set()
|
2012-10-29 17:51:44 +01:00
|
|
|
skipped = set()
|
|
|
|
for (cls, instance, recipient) in parse_zephyr_subs(verbose=verbose):
|
2012-10-29 23:09:51 +01:00
|
|
|
if cls == "message":
|
|
|
|
if recipient != "*":
|
|
|
|
# We already have a (message, *, you) subscription, so
|
|
|
|
# these are redundant
|
|
|
|
continue
|
|
|
|
# We don't support subscribing to (message, *)
|
2012-10-16 20:57:42 +02:00
|
|
|
if instance == "*":
|
2012-10-29 23:09:51 +01:00
|
|
|
if recipient == "*":
|
|
|
|
skipped.add((cls, instance, recipient, "subscribing to all of class message is not supported."))
|
2012-10-16 20:57:42 +02:00
|
|
|
continue
|
|
|
|
# If you're on -i white-magic on zephyr, get on stream white-magic on humbug
|
2012-10-29 17:51:44 +01:00
|
|
|
# instead of subscribing to stream "message" on humbug
|
2012-10-16 20:57:42 +02:00
|
|
|
zephyr_subscriptions.add(instance)
|
|
|
|
continue
|
2012-10-29 23:09:51 +01:00
|
|
|
elif cls == "mail" and instance == "inbox":
|
2012-11-02 22:22:21 +01:00
|
|
|
# We forward mail zephyrs, so no need to print a warning.
|
|
|
|
continue
|
|
|
|
elif len(cls) > 30:
|
|
|
|
skipped.add((cls, instance, recipient, "Class longer than 30 characters"))
|
2012-10-29 23:09:51 +01:00
|
|
|
continue
|
|
|
|
elif instance != "*":
|
|
|
|
skipped.add((cls, instance, recipient, "Unsupported non-* instance"))
|
2012-10-29 17:51:44 +01:00
|
|
|
continue
|
2012-10-29 23:09:51 +01:00
|
|
|
elif recipient != "*":
|
|
|
|
skipped.add((cls, instance, recipient, "Unsupported non-* recipient."))
|
|
|
|
continue
|
2012-10-12 19:40:57 +02:00
|
|
|
zephyr_subscriptions.add(cls)
|
2012-10-29 17:51:44 +01:00
|
|
|
|
2012-10-12 19:40:57 +02:00
|
|
|
if len(zephyr_subscriptions) != 0:
|
2012-11-16 19:40:03 +01:00
|
|
|
res = humbug_client.add_subscriptions(list(zephyr_subscriptions))
|
2012-10-29 23:09:51 +01:00
|
|
|
if res.get("result") != "success":
|
|
|
|
print "Error subscribing to streams:"
|
|
|
|
print res["msg"]
|
|
|
|
return
|
|
|
|
|
2012-10-29 17:51:44 +01:00
|
|
|
already = res.get("already_subscribed")
|
|
|
|
new = res.get("subscribed")
|
|
|
|
if verbose:
|
|
|
|
if already is not None and len(already) > 0:
|
|
|
|
print
|
|
|
|
print "Already subscribed to:", ", ".join(already)
|
|
|
|
if new is not None and len(new) > 0:
|
|
|
|
print
|
|
|
|
print "Successfully subscribed to:", ", ".join(new)
|
|
|
|
|
|
|
|
if len(skipped) > 0:
|
|
|
|
if verbose:
|
|
|
|
print
|
|
|
|
print "\n".join(textwrap.wrap("""\
|
|
|
|
You have some lines in ~/.zephyr.subs that could not be
|
|
|
|
synced to your Humbug subscriptions because they do not
|
|
|
|
use "*" as both the instance and recipient and not one of
|
|
|
|
the special cases (e.g. personals and mail zephyrs) that
|
|
|
|
Humbug has a mechanism for forwarding. Humbug does not
|
|
|
|
allow subscribing to only some subjects on a Humbug
|
|
|
|
stream, so this tool has not created a corresponding
|
|
|
|
Humbug subscription to these lines in ~/.zephyr.subs:
|
|
|
|
"""))
|
|
|
|
print
|
|
|
|
|
2012-10-29 23:09:51 +01:00
|
|
|
for (cls, instance, recipient, reason) in skipped:
|
2012-10-29 17:51:44 +01:00
|
|
|
if verbose:
|
2012-10-29 23:09:51 +01:00
|
|
|
if reason != "":
|
|
|
|
print " [%s,%s,%s] (%s)" % (cls, instance, recipient, reason)
|
|
|
|
else:
|
|
|
|
print " [%s,%s,%s]" % (cls, instance, recipient, reason)
|
2012-10-29 17:51:44 +01:00
|
|
|
if len(skipped) > 0:
|
|
|
|
if verbose:
|
|
|
|
print
|
|
|
|
print "\n".join(textwrap.wrap("""\
|
|
|
|
If you wish to be subscribed to any Humbug streams related
|
|
|
|
to these .zephyrs.subs lines, please do so via the Humbug
|
|
|
|
web interface.
|
|
|
|
"""))
|
|
|
|
print
|
2012-11-15 16:40:10 +01:00
|
|
|
if verbose:
|
|
|
|
print
|
|
|
|
print "IMPORTANT: Please reload the Humbug app for these changes to take effect."
|
2012-10-12 19:40:57 +02:00
|
|
|
|
2012-10-29 23:09:51 +01:00
|
|
|
def valid_stream_name(name):
|
2012-11-07 21:42:32 +01:00
|
|
|
return name != ""
|
2012-10-29 23:09:51 +01:00
|
|
|
|
2012-10-12 19:40:57 +02:00
|
|
|
def parse_zephyr_subs(verbose=False):
|
2012-10-11 22:20:38 +02:00
|
|
|
zephyr_subscriptions = set()
|
|
|
|
subs_file = os.path.join(os.environ["HOME"], ".zephyr.subs")
|
|
|
|
if not os.path.exists(subs_file):
|
2012-10-12 19:40:57 +02:00
|
|
|
if verbose:
|
2012-10-29 23:09:51 +01:00
|
|
|
print >>sys.stderr, "Couldn't find ~/.zephyr.subs!"
|
2012-10-19 00:09:47 +02:00
|
|
|
return []
|
2012-10-11 22:20:38 +02:00
|
|
|
|
|
|
|
for line in file(subs_file, "r").readlines():
|
|
|
|
line = line.strip()
|
|
|
|
if len(line) == 0:
|
|
|
|
continue
|
|
|
|
try:
|
|
|
|
(cls, instance, recipient) = line.split(",")
|
2012-10-29 23:09:51 +01:00
|
|
|
cls = cls.replace("%me%", options.user)
|
|
|
|
instance = instance.replace("%me%", options.user)
|
|
|
|
recipient = recipient.replace("%me%", options.user)
|
|
|
|
if not valid_stream_name(cls):
|
|
|
|
if verbose:
|
|
|
|
print >>sys.stderr, "Skipping subscription to unsupported class name: [%s]" % (line,)
|
|
|
|
continue
|
2012-10-11 22:20:38 +02:00
|
|
|
except:
|
2012-10-12 19:40:57 +02:00
|
|
|
if verbose:
|
|
|
|
print >>sys.stderr, "Couldn't parse ~/.zephyr.subs line: [%s]" % (line,)
|
|
|
|
continue
|
2012-10-16 20:57:42 +02:00
|
|
|
zephyr_subscriptions.add((cls.strip(), instance.strip(), recipient.strip()))
|
2012-10-12 19:40:57 +02:00
|
|
|
return zephyr_subscriptions
|
2012-10-11 22:20:38 +02:00
|
|
|
|
2012-11-13 22:30:39 +01:00
|
|
|
def fetch_fullname(username):
|
|
|
|
try:
|
|
|
|
proc = subprocess.Popen(['hesinfo', username, 'passwd'],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE)
|
|
|
|
out, _err_unused = proc.communicate()
|
|
|
|
if proc.returncode == 0:
|
|
|
|
return out.split(':')[4].split(',')[0]
|
|
|
|
except:
|
|
|
|
logger.exception("Error getting fullname for %s:" % (username,))
|
|
|
|
|
|
|
|
return username
|
|
|
|
|
2012-11-09 23:23:42 +01:00
|
|
|
def configure_logger(direction_name):
|
|
|
|
if options.forward_class_messages:
|
|
|
|
if options.test_mode:
|
|
|
|
log_file = "/home/humbug/test-mirror-log"
|
|
|
|
else:
|
|
|
|
log_file = "/home/humbug/mirror-log"
|
|
|
|
else:
|
|
|
|
log_file = "/tmp/humbug-log." + options.user
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
log_format = "%(asctime)s " + direction_name + ": %(message)s"
|
|
|
|
formatter = logging.Formatter(log_format)
|
|
|
|
logging.basicConfig(format=log_format)
|
|
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
file_handler = logging.FileHandler(log_file)
|
|
|
|
file_handler.setFormatter(formatter)
|
|
|
|
logger.addHandler(file_handler)
|
|
|
|
return logger
|
|
|
|
|
2012-11-19 18:30:15 +01:00
|
|
|
def parse_args():
|
2012-11-06 16:39:37 +01:00
|
|
|
parser = optparse.OptionParser()
|
|
|
|
parser.add_option('--forward-class-messages',
|
|
|
|
dest='forward_class_messages',
|
|
|
|
default=False,
|
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store_true')
|
|
|
|
parser.add_option('--resend-log',
|
2012-11-07 20:11:33 +01:00
|
|
|
dest='resend_log_path',
|
|
|
|
default=None,
|
2012-11-06 16:39:37 +01:00
|
|
|
help=optparse.SUPPRESS_HELP,
|
2012-11-07 20:11:33 +01:00
|
|
|
action='store')
|
2012-11-06 16:39:37 +01:00
|
|
|
parser.add_option('--enable-log',
|
2012-11-07 20:11:33 +01:00
|
|
|
dest='log_path',
|
|
|
|
default=None,
|
2012-11-06 16:39:37 +01:00
|
|
|
help=optparse.SUPPRESS_HELP,
|
2012-11-07 20:11:33 +01:00
|
|
|
action='store')
|
2012-11-06 16:39:37 +01:00
|
|
|
parser.add_option('--no-forward-personals',
|
|
|
|
dest='forward_personals',
|
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
default=True,
|
|
|
|
action='store_false')
|
|
|
|
parser.add_option('--forward-from-humbug',
|
|
|
|
dest='forward_from_humbug',
|
|
|
|
default=False,
|
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store_true')
|
|
|
|
parser.add_option('--verbose',
|
|
|
|
dest='verbose',
|
|
|
|
default=False,
|
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store_true')
|
|
|
|
parser.add_option('--sync-subscriptions',
|
|
|
|
dest='sync_subscriptions',
|
|
|
|
default=False,
|
|
|
|
action='store_true')
|
|
|
|
parser.add_option('--site',
|
|
|
|
dest='site',
|
2012-11-14 00:02:35 +01:00
|
|
|
default=DEFAULT_SITE,
|
2012-11-06 16:39:37 +01:00
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store')
|
|
|
|
parser.add_option('--user',
|
|
|
|
dest='user',
|
|
|
|
default=os.environ["USER"],
|
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store')
|
2012-11-07 20:08:04 +01:00
|
|
|
parser.add_option('--root-path',
|
|
|
|
dest='root_path',
|
2012-11-14 19:15:45 +01:00
|
|
|
default="/afs/athena.mit.edu/user/t/a/tabbott/for_friends",
|
2012-11-07 20:08:04 +01:00
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store')
|
2012-11-08 19:49:03 +01:00
|
|
|
parser.add_option('--test-mode',
|
|
|
|
dest='test_mode',
|
|
|
|
default=False,
|
|
|
|
help=optparse.SUPPRESS_HELP,
|
|
|
|
action='store_true')
|
2012-11-06 16:39:37 +01:00
|
|
|
parser.add_option('--api-key-file',
|
|
|
|
dest='api_key_file',
|
|
|
|
default=os.path.join(os.environ["HOME"], "Private", ".humbug-api-key"),
|
|
|
|
action='store')
|
2012-11-19 18:30:15 +01:00
|
|
|
return parser.parse_args()
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# Set the SIGCHLD handler back to SIG_DFL to prevent these errors
|
|
|
|
# when importing the "requests" module after being restarted using
|
|
|
|
# the restart_stamp functionality:
|
|
|
|
#
|
|
|
|
# close failed in file object destructor:
|
|
|
|
# IOError: [Errno 10] No child processes
|
|
|
|
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
|
|
|
|
|
|
|
|
(options, args) = parse_args()
|
2012-11-06 16:39:37 +01:00
|
|
|
|
2012-11-07 21:37:46 +01:00
|
|
|
sys.path[:0] = [options.root_path, os.path.join(options.root_path, "python-zephyr"),
|
|
|
|
os.path.join(options.root_path, "python-zephyr/build/lib.linux-x86_64-2.6/")]
|
2012-11-07 20:08:04 +01:00
|
|
|
|
2012-11-06 19:58:22 +01:00
|
|
|
# In case this is an automated restart of the mirroring script,
|
|
|
|
# and we have lost AFS tokens, first try reading the API key from
|
|
|
|
# the environment so that we can skip doing a filesystem read.
|
|
|
|
if os.environ.get("HUMBUG_API_KEY") is not None:
|
|
|
|
api_key = os.environ.get("HUMBUG_API_KEY")
|
|
|
|
else:
|
|
|
|
if not os.path.exists(options.api_key_file):
|
2012-11-07 20:21:17 +01:00
|
|
|
print "\n".join(textwrap.wrap("""\
|
|
|
|
Could not find API key file.
|
|
|
|
You need to either place your api key file at %s,
|
|
|
|
or specify the --api-key-file option.""" % (options.api_key_file,)))
|
2012-11-06 19:58:22 +01:00
|
|
|
sys.exit(1)
|
|
|
|
api_key = file(options.api_key_file).read().strip()
|
|
|
|
# Store the API key in the environment so that our children
|
|
|
|
# don't need to read it in
|
|
|
|
os.environ["HUMBUG_API_KEY"] = api_key
|
2012-11-06 16:39:37 +01:00
|
|
|
|
|
|
|
import api.common
|
|
|
|
humbug_client = api.common.HumbugAPI(email=options.user + "@mit.edu",
|
|
|
|
api_key=api_key,
|
|
|
|
verbose=True,
|
|
|
|
client="zephyr_mirror",
|
|
|
|
site=options.site)
|
|
|
|
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
if options.sync_subscriptions:
|
|
|
|
print "Syncing your ~/.zephyr.subs to your Humbug Subscriptions!"
|
|
|
|
add_humbug_subscriptions(True)
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
if options.forward_from_humbug:
|
|
|
|
print "This option is obsolete."
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
# First check that there are no other bots running
|
|
|
|
cmdline = " ".join(sys.argv)
|
2012-11-19 17:48:00 +01:00
|
|
|
bot_name = "zephyr_mirror.py"
|
2012-11-08 19:49:03 +01:00
|
|
|
if not options.test_mode:
|
|
|
|
proc = subprocess.Popen(['pgrep', '-U', os.environ["USER"], "-f", bot_name],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE)
|
|
|
|
out, _err_unused = proc.communicate()
|
|
|
|
for pid in out.split():
|
|
|
|
if int(pid.strip()) != os.getpid():
|
|
|
|
# Another copy of zephyr_mirror.py! Kill it.
|
|
|
|
print "Killing duplicate zephyr_mirror process %s" % (pid,)
|
2012-11-19 17:46:05 +01:00
|
|
|
try:
|
|
|
|
os.kill(int(pid), signal.SIGKILL)
|
|
|
|
except OSError:
|
|
|
|
# We don't care if the child process no longer exists, so just print the error
|
|
|
|
traceback.print_exc()
|
2012-11-06 16:39:37 +01:00
|
|
|
|
|
|
|
child_pid = os.fork()
|
|
|
|
if child_pid == 0:
|
|
|
|
# Run the humbug => zephyr mirror in the child
|
2012-11-09 23:23:42 +01:00
|
|
|
logger = configure_logger("humbug=>zephyr")
|
2012-11-13 22:30:39 +01:00
|
|
|
zsig_fullname = fetch_fullname(options.user)
|
2012-11-06 16:39:37 +01:00
|
|
|
humbug_to_zephyr(options)
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
import zephyr
|
2012-11-09 22:03:12 +01:00
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
# zephyr.init() tries to clear old subscriptions, and thus
|
|
|
|
# sometimes gets a SERVNAK from the server
|
|
|
|
zephyr.init()
|
|
|
|
break
|
|
|
|
except IOError:
|
|
|
|
traceback.print_exc()
|
|
|
|
time.sleep(1)
|
2012-11-09 23:23:42 +01:00
|
|
|
logger = configure_logger("zephyr=>humbug")
|
2012-11-14 22:02:56 +01:00
|
|
|
# Have the kernel reap children for when we fork off processes to send Humbugs
|
|
|
|
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
|
2012-11-06 16:39:37 +01:00
|
|
|
zephyr_to_humbug(options)
|