Big rename/namespace cleanup.
[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 eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
22
23 class control_conn_t;
24 class control_conn_watcher;
25
26 // forward-declaration of callback:
27 static dasynq::rearm control_conn_cb(eventloop_t *loop, control_conn_watcher *watcher, int revents);
28
29 // Pointer to the control connection that is listening for rollback completion
30 extern control_conn_t * rollback_handler_conn;
31
32 extern int active_control_conns;
33
34 // "packet" format:
35 // (1 byte) packet type
36 // (N bytes) additional data (service name, etc)
37 //   for LOADSERVICE/FINDSERVICE:
38 //      (2 bytes) service name length
39 //      (M bytes) service name (without nul terminator)
40
41 // Information packet:
42 // (1 byte) packet type, >= 100
43 // (1 byte) packet length (including all fields)
44 //       N bytes: packet data (N = (length - 2))
45
46 class service_set;
47 class service_record;
48
49 class control_conn_watcher : public eventloop_t::bidi_fd_watcher_impl<control_conn_watcher>
50 {
51     using rearm = dasynq::rearm;
52     inline rearm receive_event(eventloop_t &loop, int fd, int flags) noexcept;
53
54     eventloop_t * event_loop;
55
56     public:
57     control_conn_watcher(eventloop_t & event_loop_p) : event_loop(&event_loop_p)
58     {
59         // constructor
60     }
61
62     rearm read_ready(eventloop_t &loop, int fd) noexcept
63     {
64         return receive_event(loop, fd, dasynq::IN_EVENTS);
65     }
66     
67     rearm write_ready(eventloop_t &loop, int fd) noexcept
68     {
69         return receive_event(loop, fd, dasynq::OUT_EVENTS);
70     }
71
72     void set_watches(int flags)
73     {
74         eventloop_t::bidi_fd_watcher::set_watches(*event_loop, flags);
75     }
76 };
77
78 inline dasynq::rearm control_conn_watcher::receive_event(eventloop_t &loop, int fd, int flags) noexcept
79 {
80     return control_conn_cb(&loop, this, flags);
81 }
82
83
84 class control_conn_t : private service_listener
85 {
86     using rearm = dasynq::rearm;
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     // process_packet() 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 queue_packet(vector<char> &&v) noexcept;
126     bool queue_packet(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 process_packet();
136     
137     // Process a STARTSERVICE/STOPSERVICE packet. May throw std::bad_alloc.
138     bool process_start_stop(int pktType);
139     
140     // Process a FINDSERVICE/LOADSERVICE packet. May throw std::bad_alloc.
141     bool process_find_load(int pktType);
142
143     // Process an UNPINSERVICE packet. May throw std::bad_alloc.
144     bool process_unpin_service();
145     
146     bool list_services();
147
148     // Notify that data is ready to be read from the socket. Returns true if the connection should
149     // be closed.
150     bool data_ready() noexcept;
151     
152     bool send_data() noexcept;
153     
154     // Allocate a new handle for a service; may throw std::bad_alloc
155     handle_t allocate_service_handle(service_record *record);
156     
157     service_record *find_service_for_key(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 do_oom_close()
169     {
170         bad_conn_close = true;
171         oom_close = true;
172         iob.set_watches(dasynq::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 service_event(service_record * service, service_event_t 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                 queue_packet(std::move(pkt));
198                 ++i;
199             }
200         }
201         catch (std::bad_alloc &exc) {
202             do_oom_close();
203         }
204     }
205     
206     public:
207     control_conn_t(eventloop_t &loop, service_set * services_p, int fd)
208             : iob(loop), loop(loop), services(services_p), chklen(0)
209     {
210         iob.add_watch(loop, fd, dasynq::IN_EVENTS);
211         active_control_conns++;
212     }
213     
214     bool rollback_complete() noexcept;
215         
216     virtual ~control_conn_t() noexcept;
217 };
218
219
220 static dasynq::rearm control_conn_cb(eventloop_t * loop, control_conn_watcher * watcher, int revents)
221 {
222     // Get the address of the containing control_connt_t object:
223     _Pragma ("GCC diagnostic push")
224     _Pragma ("GCC diagnostic ignored \"-Winvalid-offsetof\"")
225     char * cc_addr = (reinterpret_cast<char *>(watcher)) - offsetof(control_conn_t, iob);
226     control_conn_t *conn = reinterpret_cast<control_conn_t *>(cc_addr);
227     _Pragma ("GCC diagnostic pop")
228
229     if (revents & dasynq::IN_EVENTS) {
230         if (conn->data_ready()) {
231             delete conn;
232             return dasynq::rearm::REMOVED;
233         }
234     }
235     if (revents & dasynq::OUT_EVENTS) {
236         if (conn->send_data()) {
237             delete conn;
238             return dasynq::rearm::REMOVED;
239         }
240     }
241     
242     return dasynq::rearm::NOOP;
243 }
244
245 #endif