#!/bin/sh 
# restart -*-Tcl-*- \
exec tclsh "$0" "$@"
package require cmdline

# bb2anno
#
#     Consolidate information from bitbake buildstats files and emake
#     annotation files into a single pseudo-annotation file that can
#     be loaded in ElectricInsight to perform aggregate analysis.
#
#         bb2anno -id NNN
#                 -buildstats ./path/to/buildstats
#                 -annoroot ./path/to/annos 
#                 -buildlogs ./path/to/buildlogs
#
#         eg:
#
#         bb2anno -id 375917
#                 -buildstats ./rpi-emake2/tmp/buildstats/20181112225633 
#                 -annoroot ./emakeassets_bbconf > /tmp/combined.xml
#                 -buildlogs ./rpi-emake2/tmp/work
#
# Copyright (c) 2018 Electric Cloud, Inc.
# All rights reserved

proc main {argv} {
    global packageList
    global jobcount

    set options {
        {id.arg         ""      "build identifier"}
        {annoroot.arg   ""      "Directory tree containing emake annofiles"}
        {buildstats.arg ""      "Directory tree containing buildstats"}
        {buildlogs.arg  ""      "Directory tree containing task logs"}
    }

    set usage "

Combine bitbake buildstats, run scripts and task logs with emake annotation
files for some of those tasks into a single pseudo-annotation file suitable
for use with ElectricInsight.


        -id             The ebitbake build identifer for the build.
        -annoroot       The root of a directory tree containing emake
                        annotation files for those tasks that were executed
                        using emake. For example, ./emakeassets
        -buildstats     The root of a directory tree containing the
                        bitbake buildstats files, such as
                        ./tmp/buildstats/20181112225633
        -buildlogs      The root of a directory tree containing bitbake task
                        logs and run scripts, such as ./tmp/work

"


    catch {unset args}
    if { [catch {
        array set args [cmdline::getoptions argv $options $usage]
    } err] } {
        if { [llength $argv] } {
            puts stderr "unknown option: $argv\n\n$err"
            exit 1
        } else {
            puts $err
            exit 0
        }
    }

    foreach arg {id buildstats buildlogs} {
        if { $args($arg) == "" } {
            puts stderr "missing required option $arg"
            exit 1
        }
    }

    set startTime [file tail $args(buildstats)]
    set startTime [clock scan $startTime -format "%Y%m%d%H%M%S" -gmt true]
    set jobcount  0

    readBuildstats $args(buildstats)
    findLogs $args(buildlogs)
    findAnnotation $args(annoroot) $args(id)
    allocateWorkers

    fconfigure stdout -buffering full -buffersize 1000000
    printPrologue $args(id) $startTime
    foreach pkg $packageList {
        set endTime [printPackage $startTime [lindex $pkg 0]]
    }
#     printMetrics
    printEpilogue $endTime
    flush stdout
}

# readBuildstats
#
#       Given a directory that is the root of a tree containing bitbake
#       buildstats files, read those files and create a data structure
#       describing the bitbake tasks.  Updates the global "tasks" array with
#       a dict for each package.task pair found; and the global "packageList"
#       variable which contains a list of all the packages sorted by start
#       time of the earliest task in each.

