Back to index

d-push  2.0
Public Member Functions | Private Member Functions | Private Attributes
ZPushTop Class Reference

List of all members.

Public Member Functions

 ZPushTop ()
 Constructor.
 run ()
 Main loop of Z-Push-top Runs until termination is requested.
 IsAvailable ()
 Indicates if TopCollector is available collecting data.
 SignalHandler ($signo)
 Signal handler function.
 scrClear ()
 Clears screen of the terminal.

Private Member Functions

 initialize ()
 Requests data from the running Z-Push processes.
 processData ($data)
 Processes data written by the running processes.
 scrOverview ()
 Prints data to the terminal.
 readLineProcess ()
 Waits for a keystroke and processes the requested command.
 scrHelp ()
 Prints a 'help' text at the end of the page.
 scrAsBold ($text)
 Encapsulates string with different color escape characters.
 getLine ($l)
 Prints one line of precessed data.
 ptStr ($str, $size, $cutmiddle=false)
 Pads and trims string.
 scrGetSize ()
 Tries to discover the size of the current terminal.
 getVersion ()
 Returns the version of the current Z-Push installation.
 sec2min ($s)
 Converts seconds in MM:SS.
 scrDefaultColors ()
 Resets the default colors of the terminal.
 scrPrintAt ($row, $col, $text="")
 Prints a text at a specific screen/terminal coordinates.

Private Attributes

 $topCollector
 $starttime
 $action
 $filter
 $status
 $statusexpire
 $wide
 $wasEnabled
 $terminate
 $scrSize
 $pingInterval
 $linesUpdate = array()
 $linesActive = array()
 $linesUnknown = array()
 $linesTerm = array()
 $pushConn = 0
 $activeConn = array()
 $activeHosts = array()
 $activeUsers = array()
 $activeDevices = array()

Detailed Description

Definition at line 89 of file z-push-top.php.


Member Function Documentation

ZPushTop::getLine ( l) [private]

Prints one line of precessed data.

Parameters:
array$lline information

private

Returns:
string

Definition at line 540 of file z-push-top.php.

                                 {
        if ($this->wide === true)
            return sprintf("%s%s%s%s%s%s%s%s", $this->ptStr($l['pid'],6), $this->ptStr($l['ip'],16), $this->ptStr($l['user'],16), $this->ptStr($l['command'],16), $this->ptStr($this->sec2min($l['time']),8), $this->ptStr($l['devagent'],28), $this->ptStr($l['devid'],40, true), $l['addinfo']);
        else
            return sprintf("%s%s%s%s%s%s%s%s", $this->ptStr($l['pid'],6), $this->ptStr($l['ip'],10), $this->ptStr($l['user'],8), $this->ptStr($l['command'],11), $this->ptStr($this->sec2min($l['time']),6), $this->ptStr($l['devagent'],20), $this->ptStr($l['devid'],18, true), $l['addinfo']);
    }

Here is the call graph for this function:

Here is the caller graph for this function:

ZPushTop::getVersion ( ) [private]

Returns the version of the current Z-Push installation.

private

Returns:
string

Definition at line 590 of file z-push-top.php.

                                  {
        if (ZPUSH_VERSION == "SVN checkout" && file_exists(REAL_BASE_PATH.".svn/entries")) {
            $svn = file(REAL_BASE_PATH.".svn/entries");
            return "SVN " . substr(trim($svn[4]),stripos($svn[4],"z-push")+7) ." r".trim($svn[3]);
        }
        return ZPUSH_VERSION;
    }

Here is the caller graph for this function:

ZPushTop::initialize ( ) [private]

Requests data from the running Z-Push processes.

private

Returns:

Definition at line 141 of file z-push-top.php.

                                  {
        // request feedback from active processes
        $this->wasEnabled = $this->topCollector->CollectData();

        // remove obsolete data
        $this->topCollector->ClearLatest(true);

        // start with default colours
        $this->scrDefaultColors();
    }

Here is the call graph for this function:

Here is the caller graph for this function:

Indicates if TopCollector is available collecting data.

