Write statistics data to disk.

@return void
773926
protected static function writeStatisticsToStatusFile()
    {
        // For master process.
        if (self::$_masterPid === getmypid()) {
            $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
            file_put_contents(self::$_statisticsFile,
                "---------------------------------------GLOBAL STATUS--------------------------------------------\n");
            file_put_contents(self::$_statisticsFile,
                'Swoole version:' . phpversion('swoole') . "          PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
            file_put_contents(self::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
                    self::$_globalStatistics['start_timestamp']) . '   run ' . floor((time() - self::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . floor(((time() - self::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours   \n",
                FILE_APPEND);
            $load_str = 'load average: ' . implode(", ", $loadavg);
            file_put_contents(self::$_statisticsFile,
                str_pad($load_str, 33) . 'event-loop:' . self::getEventLoopName() . "\n", FILE_APPEND);
            file_put_contents(self::$_statisticsFile,
                count(self::$_pidMap) . ' workers       ' . count(self::getAllWorkerPids()) . " processes\n",
                FILE_APPEND);
            file_put_contents(self::$_statisticsFile,
                str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status     exit_count\n", FILE_APPEND);
            foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
                $worker = self::$_workers[$worker_id];
                if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
                    foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
                        file_put_contents(self::$_statisticsFile,
                            str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
                                16) . " $worker_exit_count\n", FILE_APPEND);
                    }
                } else {
                    file_put_contents(self::$_statisticsFile,
                        str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
                        FILE_APPEND);
                }
            }
            file_put_contents(self::$_statisticsFile,
                "---------------------------------------PROCESS STATUS-------------------------------------------\n",
                FILE_APPEND);
            file_put_contents(self::$_statisticsFile,
                "pid\tmemory  " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name',
                    self::$_maxWorkerNameLength) . " connections " . str_pad('total_request',
                    13) . " " . str_pad('send_fail', 9) . " " . str_pad('throw_exception', 15) . "\n", FILE_APPEND);

            chmod(self::$_statisticsFile, 0722);

            foreach (self::getAllWorkerPids() as $worker_pid) {
                swoole_process::kill($worker_pid, SIGUSR2);
            }
            return;
        }

        // For child processes.
        /** @var Worker $worker */
        $worker           = current(self::$_workers);
        $worker_status_str = getmypid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M",
                7) . " " . str_pad($worker->getSocketName(),
                self::$_maxSocketNameLength) . " " . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name),
                self::$_maxWorkerNameLength) . " ";
        $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'],
                11) . " " . str_pad(ConnectionInterface::$statistics['total_request'],
                14) . " " . str_pad(ConnectionInterface::$statistics['send_fail'],
                9) . " " . str_pad(ConnectionInterface::$statistics['throw_exception'], 15) . "\n";
        file_put_contents(self::$_statisticsFile, $worker_status_str, FILE_APPEND);
    }
1239434
def dump_stats(self):
        """"""
        log.info('Dumping statistics:')
        stats = []
        stats.append(
            'client-request-errors {}'.format(self._client_request_errors))
        stats.append('denied-allocations {}'.format(self._denied_allocations))
        stats.append('num-ports-managed {}'.format(self._port_pool.num_ports()))
        stats.append('num-ports-checked-for-last-request {}'.format(
            self._port_pool.ports_checked_for_last_request))
        stats.append('total-allocations {}'.format(self._total_allocations))
        for stat in stats:
            log.info(stat)
