#!/usr/bin/tclsh

# Copyright IBM Corp. 2016. All Rights Reserved.
#
# 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.

set usage {
Usage: fabricLogger ?... parms ...? [... peers ...]

Convert a HyperLedger fabric blockchain into a file that logs all of the
transactions that are found in the blockchain. By default, the entire current
blockchain is converted to a log on standard output and the job
terminates. Options are provided to start logging from a certain block, log
only a range of blocks and/or "follow" the blockchain indefinitely.

Each line of the report is a single character followed by a single
piece of information:

b <n>    : Block number <n>
d <ccid> : A chaincode deployment. The <ccid> is the chaincode ID.
i <txid> : A chaincode invocation. The <txid> is the transaction ID.

Note that the block number is printed _after_ all of the block transactions,
to validate to a 'following' client that all transactions of a block have been
seen.

By default, the peer network is defined by the $BUSYWORK_HOME/network file.
However, if one or more peers are provided on the command line, those peers
will be used instead, and the -port option specifies the default REST API port
to use if an explicit peer does not include an explicit port.

To spread the load, if there are multiple peers this script goes to the peers
in round-robin order to try for the next block, even when requests fail in
-follow mode. NOTE: If you are running NOOPS consensus, *do not* specify more
than 1 explict peer, because the blockchains on NOOPS networks are not
guaranteed to be consistent. Note that this issue is handled automatically by
default, as the $BUSYWORK_HOME/network file includes the consensus mode and
only the first peer will be polled in NOOPS networks.

Options:

-h | -help | --help

    Print this usage information and exit normally.

-follow | -noFollow : -noFollow

    By default the job terminates as soon as the last block is processed, that
    is, as soon as a peer does not have the next block. Select -follow to keep
    following forever. In -follow mode the output file is flushed after each
    block is processed. The -follow option has slightly different semantics if
    '-from <first>:<last>' is specified; See below.

-followPoll <duration> : 1s

    In -follow mode, once the end of the current blockchain is reached
    fabricLogger will keep polling (alternate peers) at this frequency. If this
    is specified as 0 then fabricLogger will aggressively poll the set of peers
    as fast as possible.

-from <first>[:<last>] : Log all (currently existing) blocks

    Specifying for example '-from 10' starts logging from block 10. In this
    mode the -follow option is in force to determine what happens once the end
    of the current chain is met.

    Specifying for example '-from 10:20' logs blocks 10, 11, ..., 20 and then
    stops. In this mode specifying -follow causes the logger to (potentially)
    poll the network until the final block is logged. The default -noFollow
    mode causes logging to stop either when the final block is logged or the
    end of the blockchain is first encountered.

-file <file> : *Standard Output*

    Use -file to specify a log file other than standard output.

-delete | -noDelete : -noDelete

    If logging to a file, the -delete option causes the file to be deleted at
    the exit of the program. This may be useful when other processes are
    following this file.

-retry : 0

    If greater than 0, retry failing HTTP transactions at most this many
    times.

-timestamp | -noTimestamp : -noTimestamp

    This is a debugging flag. If -timestamp is selected then error logging
    from this script will be timestamped.

-force | -noForce : -noForce

    This is a debugging flag. If set, simply log an error if blocks are found
    with invalid JSON, no transactions or other errors and move on. By default
    these types of blocks are considered fatal errors.

-killOnError <pids> : N/A

    If this logger aborts due to an error it sends a SIGINT to every PID in
    this list of PIDS. This flag is used to make drivers terminate more
    quickly if the logger fails..

-port <port> : 7050

    The default REST API port.
}


############################################################################
# Option Processing
############################################################################

lappend auto_path [file dirname [info script]]/../tcl

package require busywork

setLoggingPrefix fabricLogger

set options {
    {enum    {-h -help --help}         parms(help)       0  p_help}
    {bool    {-follow -noFollow}       parms(follow)     0}
    {key     -followPoll               parms(followPoll) 1s}
    {key     -from                     parms(from)       {} p_from}
    {key     -file                     parms(file)       {} fileOption}
    {bool    {-delete -noDelete}       parms(delete)     0}
    {key     -retry                    parms(retry)      0}
    {bool    {-timestamp -noTimestamp} parms(timestamp)  0}
    {bool    {-force -noForce}         parms(force)      0}
    {key     -killOnError              parms(killPIDs)  {}}
    {key     -port                     parms(port)       7050}
}

mapKeywordArgs $argv $options parms(explicitPeers)

if {[parms help]} {
    puts $usage
    exit 0
}

setLoggingTimestamp [parms timestamp]

setLoggingLevel {} note

debug {} "$argv0 $argv"

# Convert followPoll to milliseconds. Validate the number of peers and add the
# default port to explicit peer addresses that don't specify a port. If -file
# was specified, open the log file and set up an exit handler to close and
# delete the file. This includes SIGINT sent by an exiting parent process.
# Create a CircularList of peers.  Initialize the current block index.

parms followPoll [durationToMs [parms followPoll]]