public

Returns:
boolean

Definition at line 205 of file z-push-top.php.

                                  {
        return $this->topCollector->IsActive();
    }

Here is the caller graph for this function:

ZPushTop::processData ( data) [private]

Processes data written by the running processes.

Parameters:
array$dataprivate
Returns:

Definition at line 217 of file z-push-top.php.

                                        {
        $this->linesUpdate = array();
        $this->linesActive = array();
        $this->linesUnknown = array();
        $this->linesTerm = array();
        $this->pushConn = 0;
        $this->activeConn = array();
        $this->activeHosts = array();
        $this->activeUsers = array();
        $this->activeDevices = array();

        if (!is_array($data))
            return;

        foreach ($data as $devid=>$users) {
            foreach ($users as $user=>$pids) {
                foreach ($pids as $pid=>$line) {
                    if (!is_array($line))
                        continue;

                    $line['command'] = Utils::GetCommandFromCode($line['command']);

                    if ($line["ended"] == 0) {
                        $this->activeDevices[$devid] = 1;
                        $this->activeUsers[$user] = 1;
                        $this->activeConn[$pid] = 1;
                        $this->activeHosts[$line['ip']] = 1;

                        $line["time"] = $this->currenttime - $line['start'];
                        if ($line['push'] === true) $this->pushConn += 1;

                        if ($this->filter !== false) {
                            $f = $this->filter;
                            if (!($line["pid"] == $f || $line["ip"] == $f || strtolower($line['command']) == strtolower($f) || preg_match("/.*?$f.*?/i", $line['user']) ||
                                preg_match("/.*?$f.*?/i", $line['devagent']) || preg_match("/.*?$f.*?/i", $line['devid']) || preg_match("/.*?$f.*?/i", $line['addinfo']) ))
                                continue;
                        }

                        $lastUpdate = $this->currenttime - $line["update"];
                        if ($this->currenttime - $line["update"] < 2)
                            $this->linesUpdate[$line["update"].$line["pid"]] = $line;
                        else if (($line['push'] === true  && $lastUpdate > ($this->pingInterval+2)) || ($line['push'] !== true  && $lastUpdate > 4))
                            $this->linesUnknown[$line["update"].$line["pid"]] = $line;
                        else
                            $this->linesActive[$line["update"].$line["pid"]] = $line;
                    }
                    else {
                        if ($this->filter !== false) {
                            $f = $this->filter;
                            if (!($line['pid'] == $f || $line['ip'] == $f || strtolower($line['command']) == strtolower($f) || preg_match("/.*?$f.*?/i", $line['user']) ||
                                preg_match("/.*?$f.*?/i", $line['devagent']) || preg_match("/.*?$f.*?/i", $line['devid']) || preg_match("/.*?$f.*?/i", $line['addinfo']) ))
                                continue;
                        }

                        $line['time'] = $line['ended'] - $line['start'];
                        $this->linesTerm[$line['update'].$line['pid']] = $line;
                    }
                }
            }
        }

        // sort by execution time
        krsort($this->linesUpdate);
        krsort($this->linesActive);
        krsort($this->linesUnknown);
        krsort($this->linesTerm);
    }

Here is the call graph for this function:

Here is the caller graph for this function:

ZPushTop::ptStr ( str,
size,
cutmiddle = false 
) [private]

Pads and trims string.

Parameters:
string$stringto be trimmed/padded
int$sizecharacters to be considered
boolean$cutmiddle(optional) indicates where to long information should be trimmed of, false means at the end

private

Returns:
string

Definition at line 558 of file z-push-top.php.

                                                            {
        if (strlen($str) < $size)
            return str_pad($str, $size);
        else if ($cutmiddle == true) {
            $cut = ($size-2)/2;
            return $this->ptStr(substr($str,0,$cut) ."..". substr($str,(-1)*($cut-1)), $size);
        }
        else {
            return substr($str,0,$size-3).".. ";
        }
    }

Here is the caller graph for this function:

Waits for a keystroke and processes the requested command.

private

Returns:

