Add some tests for milestone dependencies.
[oweals/dinit.git] / src / control.h
1 #ifndef DINIT_CONTROL_H
2 #define DINIT_CONTROL_H
3
4 #include <list>
5 #include <vector>
6 #include <unordered_map>
7 #include <limits>
8 #include <cstddef>
9
10 #include <unistd.h>
11
12 #include "dasynq.h"
13
14 #include "dinit-log.h"
15 #include "control-cmds.h"
16 #include "service-listener.h"
17 #include "cpbuffer.h"
18
19 // Control connection for dinit
20
21 using namespace dasynq;
22 using eventloop_t = event_loop<null_mutex>;
23
24 class control_conn_t;
25 class control_conn_watcher;
26
27 // forward-declaration of callback:
28 static rearm control_conn_cb(eventloop_t *loop, control_conn_watcher *watcher, int revents);
29
30 // Pointer to the control connection that is listening for rollback completion
31 extern control_conn_t * rollback_handler_conn;
32
33 extern int active_control_conns;
34
35 // "packet" format:
36 // (1 byte) packet type
37 // (N bytes) additional data (service name, etc)
38 //   for LOADSERVICE/FINDSERVICE:
39 //      (2 bytes) service name length
40 //      (M bytes) service name (without nul terminator)
41
42 // Information packet:
43 // (1 byte) packet type, >= 100
44 // (1 byte) packet length (including all fields)
45 //       N bytes: packet data (N = (length - 2))
46
47 class service_set;
48 class service_record;
49
50 class control_conn_watcher : public eventloop_t::bidi_fd_watcher_impl<control_conn_watcher>
51 {
52     inline rearm receiveEvent(eventloop_t &loop, int fd, int flags) noexcept;
53
54     public:
55     rearm read_ready(eventloop_t &loop, int fd) noexcept
56     {
57         return receiveEvent(loop, fd, IN_EVENTS);
58     }
59     
60     rearm write_ready(eventloop_t &loop, int fd) noexcept
61     {
62         return receiveEvent(loop, fd, OUT_EVENTS);
63     }
64     
65     eventloop_t * eventLoop;
66     
67     void set_watches(int flags)
68     {
69         eventloop_t::bidi_fd_watcher::set_watches(*eventLoop, flags);
70     }
71     
72     void registerWith(eventloop_t &loop, int fd, int flags)
73     {
74         this->eventLoop = &loop;
75         bidi_fd_watcher<eventloop_t>::add_watch(loop, fd, flags);
76     }
77 };
78
79 inline rearm control_conn_watcher::receiveEvent(eventloop_t &loop, int fd, int flags) noexcept
80 {
81     return control_conn_cb(&loop, this, flags);
82 }
83
84
85 class control_conn_t : private service_listener
86 {
87     friend rearm control_conn_cb(eventloop_t *loop, control_conn_watcher *watcher, int revents);
88     
89     control_conn_watcher iob;
90     eventloop_t *loop;
91     service_set *services;
92     
93     bool bad_conn_close = false; // close when finished output?
94     bool oom_close = false;      // send final 'out of memory' indicator
95
96     // The packet length before we need to re-check if the packet is complete.
97     // processPacket() will not be called until the packet reaches this size.
98     int chklen;
99     
100     // Receive buffer
101     cpbuffer<1024> rbuf;
102     
103     template <typename T> using list = std::list<T>;
104     template <typename T> using vector = std::vector<T>;
105     
106     // A mapping between service records and their associated numerical identifier used
107     // in communction
108     using handle_t = uint32_t;
109     std::unordered_multimap<service_record *, handle_t> serviceKeyMap;
110     std::unordered_map<handle_t, service_record *> keyServiceMap;
111     
112     // Buffer for outgoing packets. Each outgoing back is represented as a vector<char>.
113     list<vector<char>> outbuf;
114     // Current index within the first outgoing packet (all previous bytes have been sent).
115     unsigned outpkt_index = 0;
116     
117     // Queue a packet to be sent
118     //  Returns:  false if the packet could not be queued and a suitable error packet
119     //              could not be sent/queued (the connection should be closed);
120     //            true (with bad_conn_close == false) if the packet was successfully
121     //              queued;
122     //            true (with bad_conn_close == true) if the packet was not successfully
123     //              queued (but a suitable error packate has been queued).
124     // The in/out watch enabled state will also be set appropriately.
125     bool queuePacket(vector<char> &&v) noexcept;
126     bool queuePacket(const char *pkt, unsigned size) noexcept;
127
128     // Process a packet.
129     //  Returns:  true (with bad_conn_close == false) if successful
130     //            true (with bad_conn_close == true) if an error packet was queued
131     //            false if an error occurred but no error packet could be queued
132     //                (connection should be closed).
133     // Throws:
134     //    std::bad_alloc - if an out-of-memory condition prevents processing
135     bool processPacket();
136     
137     // Process a STARTSERVICE/STOPSERVICE packet. May throw std::bad_alloc.
138     bool processStartStop(int pktType);
139     
140     // Process a FINDSERVICE/LOADSERVICE packet. May throw std::bad_alloc.
141     bool processFindLoad(int pktType);
142
143     // Process an UNPINSERVICE packet. May throw std::bad_alloc.
144     bool processUnpinService();
145     
146     bool listServices();
147
148     // Notify that data is ready to be read from the socket. Returns true if the connection should
149     // be closed.
150     bool dataReady() noexcept;
151     
152     bool sendData() noexcept;
153     
154     // Allocate a new handle for a service; may throw std::bad_alloc
155     handle_t allocateServiceHandle(service_record *record);
156     
157     service_record *findServiceForKey(uint32_t key)
158     {
159         try {
160             return keyServiceMap.at(key);
161         }
162         catch (std::out_of_range &exc) {
163             return nullptr;
164         }
165     }
166     
167     // Close connection due to out-of-memory condition.
168     void doOomClose()
169     {
170         bad_conn_close = true;
171         oom_close = true;
172         iob.set_watches(OUT_EVENTS);
173     }
174     
175     // Process service event broadcast.
176     // Note that this can potentially be called during packet processing (upon issuing
177     // service start/stop orders etc).
178     void serviceEvent(service_record * service, service_event event) noexcept final override
179     {
180         // For each service handle corresponding to the event, send an information packet.
181         auto range = serviceKeyMap.equal_range(service);
182         auto & i = range.first;
183         auto & end = range.second;
184         try {
185             while (i != end) {
186                 uint32_t key = i->second;
187                 std::vector<char> pkt;
188                 constexpr int pktsize = 3 + sizeof(key);
189                 pkt.reserve(pktsize);
190                 pkt.push_back(DINIT_IP_SERVICEEVENT);
191                 pkt.push_back(pktsize);
192                 char * p = (char *) &key;
193                 for (int j = 0; j < (int)sizeof(key); j++) {
194                     pkt.push_back(*p++);
195                 }
196                 pkt.push_back(static_cast<char>(event));
197                 queuePacket(std::move(pkt));
198                 ++i;
199             }
200         }
201         catch (std::bad_alloc &exc) {
202             doOomClose();
203         }
204     }
205     
206     public:
207     control_conn_t(eventloop_t * loop, service_set * services_p, int fd)
208             : loop(loop), services(services_p), chklen(0)
209     {
210         iob.registerWith(*loop, fd, IN_EVENTS);
211         active_control_conns++;
212     }
213     
214     bool rollbackComplete() noexcept;
215         
216     virtual ~control_conn_t() noexcept;
217 };
218
219
220 static rearm control_conn_cb(eventloop_t * loop, control_conn_watcher * watcher, int revents)
221 {
222     char * cc_addr = (reinterpret_cast<char *>(watcher)) - offsetof(control_conn_t, iob);
223     control_conn_t *conn = reinterpret_cast<control_conn_t *>(cc_addr);
224     if (revents & IN_EVENTS) {
225         if (conn->dataReady()) {
226             delete conn;
227             return rearm::REMOVED;
228         }
229     }
230     if (revents & OUT_EVENTS) {
231         if (conn->sendData()) {
232             delete conn;
233             return rearm::REMOVED;
234         }
235     }
236     
237     return rearm::NOOP;
238 }
239
240 #endif