zmq-fileserver/storage_server
2020-06-19 17:04:39 +02:00

37 lines
1.2 KiB
PHP
Executable File

#!/usr/bin/env php
<?php
is_dir($rootDir = rtrim($argv[1] ?? __DIR__ . '/documents', '/')) or mkdir($rootDir, 0777, true);
$zmq = new ZMQContext();
$pullSocket = $zmq->getSocket(ZMQ::SOCKET_PULL)->bind('ipc:///tmp/storage_server_sink.ipc');
$replySocket = $zmq->getSocket(ZMQ::SOCKET_REP)->bind('ipc:///tmp/storage_server_query.ipc');
$poll = new ZMQPoll();
$poll->add($pullSocket, ZMQ::POLL_IN);
$poll->add($replySocket, ZMQ::POLL_IN);
$readable = $writable = [];
while (true) {
$poll->poll($readable, $writable);
foreach ($readable as $socket) {
$socket === $pullSocket and handleIncomingFile();
$socket === $replySocket and handleIncomingRequest();
}
}
function handleIncomingFile(): void
{
global $pullSocket, $rootDir;
$namespace = $pullSocket->recv(ZMQ::MODE_SNDMORE);
$name = $pullSocket->recv(ZMQ::MODE_SNDMORE);
$contents = $pullSocket->recv();
is_dir($targetDir = "$rootDir/$namespace") or @mkdir($targetDir, 0777, true);
file_put_contents("$targetDir/$name", $contents) and print('S');
}
function handleIncomingRequest(): void
{
global $replySocket, $rootDir;
$namespace = $replySocket->recv(ZMQ::MODE_SNDMORE);
$name = $replySocket->recv();
$replySocket->send(@file_get_contents("$rootDir/{$namespace}/{$name}") ?: 'NOT_FOUND') and print('R');
}