GithubHelp home page GithubHelp logo

kakserpom / phpdaemon Goto Github PK

View Code? Open in Web Editor NEW
1.5K 1.5K 233.0 8.13 MB

Asynchronous server-side framework for network applications implemented in PHP using libevent

Home Page: http://daemon.io/

License: GNU Lesser General Public License v3.0

PHP 99.54% Shell 0.46%

phpdaemon's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpdaemon's Issues

Проблема с авто запуском в Ubuntu

/etc/init.d/phpd.sh :

!/bin/bash

exec phpd start

Собственно делал так:
sudo chmod +x /etc/init.d/phpd.sh
sudo update-rc.d phpd.sh defaults 99

Все бы нормально, но демон, после загрузки системы не отвечает на команды stop. Не убивается через kill, или killall -9 phpd.

И еще страннее то, что запросы стали обрабатываться по 7-9 секунд.

В чем может быть причина?

С уважением Somebi

Typo in lib/Daemon_WorkerThread.class.php

  foreach (Daemon::$appInstances as $app)
  {
   foreach ($app as $appInstance)
   {
    if (!$appInstance->ready)
    {
     $this->ready = TRUE;
     $appInstance->onReady();
    }
   }
  

$appInstance->ready = TRUE; Will be better :)

Wrong use of $this

MongoNode.php

 $this->LockClient->job(__CLASS__,TRUE,function($jobname) use ($appInstance)
 {
  $this->pushRequest(new MongoNode_ReplicationRequest($this,$this));
 });

You can't use $this with closures

WS protocol 13

Когда будет релизован 13-ый протокол websocket?
Sec-WebSocket-Version:13

Автозагрузчик теряет первую часть класса

В автозагрузчикке есть смысл дописать проверку, которая бы проверяла - является ли первая часть PHPDaemon, и если нет - не теряла её... потратил какое-то время (три вечера), прежде чем нашел причину конфликта своих классов и вашими. Удачи в разработке!

Как-то так:
if (sizeof($parts) > 1 && 'PHPDaemon' == $parts[0]) {
// namespaces support (remove first "PHPDaemon" part)
array_shift($parts);
}

Worker shutdown status

Some logic problem I think.

Daemon_WorkerThread.class.php in 353

$this->setStatus(3);

And then in 360

if ($r->running) {$r->finish(-2);}

But if any Request in Queue (MongoNode_ReplicationRequest for example) then it will overwrite status at Request::onWakeup()

Конфигурация и первое приложение

День добрый. Решил попробовай ваш продукт, тот который phpdaemon, как альтернативу php-fpm (как я понял, они чемто похожи по принципу работы, но пхпд - более тру :) ). Но возникло пару вопросов по этому поводу.
Пробовал поставить все кучей как по мануале на гитхабе - но с компиляцией пхп не сложилось, потом еще были разбежности (убунта 11) и пришлось по другому мануалу ставить - http://www.welinux.ru/post/4234/

Кой-как поставилось (я с линухом пока на Вы). Пути следующие:

  1. Нгинкс - файлы конфы в /etc/nginx*
  2. phpd - /opt/phpdaemon
  3. php 5.3 - /etc/php5/cli (ставил только php5-cli, php5-dev)

1-й вопрос.
при запуске пхпд вылетает следующая ошибка в консоль:
[PHPD] Your application resolver '/etc/phpdaemon/AppResolver.php' is not available.
тут не пойму - нужно указать путь к AppResolver.php в /opt/phpdaemon/conf/phpd.conf или чтото другое?

2-й.
"Посмотрите раздел [Разработка приложений] для получения более детальной информации касаемо разработки приложений.."
Не нашел такого раздела на гитхабе.

