#!/usr/bin/env python

#   Copyright 2017 Couchbase, Inc
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#

# Tool to dump a KV-Engine trace file to JSON; which can be viewed
# with Chrome's trace viewer (chrome://tracing).

from __future__ import print_function
import argparse
import distutils.spawn
import os
import subprocess
import sys

# Python 2.6 doesn't have subprocess.check_output
def check_output(args):
    return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]

parser = argparse.ArgumentParser(
    description='Dump a KV-Engine trace file as JSON.')
parser.add_argument('--mcctl', help='Path to mcctl binary')
parser.add_argument('-H', '--hostname', required=True,
                    help='host:port to connect to (e.g. localhost:11210)')
parser.add_argument('-u', '--username', required=True, help='Username')
parser.add_argument('-P', '--password', required=True, help='Password')
parser.add_argument('-n', '--norestart', dest='restart', action='store_false',
                    help="Don't restart tracing after dumping the trace file")
parser.add_argument('outfile', type=argparse.FileType('w'))

args = parser.parse_args()

# Locate the mcctl binary
# 1. If the user specified a location, use that one.
if args.mcctl:
    mcctl_bin = args.mcctl
else:
    # 2. Try the path
    mcctl_bin = distutils.spawn.find_executable('mcctl')
    if not mcctl_bin:
        # 3. Try relative to this script (for when we are installed).
        dir_path = os.path.dirname(os.path.realpath(__file__))
        mcctl_bin = os.path.join(dir_path, "../../bin/mcctl")

if not os.path.isfile(mcctl_bin):
    print("Error: No mcctl program found at {} - cannot continue.".format(
        mcctl_bin), file=sys.stderr)
    sys.exit(1)

mcctl_args = [mcctl_bin,
              '-h', args.hostname,
              '-u', args.username,
              '-P', args.password]

subprocess.check_call(mcctl_args + ['set', 'trace.stop'])
uuid = check_output(mcctl_args + ['get', 'trace.dump.begin'])
uuid = uuid.strip()

# Repeatedly get chunks, until we get one with zero length.
while True:
    chunk = check_output(
        mcctl_args + ['get', 'trace.dump.chunk?id=' + uuid]).rstrip()
    if len(chunk) == 0:
        break
    args.outfile.write(chunk)

subprocess.check_call(mcctl_args + ['set', 'trace.dump.clear', uuid])

if args.restart:
    subprocess.check_call(mcctl_args + ['set', 'trace.start'])