proc readBuildstats {dir} {
    global tasks
    global packageList

    set packageDirs [glob -nocomplain -types d $dir/*]
    if { [llength $packageDirs] == 0 } {
        error "No buildstats packages found in $dir"
    }

    foreach packageDir $packageDirs {
        set pkg [file tail $packageDir]
        set starts [list]
        foreach taskFile [glob -nocomplain types f $packageDir/do_*] {
            set task [file tail $taskFile]
            set desc [readFile $taskFile]
            if { ![regexp -lineanchor -linestop {^Started:\s(\S*)\s$} $desc -> start] } {
                error "Invalid buildstats data (started): $taskFile"
            }
            if { ![regexp -lineanchor -linestop {^Ended:\s(\S*)\s$} $desc -> end] } {
                error "Invalid buildstats data (ended): $taskFile"
            }
            if { ![regexp -lineanchor -linestop {^Status:\s(\S*)\s$} $desc -> status] } {
                error "Invalid buildstats data (status): $taskFile"
            }

            set tasks($pkg.$task) [dict create \
                                       desc $desc \
                                       start $start \
                                       end $end \
                                       status $status]

            if { ![info exists first] || $start < $first } {
                set first $start
            }
        }
        if { [info exists first] } {
            lappend packageList [list $pkg $first]
        }
    }

    set packageList [lsort -index 1 -real $packageList]
}

# findAnnotation
#
#       Given a directory which is the root of a tree of emake asset
#       directories containing annotation files from some bitbake
#       tasks, find the annotation files and associate them with the
#       tasks descriptions in the global "tasks" array.

proc findAnnotation {dir id} {
    upvar \#0 tasks tasks
    set pkg  *
    set arch *
    set ver  *
    set task *

    if { $dir == "" } {
        return
    }

    set annos [glob -nocomplain -types f $dir/$pkg/$arch/$ver/$task/$id-*.anno]
    if { [llength $annos] == 0 } {
        puts stderr "No annotation files found in $dir/$pkg/$arch/$ver/$task/$id-*.anno"
    }

    foreach anno $annos {
        set components [file split $anno]
        set pkg        [lindex $components end-4]
        set ver        [lindex $components end-2]
        set task       [lindex $components end-1]

        if { [info exists tasks($pkg-$ver.$task)] } {
            dict append tasks($pkg-$ver.$task) anno $anno
        }
    }
}

# findLogs
#
#       Given a directory which is the root of a tree of bitbake task logs
#       and run scripts, find and associate those files with the task
#       descriptions in the global "tasks" array.

proc findLogs {dir} {
    upvar \#0 tasks tasks
    set arch *
    set pkg  *
    set ver  *
    set logs [glob -nocomplain -types l $dir/$arch/$pkg/$ver/temp/log.*]
    if { [llength $logs] == 0 } {
        error "No build logs found in $dir/$arch/$pkg/$ver/temp/log.*"
    }
    set runs [glob -nocomplain -types l $dir/$arch/$pkg/$ver/temp/run.*]
    if { [llength $runs] == 0 } {
        error "No run scripts found in $dir/$arch/$pkg/$ver/temp/log.*"
    }

    foreach log $logs {
        set components [file split $log]
        set pkg        [lindex $components end-3]
        set ver        [lindex $components end-2]
        set task       [lindex [split [lindex $components end] .] end]

        if { [info exists tasks($pkg-$ver.$task)] } {
            dict append tasks($pkg-$ver.$task) log $log
        }
    }

    foreach run $runs {
        set components [file split $run]
        set pkg        [lindex $components end-3]
        set ver        [lindex $components end-2]
        set task       [lindex [split [lindex $components end] .] end]

        if { [info exists tasks($pkg-$ver.$task)] } {
            dict append tasks($pkg-$ver.$task) run $run
        }
    }
}

# allocateWorkers
#
#     For each bitbake task, assign it to a bitbake worker, taking care to
#     use distinct worker ids for concurrently executing tasks.

proc allocateWorkers {} {
    global tasks

    # First make a sorted list of all the start and end events in the
    # system, ordered by time and with enough context to know whether
    # each is a start or stop, and of what.

    set events [list]
    foreach task [array names tasks] {
        lappend events \
            [list $task [dict get $tasks($task) start] 1] \
            [list $task [dict get $tasks($task) end] 0]
    }
    set events [lsort -real -index 1 $events]

    # Now go through the list and assign an worker to each task when
    # we find its start event, and release the worker to a free list
    # when we find the end event.  If the free list is empty when we
    # need to start something, synthesize a new worker on the fly.

    set free [list]
    set max 0
    foreach event $events {
        foreach {task time event} $event { break }
        if { $event } {
            # Starting a task.  Find a free worker, or create a new one.

            if { [llength $free] } {
                set id   [lindex $free end]
                set free [lrange $free 0 end-1]
            } else {
                set id bbworker-[incr max]
            }
            dict append tasks($task) worker $id
        } else {
            # Ending a task.  Return that task's worker to the free list.

            lappend free [dict get $tasks($task) worker]
        }
    }
}

# printPrologue
#
#       Print the boilerplate prologue for our pseudo annotation file.

proc printPrologue {id startTime} {
    global jobcount

    set jobId [format "J%016x" [incr jobcount]]
    puts [format {<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE build SYSTEM "build.dtd">
<build id="%s" start="%s">
<properties>
<property name="AnnoDetail">basic,history,waiting</property>
</properties>
<make level="0" cmd="bitbake" cwd="%s" mode="bitbake">
<job id="%s" type="alpha" thread="bbworker-1">
<timing invoked="0.000000" completed="0.000000" node="bbworker-1"/>
</job>} \
              $id [clock format $startTime] [pwd] $jobId $startTime $startTime]
}

# printEpilogue
#
#       Print the epilogue for our pseudo annotation file.

proc printEpilogue {endTime} {
    global jobcount
    global metrics

    set jobId [format "J%016x" [incr jobcount]]

    puts [format {<job id="%s" type="omega" thread="bbworker-1">
<timing invoked="%s" completed="%s" node="bbworker-1"/>
</job>
</make>} $jobId $endTime $endTime]

    printMetrics $endTime
    puts "</build>"
}

# printMetrics
#
#       Print aggregated build metrics from all the annotation files.

proc printMetrics {endTime} {
    global metrics

    puts "<metrics>"
    array set actions {
        maxArenaCount           skip
        maxMakeCount            skip
        elapsed                 skip
        historyFitness          avg
        clusterAvailability     avg
    }

    set metrics(duration) $endTime
    foreach metric [lsort [array names metrics]] {
        set action sum
        if { [info exists actions($metric)] } {
            set action $actions($metric)
        }
        if { [catch {$action $metric $metrics($metric)} err] } {
            puts stderr "error aggregating $metric: $err"
        }
    }
    puts "</metrics>"
}

# sum
#
#       Print a metric as the sum of a series of values.

proc sum {name values} {
    puts "<metric name=\"$name\">[::tcl::mathop::+ {*}$values]</metric>"
}

# avg
#
#       Print a metric as the average of a series of values.

proc avg {name values} {
    set total 0
    foreach value $values {
        set total [expr {$total + $value}]
    }
    set avg [expr {double($total) / [llength $values]}]
    puts "<metric name=\"$name\">[format %0.6f $avg]</metric>"
}

# skip
#
#       "Print" a metric by doing nothing.

proc skip {name values} { }

# printPackage
#
#       Synthesize "job" annotation for each task in a package, with
#       appropriate waitingJobs linkages.  For any task that has annotation
#       associated, arrange for that annotation to be copied to our
#       pseudo annotation as well.

proc printPackage {startTime pkg} {
    upvar \#0 tasks tasks
    upvar \#0 jobcount jobcount
    upvar \#0 ESCAPES ESCAPES
    global metrics

    # Find all the tasks we know about for this package and sort them by
    # start time, so that we print them in "serial order".

    set pkgTasks [list]
    set taskOffset [expr {[string length $pkg] + 1}]
    foreach task [array names tasks ${pkg}.*] {
        lappend pkgTasks [list $task [dict get $tasks($task) start]]
    }

    if { [llength $pkgTasks] == 0 } {
        # No tasks?  Bail out.

        return 0
    }

    set workload 0
    set pkgTasks [lsort -index 1 -real $pkgTasks]

    foreach task $pkgTasks {
        foreach {task start} $task { break }
        set start [expr {[dict get $tasks($task) start] - $startTime}]
        set end   [expr {[dict get $tasks($task) end]   - $startTime}]
        set worker [dict get $tasks($task) worker]

        set jobId   [format "J%016x" [incr jobcount]]
        set nextJob [format "J%016x" [expr {$jobcount + 1}]]

        set log ""
        if { [dict exists $tasks($task) log] && ![dict exists $tasks($task) anno] } {
            set log [readFile [dict get $tasks($task) log]]
            set log [string map $ESCAPES $log]
        }

        set run ""
        if { [dict exists $tasks($task) run] } {
            set run [readFile [dict get $tasks($task) run]]
            set run [string map $ESCAPES $run]
        }

        # Emit the start of the job tag for this task.  This is the same
        # whether or not we have annotation for the work inside the task.

        puts [format {<job id="%s" thread="%s" name="%s" type="rule">
<command>
<argv>%s
</argv>
<output src="prog">%s
</output>
</command>
<jobMetrics>%s
</jobMetrics>} \
                  $jobId \
                  $worker \
                  $task \
                  $run \
                  $log \
                  [dict get $tasks($task) desc]]

        set failed ""
        if { [dict get $tasks($task) status] != "PASSED" } {
            set failed "\n<failed code=\"1\"/>"
        }

        if { ![dict exists $tasks($task) anno] } {
            # No annotation for this task so just close out the job tag.

            puts [format {<timing invoked="%0.6f" completed="%0.6f" node="%s"/>
<waitingJobs idList="%s"/>%s
</job>} $start $end $worker $nextJob $failed]
            set workload [expr {$workload + ($end - $start)}]
            continue
        }

        # We have annotation for this task.  Each annotation will be treated
        # like a submake started by the rule job for this task.  The challenge
        # is in getting the timing and waiting jobs details correct across
        # all of it.

        set count [llength [dict get $tasks($task) anno]]
        set ruleJobId  $jobId
        set nextRuleId [format "J%016x" [expr {$jobcount + ($count * 2) + 1}]]

        foreach anno [dict get $tasks($task) anno] {
            set start [incorporateAnno $anno $startTime $nextRuleId $start $worker]
            set followId [format "J%016x" [incr jobcount]]

            puts [format {<job id="%s" type="follow" partof="%s" thread="%s">
<timing invoked="%0.6f" completed="%0.6f" node="%s"/>
<waitingJobs idList="%s"/>
</job>} $followId $jobId $worker $start $end $worker $nextRuleId]
            set workload [expr {$workload + ($end - $start)}]

            if { [incr count -1] > 0 } {
                # There's another annotation file to incorporate.  Create a
                # continuation job to mark the start of it.

                set jobId [format "J%016x" [incr jobcount]]
                puts [format {<job id="%s" thread="%s" type="continuation" partof="%s">} \
                          $jobId $worker $ruleJobId]
            }
        }
    }
    lappend metrics(workload) $workload
    return $end
}

# incorporateAnno
#
#       Given the path to an annotation file and some meta data about
#       the relationship of the build described by that anno to the
#       overall bitbake process, incorporate the annotation data into
#       the pseudo annotation we're creating, with job id's and timing
#       data adjusted so that it is relative to the overall process.

proc incorporateAnno {anno buildStart nextRuleId jobStart worker} {
    upvar 1 workload workload
    global jobcount
    global metrics

    set f [open $anno r]
    fconfigure $f -encoding utf-8 -buffering full -buffersize 1000000

    # Skip the xml declaration and the doctype declaration.

    gets $f
    gets $f

    # Get the build tag.

    set line [gets $f]
    regexp {<build id="([^\"]+)".* start="([^\"]+)"} $line -> annoId annoStart
    set annoStart [clock scan $annoStart]
    append annoId _

    # Find the first <make> tag.

    set annodetail ""
    while { ![eof $f] } {
        set makeOffset [tell $f]
        set line [gets $f]
        if { [string equal -length 28 {<property name="AnnoDetail">} $line] } {
            set annodetail [string range $line 28 end-11]
        }
        if { [string equal -length 6 "<make " $line] } {
            break
        }
    }

    # bb2anno requires waiting detail to incorporate task-specific annotation
    # into the combined anno -- since we already declared that the combined
    # anno has that level of detail and we've gone to some lengths to setup
    # waitingJobs information for the synthesized jobs, to then _not_ have that
    # detail in submakes would just confuse everything.

    foreach detail [split $annodetail ,] {
        set details($detail) 1
    }
    if { ![info exists details(waiting)] } {
        puts stderr "WARNING: bb2anno requires waiting annodetail"
        puts stderr "WARNING: $anno does not have required annodetail"
        close $f
        return
    }

    # Find the first <job> tag.

    while { ![eof $f] } {
        set line [gets $f]
        if { [string equal -length 5 "<job " $line] } {
            if { [string index $line 18] eq "\"" } {
                set parseId "J${annoId}[string range $line 9 17]"
            } else {
                set parseId "J${annoId}[string range $line 9 25]"
            }
            break
        }
    }

    if { ![info exists parseId] } {
        # Couldn't find any jobs in this annotation file.  This is probably
        # a bad or incomplete bitbake build overall.  Print a warning
        # on stderr, then bail out.

        puts stderr "WARNING: No jobs found in $anno"
        close $f
        return
    }

    # Now we have the start time of this anno file and the id of the first
    # job, so we have enough information to close the partially written
    # job in the parent make.

    set end [expr {$annoStart - $buildStart}]
    puts [format {<timing invoked="%s" completed="%d" node="%s"/>
<waitingJobs idList="%s %s"/>
</job>} $jobStart $end $worker $nextRuleId $parseId]
    set workload [expr {$workload + ($end - $jobStart)}]

    # back up to the <make> tag and start copying the output, swizzling the job
    # id's and timing data as we go.

    seek $f $makeOffset start
    set timingOffset [expr {$annoStart - $buildStart}]

    set lastJobId ""
    set done [expr {0}]
    set ZERO [expr {0}]
    while { $done == $ZERO } {
        set line [gets $f]
        if { [eof $f] } {
            break
        }
        if { [string index $line 0] != "<" } {
            puts $line
            continue
        }

        set word [string range $line 0 5]
        if { $word eq "<job i" } {
            regexp {job id="(J[[:xdigit:]]+)"} $line -> lastJobId
            regsub -all {J([[:xdigit:]]+)} $line "J${annoId}\\1" line
            set isEnd [expr {([string first {type="end"} $line] != -1) || ([string first {type="omega"} $line] != -1)}]
            set haveWaiters false
        } elseif { $word eq "<timin" } {
            foreach {x invoked completed node} $line { break }
            set start [expr {[string range $invoked 9 end-1] + $timingOffset}]
            set end   [expr {[string range $completed 11 end-1] + $timingOffset}]
            set line "<timing invoked=\"$start\" completed=\"$end\" $node"
        } elseif { $word eq "</job>" } {
            if { $isEnd && !$haveWaiters } {
                # This must be the last end job in the annotation, so create a
                # waitingJobs tag to links it to the follow job in the parent.

                set followJobId [format "J%016x" [expr {$jobcount + 1}]]
                set line [format {<waitingJobs type="internal" idList="%s"/>
</job>
</make>} $followJobId]

                # all done

                set done [expr {1}]
            }
        } elseif { $word eq "<waiti" } {
            if { $isEnd && $line eq "<waitingJobs idList=\"$lastJobId\"/>" } {
                # Sometimes emake indicates that an end job depends on itself.
                # Ignore this.

                continue
            }
            regsub -all {J([[:xdigit:]]+)} $line "J${annoId}\\1" line
            set haveWaiters true
        } elseif { $word eq "<dep w" || $word eq "<confl" } {
            regsub -all {J([[:xdigit:]]+)} $line "J${annoId}\\1" line
        } elseif { $word eq "</bui" && $line eq "</build>" } {
            break
        }

        puts $line
    }

    # Keep scanning the annofile to find the build metrics, for inclusion
    # in the combined annotation.

    set done [expr {0}]
    while { $done == $ZERO } {
        set line [gets $f]
        if { [eof $f] } {
            break
        }
        if { ![string equal -length 8 "<metric " $line] } {
            if { [string equal "</build>" $line] } {
                break
            }
            continue
        }

        regexp {<metric name=\"([^\"]+)\">(.*)</metric>} $line -> name value
        lappend metrics($name) $value
    }
    close $f
    return $end
}

# readFile
#
#       Read the given file and return the content.

proc readFile {name} {
    set f [open $name r]
    set data [read $f]
    close $f
    return $data
}

set ESCAPES [list "<" "&lt;" \
                 ">" "&gt;" \
                 "&" "&amp;" \
                 "\"" "&quot;" \
                 "%"  "%%" \
                 "\000" "%00" \
                 "\001" "%01" \
                 "\002" "%02" \
                 "\003" "%03" \
                 "\004" "%04" \
                 "\005" "%05" \
                 "\006" "%06" \
                 "\007" "%07" \
                 "\010" "%08" \
                 "\013" "%0b" \
                 "\014" "%0c" \
                 "\016" "%0e" \
                 "\017" "%0f" \
                 "\020" "%10" \
                 "\021" "%11" \
                 "\022" "%12" \
                 "\023" "%13" \
                 "\024" "%14" \
                 "\025" "%15" \
                 "\026" "%16" \
                 "\027" "%17" \
                 "\030" "%18" \
                 "\031" "%19" \
                 "\032" "%1a" \
                 "\033" "%1b" \
                 "\034" "%1c" \
                 "\035" "%1d" \
                 "\036" "%1e" \
                 "\037" "%1f" \
                ]

main $argv
