First commit
[anna.git] / source / timex / internal / TickConsumer.cpp
1 // ANNA - Anna is Not 'N' 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 #include <unistd.h>
38 #include <fcntl.h>
39 #include <stdlib.h>
40 #include <sys/types.h>
41
42 #include <anna/core/tracing/Logger.hpp>
43
44 #include <anna/timex/Engine.hpp>
45 #include <anna/timex/internal/TickConsumer.hpp>
46 #include <anna/timex/internal/TickProducer.hpp>
47
48 using namespace std;
49 using namespace anna;
50
51 //--------------------------------------------------------------------------------------------
52 // (1) Para evitar que el 'write' sobre el pipe se pueda quedar bloqueado cuando halla algn
53 //     problema. Se detecto el bloqueo cuando el disco sobre el que se ejecutaba la aplicacin
54 //     se llenaba.
55 // (2) Puede ser que se invoque mas de una vez.
56 //--------------------------------------------------------------------------------------------
57 void timex::TickConsumer::initialize()
58 throw(RuntimeException) {
59   if(a_pipe [0] != -1)                                        // (2)
60     return;
61
62   if(pipe(a_pipe) != 0)
63     throw RuntimeException("Cannot create the pipe", errno, ANNA_FILE_LOCATION);
64
65   if(fcntl(a_pipe [1], F_SETFL, O_NONBLOCK | O_NDELAY) == -1)    // (1)
66     throw RuntimeException("Cannot establish Non-Block mode on pipe", errno, ANNA_FILE_LOCATION);
67
68   setfd(a_pipe [0]);
69 }
70
71 void timex::TickConsumer::apply()
72 throw(RuntimeException) {
73   char buffer [256];
74
75   if(a_pipe [0] == -1)
76     return;
77
78   int r;
79
80   try {
81     anna_signal_shield(r, read(a_pipe [0], buffer, sizeof(buffer)));
82
83     if(r < 0)
84       Logger::write(Logger::Critical, "Cannot recover the tick", strerror(errno), ANNA_FILE_LOCATION);
85
86     while(r > 0) {
87       a_timeController.tick();
88       r --;
89     }
90   } catch(Exception& ex) {
91     ex.trace();
92   }
93 }
94
95 void timex::TickConsumer::finalize()
96 throw() {
97   if(a_timeController.a_tickProducer)
98     a_timeController.a_tickProducer->requestStop();
99 }
100
101 /**
102  * Si usaramos directamente el duplicado de los fd's que hace fork, todos los procesos compartirian el
103  * mismo pipe, es decir, el proceso padre podria escribir al generar la alarma, pero el tratamiento del
104  * tick podria hacerlo el tercer hijo, lo que haria imposible el correcto funcionamiento de las transaciones.
105  *
106  * Asi que cada proceso debe tener su propia copia del pipe, para que cada uno lleve independientemente
107  * el control de tiempos.
108  */
109 void timex::TickConsumer::clone()
110 throw(RuntimeException) {
111   close(a_pipe [0]);
112   close(a_pipe [1]);
113
114   if(pipe(a_pipe) != 0)
115     throw RuntimeException("Cannot create the pipe", errno, ANNA_FILE_LOCATION);
116
117   if(fcntl(a_pipe [1], F_SETFL, O_NONBLOCK | O_NDELAY) == -1)    // (1)
118     throw RuntimeException("Cannot establish Non-Block mode on pipe", errno, ANNA_FILE_LOCATION);
119
120   setfd(a_pipe [0]);
121
122   if(a_timeController.a_tickProducer)
123     a_timeController.a_tickProducer->setfd(a_pipe [1]);
124 }
125
126 std::string timex::TickConsumer::asString() const
127 throw() {
128   string result("timex::TickConsumer { ");
129   result += Handler::asString();
130   return result += functions::asString(" | Pipe (Read = %d, Write = %d) } ", a_pipe [0], a_pipe [1]);
131 }
132
133