]> git.llucax.com Git - z.facultad/75.42/plaqui.git/blob - Server/src/server.cpp
- Se agrega una planta de prueba (usando Simulator).
[z.facultad/75.42/plaqui.git] / Server / src / server.cpp
1 // vim: set noexpandtab tabstop=4 shiftwidth=4:
2 //----------------------------------------------------------------------------
3 //                                  PlaQui
4 //----------------------------------------------------------------------------
5 // This file is part of PlaQui.
6 //
7 // PlaQui is free software; you can redistribute it and/or modify it under the
8 // terms of the GNU General Public License as published by the Free Software
9 // Foundation; either version 2 of the License, or (at your option) any later
10 // version.
11 //
12 // PlaQui is distributed in the hope that it will be useful, but WITHOUT ANY
13 // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 // details.
16 //
17 // You should have received a copy of the GNU General Public License along
18 // with PlaQui; if not, write to the Free Software Foundation, Inc., 59 Temple
19 // Place, Suite 330, Boston, MA  02111-1307  USA
20 //----------------------------------------------------------------------------
21 // Creado:  Sat Oct 18 18:18:36 2003
22 // Autores: Leandro Lucarella <llucare@fi.uba.ar>
23 //----------------------------------------------------------------------------
24 //
25 // $Id$
26 //
27
28 #include "plaqui/server/server.h"
29 #include "plaqui/server/connection.h"
30 #include "plaqui/server/controlserver.h"
31 #include <sigc++/class_slot.h>
32 // FIXME - sacar sstream (a menos que se necesite)
33 #include <sstream>
34 #ifdef DEBUG
35 #       include "plaqui/server/string.h"
36 #       include <iostream>
37 #endif // DEBUG
38
39 using namespace std;
40
41 namespace PlaQui {
42
43 namespace Server {
44
45 Server::~Server(void) {
46 #ifdef DEBUG
47         cerr << __FILE__ <<  ": destructor." << endl;
48 #endif // DEBUG
49         // Termino plantas.
50         Glib::Mutex::Lock lock(plants_mutex);
51         for (PlantList::iterator i = plants.end(); i != plants.end(); i++) {
52                 i->second->finish(true);
53         }
54 }
55
56 Server::Server(int port): TCPServer(port) {
57 #ifdef DEBUG
58         cerr << __FILE__ <<  ": port = " << port << endl;
59 #endif // DEBUG
60         // FIXME
61         Glib::Mutex::Lock lock(plants_mutex);
62         plants["prueba"] = new Plant("prueba.xml");
63         plants["prueba"]->signal_finished().connect(
64                         SigC::bind<const char*>(
65                                 SigC::slot_class(*this, &Server::on_plant_finished),
66                                 "prueba"));
67         plants["prueba"]->run();
68 }
69
70 Connection* Server::new_connection(
71                 const sockbuf::sockdesc& sd) {
72 #ifdef DEBUG
73         cerr << __FILE__ <<  ": new_connection(sd = " << sd.sock << ")"
74                 << endl;
75 #endif // DEBUG
76         ControlServer* connection = new ControlServer(sd);
77         // TODO verificar si el new se hace bien? no creo.
78         connection->signal_command_received().connect(
79                         SigC::bind<ControlServer*>(
80                                 SigC::slot_class(*this, &Server::on_control_command_received),
81                                 connection));
82         // TODO: 
83         return connection;
84 }
85
86 void Server::on_plant_updated(const Plant* plant) {
87 #ifdef DEBUG
88         cerr << __FILE__ << ": on_plant_updated(plant = " << plant << ")." << endl;
89 #endif // DEBUG
90 }
91
92 void Server::on_plant_finished(const char* plant) {
93 #ifdef DEBUG
94         cerr << __FILE__ <<  ": on_plant_finished(plant_name = " << plant << endl;
95 #endif // DEBUG
96         Glib::Mutex::Lock lock(plants_mutex);
97         plants.erase(plant);
98 }
99
100 /// \todo Terminar de implementar.
101 void Server::on_control_command_received(const Command& command,
102                 ControlServer* controlserver) {
103 #ifdef DEBUG
104         cerr << __FILE__ <<  ": on_control_command_received(target = "
105                 << command.get_target() << ", command = " << command.get_command()
106                 << ", args = [" << String::join(command.get_args(), ", ") << "])"
107                 << endl;
108 #endif // DEBUG
109         HTTPResponse* response;
110         //bool stop_controlserver = false;
111         if (command.get_target() == "server") {
112                 if (command.get_command() == "status") {
113                         response = cmd_server_status();
114                 } else if (command.get_command() == "stop") {
115                         finish();
116                         response = new HTTPResponse(HTTPMessage::OK,
117                                         "El server se apagará en instantes...");
118                 } else {
119                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
120                                         "Invalid command for 'server' taget!");
121                 }
122         } else if (command.get_target() == "connection") {
123                 if (command.get_command() == "list") {
124                         response = cmd_connection_list();
125                 } else if (command.get_command() == "stop") {
126                         response = cmd_connection_stop(command);
127                 } else {
128                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
129                                         "Invalid command for 'connection' taget!");
130                 }
131         } else if (command.get_target() == "transmission") {
132                 if (command.get_command() == "list") {
133                         response = cmd_transmission_list();
134                 } else if (command.get_command() == "start") {
135                         response = cmd_transmission_start(command);
136                 } else if (command.get_command() == "stop") {
137                         response = cmd_transmission_stop(command);
138                 } else {
139                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
140                                         "Invalid command for 'transmission' taget!");
141                 }
142         } else if (command.get_target() == "plant") {
143                 if (command.get_command() == "list") {
144                         response = cmd_plant_list();
145                 } else if (command.get_command() == "stop") {
146                         response = cmd_plant_stop(command);
147                 } else {
148                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
149                                         "Invalid command for 'plant' taget!");
150                 }
151         } else {
152                 response = new HTTPResponse(HTTPMessage::NOT_FOUND, "Invalid taget!");
153         }
154         // FIXME
155         response->headers["Content-Type"] = "text/html; charset=iso-8859-1";
156         //response->headers["Connection"] = "close";
157         controlserver->send(*response);
158         delete response;
159         // FIXME con timeout no debería ser necesario. Verificar cabecera Connection
160         // para saber si hay que finish()earlo o no.
161         //if (stop_controlserver) {
162         //      controlserver->finish();
163         //}
164 }
165
166 HTTPResponse* Server::cmd_server_status(void) const {
167         // FIXME
168         stringstream response_xml;
169         response_xml << "<html>" << endl;
170         response_xml << "    <head>" << endl;
171         response_xml << "        <title>PlaQui v0.8</title>" << endl;
172         response_xml << "    </head>" << endl;
173         response_xml << "    <body>" << endl;
174         response_xml << "        <h1>PlaQui</h1>" << endl;
175         response_xml << "        <p>versión 0.8</p>" << endl;
176 /*      response_xml << "        <h2>Comando</h2>" << endl;
177         response_xml << "        <ul>" << endl;
178         response_xml << "           <li><b>Target:</b> " << command.get_target() << endl;
179         response_xml << "           <li><b>Command:</b> " << command.get_command() << endl;
180         response_xml << "           <li><b>Argumentos:</b>" << endl;
181         response_xml << "               <ol>" << endl;
182         for (Command::Arguments::const_iterator i = command.get_args().begin();
183                         i != command.get_args().end(); i++) {
184                 response_xml << "                   <li>" << *i << "</li>" << endl;
185         }
186         response_xml << "               </ol>" << endl;
187         response_xml << "        </ul>" << endl;*/
188         response_xml << "        <h2>Desarrollado por</h2>" << endl;
189         response_xml << "        <ul>" << endl;
190         response_xml << "            <li>Nicolás Dimov.</li>" << endl;
191         response_xml << "            <li>Leandro Lucarella.</li>" << endl;
192         response_xml << "            <li>Ricardo Markiewicz.</li>" << endl;
193         response_xml << "        </ul>" << endl;
194         response_xml << "        <address>" << endl;
195         response_xml << "             Copyleft 2003 - bajo los " << endl;
196         response_xml << "             términos de la licencia GPL" << endl;
197         response_xml << "        </address>" << endl;
198         response_xml << "    </body>" << endl;
199         response_xml << "</html>" << endl;
200         return new HTTPResponse(HTTPMessage::OK, response_xml.str());
201 }
202
203 HTTPResponse* Server::cmd_connection_list(void) {
204         // FIXME
205         TCPServer::ConnectionInfoList cil = get_connected();
206         stringstream response_xml;
207         response_xml << "<html>" << endl;
208         response_xml << "    <head>" << endl;
209         response_xml << "        <title>PlaQui v0.8</title>" << endl;
210         response_xml << "    </head>" << endl;
211         response_xml << "    <body>" << endl;
212         response_xml << "        <h1>PlaQui</h1>" << endl;
213         response_xml << "        <p>versión 0.8</p>" << endl;
214         response_xml << "        <h2>Lista de conexiones:</h2>" << endl;
215         response_xml << "        <ul>" << endl;
216         for (TCPServer::ConnectionInfoList::const_iterator i = cil.begin();
217                         i != cil.end(); i++) {
218                 response_xml << "       <li>" << i->host
219                         << ":" << i->port << " [<a href=\"/connection/stop/"
220                         << i->host << "/" << i->port << "\">deconectar</a>]</li>"
221                         << endl;
222         }
223         response_xml << "        </ul>" << endl;
224         response_xml << "        <address>" << endl;
225         response_xml << "             Copyleft 2003 - bajo los " << endl;
226         response_xml << "             términos de la licencia GPL" << endl;
227         response_xml << "        </address>" << endl;
228         response_xml << "    </body>" << endl;
229         response_xml << "</html>" << endl;
230         return new HTTPResponse(HTTPMessage::OK, response_xml.str());
231 }
232
233 HTTPResponse* Server::cmd_connection_stop(const Command& command) {
234         const Command::Arguments& args = command.get_args();
235         Connection::Port port;
236         if (args.size() < 2) {
237                 return new HTTPResponse(HTTPMessage::CONFLICT,
238                                 "Faltan argumentos.");
239         } else if (disconnect(args[0], String(args[1]).to(port))) {
240                 return new HTTPResponse(HTTPMessage::OK,
241                                 string("La conexión a ") + args[0] + ":" + args[1]
242                                 + " se cerrará en instantes...");
243         } else {
244                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
245                                 string("No existe una conexión a ") + args[0]
246                                 + ":" + args[1]);
247         }
248 }
249
250 HTTPResponse* Server::cmd_transmission_list(void) {
251         // FIXME
252         stringstream response_xml;
253         response_xml << "<html>" << endl;
254         response_xml << "    <head>" << endl;
255         response_xml << "        <title>PlaQui v0.8</title>" << endl;
256         response_xml << "    </head>" << endl;
257         response_xml << "    <body>" << endl;
258         response_xml << "        <h1>PlaQui</h1>" << endl;
259         response_xml << "        <p>versión 0.8</p>" << endl;
260         response_xml << "        <h2>Lista de transmisiones:</h2>" << endl;
261         response_xml << "        <ul>" << endl;
262         // TODO - recorrer todas las plantas y sus transmisiones.
263 /*      transmissions_mutex.lock();
264         for (TransmitterList::const_iterator i = transmissions.begin();
265                         i != transmissions.end(); i++) {
266                 response_xml << "       <li>" << (*i)->get_host() << ":"
267                         << (*i)->get_port() << " [<a href=\"/transmission/stop/"
268                         << (*i)->get_host() << "/" << (*i)->get_port()
269                         << "\">desconectar</a>]</li>" << endl;
270         }
271         transmissions_mutex.unlock();*/
272         response_xml << "        </ul>" << endl;
273         response_xml << "        <address>" << endl;
274         response_xml << "             Copyleft 2003 - bajo los " << endl;
275         response_xml << "             términos de la licencia GPL" << endl;
276         response_xml << "        </address>" << endl;
277         response_xml << "    </body>" << endl;
278         response_xml << "</html>" << endl;
279         return new HTTPResponse(HTTPMessage::OK, response_xml.str());
280 }
281
282 HTTPResponse* Server::cmd_transmission_start(const Command& command) {
283         const Command::Arguments& args = command.get_args();
284         if (args.size() < 3) {
285                 return new HTTPResponse(HTTPMessage::CONFLICT,
286                                 "Faltan argumentos.");
287         } else {
288                 const string& plant = args[0];
289                 const string& host = args[1];
290                 Connection::Port port = String(args[2]).to(port);
291                 Glib::Mutex::Lock lock(plants_mutex);
292                 PlantList::iterator p = plants.find(plant);
293                 if (p == plants.end()) {
294                         return new HTTPResponse(HTTPMessage::NOT_FOUND,
295                                         string("No existe la planta '") + plant + "'.");
296                 // TODO - agregar chequeo de que la transmision a ese host:port no
297                 //        exista para otra planta?
298                 } else if (plants[plant]->transmission_start(host, port)) {
299                         return new HTTPResponse(HTTPMessage::OK,
300                                         string("Se empieza a transmitir la planta '") + plant
301                                         + "' a " + host + ":" + args[1] + ".");
302                 } else {
303                         return new HTTPResponse(HTTPMessage::INTERNAL_SERVER_ERROR,
304                                         string("Error al crear la transmisión a de la planta '")
305                                         + plant + "' a " + host + ":" + args[2] + ".");
306                 }
307         }
308 }
309
310 HTTPResponse* Server::cmd_transmission_stop(const Command& command) {
311         const Command::Arguments& args = command.get_args();
312         if (args.size() < 2) {
313                 return new HTTPResponse(HTTPMessage::CONFLICT,
314                                 "Faltan argumentos.");
315         } else {
316                 const string& host = args[0];
317                 Connection::Port port = String(args[1]).to(port);
318                 for (PlantList::iterator i = plants.begin(); i != plants.end(); i++) {
319                         // TODO - agregar chequeo para saber si existe una conexion (para
320                         // tirar error de que no hay conexion o de que no se pudo
321                         // desconectar.
322                         if (i->second->transmission_stop(host, port)) {
323                                 return new HTTPResponse(HTTPMessage::OK,
324                                                 string("Se finaliza la transmisión de la planta '")
325                                                 + i->first + "' a " + host + ":" + args[1] + ".");
326                         }
327                 }
328                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
329                                 string("No se puede finalizar la transmisión a ")
330                                 + host + ":" + args[1] + ".");
331         }
332 }
333
334 HTTPResponse* Server::cmd_plant_list(void) {
335         // FIXME
336         stringstream response_xml;
337         response_xml << "<html>" << endl;
338         response_xml << "    <head>" << endl;
339         response_xml << "        <title>PlaQui v0.8</title>" << endl;
340         response_xml << "    </head>" << endl;
341         response_xml << "    <body>" << endl;
342         response_xml << "        <h1>PlaQui</h1>" << endl;
343         response_xml << "        <p>versión 0.8</p>" << endl;
344         response_xml << "        <h2>Lista de plantas:</h2>" << endl;
345         response_xml << "        <ul>" << endl;
346         plants_mutex.lock();
347         for (PlantList::const_iterator i = plants.begin();
348                         i != plants.end(); i++) {
349                 response_xml << "       <li>" << i->first
350                         << " [<a href=\"/plant/stop/" << i->first << "\">parar</a>]</li>"
351                         << endl;
352         }
353         plants_mutex.unlock();
354         response_xml << "        </ul>" << endl;
355         response_xml << "        <address>" << endl;
356         response_xml << "             Copyleft 2003 - bajo los " << endl;
357         response_xml << "             términos de la licencia GPL" << endl;
358         response_xml << "        </address>" << endl;
359         response_xml << "    </body>" << endl;
360         response_xml << "</html>" << endl;
361         return new HTTPResponse(HTTPMessage::OK, response_xml.str());
362 }
363
364 HTTPResponse* Server::cmd_plant_stop(const Command& command) {
365         if (!command.get_args().size()) {
366                 return new HTTPResponse(HTTPMessage::CONFLICT,
367                                 "Faltan argumentos.");
368         }
369         Glib::Mutex::Lock lock(plants_mutex);
370         const string name = command.get_args()[0];
371         if (plants.find(name) == plants.end()) {
372                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
373                                 string("No existe la planta ") + name);
374         }
375         // TODO Ver si al frenar la planta se destruye (no deberia!!!)
376         plants[name]->finish();
377         return new HTTPResponse(HTTPMessage::OK,
378                         string("La planta '") + name + "' se cerrará en instantes...");
379 }
380
381 } // namespace Server
382
383 } // namespace PlaQui
384