Definition at line 394 of file z-push-top.php.

                                       {
        $ans = explode("^^", `bash -c "read -n 1 -t 1 ANS ; echo \\\$?^^\\\$ANS;"`);

        if ($ans[0] < 128) {
            if (isset($ans[1]) && bin2hex(trim($ans[1])) == "7f") {
                $this->action = substr($this->action,0,-1);
            }

            if (isset($ans[1]) && $ans[1] != "" ){
                $this->action .= trim(preg_replace("/[^A-Za-z0-9:]/","",$ans[1]));
            }

            if (bin2hex($ans[0]) == "30" && bin2hex($ans[1]) == "0a")  {
                $cmds = explode(':', $this->action);
                if ($cmds[0] == "quit" || $cmds[0] == "q" || (isset($cmds[1]) && $cmds[0] == "" && $cmds[1] == "q")) {
                    $this->topCollector->CollectData(true);
                    $this->topCollector->ClearLatest(true);

                    $this->terminate = true;
                }
                else if ($cmds[0] == "clear" ) {
                    $this->topCollector->ClearLatest(true);
                    $this->topCollector->CollectData(true);
                    $this->topCollector->ReInitSharedMem();
                }
                else if ($cmds[0] == "filter" || $cmds[0] == "f") {
                    if (!isset($cmds[1]) || $cmds[1] == "") {
                        $this->filter = false;
                        $this->status = "No filter";
                        $this->statusexpire = $this->currenttime+5;
                    }
                    else {
                        $this->filter = $cmds[1];
                        $this->status = false;
                    }
                }
                else if ($cmds[0] == "reset" || $cmds[0] == "r") {
                    $this->filter = false;
                    $this->wide = false;
                    $this->helpexpire = 0;
                    $this->status = "resetted";
                    $this->statusexpire = $this->currenttime+2;
                }
                else if ($cmds[0] == "wide" || $cmds[0] == "w") {
                    $this->wide = true;
                    $this->status = "w i d e  view";
                    $this->statusexpire = $this->currenttime+2;
                }
                else if ($cmds[0] == "help" || $cmds[0] == "h") {
                    $this->helpexpire = $this->currenttime+20;
                }
                else if (($cmds[0] == "log" || $cmds[0] == "l") && isset($cmds[1]) ) {
                    if (!file_exists(LOGFILE)) {
                        $this->status = "Logfile can not be found: ". LOGFILE;
                    }
                    else {
                        system('bash -c "fgrep -a '.escapeshellarg($cmds[1]).' '. LOGFILE .' | less +G" > `tty`');
                        $this->status = "Returning from log, updating data";
                    }
                    $this->statusexpire = time()+5; // it might be much "later" now
                }
                else if (($cmds[0] == "tail" || $cmds[0] == "t")) {
                    if (!file_exists(LOGFILE)) {
                        $this->status = "Logfile can not be found: ". LOGFILE;
                    }
                    else {
                        $this->doingTail = true;
                        $this->scrClear();
                        $this->scrPrintAt(1,0,$this->scrAsBold("Press CTRL+C to return to Z-Push-Top\n\n"));
                        $secondary = "";
                        if (isset($cmds[1])) $secondary =  " -n 200 | grep ".escapeshellarg($cmds[1]);
                        system('bash -c "tail -f '. LOGFILE . $secondary . '" > `tty`');
                        $this->doingTail = false;
                        $this->status = "Returning from tail, updating data";
                    }
                    $this->statusexpire = time()+5; // it might be much "later" now
                }

                else if ($cmds[0] != "") {
                    $this->status = sprintf("Command '%s' unknown", $cmds[0]);
                    $this->statusexpire = $this->currenttime+8;
                }
                $this->action = "";
            }
        }
    }

Here is the call graph for this function:

Here is the caller graph for this function:

Main loop of Z-Push-top Runs until termination is requested.

public

Returns:

