#!/usr/bin/env python3

#   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).


import argparse
import distutils.spawn
import os
import subprocess
import sys

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.
mcctl_bin = None
if args.mcctl:
    mcctl_bin = args.mcctl
else:
    # 2. Try the path
    mcctl_bin = distutils.spawn.find_executable('mcctl')
    # find_executable() has the odd behaviour that it always looks in the
    # current working directory first, and returns that relative path if
    # it is. We don't want that though.
    if not mcctl_bin or mcctl_bin == "mcctl":
        # 3. Look for mcctl in the same directory as the path used to invoke
        # kv_trace_dump, which should be INSTALL_DIR/bin. Note: that
        # location will likely be a symlink on Unix, but we still want that
        # location, not the location the symlink points to.
        mcctl_bin = os.path.normpath(
            os.path.join(
                os.getcwd(), sys.argv[0], "..", "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 = subprocess.check_output(mcctl_args + ['get', 'trace.dump.begin'],
                               universal_newlines=True)
uuid = uuid.strip()

# Repeatedly get chunks, until we get one with zero length.
while True:
    chunk = subprocess.check_output(
        mcctl_args + ['get', 'trace.dump.chunk?id=' + uuid],
        universal_newlines=True).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'])