1176411
protected static function writeStatisticsToStatusFile()
    {
        // For master process.
        if (static::$_masterPid === posix_getpid()) {
            $all_worker_info = array();
            foreach(static::$_pidMap as $worker_id => $pid_array) {
                /** @var /Workerman/Worker $worker */
                $worker = static::$_workers[$worker_id];
                foreach($pid_array as $pid) {
                    $all_worker_info[$pid] = array('name' => $worker->name, 'listen' => $worker->getSocketName());
                }
            }

            file_put_contents(static::$_statisticsFile, json_encode($all_worker_info)."\n", FILE_APPEND);
            $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
            file_put_contents(static::$_statisticsFile,
                "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
            file_put_contents(static::$_statisticsFile,
                'Workerman version:' . static::VERSION . "          PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
            file_put_contents(static::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
                    static::$_globalStatistics['start_timestamp']) . '   run ' . floor((time() - static::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . floor(((time() - static::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours   \n",
                FILE_APPEND);
            $load_str = 'load average: ' . implode(", ", $loadavg);
            file_put_contents(static::$_statisticsFile,
                str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", FILE_APPEND);
            file_put_contents(static::$_statisticsFile,
                count(static::$_pidMap) . ' workers       ' . count(static::getAllWorkerPids()) . " processes\n",
                FILE_APPEND);
            file_put_contents(static::$_statisticsFile,
                str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status      exit_count\n", FILE_APPEND);
            foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
                $worker = static::$_workers[$worker_id];
                if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
                    foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
                        file_put_contents(static::$_statisticsFile,
                            str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
                                16) . " $worker_exit_count\n", FILE_APPEND);
                    }
                } else {
                    file_put_contents(static::$_statisticsFile,
                        str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
                        FILE_APPEND);
                }
            }
            file_put_contents(static::$_statisticsFile,
                "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
                FILE_APPEND);
            file_put_contents(static::$_statisticsFile,
                "pid\tmemory  " . str_pad('listening', static::$_maxSocketNameLength) . " " . str_pad('worker_name',
                    static::$_maxWorkerNameLength) . " connections " . str_pad('send_fail', 9) . " "
                . str_pad('timers', 8) . str_pad('total_request', 13) ." qps    status\n", FILE_APPEND);

            chmod(static::$_statisticsFile, 0722);

            foreach (static::getAllWorkerPids() as $worker_pid) {
                posix_kill($worker_pid, SIGUSR2);
            }
            return;
        }

        // For child processes.
        reset(static::$_workers);
        /** @var \Workerman\Worker $worker */
        $worker            = current(static::$_workers);
        $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
            . " " . str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
            . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
            . " ";
        $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'], 11)
            . " " .  str_pad(ConnectionInterface::$statistics['send_fail'], 9)
            . " " . str_pad(static::$globalEvent->getTimerCount(), 7)
            . " " . str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
        file_put_contents(static::$_statisticsFile, $worker_status_str, FILE_APPEND);
    }
7385
private function write_header()
    {
        $this->write(DataIO::magic());
        $this->datum_writer->write_data(DataIO::metadata_schema(),
            $this->metadata, $this->encoder);
        $this->write($this->sync_marker);
    }
213618
def report_saved(report_stats):
    """"""
    if Settings.verbose:
        report = ''
        truncated_filename = truncate_cwd(report_stats.final_filename)

        report += '{}: '.format(truncated_filename)
        total = new_percent_saved(report_stats)
        if total:
            report += total
        else:
            report += '0%'
        if Settings.test:
            report += ' could be saved.'
        if Settings.verbose > 1:
            tools_report = ', '.join(report_stats.report_list)
            if tools_report:
                report += '\n\t' + tools_report
        print(report)
11839
public function stats()
    {
        $ResqueStatus = $this->ResqueStatus;

        $workers = CakeResque::getWorkers();

        // List of all queues
        $queues = array_unique(CakeResque::getQueues());

        // List of queues monitored by a worker
        $activeQueues = [];
        foreach ($workers as $worker) {
            $workerParams = explode(':', $worker);
            $activeQueues = array_merge($activeQueues, explode(',', array_pop($workerParams)));
        }

        $this->out("\n");
        $this->out('<info>' . __d('cake_resque', 'Resque Statistics') . '</info>');
        $this->hr();
        $this->out("\n");

        $this->out('<info>' . __d('cake_resque', 'Jobs Stats') . '</info>');
        $this->out('   ' . __d('cake_resque', 'Processed Jobs : {0}', number_format(Resque_Stat::get('processed'))));
        $this->out('   <warning>' . __d('cake_resque', 'Failed Jobs    : {0}', number_format(Resque_Stat::get('failed'))) . '</warning>');

        if (Configure::read('CakeResque.Scheduler.enabled') === true) {
            $this->out('   ' . __d('cake_resque', 'Scheduled Jobs : {0}', number_format(Stat::get())));
        }

        $this->out("\n");

        $count = [];
        $this->out('<info>' . __d('cake_resque', 'Queues Stats') . '</info>');
        for ($i = count($queues) - 1; $i >= 0; --$i) {
            $count[ $queues[ $i ] ] = CakeResque::getQueueSize($queues[ $i ]);
            if (!in_array($queues[ $i ], $activeQueues) && $count[ $queues[ $i ] ] == 0) {
                unset($queues[ $i ]);
            }
        }

        $this->out('   ' . __d('cake_resque', 'Queues count : {0}', count($queues)));
        foreach ($queues as $queue) {
            $this->out(sprintf("\t- %-15s : %12s %s", $queue, number_format($count[ $queue ]), __dn('cake_resque', 'pending job', 'pending jobs', $count[ $queue ]) . (!in_array($queue, $activeQueues) ? " <error>(unmonitored queue)</error>" : '')));
        }

        $this->out("\n");
        $this->out('<info>' . __d('cake_resque', 'Workers Stats') . '</info>');
        $this->out('   ' . __d('cake_resque', 'Workers count : {0}', count($workers)));

        $pausedWorkers = $ResqueStatus->getPausedWorker();
        $schedulerWorkers = [];

        if (!empty($workers)) {
            $this->out("\t<info>" . strtoupper(__d('cake_resque', 'regular workers')) . "</info>");
            foreach ($workers as $worker) {
                if (Configure::read('CakeResque.Scheduler.enabled') === true && $ResqueStatus->isSchedulerWorker($worker)) {
                    $schedulerWorkers[] = $worker;
                    continue;
                }
                $this->out("\t* <bold>" . (string)$worker . '</bold>' . (in_array((string)$worker, $pausedWorkers) ? ' <warning>(' . __d('cake_resque', 'paused') . ')</warning>' : ''));
                $this->out("\t   - " . __d('cake_resque', 'Started on') . "     : " . CakeResque::getWorkerStartDate($worker));
                $this->out("\t   - " . __d('cake_resque', 'Processed Jobs') . " : " . $worker->getStat('processed'));
                $worker->getStat('failed') == 0
                    ? $this->out("\t   - " . __d('cake_resque', 'Failed Jobs') . "    : " . $worker->getStat('failed'))
                    : $this->out("\t   - <warning>" . __d('cake_resque', 'Failed Jobs') . "    : " . $worker->getStat('failed') . "</warning>");
            }
        }

        $this->out("\n");

        if (!empty($schedulerWorkers)) {
            $this->out("\t<info>" . strtoupper(__d('cake_resque', 'scheduler worker')) . "</info>" . (in_array((string)$schedulerWorkers[0], $pausedWorkers) ? ' <warning>(' . __d('cake_resque', 'paused') . ')</warning>' : ''));
            foreach ($schedulerWorkers as $worker) {
                $schedulerWorker = new ResqueScheduler();
                $delayedJobCount = $schedulerWorker->getDelayedQueueScheduleSize();
                $this->out("\t   - " . __d('cake_resque', 'Started on') . "     : " . CakeResque::getWorkerStartDate($worker));
                $this->out("\t   - " . __d('cake_resque', 'Delayed Jobs') . "   : " . $delayedJobCount);

                if ($delayedJobCount > 0) {
                    $this->out("\t   - " . __d('cake_resque', 'Next Job on') . "    : " . strftime('%a %b %d %H:%M:%S %Z %Y', $schedulerWorker->nextDelayedTimestamp()));
                }
            }
            $this->out("\n");
        } elseif (Configure::read('CakeResque.Scheduler.enabled') === true) {
            $jobsCount = ResqueScheduler::getDelayedQueueScheduleSize();
            if ($jobsCount > 0) {
                $this->out("\t<error>************ " . __d('cake_resque', 'Alert') . " ************</error>");
                $this->out("\t<bold>" . __d('cake_resque', 'The Scheduler Worker is not running') . "</bold>");
                $this->out("\t" . __d('cake_resque', 'But there is still <bold>{0}</bold> scheduled jobs left in its queue', $jobsCount));
                $this->out("\t<error>********************************</error>");
                $this->out("\n");
            }
        }
    }
536643
public function Write()
    {
        $content = "";

        foreach($this->preferences as $key => $data)
        {
            if(is_array($data))
            {
                $is_section = true;

                foreach($data as $dataKey => $dataValues)
                {
                    if(is_long($dataKey))
                    {
                        $is_section = false;
                        break;
                    }
                }

                $content .= "\n";

                //Write global array value
                if(!$is_section)
                {
                    foreach($data as $dataKey => $dataValue)
                    {
                        $content .= $key . '[] = "' . $dataValue . '"' . "\n";
                    }
                }

                //Write section
                else
                {
                    $content .= "[" . $key . "]\n";

                    foreach($data as $dataKey => $dataValue)
                    {
                        if(is_array($dataValue))
                        {
                            foreach($dataValue as $dataInnerValue)
                            {
                                $content .= $dataKey . '[] = "' . $dataInnerValue . '"' . "\n";
                            }
                        }
                        else
                        {
                            $content .= $dataKey . ' = "' . $dataValue . '"' . "\n";
                        }
                    }
                }

                $content .= "\n";
            }

            //Write global value
            else
            {
                $content .= $key . ' = "' . $data . '"' . "\n";
            }
        }

        file_put_contents($this->file, $content);
    }
537966
public function write()
	{
		// do we have something to write?
		if ( ! empty($this->keys) or ! empty($this->data) or ! empty($this->flash))
		{
			parent::write();

			// rotate the session id if needed
			$this->rotate(false);

			// record the last update time of the session
			$this->keys['updated'] = $this->time->get_timestamp();

			// add a random identifier, we need the payload to be absolutely unique
			$this->flash[$this->config['flash_id'].'::__session_identifier__'] = array('state' => 'expire', 'value' => sha1(uniqid(rand(), true)));

			// create the session record, and add the session payload
			$session = $this->keys;
			$session['payload'] = $this->_serialize(array($this->keys, $this->data, $this->flash));

			try
			{
				// do we need to create a new session?
				if (is_null($this->record))
				{
					// create the new session record
					list($notused, $result) = \DB::insert($this->config['table'], array_keys($session))->values($session)->execute($this->config['database']);
				}
				else
				{
					// update the database
					$result = \DB::update($this->config['table'])->set($session)->where('session_id', '=', $this->record->get('session_id'))->execute($this->config['database']);

					// if it failed, perhaps we have lost a session id due to rotation?
					if ($result === 0)
					{
						// if so, there must be a session record with our session_id as previous_id
						$result = \DB::select()->where('previous_id', '=', $this->record->get('session_id'))->from($this->config['table'])->execute($this->config['database']);
						if ($result->count())
						{
							logger(\Fuel::L_WARNING, 'Session update failed, session record recovered using previous id. Lost rotation data?');

							// update the session data
							$this->keys['session_id'] = $result->get('session_id');
							$this->keys['previous_id'] = $result->get('previous_id');

							// and recreate the payload
							$session = $this->keys;
							$session['payload'] = $this->_serialize(array($this->keys, $this->data, $this->flash));

							// and update the database
							$result = \DB::update($this->config['table'])->set($session)->where('session_id', '=', $this->keys['session_id'])->execute($this->config['database']);
						}
						else
						{
							logger(\Fuel::L_ERROR, 'Session update failed, session record could not be recovered using the previous id');
							$result = false;
						}
					}
				}

				// update went well?
				if ($result !== 0)
				{
					// then update the cookie
					$this->_set_cookie(array($this->keys['session_id']));
				}

				// do some garbage collection
				if (mt_rand(0,100) < $this->config['gc_probability'])
				{
					$expired = $this->time->get_timestamp() - $this->config['expiration_time'];
					$result = \DB::delete($this->config['table'])->where('updated', '<', $expired)->execute($this->config['database']);
				}
			}
			catch (Database_Exception $e)
			{
				// strip the actual query from the message
				$msg = $e->getMessage();
				$msg = substr($msg, 0, strlen($msg)  - strlen(strrchr($msg, ':')));

				// and rethrow it
				throw new \Database_Exception($msg);
			}
		}

		return $this;
	}
1369454
protected function outputEndStatistics()
    {
        $runtime = $this->getTime('end') - $this->getTime('start');

        $this->output('');
        $this->output('Finish', self::OUTPUT_COMMENT);
        $this->output(
            'Runtime: ' . number_format(($runtime / 60), 2, ',', '.') . ' Min. (' . $runtime . ' seconds)',
            self::OUTPUT_COMMENT
        );
        $this->outputMemoryUsage();
        $this->output('');
    }
80497
def _write_model_stats(self, iteration:int)->None:
        ""
        self.stats_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter)
299710
def write_stats_to_json(cls, file_name, stats):
    """"""
    params = cls._json_dump_options(stats)
    mode = 'w' if PY3 else 'wb'
    try:
      safe_file_dump(file_name, params, mode=mode)
    except Exception as e: # Broad catch - we don't want to fail in stats related failure.
      print('WARNING: Failed to write stats to {} due to Error: {}'.format(file_name, e),
            file=sys.stderr)
160425
protected function _writeTimestamp($data)
    {
        $data = serialize($data);
        file_put_contents($this->path . static::BUILD_TIME_FILE, $data);
        chmod($this->path . static::BUILD_TIME_FILE, 0644);
    }
1113448
protected function _writeDataOnShutdown()
    {
        if (
            !isset( $this->_states[$this->getRealm()] )
            || $this->_states[$this->getRealm()] === self::$STATE_OK
        )
            // Nothing Has Changed
            return;

        $this->save();
    }
1298333
private function write()
    {
        $cache = serialize($this->records);
        flock($this->file, LOCK_EX);
        rewind($this->file);
        ftruncate($this->file, 0);
        $bytes = fwrite($this->file, $cache);
        flock($this->file, LOCK_UN);

        return $bytes === strlen($cache);
    }
972586
public function write()
    {
        foreach ($this->parameters as $prop => $value) {
            $placeHolders[] = sprintf('<%s>', $prop);
            $replacements[] = $value;
        }

        $config = str_replace($placeHolders, $replacements, self::$configTemplate);
        $config = sprintf('%s%s%s', self::$defaultConfigTemplate, PHP_EOL, $config);

        if (true === $this->parameters['composer']) {
            $config = sprintf('%s%s%s', $config, PHP_EOL, self::$downloadComposerTaskTemplate);
        }

        if (true === $this->parameters['schemadb']) {
            $config = sprintf('%s%s%s', $config, PHP_EOL, self::$updateSchemaTaskTemplate);
        }

        fwrite($this->file, $this->addHeaders($config));
    }
1021796
public function write()
    {
        
        $tf = $this->getTranslationFile();
        $buffer = "<?php\n";
        foreach ($tf->getTranslationUnits() as $tu){
            // Prevent empty messages.
            if ($tu->getSource() != '' && $tu->getTarget() != ''){
                $escapes = array("\\", '$', '"', "\n", "\t", "\v", "\r", "\f");
                $replace = array("\\\\", '\\$', '\\"', "\\n", "\\t", "\\v", "\\r", "\\f");
                $source = str_replace($escapes, $replace, $tu->getSource());
                $target = str_replace($escapes, $replace, $tu->getTarget());
                $buffer .= '$GLOBALS[\'__l10n\']["' . $source . '"]="' . $target . '";' . "\n";
            }
        }
        $buffer .= "\n?>";
        
        file_put_contents($this->getFilePath(), $buffer);
        
    }
567736
public function serialize(): void
    {
        $voteBytes = [];

        foreach ($this->transaction['asset']['votes'] as $vote) {
            $voteBytes[] = '+' === substr($vote, 0, 1)
                ? '01'.substr($vote, 1)
                : '00'.substr($vote, 1);
        }

        $this->buffer->writeUInt8(count($this->transaction['asset']['votes']));
        $this->buffer->writeHexBytes(implode('', $voteBytes));
    }