]> git.llucax.com Git - z.facultad/75.42/plaqui.git/blobdiff - Server/src/server.cpp
arregle un poquito la and
[z.facultad/75.42/plaqui.git] / Server / src / server.cpp
index 134bcf517f9f1d386c1d8a75ea648c744a651e5d..340c2f05801dbeebdc216f63a056e851f5413b16 100644 (file)
 #include "plaqui/server/connection.h"
 #include "plaqui/server/controlserver.h"
 #include <sigc++/class_slot.h>
+#include <sstream>
+#include <exception>
 #ifdef DEBUG
+#      include "plaqui/server/string.h"
 #      include <iostream>
 #endif // DEBUG
 
-PlaQui::Server::Server::~Server(void) {
-#ifdef DEBUG
-       std::cerr << __FILE__ <<  ": destructor." << std::endl;
-#endif // DEBUG
-}
+using namespace std;
+
+namespace PlaQui {
 
-PlaQui::Server::Server::Server(int port):
-               TCPServer(port) {
+namespace Server {
+
+Server::~Server(void) {
 #ifdef DEBUG
-       std::cerr << __FILE__ <<  ": port = " << port << std::endl;
+       cerr << __FILE__ << "(" << __LINE__ << ")"
+               <<  ": destructor." << endl;
 #endif // DEBUG
+       // Termino plantas.
+       Glib::Mutex::Lock lock(plants_mutex);
+       for (PlantList::iterator i = plants.end(); i != plants.end(); i++) {
+               i->second->finish(true);
+       }
 }
 
-/// \todo Implementar.
-bool PlaQui::Server::Server::start_transmission(std::string host, int port) {
+Server::Server(const string& plant_filename, const Connection::Port& port)
+               throw(sockerr): TCPServer(port) {
 #ifdef DEBUG
-       std::cerr << __FILE__ <<  ": start_transmission(host = " << host
-               << " | port = " << port << ")" << std::endl;
+       cerr << __FILE__ << "(" << __LINE__ << ")"
+               <<  ": port = " << port << endl;
 #endif // DEBUG
-       // TODO
-       return false;
+       // FIXME
+       Glib::Mutex::Lock lock(plants_mutex);
+       plants["default"] = new Plant(plant_filename);
+       plants["default"]->signal_finished().connect(
+                       SigC::bind<const char*>(
+                               SigC::slot_class(*this, &Server::on_plant_finished),
+                               "default"));
+       plants["default"]->run();
 }
-                       
-PlaQui::Server::Connection* PlaQui::Server::Server::new_connection(
-               const sockbuf::sockdesc& sd) {
+
+Connection* Server::new_connection(const sockbuf::sockdesc& sd) {
 #ifdef DEBUG
-       std::cerr << __FILE__ <<  ": new_connection(sd = " << sd.sock << ")"
-               << std::endl;
+       cerr << __FILE__ << "(" << __LINE__ << ")"
+               <<  ": new_connection(sd = " << sd.sock << ")"
+               << endl;
 #endif // DEBUG
        ControlServer* connection = new ControlServer(sd);
        // TODO verificar si el new se hace bien? no creo.
        connection->signal_command_received().connect(
-                       SigC::slot_class(*this, &Server::on_control_command_received));
+                       SigC::bind<ControlServer*>(
+                               SigC::slot_class(*this, &Server::on_control_command_received),
+                               connection));
        // TODO: 
        return connection;
 }
 
-/// \todo Implementar.
-bool PlaQui::Server::Server::stop_transmission(std::string host, int port) {
+void Server::on_plant_finished(const char* plant) {
 #ifdef DEBUG
-       std::cerr << __FILE__ <<  ": stop_transmission(host = " << host
-               << " | port = " << port << ")" << std::endl;
+       cerr << __FILE__ << "(" << __LINE__ << ")"
+               <<  ": on_plant_finished(plant_name = " << plant << endl;
 #endif // DEBUG
-       // TODO
-       return false;
+       Glib::Mutex::Lock lock(plants_mutex);
+       plants.erase(plant);
 }
 
-/// \todo Implementar.
-void PlaQui::Server::Server::on_control_command_received(void* command) {
+/// \todo Terminar de implementar.
+void Server::on_control_command_received(const Command& command,
+               ControlServer* controlserver) {
 #ifdef DEBUG
-       std::cerr << __FILE__ <<  ": on_control_command_received(command = "
-               << command << ")" << std::endl;
+       cerr << __FILE__ << "(" << __LINE__ << ")"
+               <<  ": on_control_command_received(target = "
+               << command.get_target() << ", command = " << command.get_command()
+               << ", args = [" << String::join(command.get_args(), ", ") << "])"
+               << endl;
 #endif // DEBUG
+       HTTPResponse* response;
+       //bool stop_controlserver = false;
+       if (command.get_target() == "server") {
+               if (command.get_command() == "status") {
+                       response = cmd_server_status();
+               } else if (command.get_command() == "stop") {
+                       finish();
+                       response = new HTTPResponse(HTTPMessage::OK,
+                                       "<response desc=\"El server se apagará en instantes...\" />");
+               } else {
+                       response = new HTTPResponse(HTTPMessage::NOT_FOUND,
+                                       "<response desc=\"Invalid command for 'server' taget!\" />");
+               }
+       } else if (command.get_target() == "connection") {
+               if (command.get_command() == "list") {
+                       response = cmd_connection_list();
+               } else if (command.get_command() == "stop") {
+                       response = cmd_connection_stop(command);
+               } else {
+                       response = new HTTPResponse(HTTPMessage::NOT_FOUND,
+                                       "<response desc=\"Invalid command for 'connection' taget!\" />");
+               }
+       } else if (command.get_target() == "transmission") {
+               if (command.get_command() == "list") {
+                       response = cmd_transmission_list();
+               } else if (command.get_command() == "start") {
+                       response = cmd_transmission_start(command);
+               } else if (command.get_command() == "stop") {
+                       response = cmd_transmission_stop(command);
+               } else {
+                       response = new HTTPResponse(HTTPMessage::NOT_FOUND,
+                                       "<response desc=\"Invalid command for 'transmission' taget!\" />");
+               }
+       } else if (command.get_target() == "plant") {
+               if (command.get_command() == "list") {
+                       response = cmd_plant_list();
+               } else if (command.get_command() == "get") {
+                       response = cmd_plant_get(command);
+               } else if (command.get_command() == "set") {
+                       response = cmd_plant_set(command);
+               } else if (command.get_command() == "stop") {
+                       response = cmd_plant_stop(command);
+               } else {
+                       response = new HTTPResponse(HTTPMessage::NOT_FOUND,
+                                       "<response desc=\"Invalid command for 'plant' taget!\" />");
+               }
+       } else {
+               response = new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               "<response desc=\"Invalid taget!\" />");
+       }
+       // FIXME
+       response->headers["Content-Type"] = "text/xml; charset=iso-8859-1";
+       //response->headers["Connection"] = "close";
+       controlserver->send(*response);
+       delete response;
+       // FIXME con timeout no debería ser necesario. Verificar cabecera Connection
+       // para saber si hay que finish()earlo o no.
+       //if (stop_controlserver) {
+       //      controlserver->finish();
+       //}
+}
+
+HTTPResponse* Server::cmd_server_status(void) const {
+       // FIXME
+       stringstream xml;
+       xml << "<serverstatus>" << endl;
+       xml << "\t<version>" VERSION "</version>" << endl;
+       xml << "\t<authors>" << endl;
+       xml << "\t\t<author>Nicolás Dimov</author>" << endl;
+       xml << "\t\t<author>Leandro Lucarella</author>" << endl;
+       xml << "\t\t<author>Ricardo Markiewicz</author>" << endl;
+       xml << "\t</authors>" << endl;
+       xml << "</serverstatus>" << endl;
+       return new HTTPResponse(HTTPMessage::OK, xml.str());
+}
+
+HTTPResponse* Server::cmd_connection_list(void) {
+       // FIXME
+       TCPServer::ConnectionInfoList cil = get_connected();
+       stringstream xml;
+       xml << "<list type=\"connection\">" << endl;
+       for (TCPServer::ConnectionInfoList::const_iterator i = cil.begin();
+                       i != cil.end(); i++) {
+               xml << "\t<row>" << endl;
+               xml << "\t\t<cell>" << i->host << "</cell>" << endl;
+               xml << "\t\t<cell>" << i->port << "</cell>" << endl;
+               xml << "\t</row>" << endl;
+       }
+       xml << "</list>" << endl;
+       return new HTTPResponse(HTTPMessage::OK, xml.str());
+}
+
+HTTPResponse* Server::cmd_connection_stop(const Command& command) {
+       const Command::Arguments& args = command.get_args();
+       Connection::Port port;
+       if (args.size() < 2) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               "<response desc=\"Faltan argumentos.\" />");
+       } else if (disconnect(args[0], to(args[1], port))) {
+               return new HTTPResponse(HTTPMessage::OK,
+                               string("<response desc=\"La conexión a ") + args[0] + ":" + args[1]
+                               + " se cerrará en instantes...\" />");
+       } else {
+               return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               string("<response desc=\"No existe una conexión a ") + args[0]
+                               + ":" + args[1] + "\" />");
+       }
+}
+
+HTTPResponse* Server::cmd_transmission_list(void) {
+       // FIXME
+       stringstream xml;
+       xml << "<list type=\"transmission\">" << endl;
+/*TODO plants_mutex.lock();
+       for (PlantList::const_iterator i = plants.begin();
+                       i != plants.end(); i++) {
+               trans
+               xml << "       <li>" << (*i)->get_host() << ":"
+                       << (*i)->get_port() << " [<a href=\"/transmission/stop/"
+                       << (*i)->get_host() << "/" << (*i)->get_port()
+                       << "\">desconectar</a>]</li>" << endl;
+       }
+       transmissions_mutex.unlock();*/
+       xml << "</list>" << endl;
+       return new HTTPResponse(HTTPMessage::OK, xml.str());
 }
 
+HTTPResponse* Server::cmd_transmission_start(const Command& command) {
+       const Command::Arguments& args = command.get_args();
+       if (args.size() < 3) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               "<response desc=\"Faltan argumentos.\" />");
+       } else {
+               string plant = args[0];
+               string host = args[1];
+               Connection::Port port = to(args[2], port);
+               Glib::Mutex::Lock lock(plants_mutex);
+               PlantList::iterator p = plants.find(plant);
+               if (p == plants.end()) {
+                       return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                                       string("<response desc=\"No existe la planta '") + plant + "'.\" />");
+               // TODO - agregar chequeo de que la transmision a ese host:port no
+               //        exista para otra planta?
+               } else if (plants[plant]->transmission_start(host, port)) {
+                       return new HTTPResponse(HTTPMessage::OK,
+                                       string("<response desc=\"Se empieza a transmitir la planta '") + plant
+                                       + "' a " + host + ":" + String().from(port) + ".\" />");
+               } else {
+                       return new HTTPResponse(HTTPMessage::INTERNAL_SERVER_ERROR,
+                                       string("<response desc=\"Error al crear la transmisión a de la planta '")
+                                       + plant + "' a " + host + ":" + args[2] + ".\" />");
+               }
+       }
+}
+
+HTTPResponse* Server::cmd_transmission_stop(const Command& command) {
+       const Command::Arguments& args = command.get_args();
+       if (args.size() < 2) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               "<response desc=\"Faltan argumentos.\" />");
+       } else {
+               const string& host = args[0];
+               Connection::Port port = to(args[1], port);
+               for (PlantList::iterator i = plants.begin(); i != plants.end(); i++) {
+                       // TODO - agregar chequeo para saber si existe una conexion (para
+                       // tirar error de que no hay conexion o de que no se pudo
+                       // desconectar.
+                       if (i->second->transmission_stop(host, port)) {
+                               return new HTTPResponse(HTTPMessage::OK,
+                                               string("<response desc=\"Se finaliza la transmisión de la planta '")
+                                               + i->first + "' a " + host + ":" + args[1] + ".\" />");
+                       }
+               }
+               return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               string("<response desc=\"No se puede finalizar la transmisión a ")
+                               + host + ":" + args[1] + ".\" />");
+       }
+}
+
+HTTPResponse* Server::cmd_plant_list(void) {
+       // FIXME
+       stringstream xml;
+       xml << "<list type=\"plant\">" << endl;
+       plants_mutex.lock();
+       for (PlantList::const_iterator i = plants.begin();
+                       i != plants.end(); i++) {
+               xml << "\t<row>" << endl;
+               xml << "\t\t<cell>" << i->first << "</cell>" << endl;
+               xml << "\t</row>" << endl;
+       }
+       plants_mutex.unlock();
+       xml << "</list>" << endl;
+       return new HTTPResponse(HTTPMessage::OK, xml.str());
+}
+
+HTTPResponse* Server::cmd_plant_get(const Command& command) {
+       if (!command.get_args().size()) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               "<response desc=\"Faltan argumentos.\" />");
+       }
+       Glib::Mutex::Lock lock(plants_mutex);
+       string plant = command.get_args()[0];
+       if (plants.find(plant) == plants.end()) {
+               return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               string("<response desc=\"No existe la planta ") + plant + "\" />");
+       }
+       // TODO try/catch?
+       string xml = plants[plant]->get_xml();
+       if (xml.length()) {
+               return new HTTPResponse(HTTPMessage::OK, xml);
+       } else {
+               return new HTTPResponse(HTTPMessage::INTERNAL_SERVER_ERROR,
+                               ("<response desc=\"No se pudo obtener el XML de la planta ") + plant + "\" />");
+       }
+}
+
+HTTPResponse* Server::cmd_plant_set(const Command& command) {
+       const Command::Arguments& args = command.get_args();
+       if (args.size() < 4) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               "<response desc=\"Faltan argumentos.\" />");
+       }
+       string plant = args[0];
+       string element = args[1];
+       string key = args[2];
+       if (key != "open") {
+               return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               string("<response desc=\"La clave '") + key + "' es inválida.\" />");
+       }
+       string value = args[3];
+       Glib::Mutex::Lock lock(plants_mutex);
+       PlantList::iterator p = plants.find(plant);
+       if (p == plants.end()) {
+               return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               string("<response desc=\"No existe la planta '") + plant + "'.\" />");
+       }
+       bool open = true;
+       if ((value == "false") || (value == "0") || (value == "off")
+                       || (value == "no")) {
+               open = false;
+       }
+       if (!plants[plant]->set_open(element, open)) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               string("<response desc=\"No se pudo cambiar el estado del elemento '") + element + "'.\" />");
+       }
+       return new HTTPResponse(HTTPMessage::OK,
+                       string("<response desc=\"Se cambió el estado del elemento '") + element + "'.\" />");
+}
+
+HTTPResponse* Server::cmd_plant_stop(const Command& command) {
+       if (!command.get_args().size()) {
+               return new HTTPResponse(HTTPMessage::CONFLICT,
+                               "<response desc=\"Faltan argumentos.\" />");
+       }
+       Glib::Mutex::Lock lock(plants_mutex);
+       const string name = command.get_args()[0];
+       if (plants.find(name) == plants.end()) {
+               return new HTTPResponse(HTTPMessage::NOT_FOUND,
+                               string("<response desc=\"No existe la planta ") + name + "\" />");
+       }
+       // TODO Ver si al frenar la planta se destruye (no deberia!!!)
+       plants[name]->finish();
+       return new HTTPResponse(HTTPMessage::OK,
+                       string("<response desc=\"La planta '") + name + "' se cerrará en instantes...\" />");
+}
+
+} // namespace Server
+
+} // namespace PlaQui
+