Updated license
[anna.git] / example / comm / blocker / main.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 /*
38    El objetivo de éste programa es generar errores en el cliente que se conecte a él.
39
40    Como no atiendo ningún tipo de.tráfico llegará un momento en el que su cola de entrada
41    alcanzará el límite y el cliente obtendrá un error al intentar enviar el mensaje.
42
43    Se trata de verificar que los servicios de reparto son capaces de asumir ciertos
44    tipos de error.
45 */
46 #include <iostream>
47 #include <signal.h>
48
49 #include <anna/core/core.hpp>
50 #include <anna/comm/comm.hpp>
51
52 #include <anna/xml/Node.hpp>
53 #include <anna/xml/Attribute.hpp>
54
55 using namespace std;
56
57 class MyCommunicator : public Communicator {
58 public:
59    MyCommunicator () {;}
60       
61 private:
62    void eventReceiveMessage (comm::ClientSocket&, const Message&) throw (RuntimeException);
63 };
64
65 class Blocker : public comm::Application {
66 public:
67    Blocker ();
68       
69 private:
70    MyCommunicator a_communicator;
71    comm::ServerSocket* a_blockerSocket;
72
73    void initialize () throw (RuntimeException);
74    void run () throw (RuntimeException);
75 };
76
77 using namespace std;
78 using namespace anna::comm;
79
80 int main (int argc, const char** argv)
81 {
82    CommandLine& commandLine (CommandLine::instantiate ());
83    Blocker app;
84
85    srand (time (NULL));
86
87    sigignore (SIGABRT);
88    
89    try {
90       commandLine.initialize (argv, argc);
91       commandLine.verify ();
92
93       Logger::setLevel (Logger::Debug); 
94       Logger::initialize ("Blocker", new TraceWriter ("file.trace",4096000));
95  
96       app.start ();
97    }
98    catch (Exception& ex) {
99       cout << ex.asString () << endl;
100    }
101    
102    return 0;
103 }
104
105 Blocker::Blocker () : 
106    Application ("Blocker", "Bloqueador de comunicaciones", "1.0") 
107 {
108    CommandLine& commandLine (CommandLine::instantiate ());
109       
110    commandLine.add ("p", CommandLine::Argument::Mandatory, "Puerto en el que atender peticiones");
111    commandLine.add ("a", CommandLine::Argument::Mandatory, "Direccin IP en la que atender");
112    commandLine.add ("trace", CommandLine::Argument::Optional, "Nivel de trazas (debug,warning, error,...)");
113 }
114
115 //-----------------------------------------------------------------------------------------
116 // Inicializa el servidor de sockets.
117 //-----------------------------------------------------------------------------------------
118 void Blocker::initialize () 
119    throw (RuntimeException)
120 {
121    CommandLine& cl (CommandLine::instantiate ());
122
123    int port = cl.getIntegerValue ("p");
124    const comm::Device* device = Network::instantiate ().find (Device::asAddress (cl.getValue ("a")));
125
126    a_blockerSocket = new ServerSocket (INetAddress (device, port), false);
127    a_blockerSocket->setCategory (777);
128 }
129
130 //-----------------------------------------------------------------------------------------
131 // Atiende las peticiones.
132 // Cuando hay un nuevo mensaje invocar�a Communicator::eventReceiveMessage
133 //-----------------------------------------------------------------------------------------
134 void Blocker::run ()
135    throw (RuntimeException)
136 {
137    CommandLine& cl (CommandLine::instantiate ());
138
139    a_communicator.attach (a_blockerSocket);
140
141    if (cl.exists ("trace"))
142       Logger::setLevel (Logger::asLevel (cl.getValue ("trace")));
143
144    a_communicator.accept ();
145 }
146
147 //-----------------------------------------------------------------------------------------
148 // Cuando recibe el primer mensaje deja al sistema bloqueado esperando una tecla.
149 //-----------------------------------------------------------------------------------------
150 void MyCommunicator::eventReceiveMessage (ClientSocket& clientSocket, const Message& message)
151    throw (RuntimeException)
152 {
153    LOGMETHOD (TraceMethod tm ("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
154    static bool blocking = true;
155
156    if (blocking == false) 
157       return;
158
159    char aux [1024];
160    bool stop = false;
161
162    app::Application& app = app::functions::getApp ();
163    cout << "Bloqueando las comunicaciones ejecute (kill -9 " << app.getPid ()  << ") ... " << flush;
164    while (stop == false) {
165       if (gets (aux) != NULL) {
166          if (aux [0] == 'q' || aux [0] == 'Q')
167             stop = true;
168       }
169       sleep (10);
170    } 
171
172    blocking = false;
173 }
174