]> git.llucax.com Git - z.facultad/75.42/plaqui.git/blob - Server/src/server.cpp
Se arregla un bug y se ponen caudales > 0 en el ejemplo :)
[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 #include <sstream>
33 #include <exception>
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__ << "(" << __LINE__ << ")"
48                 <<  ": destructor." << endl;
49 #endif // DEBUG
50         // Termino plantas.
51         Glib::Mutex::Lock lock(plants_mutex);
52         for (PlantList::iterator i = plants.end(); i != plants.end(); i++) {
53                 i->second->finish(true);
54         }
55 }
56
57 Server::Server(const string& plant_filename, const Connection::Port& port)
58                 throw(sockerr): TCPServer(port) {
59 #ifdef DEBUG
60         cerr << __FILE__ << "(" << __LINE__ << ")"
61                 <<  ": port = " << port << endl;
62 #endif // DEBUG
63         // FIXME
64         Glib::Mutex::Lock lock(plants_mutex);
65         plants["default"] = new Plant(plant_filename);
66         plants["default"]->signal_finished().connect(
67                         SigC::bind<const char*>(
68                                 SigC::slot_class(*this, &Server::on_plant_finished),
69                                 "default"));
70         plants["default"]->run();
71 }
72
73 Connection* Server::new_connection(const sockbuf::sockdesc& sd) {
74 #ifdef DEBUG
75         cerr << __FILE__ << "(" << __LINE__ << ")"
76                 <<  ": new_connection(sd = " << sd.sock << ")"
77                 << endl;
78 #endif // DEBUG
79         ControlServer* connection = new ControlServer(sd);
80         // TODO verificar si el new se hace bien? no creo.
81         connection->signal_command_received().connect(
82                         SigC::bind<ControlServer*>(
83                                 SigC::slot_class(*this, &Server::on_control_command_received),
84                                 connection));
85         // TODO: 
86         return connection;
87 }
88
89 void Server::on_plant_finished(const char* plant) {
90 #ifdef DEBUG
91         cerr << __FILE__ << "(" << __LINE__ << ")"
92                 <<  ": on_plant_finished(plant_name = " << plant << endl;
93 #endif // DEBUG
94         Glib::Mutex::Lock lock(plants_mutex);
95         plants.erase(plant);
96 }
97
98 /// \todo Terminar de implementar.
99 void Server::on_control_command_received(const Command& command,
100                 ControlServer* controlserver) {
101 #ifdef DEBUG
102         cerr << __FILE__ << "(" << __LINE__ << ")"
103                 <<  ": on_control_command_received(target = "
104                 << command.get_target() << ", command = " << command.get_command()
105                 << ", args = [" << String::join(command.get_args(), ", ") << "])"
106                 << endl;
107 #endif // DEBUG
108         HTTPResponse* response;
109         //bool stop_controlserver = false;
110         if (command.get_target() == "server") {
111                 if (command.get_command() == "status") {
112                         response = cmd_server_status();
113                 } else if (command.get_command() == "stop") {
114                         finish();
115                         response = new HTTPResponse(HTTPMessage::OK,
116                                         "<response desc=\"El server se apagará en instantes...\" />");
117                 } else {
118                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
119                                         "<response desc=\"Invalid command for 'server' taget!\" />");
120                 }
121         } else if (command.get_target() == "connection") {
122                 if (command.get_command() == "list") {
123                         response = cmd_connection_list();
124                 } else if (command.get_command() == "stop") {
125                         response = cmd_connection_stop(command);
126                 } else {
127                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
128                                         "<response desc=\"Invalid command for 'connection' taget!\" />");
129                 }
130         } else if (command.get_target() == "transmission") {
131                 if (command.get_command() == "list") {
132                         response = cmd_transmission_list();
133                 } else if (command.get_command() == "start") {
134                         response = cmd_transmission_start(command);
135                 } else if (command.get_command() == "stop") {
136                         response = cmd_transmission_stop(command);
137                 } else {
138                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
139                                         "<response desc=\"Invalid command for 'transmission' taget!\" />");
140                 }
141         } else if (command.get_target() == "plant") {
142                 if (command.get_command() == "list") {
143                         response = cmd_plant_list();
144                 } else if (command.get_command() == "get") {
145                         response = cmd_plant_get(command);
146                 } else if (command.get_command() == "set") {
147                         response = cmd_plant_set(command);
148                 } else if (command.get_command() == "stop") {
149                         response = cmd_plant_stop(command);
150                 } else {
151                         response = new HTTPResponse(HTTPMessage::NOT_FOUND,
152                                         "<response desc=\"Invalid command for 'plant' taget!\" />");
153                 }
154         } else {
155                 response = new HTTPResponse(HTTPMessage::NOT_FOUND,
156                                 "<response desc=\"Invalid taget!\" />");
157         }
158         // FIXME
159         response->headers["Content-Type"] = "text/xml; charset=iso-8859-1";
160         //response->headers["Connection"] = "close";
161         controlserver->send(*response);
162         delete response;
163         // FIXME con timeout no debería ser necesario. Verificar cabecera Connection
164         // para saber si hay que finish()earlo o no.
165         //if (stop_controlserver) {
166         //      controlserver->finish();
167         //}
168 }
169
170 HTTPResponse* Server::cmd_server_status(void) const {
171         // FIXME
172         stringstream xml;
173         xml << "<serverstatus>" << endl;
174         xml << "\t<version>" VERSION "</version>" << endl;
175         xml << "\t<authors>" << endl;
176         xml << "\t\t<author>Nicolás Dimov</author>" << endl;
177         xml << "\t\t<author>Leandro Lucarella</author>" << endl;
178         xml << "\t\t<author>Ricardo Markiewicz</author>" << endl;
179         xml << "\t</authors>" << endl;
180         xml << "</serverstatus>" << endl;
181         return new HTTPResponse(HTTPMessage::OK, xml.str());
182 }
183
184 HTTPResponse* Server::cmd_connection_list(void) {
185         // FIXME
186         TCPServer::ConnectionInfoList cil = get_connected();
187         stringstream xml;
188         xml << "<list type=\"connection\">" << endl;
189         for (TCPServer::ConnectionInfoList::const_iterator i = cil.begin();
190                         i != cil.end(); i++) {
191                 xml << "\t<row>" << endl;
192                 xml << "\t\t<cell>" << i->host << "</cell>" << endl;
193                 xml << "\t\t<cell>" << i->port << "</cell>" << endl;
194                 xml << "\t</row>" << endl;
195         }
196         xml << "</list>" << endl;
197         return new HTTPResponse(HTTPMessage::OK, xml.str());
198 }
199
200 HTTPResponse* Server::cmd_connection_stop(const Command& command) {
201         const Command::Arguments& args = command.get_args();
202         Connection::Port port;
203         if (args.size() < 2) {
204                 return new HTTPResponse(HTTPMessage::CONFLICT,
205                                 "<response desc=\"Faltan argumentos.\" />");
206         } else if (disconnect(args[0], to(args[1], port))) {
207                 return new HTTPResponse(HTTPMessage::OK,
208                                 string("<response desc=\"La conexión a ") + args[0] + ":" + args[1]
209                                 + " se cerrará en instantes...\" />");
210         } else {
211                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
212                                 string("<response desc=\"No existe una conexión a ") + args[0]
213                                 + ":" + args[1] + "\" />");
214         }
215 }
216
217 HTTPResponse* Server::cmd_transmission_list(void) {
218         // FIXME
219         stringstream xml;
220         xml << "<list type=\"transmission\">" << endl;
221 /*TODO  plants_mutex.lock();
222         for (PlantList::const_iterator i = plants.begin();
223                         i != plants.end(); i++) {
224                 trans
225                 xml << "       <li>" << (*i)->get_host() << ":"
226                         << (*i)->get_port() << " [<a href=\"/transmission/stop/"
227                         << (*i)->get_host() << "/" << (*i)->get_port()
228                         << "\">desconectar</a>]</li>" << endl;
229         }
230         transmissions_mutex.unlock();*/
231         xml << "</list>" << endl;
232         return new HTTPResponse(HTTPMessage::OK, xml.str());
233 }
234
235 HTTPResponse* Server::cmd_transmission_start(const Command& command) {
236         const Command::Arguments& args = command.get_args();
237         if (args.size() < 3) {
238                 return new HTTPResponse(HTTPMessage::CONFLICT,
239                                 "<response desc=\"Faltan argumentos.\" />");
240         } else {
241                 string plant = args[0];
242                 string host = args[1];
243                 Connection::Port port = to(args[2], port);
244                 Glib::Mutex::Lock lock(plants_mutex);
245                 PlantList::iterator p = plants.find(plant);
246                 if (p == plants.end()) {
247                         return new HTTPResponse(HTTPMessage::NOT_FOUND,
248                                         string("<response desc=\"No existe la planta '") + plant + "'.\" />");
249                 // TODO - agregar chequeo de que la transmision a ese host:port no
250                 //        exista para otra planta?
251                 } else if (plants[plant]->transmission_start(host, port)) {
252                         return new HTTPResponse(HTTPMessage::OK,
253                                         string("<response desc=\"Se empieza a transmitir la planta '") + plant
254                                         + "' a " + host + ":" + String().from(port) + ".\" />");
255                 } else {
256                         return new HTTPResponse(HTTPMessage::INTERNAL_SERVER_ERROR,
257                                         string("<response desc=\"Error al crear la transmisión a de la planta '")
258                                         + plant + "' a " + host + ":" + args[2] + ".\" />");
259                 }
260         }
261 }
262
263 HTTPResponse* Server::cmd_transmission_stop(const Command& command) {
264         const Command::Arguments& args = command.get_args();
265         if (args.size() < 2) {
266                 return new HTTPResponse(HTTPMessage::CONFLICT,
267                                 "<response desc=\"Faltan argumentos.\" />");
268         } else {
269                 const string& host = args[0];
270                 Connection::Port port = to(args[1], port);
271                 for (PlantList::iterator i = plants.begin(); i != plants.end(); i++) {
272                         // TODO - agregar chequeo para saber si existe una conexion (para
273                         // tirar error de que no hay conexion o de que no se pudo
274                         // desconectar.
275                         if (i->second->transmission_stop(host, port)) {
276                                 return new HTTPResponse(HTTPMessage::OK,
277                                                 string("<response desc=\"Se finaliza la transmisión de la planta '")
278                                                 + i->first + "' a " + host + ":" + args[1] + ".\" />");
279                         }
280                 }
281                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
282                                 string("<response desc=\"No se puede finalizar la transmisión a ")
283                                 + host + ":" + args[1] + ".\" />");
284         }
285 }
286
287 HTTPResponse* Server::cmd_plant_list(void) {
288         // FIXME
289         stringstream xml;
290         xml << "<list type=\"plant\">" << endl;
291         plants_mutex.lock();
292         for (PlantList::const_iterator i = plants.begin();
293                         i != plants.end(); i++) {
294                 xml << "\t<row>" << endl;
295                 xml << "\t\t<cell>" << i->first << "</cell>" << endl;
296                 xml << "\t</row>" << endl;
297         }
298         plants_mutex.unlock();
299         xml << "</list>" << endl;
300         return new HTTPResponse(HTTPMessage::OK, xml.str());
301 }
302
303 HTTPResponse* Server::cmd_plant_get(const Command& command) {
304         if (!command.get_args().size()) {
305                 return new HTTPResponse(HTTPMessage::CONFLICT,
306                                 "<response desc=\"Faltan argumentos.\" />");
307         }
308         Glib::Mutex::Lock lock(plants_mutex);
309         string plant = command.get_args()[0];
310         if (plants.find(plant) == plants.end()) {
311                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
312                                 string("<response desc=\"No existe la planta ") + plant + "\" />");
313         }
314         // TODO try/catch?
315         string xml = plants[plant]->get_xml();
316         if (xml.length()) {
317                 return new HTTPResponse(HTTPMessage::OK, xml);
318         } else {
319                 return new HTTPResponse(HTTPMessage::INTERNAL_SERVER_ERROR,
320                                 ("<response desc=\"No se pudo obtener el XML de la planta ") + plant + "\" />");
321         }
322 }
323
324 HTTPResponse* Server::cmd_plant_set(const Command& command) {
325         const Command::Arguments& args = command.get_args();
326         if (args.size() < 4) {
327                 return new HTTPResponse(HTTPMessage::CONFLICT,
328                                 "<response desc=\"Faltan argumentos.\" />");
329         }
330         string plant = args[0];
331         string element = args[1];
332         string key = args[2];
333         if (key != "open") {
334                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
335                                 string("<response desc=\"La clave '") + key + "' es inválida.\" />");
336         }
337         string value = args[3];
338         Glib::Mutex::Lock lock(plants_mutex);
339         PlantList::iterator p = plants.find(plant);
340         if (p == plants.end()) {
341                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
342                                 string("<response desc=\"No existe la planta '") + plant + "'.\" />");
343         }
344         bool open = true;
345         if ((value == "false") || (value == "0") || (value == "off")
346                         || (value == "no")) {
347                 open = false;
348         }
349         if (!plants[plant]->set_open(element, open)) {
350                 return new HTTPResponse(HTTPMessage::CONFLICT,
351                                 string("<response desc=\"No se pudo cambiar el estado del elemento '") + element + "'.\" />");
352         }
353         return new HTTPResponse(HTTPMessage::OK,
354                         string("<response desc=\"Se cambió el estado del elemento '") + element + "'.\" />");
355 }
356
357 HTTPResponse* Server::cmd_plant_stop(const Command& command) {
358         if (!command.get_args().size()) {
359                 return new HTTPResponse(HTTPMessage::CONFLICT,
360                                 "<response desc=\"Faltan argumentos.\" />");
361         }
362         Glib::Mutex::Lock lock(plants_mutex);
363         const string name = command.get_args()[0];
364         if (plants.find(name) == plants.end()) {
365                 return new HTTPResponse(HTTPMessage::NOT_FOUND,
366                                 string("<response desc=\"No existe la planta ") + name + "\" />");
367         }
368         // TODO Ver si al frenar la planta se destruye (no deberia!!!)
369         plants[name]->finish();
370         return new HTTPResponse(HTTPMessage::OK,
371                         string("<response desc=\"La planta '") + name + "' se cerrará en instantes...\" />");
372 }
373
374 } // namespace Server
375
376 } // namespace PlaQui
377