1
0
Fork 0
oldhaven/php-bak/bin/parser/worker_html_grabber.php

98 lines
2.9 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/opt/local/bin/php
<?php
// Демонизация процесса
$child_pid = pcntl_fork();
if ($child_pid == -1) {
die('Error while forking process.');
} elseif ($child_pid) {
// Выходим из родительского, привязанного к консоли, процесса
exit;
}
require_once '/www/server/php/common.php';
// Минимальный интервал между запросами
define('VKTIMEOUT', 10);
define('QUEUE_PACK', 30);
define('EMPTY_QUEUE_TIMEOUT', 60);
// Получаем имя бота
if (!isset($argv[1]) || !Config::get('bot:'. $argv[1])) {
die('Wrong bot name: '. @$argv[1]);
}
$bot_name = ucfirst($argv[1]);
// Инициализация бота по имени
$vk = new Vkontakte($bot_name);
// Данные о работе бота
$stats = array(
'started_job' => time(),
'eneded_job' => time(),
'pid' => getmypid(),
'good_results' => 0,
'bad_results' => 0,
'queue_size' => 0,
'last_request' => ''
);
// Устанавливаем коннект с БД
$db = Db::getInstance();
// Бот работает все время
while (true) {
// Получаем список песен для загрузки, помечаем в очереди, что мы их взяли в работу
$db->q('BEGIN');
$queue = $db->getRows($db->q("SELECT * FROM beathaven.queue WHERE status=0 ORDER BY priority DESC, times_failed ASC LIMIT ". QUEUE_PACK));
$ids = array();
foreach ($queue as $t) {
$ids[] = $t['track_id'];
}
$db->q('UPDATE beathaven.queue SET status=1 WHERE track_id IN('. implode(',', $ids) .')');
$db->q('COMMIT');
if (!$queue || count($queue) == 0) {
sleep(EMPTY_QUEUE_TIMEOUT);
} else {
$stats['queue_size'] = count($queue);
foreach ($queue as $t) {
$t1 = microtime(true);
echo "#{$t['track_id']} {$t['track_title']} -- ";
$ok = $vk->getTracks($t['track_title']);
if (strpos($vk->getHtml(), 'searchOffset') === false) {
echo "Session kaput!\n";
die;
}
if ($ok) {
echo "OK\n";
$db->q("UPDATE beathaven.queue SET status=3 WHERE track_id=". $t['track_id']);
$file_name = Config::get('app:Parser:good_html_dir'). $t['track_id'] .'.html';
$stats['good_results']++;
} else {
echo "FAILED\n";
$db->q("UPDATE beathaven.queue SET status = 2, times_failed = times_failed + 1 WHERE track_id=". $t['track_id']);
$file_name = Config::get('app:Parser:bad_html_dir'). $t['track_id'] .'.html';
$stats['bad_results']++;
}
file_put_contents($file_name, $vk->getHtml());
chmod($file_name, 0777);
$stats['last_request'] = $t['track_title'];
$stats['queue_size']--;
$stats['eneded_job'] = time();
$bot_stats_file_name = Config::get('app:Parser:bot_stats_dir'). $bot_name .'.json';
file_put_contents($bot_stats_file_name, json_encode($stats));
chmod($bot_stats_file_name, 0777);
$t2 = microtime(true);
if ($t2 - $t1 < VKTIMEOUT) {
sleep(ceil(VKTIMEOUT - ($t2 - $t1)));
}
}
}
}