Definition at line 159 of file z-push-top.php.

                          {
        $this->initialize();

        do {
            $this->currenttime = time();

            // see if shared memory is active
            if (!$this->IsAvailable())
                $this->terminate = true;

            // active processes should continue sending data
            $this->topCollector->CollectData();

            // get and process data from processes
            $this->topCollector->ClearLatest();
            $topdata = $this->topCollector->ReadLatest();
            $this->processData($topdata);

            // clear screen
            $this->scrClear();

            // check if screen size changed
            $s = $this->scrGetSize();
            if ($this->scrSize['width'] != $s['width']) {
                if ($s['width'] > 180)
                    $this->wide = true;
                else
                    $this->wide = false;
            }
            $this->scrSize = $s;

            // print overview
            $this->scrOverview();

            // wait for user input
            $this->readLineProcess();
        }
        while($this->terminate != true);
    }

Here is the call graph for this function:

ZPushTop::scrAsBold ( text) [private]

Encapsulates string with different color escape characters.

Parameters:
string$textprivate
Returns:
string same text as bold

Definition at line 528 of file z-push-top.php.

                                      {
        return "\033[01m" . $text  ."\033[0m";
    }

Here is the caller graph for this function:

Clears screen of the terminal.

Parameters:
array$dataprivate
Returns:

Definition at line 630 of file z-push-top.php.

                               {
        echo "\033[2J";
    }

Here is the caller graph for this function:

Resets the default colors of the terminal.

private

Returns:

Definition at line 618 of file z-push-top.php.

                                        {
        echo "\033[0m";
    }

Here is the caller graph for this function:

ZPushTop::scrGetSize ( ) [private]

Tries to discover the size of the current terminal.

private

Returns:
array 'width' and 'height' as keys

Definition at line 576 of file z-push-top.php.

                                  {
        preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a | fgrep columns')), $output);
        if(sizeof($output) == 3)
            return array('width' => $output[2][0], 'height' => $output[1][0]);

        return array('width' => 80, 'height' => 24);
    }

Here is the caller graph for this function:

ZPushTop::scrHelp ( ) [private]

Prints a 'help' text at the end of the page.

private

Returns:
array with help lines

Definition at line 504 of file z-push-top.php.

                               {
        $h = array();
        $secs = $this->helpexpire - $this->currenttime;
        $h[] = "Actions supported by Z-Push-Top (help page still displayed for ".$secs."secs)";
        $h[] = "  ".$this->scrAsBold("Action")."\t\t".$this->scrAsBold("Comment");
        $h[] = "  ".$this->scrAsBold("h")." or ".$this->scrAsBold("help")."\t\tDisplays this information.";
        $h[] = "  ".$this->scrAsBold("q").", ".$this->scrAsBold("quit")." or ".$this->scrAsBold(":q")."\t\tExits Z-Push-Top.";
        $h[] = "  ".$this->scrAsBold("w")." or ".$this->scrAsBold("wide")."\t\tTries not to truncate data. Automatically done if more than 180 columns available.";
        $h[] = "  ".$this->scrAsBold("f:VAL")." or ".$this->scrAsBold("filter:VAL")."\tOnly display connections which contain VAL. This value is case-insensitive.";
        $h[] = "  ".$this->scrAsBold("f:")." or ".$this->scrAsBold("filter:")."\t\tWithout a search word: resets the filter.";
        $h[] = "  ".$this->scrAsBold("l:STR")." or ".$this->scrAsBold("log:STR")."\tIssues 'less +G' on the logfile, after grepping on the optional STR.";
        $h[] = "  ".$this->scrAsBold("t:STR")." or ".$this->scrAsBold("tail:STR")."\tIssues 'tail -f' on the logfile, grepping for optional STR.";
        $h[] = "  ".$this->scrAsBold("r")." or ".$this->scrAsBold("reset")."\t\tResets 'wide' or 'filter'.";
        return $h;
    }

Here is the call graph for this function:

Here is the caller graph for this function:

ZPushTop::scrOverview ( ) [private]

Prints data to the terminal.

private

Returns:

