segment.io tracking

This commit is contained in:
Michael Gummelt
2015-04-14 14:25:33 -07:00
parent 216e00026e
commit a030c30110
3 changed files with 81 additions and 2 deletions

View File

@@ -28,8 +28,11 @@ to read about a specific subcommand.
import os
import subprocess
import sys
import logging
from subprocess import Popen, PIPE
import analytics
import dcoscli
import docopt
from dcos.api import constants, emitting, subcommand, util
@@ -54,6 +57,10 @@ def main():
emitter.publish(err)
return 1
# The requests package emits INFO logs. We want to exclude those,
# even if the user has selected --log-level=INFO.
logging.getLogger('requests').setLevel(logging.WARNING)
command = args['<command>']
if not command:
@@ -64,7 +71,43 @@ def main():
emitter.publish(err)
return 1
return subprocess.call([executable, command] + args['<args>'])
subproc = Popen([executable, command] + args['<args>'],
stderr=PIPE)
return wait_and_track(subproc)
WRITE_KEY = '51ybGTeFEFU1xo6u10XMDrr6kATFyRyh'
def wait_and_track(subproc):
# capture and print stderr
err = ''
while subproc.poll() is None:
err_buff = subproc.stderr.read()
sys.stderr.write(err_buff)
err += err_buff
exit_code = subproc.poll()
# segment.io analytics
analytics.write_key = WRITE_KEY
try:
# We don't have user id's right now, but segment.io requires
# them, so we use a constant (1)
analytics.track(1, 'dcos-cli', {
'cmd': ' '.join(sys.argv),
'exit_code': exit_code,
'err': err or None
})
analytics.flush()
except:
# ignore segment.io exceptions
pass
return exit_code
def _config_log_level_environ(log_level):

View File

@@ -67,6 +67,8 @@ setup(
'pkginfo',
'toml',
'virtualenv',
'analytics-python',
'requests[security]'
],
# If there are data files included in your packages that need to be

View File

@@ -1,10 +1,16 @@
import os
import mock
from mock import Mock
import analytics
from dcoscli.main import main
from dcos.api import constants, util
from common import exec_command
def test_default():
dcos_path = os.path.dirname(os.path.dirname(util.which('dcos')))
returncode, stdout, stderr = exec_command(['dcos'])
@@ -124,3 +130,31 @@ def test_invalid_log_level_flag():
b"values are ['debug', 'info', 'warning', 'error', "
b"'critical']\n")
assert stderr == b''
def test_analytics_no_err():
args = ['dcos']
with mock.patch('sys.argv', args):
analytics.track = Mock()
analytics.flush = Mock()
exit_code = main()
analytics.track.assert_called_with(1, 'dcos-cli',
{'cmd': ' '.join(args),
'exit_code': 0,
'err': None})
analytics.flush.assert_called_with()
assert exit_code == 0
def test_analytics_err():
args = ['dcos', 'marathon', 'task', 'show', 'asdf']
with mock.patch('sys.argv', args):
analytics.track = Mock()
analytics.flush = Mock()
exit_code = main()
analytics.track.assert_called_with(1, 'dcos-cli',
{'cmd': ' '.join(args),
'exit_code': 1,
'err': "Task 'asdf' does not exist\n"})
analytics.flush.assert_called_with()
assert exit_code == 1