if {[null [parms explicitPeers]]} {
    if {[catch {busywork::networkToArray ::parms network.} msg]} {
        errorExit $msg
    }
    parms peers [parms network.peer.restAddresses]
    if {[parms network.consensus] eq "noops"} {
        parms peers [first [parms peers]]
    }
} else {
    parms peers [addPortToHosts [parms explicitPeers] [parms port]]
}

CircularList create peerList [parms peers]

proc closeAndDeleteFile {} {
    debug {} "Close and delete [parms file]"
    close [parms log]
    exec rm -rf [parms file]
}

parms log stdout
if {$fileOption} {

    if {[catch {parms log [open [parms file] w]}]} {
        errorExit "Error opening log file '[parms file]'"
    }
    if {[parms delete]} {
        atExit {closeAndDeleteFile}
        signal trap SIGINT {exit 0}
    }
}

proc killPIDs {} {
    foreach pid [parms killPIDs] {
        catch {kill SIGINT $pid}
    }
}

atErrorExit {killPIDs}


# Interpret the -from <first>[:<last>] specification. The condition
# finalBlock == -1 means "forever".

if {!$p_from} {

    parms block 0
    parms finalBlock -1

} else {

    set spec [split [parms from] :]
    switch [llength $spec] {
        0 {
            errorExit "-from specification is empty"
        }
        1 {
            parms block $spec
            parms finalBlock -1
        }
        2 {
            set first [first $spec]
            set last [last $spec]
            if {![string is integer $first] || ![string is integer $last] ||
                ($first < 0) || ($last < $first)} {
                errorExit "Invalid -from specification"
            }
            parms block $first
            parms finalBlock $last
        }
        default {
            errorExit "Invalid -from specification"
        }
    }
}

############################################################################
# Do it
############################################################################

# TODO : Move block access to ::fabric package procedures

# NB: To avoid memory leaks the HTTP token must always be cleaned up
# (deleted). We even delete the token on errorExit paths, as one day we may
# decide to add an option to return errors instead of exiting from errorExit.

proc forceBreakOrErrorExit {i_token} {
    if {[parms force]} {
        http::cleanup $i_token
        err {} "Continuing after error (-force mode)"
        return -code break
    } else {
        httpErrorExit $i_token
    }
}

set log [parms log]
set follow [parms follow]
set block [parms block]
set finalBlock [parms finalBlock]
set lastBlock $block

while {1} {

    for {set retry [parms retry]} {$retry >= 0} {incr retry -1} {

        set peer [peerList next]

        if {[catch {http::geturl http://$peer/chain/blocks/$block} token]} {
            if {$retry > 0} {
                if {$retry == [parms retry]} {
                    warn {} \
                        "$peer @ block $block: " \
                        "Retrying after catastrophic HTTP error"
                }
                http::cleanup $token
                continue
            }
            http::cleanup $token
            errorExit \
                "$peer @ block $block: ::http::geturl failed " \
                "with [parms retry] retries : $token"
        }

        if {[http::ncode $token] == 404} {

            # End of blockchain

            http::cleanup $token
            if {![parms follow]} {exit 0}
            if {[parms followPoll] == 0} break
            after [parms followPoll]
            break
        }

        if {[http::ncode $token] != 200} {

            # Failure

            if {$retry > 0} {
                if {$retry == [parms retry]} {
                    warn {} \
                        "$peer @ block $block: " \
                        "Retrying after HTTP error return"
                }
                http::cleanup $token
                continue
            }

            err {} \
                "REST API call to $peer for block $block failed " \
                "with [parms retry] retries"
            httpErrorExit $token
        }

        if {[catch {json::json2dict [http::data $token]} parse]} {
            err {} "$peer @ block $block: JSON response does not parse: $parse"
            forceBreakOrErrorExit $token
        }

        if {$block != 0} {

            if {[catch {dict get $parse transactions} transactions]} {
                err {} \
                    "$peer @ block $block: " \
                    "Error getting transactions: $transactions"
                forceBreakOrErrorExit $token
            }

            foreach tx $transactions {

                # The chaincodeID comes back as bytes so that it can be
                # encrypted. We don't log it or the timestamp now.

                if {[catch {dict get $tx type} type]} {
                    err {} \
                        "$peer @ block $block: " \
                        "Error parsing type field: $type"
                    forceBreakOrErrorExit $token
                }
                if {[catch {dict get $tx txid} txid]} {
                    err {} "$peer @ block $block: " \
                        "Error parsing txid field: $txid"
                    forceBreakOrErrorExit $token
                }
                switch $type {
                    1 {
                        puts $log "d $txid"
                    }
                    2 {
                        puts $log "i $txid"
                    }
                    default {
                        err {} "$peer @ block $block: " \
                            "Illegal transaction type: $type"
                        forceBreakOrErrorExit $token
                    }
                }
            }
        }

        http::cleanup $token
        puts $log "b $block"

        if {$follow} {flush $log}

        set lastBlock $block
        incr block

        break
    }

    if {$retry != [parms retry]} {
        note note \
        "$peer @ block $lastBlock: " \
        "Success after [expr {[parms retry] - $retry}] HTTP retries"
    }

    if {($finalBlock >= 0) && ($block > $finalBlock)} {
        break
    }
}