Definition at line 291 of file z-push-top.php.

                                   {
        $linesAvail = $this->scrSize['height'] - 8;
        $lc = 1;
        $this->scrPrintAt($lc,0, "\033[1mZ-Push top live statistics\033[0m\t\t\t\t\t". @strftime("%d/%m/%Y %T")."\n"); $lc++;

        $this->scrPrintAt($lc,0, sprintf("Open connections: %d\t\t\t\tUsers:\t %d\tZ-Push:   %s ",count($this->activeConn),count($this->activeUsers), $this->getVersion())); $lc++;
        $this->scrPrintAt($lc,0, sprintf("Push connections: %d\t\t\t\tDevices: %d\tPHP-MAPI: %s", $this->pushConn, count($this->activeDevices),phpversion("mapi"))); $lc++;
        $this->scrPrintAt($lc,0, sprintf("                                                Hosts:\t %d", $this->pushConn, count($this->activeHosts))); $lc++;
        $lc++;

        $this->scrPrintAt($lc,0, "\033[4m". $this->getLine(array('pid'=>'PID', 'ip'=>'IP', 'user'=>'USER', 'command'=>'COMMAND', 'time'=>'TIME', 'devagent'=>'AGENT', 'devid'=>'DEVID', 'addinfo'=>'Additional Information')). str_repeat(" ",20)."\033[0m"); $lc++;

        // print help text if requested
        if ($this->helpexpire > $this->currenttime) {
            $help = $this->scrHelp();
            $linesAvail -= count($help);
            $hl = $this->scrSize['height'] - count($help) -1;
            foreach ($help as $h) {
                $this->scrPrintAt($hl,0, $h);
                $hl++;
            }
        }

        $toPrintUpdate = $linesAvail;
        $toPrintActive = $linesAvail;
        $toPrintUnknown = $linesAvail;

        // TODO this could be optimized to use the max amount of lines available on the screen
        if (count($this->linesUpdate) + count($this->linesActive) + count($this->linesUnknown) > $linesAvail) {
            $toPrintUpdate = $linesAvail/3;
            $toPrintActive = $linesAvail/3;
            $toPrintUnknown = $linesAvail/3;
        }

        $linesprinted = 0;
        foreach ($this->linesUpdate as $time=>$l) {
            $this->scrPrintAt($lc,0, "\033[01m" . $this->getLine($l)  ."\033[0m");
            $lc++;
            $linesprinted++;
            if ($linesprinted >= $toPrintUpdate)
                break;
        }

        $linesprinted = 0;
        foreach ($this->linesActive as $time=>$l) {
            $this->scrPrintAt($lc,0, $this->getLine($l));
            $lc++;
            $linesprinted++;
            if ($linesprinted >= $toPrintActive)
                break;
        }

        $linesprinted = 0;
        foreach ($this->linesUnknown as $time=>$l) {
            $color = "0;31m";
            if ($l['push'] == false && $time - $l["start"] > 30)
                $color = "1;31m";
            $this->scrPrintAt($lc,0, "\033[0". $color . $this->getLine($l)  ."\033[0m");
            $lc++;
            $linesprinted++;
            if ($linesprinted >= $toPrintUnknown)
                break;
        }

        foreach ($this->linesTerm as $time=>$l){
            $this->scrPrintAt($lc,0, "\033[01;30m" . $this->getLine($l)  ."\033[0m");
            $lc++;
            if ($lc > $linesAvail+6)
                break;
        }
        $this->scrPrintAt($lc,0, "\033[K"); $lc++;
        $this->scrPrintAt($lc,0, "Colorscheme: \033[01mActive  \033[0mOpen  \033[01;31mUnknown  \033[01;30mTerminated\033[0m");

        // remove old status
        if ($this->statusexpire < $this->currenttime)
            $this->status = false;

        // show request information and help command
        if ($this->starttime + 6 > $this->currenttime) {
            $this->status = sprintf("Requesting information (takes up to %dsecs)", $this->pingInterval). str_repeat(".", ($this->currenttime-$this->starttime)) . "  type \033[01;31mh\033[00;31m or \033[01;31mhelp\033[00;31m for usage instructions";
            $this->statusexpire = $this->currenttime+1;
        }

        if ($this->filter !== false || ($this->status !== false && $this->statusexpire > $this->currenttime)) {
            $str = "";
            // print filter in green
            if ($this->filter !== false)
                $str = "\033[00;32mFilter: \033[01;32m$this->filter\033[0m   ";
            // print status in red
            if ($this->status !== false)
                $str .= "\033[00;31m$this->status\033[0m";
            $this->scrPrintAt(5,0, $str);
        }

        $this->scrPrintAt(4,0,"Action: \033[01m".$this->action . "\033[0m");
    }