3.й
Обьясните вкратце следующее. Допустим, в nginx'е при запросе к пхп-файлам происходит обращение к пхпдемону. (fastcgi_pass 127.0.0.1:9000; fastcgi_param APPNAME yourapplication;
). Точка входа (index.php) должна содержать какойто специальный код или он без изменения (например, просто echo 'hello';)?
И в какой момент происходит обращение ко всем файлам /opt/phpdaemon/application/*, да и вообще ко всем пхп-файлам в пхпдемоне?
Прочитал все те 5 статей про этот демон, некоторе дважды, но вопросы вот остались. Заранее спасибо.

PS. Вроде туда запостил :)

MongoClient cursors

After findOne() call, "cursor" will not be instance of MongoClientCursor but stdClass and will NEVER be removed from $this->appInstance->cursors array.

I've replaced (MongoClient.php at 657)

if (isset($this->appInstance->cursors[$cur]) && ($this->appInstance->cursors[$cur] instanceof MongoClientCursor)) {$this->appInstance->cursors[$cur]->destroy();}

with

if (isset($this->appInstance->cursors[$cur]))
{
 if ($this->appInstance->cursors[$cur] instanceof MongoClientCursor)
 {
  $this->appInstance->cursors[$cur]->destroy();
 }
 else
 {
  unset($this->appInstance->cursors[$cur]);
 }
}

Пример с сессиями.

Не хватает примера с сессиями.

Не могли бы вы пожалуйста сделать простой пример использования стандартных обращений с сессии.

Так как у меня не получилось.

Выкидывает ошибку:

PHP Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /usr/local/lib/phpdaemon/lib/Request.php:382) in /usr/local/lib/phpdaemon/app-examples/MyApp.php on line 82

382 строка у нас ob_flush();

public function onWakeup() {
    if (!Daemon::$compatMode) {
        Daemon::$process->setStatus(2);
    }

    ob_flush();

    $this->running = TRUE;

    Daemon::$req = $this;
}

Где правильнее будет вызывать session_start() чтобы она вызывалась до отдачи заголовков?

Спасибо за замечательную реализацию. Благодаря вам смог быстро и практически безболезненно отказаться от apache2.

Проблемы с ajax запросами при True FastCGI

Пытаюсь выяснить что именно обрезает или вообще не возвращает html при ajax запросах.

На стадии onFinish() экземпляра HTTPRequest html строка еще целая.

А дальше уже нет.

Что идет дальше, после onFinish?

С уважением Somebi.

namespaces support

Subj. phpDaemon require PHP > 5.3, so providing namespaces will a good step.

Typo in conf/phpdaemon.conf.php

The file has an error in a comment.

The comment says "// 'mod-websocket-enable' => 1," but it should have been "// 'mod-websocketserver-enable' => 1,", or it won't work.

This caused me a lot of frustration :D.

php 5.4 web-server

С появлением 5.4 ветки появилась замечательная возможность, поднимать веб-сервер средствами самого интерпретатора.

Возможно стоит ввести какую поддержку этой фичи во фреймворк?

http://php.net/manual/ru/features.commandline.webserver.php

Memoy leaks

I wrote some simple tests with rtep+memcache+mongo and face a memory leak problem after each session. Unfortunately, I still can't find source of this leaks.

Rename class Request

A lot of frameworks and projects, has a class of Request, which can interfere with the class of phpDaemon. The conflict in that class of project simply not declared.

called from Flash webSocketError() on server stop

When I stop server there are so error in javascript console:

[WebSocket] failed to connect Web Socket server (SecurityError) make sure the server is running and Flash socket policy file is correctly placed
webSocketError(message="%5BWebSocket%5D%20faile...is%20correctly%20placed")websoc...lash.js (line 309)
message = "%5BWebSocket%5D%20faile...is%20correctly%20placed"
websocket_flash.js (line 309)

And when I start server I must press F5 on web interface.

Passing HTTPRequest

There are no method to pass HTTP request from method HTTPRequest::run() of the one application to the another application in phpDaemon. I can't use FileReader functionality in HTTPRequest::run() of the my application. I copy some code of the FileReader in my application now.

asyncServer leak

asyncServer::closeConnection() doesn't clear poolState array.

I've added

unset($this->poolState[$connId]);

at line 304

PHP Notice on phpd update

PHP Notice: Undefined offset: 1 in /usr/local/phpdaemon/lib/Daemon_ConfigParser.class.php on line 202
PHP Notice: Undefined offset: 1 in /usr/local/phpdaemon/lib/Daemon_ConfigParser.class.php on line 197

ошибка использования сокетов при более чем одном рабочем процессе и FastCGI

При попытке использовать FastCGI сервер с более чем одним рабочим процессом возникает ряд ошибок вида
[PHPD] FastCGI: Couldn't bind TCP-socket '127.0.0.1:9001' (98 - Address already in use).
ОС Ubuntu x64
Используемая конфигурация:

max-workers 10;

min-workers 1;
start-workers 2;

max-requests 1m;
max-idle 0;

FastCGI {
  enable 1;
  listen tcp://127.0.0.1:9001;
  expose 0;
}

Could not to get all MongoDb collection items

I do so, then plan to get all collection items:
$this->db->objects->find(function($cursor) {
foreach($cursor->items as $k => $object) {
// do something....
unset($cursor->items[$k]);
}
if (!$cursor->finished) {$cursor->getMore();}
else {
// trigger my ather code there
....
$cursor->destroy();
}
});
But this does not work properly:
PHP Notice: Undefined property: stdClass::$callback in /usr/local/phpdaemon/app-clients/MongoClient.php on line 1128
PHP Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in /usr/local/phpdaemon/app-clients/MongoClient.php on line 1128
And only some part of the collection items was fetched.

Fedora rpm - PHP Fatal error: Class 'HTTPRequest'

Добрый день/вечер.

Ранее устанавливал phpdaemon с git репозитория. Поскольку использую релиз Fedora, решил попробывать rpm версию.
При установке заметил что конфиги "перенесены" в /etc/phpdaemon

За основу для теста взял ExampleWebSocket.php переименовав его в WebSocketWorker.php (и класс соответственно) поместил в директорию /usr/share/phpdaemon/applications

Запустив демон, пытался подключиться, но, к сожалению, безуспешно.

Вот подробно мои действия после установки (как это описано в https://github.com/kakserpom/phpdaemon/wiki/%D0%A3%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0-%28centos-%D0%B8-fedora-linux%29 )

В phpd.conf добавил:

path '/etc/phpdaemon/conf/AppResolver.php';

autoload WebSocketWorker;
WebSocketServer {
    privileged;

    enable 1;
    listen tcp://XXX.XXX.XXX.XXX;
    listenport 8049;
}

В результате получаю:

  • на стороне клиента

    [WebSocket] policy file: xmlsocket://some-site.com:843
    [WebSocket] connected
    [WebSocket] request header: GET /chat HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: XXX.XXX.XXX.XXX:8049 Origin: http://some-site.com Cookie: Sec-WebSocket-Key1: g3q9b1 (5gs 9 t 4427 4l Sec-WebSocket-Key2: Sk12 I7 F2 8 K 66; 9J$C84S
    [WebSocket] sent key3: ,$Ó¨?ó�G
    [WebSocket] closed
    [WebSocket] connected
    [WebSocket] request header: GET /chat HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: XXX.XXX.XXX.XXX:8049 Origin: http://some-site.com Cookie: Sec-WebSocket-Key1: 581 3P"I 1 4es = 1i3 &1BS Sec-WebSocket-Key2: >DT3A +H66 (421247 7D
    [WebSocket] sent key3: wv÷1yظò
    [WebSocket] closed
    
  • на стороне сервера

[root@dev conf]# phpd start

(до подключения WebSocket-клиента)

[PHPD] M#25596 IPCManager instantiated.
[root@dev conf]# [PHPD] M#25596 WebSocketServer instantiated.
[PHPD] M#25596 WebSocketServer up.

(после подключения WebSocket-клиента)

[root@dev conf]# PHP Fatal error:  Class 'HTTPRequest' not found in /usr/share/phpdaemon/app-servers/WebSocketServer.php on line 433
[PHPD] Spawning 1 worker(s).
PHP Fatal error:  Class 'HTTPRequest' not found in /usr/share/phpdaemon/app-servers/WebSocketServer.php on line 433
[PHPD] Spawning 1 worker(s).

Как нужно настраивать конфиг phpdaemon-a чтобы избежать данной ошибки?

Благодарю за внимание.

bug in public function computeKey($key) {

bug in public function computeKey($key) {

$result = (int) $digits; // bug (int)
if ($spaces > 0) {
$result = (int) floor($result / $spaces);

when try to connect with key > then 2147483647
test:
echo (int)'7683287632687924324';
print: 2147483647

// fixed
$result = 0;
if ($spaces > 0) {
$result = (int) @floor($digits / $spaces);

Error when adding signal when starting phpd

Libevent version: 2.0.11-stable
php_libevent version: 0.0.4
php version: 5.3.3-1ubuntu9.5
phpd version: currently from git

When starting get an error:

[warn] Added a signal to event base 0x146baf0 with signals already added to event_base 0x134d980. Only one can have signals at a time with the epoll backend. The base with the most recently added signal or the most recent event_base_loop() call gets preference; do not rely on this behavior in future Libevent versions.

Single worker issue

Have problems working with FASTCGI server with one worker. I'm not sure, but it seems it gets unresponsive. I found nothing in stderr or stdout output, but Nginx had this in his log:

2011/07/29 17:03:40 [error] 7703#0: *266549 upstream sent too big header while reading response header from upstream, client: client_ip, server: www.example.com, request: "GET /someurl HTTP/1.1", upstream: "fastcgi://unix:/tmp/phpdaemon.fcgi.sock:", host: "www.example.com", referrer: "some url from google search results"

2011/07/29 17:05:59 [error] 7704#0: *266185 upstream prematurely closed connection while reading response header from upstream, client: my_server_ip, server: www.example.com, request: "GET /someurl HTTP/1.1", upstream: "fastcgi://unix:/tmp/phpdaemon.fcgi.sock:", host: "www.example.com", referrer: "my website url"

I have checked your sources and chunk size is 8196 as it's intended and required by nginx proxy buffers config defaults.

I have tried to increase buffer size of nginx even up to:

proxy_buffers 8 1024k;
proxy_buffer_size 2048k;

but it didn't helped.

Then i have decided to increase workers count from one to 20 and everything is fine now.

How much RPS one worker is capable to handle when weight of document is 80kb~?

I gonna dig sources to figure out what's happening inside there when i'll have some time for it, but would like to hear from you as well.

Thanks ;)

Cookies parsing

WebSocketSession has property server['HTTP_COOKIE'] but not parsed.

MySQLClient authentication bug

MySqlClient cannot handle authenticating using pre-4.1 password scheme

Old passwords can exist even on mysql 5 servers, and this is important because some Centos distributions are still enabling old passwords by default in my.cnf

To reproduce....

Create a test account on any mysql server.....

mysql> grant all on mysql.* to testing@localhost identified by OLD_PASSWORD('testing');
mysql> update user set Password = OLD_PASSWORD('testing') where User = 'testing' and Host = 'localhost';
mysql> flush privileges;

now try using MySQLClient to connect using this login...

if ($sqlclient && ($this->sql = $sqlclient->getConnection('mysql://testing:testing@localhost/mysql')))

The authentication succeeds and mysql returns some sort of confirmation packet [\x01\x00\x00\x02\xfe]

phpdaemon treats this as simply an EOF packet, and nothing more, and as a result the onConnected callback never gets fired.

One solution is to add this into the existing EOF packet routine, but it might be better to properly parse the response elsewhere

elseif ($fieldCount === 0xFE)
{
// EOF Packet
++$this->instate;

// --- NEW: If waiting for authentication reply
if (($this->cstate == 2) && ($this->buf == "\x01\x00\x00\x02\xfe"))
{
        Daemon::log("Matched token\n");
        $this->instate = 3;
}

if ($this->instate === 3) {
        $this->onResultDone();
}

} else {

MongoClient improvement request

Connection pool behaviour needed:

  1. min_idle_pool_connections - setting needed
  2. max_concurent_connections - setting needed
  3. when max_concurent_connections limit is reached, store requests and callbacks in the queue
    MysqlDriver, also need's this behaviour

HTTPserver max_concurent_request setting, not working properly

  1. When max_concurent_request limit reached, server stops accepting new connections, but when requests are done, it doesn't start accepting new connections
  2. Keep-alive connections can generate any request rate bypassing max_concurent_request setting

configtest in init-script return 0 when config has error

When loading config file in Daemon_Bootstrap.class.php and it has error then application should terminate program with error_code = 6. IMHO...

if (!Daemon::loadConfig(Daemon::$config->configfile->value)) {
    exit(6);
}

PS: Now, application continue working and show some config variables and return 0 when exit.

Будет ли RedisClient?

Добрый день/вечер.
Пользуясь phpdaemon-ом, обнаружил наличие MongoClient-а.
На сколько я знаю, RedisDB побыстрее будет, но клиента к нему нету (

Хотелось бы знать, будет ли написан клиент для RedisDB, и если да, то когда его можно будет ожидать?

отправка сообщений между сессиями?

В общем у меня тут такой вопрос по конкретной возможности рассылки сообщения другим пользователям, на самом деле с демоном начал возиться совсем не давно но ни как не могу найти информации как это сделать.

Если быть точным нужна возможность отправки сообщений как одному так и нескольким людям но не рассылать всем кто подключен… например пользователь отправляет сообщение и в нутрии его класса находится массив с перечисленными ключами сессии тех кому нужно отправить сообщение.

Пожалуйста объясни как достучаться до чужой сессии?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.