Creating and communicating with daemon

4

I have a Python application where I need to keep it online all the time.

The application has its own console, which is where I make the communication and step parameters.

I understand that I can create the Daemon to leave it online all the time, now the problem is that I still do not understand how to pass commands to the application while being online.

I'm more familiar with PHP, so I'm creating the daemon as well. I can even give start , but I still have no idea how to have a communication with it that has the console open waiting commands.

I imagine that solving everything here will be difficult, but if you can give me some references and a way I study and I'll share the results.

    
asked by anonymous 18.02.2015 / 15:32

1 answer

1

You need to look for an inter-process communication solution.

A popular way that works similarly across multiple platforms and programming languages is to create a queue server (MQ). One of these is ZeroMQ and you can see some examples here .

Another way is to use Python's multiprocessing module. Here's a tried-and-tested example, just to give you an idea where to start:

In your daemon, start the server that expects client (console) connections

from multiprocessing.connection import Listener
import threading
import time

def processa_comando(comando):
    print 'Recebi o comando:', comando
    return {'status': 'OK', 'commando': comando}

def inicia_servidor():
    servidor = Listener(('localhost', 12345), authkey='senha')
    try:
        while True:
            # esperar conexao
            cnx = servidor.accept()
            # o codigo a seguir, em uma implementacao real,
            # poderia ser movido para uma thread nova (uma
            # para cada cliente conectado)
            print 'Client connected.'
            while True:
                # esperar comandos do cliente
                mensagem = cnx.recv()
                if mensagem['tipo'] == 'comando':
                    resposta = processa_comando(mensagem['comando'])
                    cnx.send(resposta)
                elif mensagem['tipo'] == 'exit':
                    print 'Client left.'
                    cnx.close()
                    break
    except Exception as err:
        print 'Erro', err
    finally:
        servidor.close()

# o servidor executa em uma thread separada para nao
# bloquear o programa principal
t = threading.Thread(target=inicia_servidor)
t.start()

# simulacao para mostrar que o servidor continua a
# trabalhar enquanto aguarda comandos
while True:
    print 'Servidor trabalhando...'
    time.sleep(5)

On your client (console) connect to the daemon

from multiprocessing.connection import Client

def aguarda_proximo_commando():
    commando = raw_input()
    return commando

cliente = Client(('localhost', 12345), authkey='senha')
try:
    while True:
        # fica em loop ate um CTRL+C
        print 'server>',
        texto = aguarda_proximo_commando()
        cliente.send({'tipo': 'comando', 'comando': texto})
        resposta = cliente.recv()
        print '  =>', resposta
except KeyboardInterrupt:
    cliente.send({'tipo': 'exit'})
except Exception as err:
    print 'Erro', err
finally:
    cliente.close()

Example of client execution:

~/teste $ python client.py 
server> ola
  => {'status': 'OK', 'commando': 'ola'}
server> tudo bem
  => {'status': 'OK', 'commando': 'tudo bem'}
server> ^C
~/teste $ python client.py 
server> ola de novo
  => {'status': 'OK', 'commando': 'ola de novo'}
server> ja vou
  => {'status': 'OK', 'commando': 'ja vou'}
server> ^C
~/teste $

Sample result on server:

~/teste $ python server.py 
Servidor trabalhando...
Servidor trabalhando...
Client connected.
Recebi o comando: ola
Servidor trabalhando...
Recebi o comando: tudo bem
Servidor trabalhando...
Client left.
Servidor trabalhando...
Client connected.
Servidor trabalhando...
Servidor trabalhando...
Recebi o comando: ola de novo
Servidor trabalhando...
Servidor trabalhando...
Recebi o comando: ja vou
Servidor trabalhando...
Client left.
Servidor trabalhando...
^CTraceback (most recent call last):
  File "server.py", line 46, in <module>
    time.sleep(5)
KeyboardInterrupt
^C^CTerminated: 15
~/teste $
    
06.03.2015 / 18:03