Here is the call graph for this function:

Here is the caller graph for this function:

ZPushTop::scrPrintAt ( row,
col,
text = "" 
) [private]

Prints a text at a specific screen/terminal coordinates.

Parameters:
int$rowrow number
int$colcolumn number
string$textto be printed

private

Returns:

Definition at line 644 of file z-push-top.php.

                                                      {
        echo "\033[".$row.";".$col."H".$text;
    }

Here is the caller graph for this function:

ZPushTop::sec2min ( s) [private]

Converts seconds in MM:SS.

Parameters:
int$sseconds

private

Returns:
string

Definition at line 606 of file z-push-top.php.

                                 {
        if (!is_int($s))
            return $s;
        return sprintf("%02.2d:%02.2d", floor($s/60), $s%60);
    }

Here is the caller graph for this function:

Signal handler function.

Parameters:
int$signosignal number

public

Returns:

Definition at line 489 of file z-push-top.php.

                                          {
        // don't terminate if the signal was sent by terminating tail
        if (!$this->doingTail) {
            $this->topCollector->CollectData(true);
            $this->topCollector->ClearLatest(true);
            $this->terminate = true;
        }
    }

Constructor.

public

Definition at line 117 of file z-push-top.php.

                               {
        $this->starttime = time();
        $this->currenttime = time();
        $this->action = "";
        $this->filter = false;
        $this->status = false;
        $this->statusexpire = 0;
        $this->helpexpire = 0;
        $this->doingTail = false;
        $this->wide = false;
        $this->terminate = false;
        $this->scrSize = array('width' => 80, 'height' => 24);
        $this->pingInterval = (defined('PING_INTERVAL') && PING_INTERVAL > 0) ? PING_INTERVAL : 12;

        // get a TopCollector
        $this->topCollector = new TopCollector();
    }

Member Data Documentation

ZPushTop::$action [private]

Definition at line 92 of file z-push-top.php.

ZPushTop::$activeConn = array() [private]

Definition at line 107 of file z-push-top.php.

ZPushTop::$activeDevices = array() [private]

Definition at line 110 of file z-push-top.php.

ZPushTop::$activeHosts = array() [private]

Definition at line 108 of file z-push-top.php.

ZPushTop::$activeUsers = array() [private]

Definition at line 109 of file z-push-top.php.

ZPushTop::$filter [private]

Definition at line 93 of file z-push-top.php.

ZPushTop::$linesActive = array() [private]

Definition at line 103 of file z-push-top.php.

ZPushTop::$linesTerm = array() [private]

Definition at line 105 of file z-push-top.php.

ZPushTop::$linesUnknown = array() [private]

Definition at line 104 of file z-push-top.php.

ZPushTop::$linesUpdate = array() [private]

Definition at line 102 of file z-push-top.php.

Definition at line 100 of file z-push-top.php.

ZPushTop::$pushConn = 0 [private]

Definition at line 106 of file z-push-top.php.

ZPushTop::$scrSize [private]

Definition at line 99 of file z-push-top.php.

Definition at line 91 of file z-push-top.php.

ZPushTop::$status [private]

Definition at line 94 of file z-push-top.php.

Definition at line 95 of file z-push-top.php.

Definition at line 98 of file z-push-top.php.

Definition at line 90 of file z-push-top.php.

Definition at line 97 of file z-push-top.php.

ZPushTop::$wide [private]

Definition at line 96 of file z-push-top.php.


The documentation for this class was generated from the following file: