nsmcp::ServerHistory method poolThreads (protected)

 <instance of nsmcp::ServerHistory[i]> poolThreads context options

Defined in /usr/local/ns/tcl/nsmcp/stats-tools.tcl

Parameters:
context (required)
options (required)

Testcases:
No testcase defined.
Source code:
set from [dict get $options from]
set to [dict get $options to]
set pool [dict get $options pool]
set bucket [dict get $options bucketSeconds]
set first [expr {($from/$bucket)*$bucket}]
set end [expr {(($to+$bucket-1)/$bucket)*$bucket}]
set slots [expr {($end-$first)/$bucket}]
set pools {}
set driverWaiting [lrepeat $slots {}]
set driverSamples [lrepeat $slots 0]
set driverPeakTotal -1
set driverPeakAt {}
set driverPeakBucket -1
set driverPeakValues {}
set databasePools {}
set disks {}
set omittedDatabasePools {}
set omittedDisks {}
set databaseSourceAvailable false
set diskSourceAvailable false
set previousRecord {}
set cursor 0
set pages 0
set total 0
while {1} {
    set h [${:command} history query -server [$context server] -from $from -to $to -limit 1000 -cursor $cursor]
    incr pages
    foreach record [dict get $h records] {
        incr total
        if {![dict exists $record sampling to]} {
            continue
        }
        set at [dict get $record sampling to]
        if {![string is double -strict $at]} {continue}
        set index [expr {int(floor(($at-$first)/double($bucket)))}]
        if {$index<0 || $index>=$slots} {continue}

        # Driver-owned sockets retried after a full pool are outside
        # that pool's waiting gauge. This is process-wide evidence:
        # driver counters cannot be assigned to a connection pool.
        if {[dict exists $record drivers] && [dict size [dict get $record drivers]]>0} {
            set driverTotal 0
            set driverValid true
            set driverValues {}
            dict for {driverName driverEntry} [dict get $record drivers] {
                if {![dict exists $driverEntry socketStates waitingForConnection]
                    || ![string is integer -strict [dict get $driverEntry socketStates waitingForConnection]]
                    || [dict get $driverEntry socketStates waitingForConnection]<0} {
                    set driverValid false
                    break
                }
                set value [dict get $driverEntry socketStates waitingForConnection]
                incr driverTotal $value
                dict set driverValues $driverName $value
            }
            if {$driverValid} {
                if {[lindex $driverWaiting $index] eq {} || $driverTotal>[lindex $driverWaiting $index]} {
                    lset driverWaiting $index $driverTotal
                }
                lset driverSamples $index [expr {[lindex $driverSamples $index]+1}]
                if {$driverTotal>$driverPeakTotal} {
                    set driverPeakTotal $driverTotal
                    set driverPeakAt $at
                    set driverPeakBucket $index
                    set driverPeakValues $driverValues
                }
            }
        }

        # The retained sample carries its preceding disk snapshot. DB
        # pool statistics are cumulative, so compare adjacent retained
        # samples only when their sampling boundary and instance match.
        set validInterval [expr {
            [dict exists $record sampling ready] && [dict get $record sampling ready]
            && [dict exists $record sampling from]
            && [dict exists $record sampling elapsedSeconds]
            && !([dict exists $record sampling reset] && [dict get $record sampling reset])
        }]
        if {$validInterval} {
            set elapsed [dict get $record sampling elapsedSeconds]
            if {![string is double -strict [dict get $record sampling from]]
                || ![string is double -strict $elapsed] || $elapsed<=0
                || ([dict exists $record sampling intervalSeconds]
                    && (![string is double -strict [dict get $record sampling intervalSeconds]]
                        || $elapsed>1.5*[dict get $record sampling intervalSeconds]))} {
                set validInterval false
            }
        }
        if {[dict exists $record databasePools] && [dict size [dict get $record databasePools]]>0} {
            set databaseSourceAvailable true
        }
        if {[dict exists $record linuxNetwork disks] && [dict size [dict get $record linuxNetwork disks]]>0} {
            set diskSourceAvailable true
        }
        if {$validInterval && $previousRecord ne ""
            && [dict exists $record instance] && [dict exists $previousRecord instance]
            && [dict get $record instance] eq [dict get $previousRecord instance]
            && [dict exists $previousRecord sampling to]
            && abs([dict get $record sampling from]-[dict get $previousRecord sampling to])<0.001
            && [dict exists $record databasePools]
            && [dict exists $previousRecord databasePools]} {
            dict for {name current} [dict get $record databasePools] {
                if {![dict exists $previousRecord databasePools $name]} {continue}
                if {![dict exists $databasePools $name] && [dict size $databasePools]>=16} {
                    dict set omittedDatabasePools $name true
                    continue
                }
                set before [dict get $previousRecord databasePools $name]
                set deltas {}
                foreach key {sqltime waittime statements gethandles} {
                    if {![dict exists $current $key] || ![dict exists $before $key]} {
                        set deltas {}
                        break
                    }
                    set delta [:nonnegativeDelta [dict get $current $key] [dict get $before $key]]
                    if {$delta eq ""} {set deltas {}; break}
                    dict set deltas $key $delta
                }
                if {[dict size $deltas]!=4} {continue}
                set row [expr {[dict exists $databasePools $name $index]
                    ? [dict get $databasePools $name $index]
                    : {sqltime 0.0 waittime 0.0 statements 0 gethandles 0 seconds 0.0 samples 0}}]
                foreach key {sqltime waittime statements gethandles} {
                    dict set row $key [expr {[dict get $row $key]+[dict get $deltas $key]}]
                }
                dict set row seconds [expr {[dict get $row seconds]+$elapsed}]
                dict incr row samples
                dict set databasePools $name $index $row
            }
        }
        set previousRecord $record

        if {$validInterval && [dict exists $record linuxNetwork disks]
            && [dict exists $record previousLinuxNetwork disks]} {
            dict for {name current} [dict get $record linuxNetwork disks] {
                if {![dict exists $record previousLinuxNetwork disks $name]} {continue}
                if {![dict exists $disks $name] && [dict size $disks]>=8} {
                    dict set omittedDisks $name true
                    continue
                }
                set before [dict get $record previousLinuxNetwork disks $name]
                set deltas {}
                foreach key {reads readMs writes writeMs weightedIoMs ioMs} {
                    if {![dict exists $current $key] || ![dict exists $before $key]} {
                        set deltas {}
                        break
                    }
                    set delta [:nonnegativeDelta [dict get $current $key] [dict get $before $key]]
                    if {$delta eq ""} {set deltas {}; break}
                    dict set deltas $key $delta
                }
                if {[dict size $deltas]!=6} {continue}
                set row [expr {[dict exists $disks $name $index]
                    ? [dict get $disks $name $index]
                    : {reads 0 readMs 0.0 writes 0 writeMs 0.0 weightedIoMs 0.0 ioMs 0.0 seconds 0.0 samples 0}}]
                foreach key {reads readMs writes writeMs weightedIoMs ioMs} {
                    dict set row $key [expr {[dict get $row $key]+[dict get $deltas $key]}]
                }
                dict set row seconds [expr {[dict get $row seconds]+$elapsed}]
                dict incr row samples
                dict set disks $name $index $row
            }
        }
        if {![dict exists $record servers [$context server] pools]} {continue}
        dict for {candidate entry} [dict get $record servers [$context server] pools] {
            if {$pool ne "all" && $candidate ne $pool} {continue}
            if {![dict exists $entry gauges threads]} {continue}
            set threads [dict get $entry gauges threads]
            if {![dict exists $threads current] || ![dict exists $threads idle] || ![dict exists $threads max]} {continue}
            set current [dict get $threads current]
            set idle [dict get $threads idle]
            set max [dict get $threads max]
            if {![string is integer -strict $current] || ![string is integer -strict $idle]
                || ![string is integer -strict $max] || $current<0 || $idle<0 || $idle>$current || $max<0} {
                continue
            }
            if {![dict exists $pools $candidate]} {
                if {[dict size $pools]>=16} {continue}
                dict set pools $candidate [dict create busy [lrepeat $slots {}]  maximum [lrepeat $slots {}] samples [lrepeat $slots 0]  busyPercentMax [lrepeat $slots {}]  busyPercentSum [lrepeat $slots 0.0]  busyPercentValues [lrepeat $slots {}]  busyPercentSamples [lrepeat $slots 0]  waiting [lrepeat $slots {}] waitingSamples [lrepeat $slots 0]  slotUsed [lrepeat $slots {}] slotLimit [lrepeat $slots {}]  slotSamples [lrepeat $slots 0] fullSamples [lrepeat $slots 0]]
            }
            set busy [dict get $pools $candidate busy]
            set maximum [dict get $pools $candidate maximum]
            set samples [dict get $pools $candidate samples]
            set busyPercentMax [dict get $pools $candidate busyPercentMax]
            set busyPercentSum [dict get $pools $candidate busyPercentSum]
            set busyPercentValues [dict get $pools $candidate busyPercentValues]
            set busyPercentSamples [dict get $pools $candidate busyPercentSamples]
            set waiting [dict get $pools $candidate waiting]
            set waitingSamples [dict get $pools $candidate waitingSamples]
            set slotUsed [dict get $pools $candidate slotUsed]
            set slotLimit [dict get $pools $candidate slotLimit]
            set slotSamples [dict get $pools $candidate slotSamples]
            set fullSamples [dict get $pools $candidate fullSamples]
            set observed [expr {$current-$idle}]
            if {[lindex $busy $index] eq {} || $observed>[lindex $busy $index]} {
                lset busy $index $observed
            }
            lset maximum $index $max
            lset samples $index [expr {[lindex $samples $index]+1}]
            set stopping [expr {[dict exists $threads stopping] ? [dict get $threads stopping] : 0}]
            if {[string is integer -strict $stopping] && $stopping>=0 && $stopping<=$observed} {
                # Match nsstats' live utilization ratio: busy/current,
                # excluding threads that are stopping. Compute this
                # from each sample, not from independent bucket maxima.
                set percent [expr {$current>0
                    ? 100.0*($observed-$stopping)/$current : 0.0}]
                if {[lindex $busyPercentMax $index] eq {} ||
                    $percent>[lindex $busyPercentMax $index]} {
                    lset busyPercentMax $index $percent
                }
                lset busyPercentSum $index [expr {[lindex $busyPercentSum $index]+$percent}]
                lset busyPercentValues $index [linsert [lindex $busyPercentValues $index] end $percent]
                lset busyPercentSamples $index [expr {[lindex $busyPercentSamples $index]+1}]
            }
            if {[dict exists $entry gauges waitingRequests]} {
                set queued [dict get $entry gauges waitingRequests]
                if {[string is integer -strict $queued] && $queued>=0} {
                    if {[lindex $waiting $index] eq {} || $queued>[lindex $waiting $index]} {
                        lset waiting $index $queued
                    }
                    lset waitingSamples $index [expr {[lindex $waitingSamples $index]+1}]
                    if {[dict exists $record topologyId]
                        && [dict exists $h topologies [dict get $record topologyId] servers [$context server] pools $candidate maxconnections]} {
                        set limit [dict get $h topologies [dict get $record topologyId] servers [$context server] pools $candidate maxconnections]
                        set used [expr {$observed+$queued}]
                        if {[string is integer -strict $limit] && $limit>0 && $used<=$limit} {
                            if {[lindex $slotUsed $index] eq {} || $used>[lindex $slotUsed $index]} {
                                lset slotUsed $index $used
                            }
                            lset slotLimit $index $limit
                            lset slotSamples $index [expr {[lindex $slotSamples $index]+1}]
                            if {$used==$limit} {
                                lset fullSamples $index [expr {[lindex $fullSamples $index]+1}]
                            }
                        }
                    }
                }
            }
            dict set pools $candidate [dict create busy $busy maximum $maximum samples $samples  busyPercentMax $busyPercentMax busyPercentSum $busyPercentSum  busyPercentValues $busyPercentValues  busyPercentSamples $busyPercentSamples  waiting $waiting waitingSamples $waitingSamples  slotUsed $slotUsed slotLimit $slotLimit slotSamples $slotSamples fullSamples $fullSamples]
        }
    }
    if {![dict get $h more]} {break}
    set next [dict get $h nextCursor]
    if {![string is entier -strict $next] || $next<=$cursor || $pages>=12} {
        error "Pool thread history exceeded the bounded page budget"
    }
    set cursor $next
}
if {$pool ne "all" && ![dict exists $pools $pool]} {
    dict set pools $pool [dict create busy [lrepeat $slots {}]  maximum [lrepeat $slots {}] samples [lrepeat $slots 0]  busyPercentMax [lrepeat $slots {}]  busyPercentSum [lrepeat $slots 0.0]  busyPercentValues [lrepeat $slots {}]  busyPercentSamples [lrepeat $slots 0]  waiting [lrepeat $slots {}] waitingSamples [lrepeat $slots 0]  slotUsed [lrepeat $slots {}] slotLimit [lrepeat $slots {}]  slotSamples [lrepeat $slots 0] fullSamples [lrepeat $slots 0]]
}
set poolFields {}
dict for {name values} $pools {
    set busyPercentMean {}
    set busyPercentMedian {}
    for {set i 0} {$i<$slots} {incr i} {
        set count [lindex [dict get $values busyPercentSamples] $i]
        lappend busyPercentMean [expr {$count>0
            ? [lindex [dict get $values busyPercentSum] $i]/$count : ""}]
        if {$count==0} {
            lappend busyPercentMedian {}
        } else {
            set sorted [lsort -real [lindex [dict get $values busyPercentValues] $i]]
            set middle [expr {$count/2}]
            lappend busyPercentMedian [expr {$count%2
                ? [lindex $sorted $middle]
                : ([lindex $sorted [expr {$middle-1}]]+[lindex $sorted $middle])/2.0}]
        }
    }
    lappend poolFields $name object [list  busyMax array [:numericOrNullArray [dict get $values busy]]  configuredMax array [:numericOrNullArray [dict get $values maximum]]  sampleCount array [:numericArray [dict get $values samples]]  busyPercentMax array [:numericOrNullArray [dict get $values busyPercentMax]]  busyPercentMean array [:numericOrNullArray $busyPercentMean]  busyPercentMedian array [:numericOrNullArray $busyPercentMedian]  busyPercentSampleCount array [:numericArray [dict get $values busyPercentSamples]]  waitingMax array [:numericOrNullArray [dict get $values waiting]]  waitingSampleCount array [:numericArray [dict get $values waitingSamples]]  connectionSlotsUsedMax array [:numericOrNullArray [dict get $values slotUsed]]  maxConnections array [:numericOrNullArray [dict get $values slotLimit]]  slotSampleCount array [:numericArray [dict get $values slotSamples]]  capacityReachedSamples array [:numericArray [dict get $values fullSamples]]]
}
set databaseFields {}
dict for {name buckets} $databasePools {
    set sqlMsPerStatement {}
    set waitMsPerCheckout {}
    set sqlSecondsPerSecond {}
    set waitSecondsPerSecond {}
    set statementsPerSecond {}
    set checkoutsPerSecond {}
    set observedSeconds {}
    set sampleCount {}
    for {set i 0} {$i<$slots} {incr i} {
        if {[dict exists $buckets $i]} {
            set row [dict get $buckets $i]
            set seconds [dict get $row seconds]
            set statements [dict get $row statements]
            set checkouts [dict get $row gethandles]
            lappend sqlMsPerStatement [expr {$statements>0 ? 1000.0*[dict get $row sqltime]/$statements : ""}]
            lappend waitMsPerCheckout [expr {$checkouts>0 ? 1000.0*[dict get $row waittime]/$checkouts : ""}]
            lappend sqlSecondsPerSecond [expr {[dict get $row sqltime]/$seconds}]
            lappend waitSecondsPerSecond [expr {[dict get $row waittime]/$seconds}]
            lappend statementsPerSecond [expr {$statements/$seconds}]
            lappend checkoutsPerSecond [expr {$checkouts/$seconds}]
            lappend observedSeconds $seconds
            lappend sampleCount [dict get $row samples]
        } else {
            foreach variable {sqlMsPerStatement waitMsPerCheckout sqlSecondsPerSecond waitSecondsPerSecond statementsPerSecond checkoutsPerSecond} {
                lappend $variable {}
            }
            lappend observedSeconds 0
            lappend sampleCount 0
        }
    }
    lappend databaseFields $name object [list  sqlMsPerStatement array [:numericOrNullArray $sqlMsPerStatement]  waitMsPerCheckout array [:numericOrNullArray $waitMsPerCheckout]  sqlSecondsPerSecond array [:numericOrNullArray $sqlSecondsPerSecond]  waitSecondsPerSecond array [:numericOrNullArray $waitSecondsPerSecond]  statementsPerSecond array [:numericOrNullArray $statementsPerSecond]  checkoutsPerSecond array [:numericOrNullArray $checkoutsPerSecond]  observedSeconds array [:numericArray $observedSeconds]  sampleCount array [:numericArray $sampleCount]]
}
set diskFields {}
dict for {name buckets} $disks {
    set readLatencyMs {}
    set writeLatencyMs {}
    set averageQueueDepth {}
    set utilizationPercent {}
    set readOpsPerSecond {}
    set writeOpsPerSecond {}
    set observedSeconds {}
    set sampleCount {}
    for {set i 0} {$i<$slots} {incr i} {
        if {[dict exists $buckets $i]} {
            set row [dict get $buckets $i]
            set seconds [dict get $row seconds]
            set reads [dict get $row reads]
            set writes [dict get $row writes]
            lappend readLatencyMs [expr {$reads>0 ? double([dict get $row readMs])/$reads : ""}]
            lappend writeLatencyMs [expr {$writes>0 ? double([dict get $row writeMs])/$writes : ""}]
            lappend averageQueueDepth [expr {[dict get $row weightedIoMs]/($seconds*1000.0)}]
            lappend utilizationPercent [expr {[dict get $row ioMs]/($seconds*10.0)}]
            lappend readOpsPerSecond [expr {$reads/$seconds}]
            lappend writeOpsPerSecond [expr {$writes/$seconds}]
            lappend observedSeconds $seconds
            lappend sampleCount [dict get $row samples]
        } else {
            foreach variable {readLatencyMs writeLatencyMs averageQueueDepth utilizationPercent readOpsPerSecond writeOpsPerSecond} {
                lappend $variable {}
            }
            lappend observedSeconds 0
            lappend sampleCount 0
        }
    }
    lappend diskFields $name object [list  readLatencyMs array [:numericOrNullArray $readLatencyMs]  writeLatencyMs array [:numericOrNullArray $writeLatencyMs]  averageQueueDepth array [:numericOrNullArray $averageQueueDepth]  utilizationPercent array [:numericOrNullArray $utilizationPercent]  readOpsPerSecond array [:numericOrNullArray $readOpsPerSecond]  writeOpsPerSecond array [:numericOrNullArray $writeOpsPerSecond]  observedSeconds array [:numericArray $observedSeconds]  sampleCount array [:numericArray $sampleCount]]
}
set resources [list scope string process from number $first to number $end bucketSeconds number $bucket  databasePools object $databaseFields disks object $diskFields  coverage object [list databaseSourceAvailable boolean $databaseSourceAvailable  diskSourceAvailable boolean $diskSourceAvailable  omittedDatabasePools number [dict size $omittedDatabasePools]  omittedDisks number [dict size $omittedDisks]]  limitations string {Database SQL and handle-wait times are cumulative ns_db pool counters; each plotted bucket uses valid adjacent retained samples and reports observedSeconds. A missing baseline, reset, invalid counter or history gap leaves the corresponding interval unknown. SQL seconds per second can exceed one when handles execute concurrently. Mean SQL milliseconds per statement can hide slow outliers. Disk latency is operation-weighted; average queue depth is time-weighted. Disk counters cover all users of the device, not only NaviServer. Samples crossing bucket boundaries are assigned by sample end. Neither temporal overlap nor a common peak establishes causation.}]
set driverPeak {available boolean false}
if {$driverPeakTotal>=0} {
    set ranked {}
    dict for {name value} $driverPeakValues {lappend ranked [list $value $name]}
    set driverFields {}
    foreach entry [lrange [lsort -decreasing -integer -index 0 $ranked] 0 15] {
        lassign $entry value name
        lappend driverFields $name number $value
    }
    set driverPeak [list available boolean true at number $driverPeakAt  bucketFrom number [expr {$first+$driverPeakBucket*$bucket}]  waiting number $driverPeakTotal byDriver object $driverFields  omittedDrivers number [expr {max(0,[llength $ranked]-16)}]]
}
set fields [list pool string $pool from number $first to number $end bucketSeconds number $bucket  pools object $poolFields  driverBacklog object [list scope string process  waitingMax array [:numericOrNullArray $driverWaiting]  sampleCount array [:numericArray $driverSamples]  peakDetails object $driverPeak]  resourceIndicators object $resources totalSamples number $total  coverage object [:encode coverage [dict get $h coverage]]  limitations string {busyMax is the highest sampled current-minus-idle thread count in each bucket, not an exact peak. configuredMax is the last sampled thread limit. busyPercentMean, busyPercentMedian and busyPercentMax use the per-sample ratio of current-minus-idle-minus-stopping to current threads, matching the utilization page; the mean averages retained sample ratios, the median is the middle retained ratio (or average of the middle two), and the maximum is the highest retained sample ratio. None is time-weighted; 100 percent busy does not prove that maxconnections was reached. busyPercentSampleCount is their denominator. waitingMax is the highest retained ns_stats waitingRequests gauge; it can miss peaks between samples. connectionSlotsUsedMax is the highest per-sample current-minus-idle plus waiting value, not the sum of bucket maxima. maxConnections comes from the matching retained topology. capacityReachedSamples counts valid samples at that limit; slotSampleCount is its denominator. Thread and waiting gauges are read separately, so a transitional mismatch above the configured limit is omitted. Missing occupancy and waiting samples are null, not zero. A full pool with rejectoverrun disabled can leave additional sockets waiting in the driver; the pool waiting gauge does not count them. driverBacklog sums the sampled waitingForConnection socket gauge across all reported driver entries, without pool attribution; peakDetails shows each driver's contribution in the same peak sample, not the sum of independent bucket maxima. It is not a count of all network backlog. Slow-log threshold counts have different units.}]
return $fields
XQL Not present:
Generic, PostgreSQL, Oracle
[ hide source ] | [ make this the default ]
Show another procedure: