added marshalling helper functions
[metze/ctdb/wip.git] / common / ctdb_util.c
1 /* 
2    ctdb utility code
3
4    Copyright (C) Andrew Tridgell  2006
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "lib/events/events.h"
22 #include "lib/tdb/include/tdb.h"
23 #include "system/network.h"
24 #include "system/filesys.h"
25 #include "system/wait.h"
26 #include "../include/ctdb_private.h"
27
28 int LogLevel = DEBUG_NOTICE;
29 int this_log_level = 0;
30
31 /*
32   return error string for last error
33 */
34 const char *ctdb_errstr(struct ctdb_context *ctdb)
35 {
36         return ctdb->err_msg;
37 }
38
39
40 /*
41   remember an error message
42 */
43 void ctdb_set_error(struct ctdb_context *ctdb, const char *fmt, ...)
44 {
45         va_list ap;
46         talloc_free(ctdb->err_msg);
47         va_start(ap, fmt);
48         ctdb->err_msg = talloc_vasprintf(ctdb, fmt, ap);
49         DEBUG(DEBUG_ERR,("ctdb error: %s\n", ctdb->err_msg));
50         va_end(ap);
51 }
52
53 /*
54   a fatal internal error occurred - no hope for recovery
55 */
56 void ctdb_fatal(struct ctdb_context *ctdb, const char *msg)
57 {
58         DEBUG(DEBUG_ALERT,("ctdb fatal error: %s\n", msg));
59         abort();
60 }
61
62 /*
63   parse a IP:port pair
64 */
65 int ctdb_parse_address(struct ctdb_context *ctdb,
66                        TALLOC_CTX *mem_ctx, const char *str,
67                        struct ctdb_address *address)
68 {
69         struct servent *se;
70
71         setservent(0);
72         se = getservbyname("ctdb", "tcp");
73         endservent();
74         
75         address->address = talloc_strdup(mem_ctx, str);
76         if (se == NULL) {
77                 address->port = CTDB_PORT;
78         } else {
79                 address->port = ntohs(se->s_port);
80         }
81         return 0;
82 }
83
84
85 /*
86   check if two addresses are the same
87 */
88 bool ctdb_same_address(struct ctdb_address *a1, struct ctdb_address *a2)
89 {
90         return strcmp(a1->address, a2->address) == 0 && a1->port == a2->port;
91 }
92
93
94 /*
95   hash function for mapping data to a VNN - taken from tdb
96 */
97 uint32_t ctdb_hash(const TDB_DATA *key)
98 {
99         uint32_t value; /* Used to compute the hash value.  */
100         uint32_t i;     /* Used to cycle through random values. */
101
102         /* Set the initial value from the key size. */
103         for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
104                 value = (value + (key->dptr[i] << (i*5 % 24)));
105
106         return (1103515243 * value + 12345);  
107 }
108
109 /*
110   a type checking varient of idr_find
111  */
112 static void *_idr_find_type(struct idr_context *idp, int id, const char *type, const char *location)
113 {
114         void *p = idr_find(idp, id);
115         if (p && talloc_check_name(p, type) == NULL) {
116                 DEBUG(DEBUG_ERR,("%s idr_find_type expected type %s  but got %s\n",
117                          location, type, talloc_get_name(p)));
118                 return NULL;
119         }
120         return p;
121 }
122
123
124 /*
125   update a max latency number
126  */
127 void ctdb_latency(double *latency, struct timeval t)
128 {
129         double l = timeval_elapsed(&t);
130         if (l > *latency) {
131                 *latency = l;
132         }
133 }
134
135 uint32_t ctdb_reqid_new(struct ctdb_context *ctdb, void *state)
136 {
137         uint32_t id;
138
139         id  = ctdb->idr_cnt++ & 0xFFFF;
140         id |= (idr_get_new(ctdb->idr, state, 0xFFFF)<<16);
141         return id;
142 }
143
144 void *_ctdb_reqid_find(struct ctdb_context *ctdb, uint32_t reqid, const char *type, const char *location)
145 {
146         void *p;
147
148         p = _idr_find_type(ctdb->idr, (reqid>>16)&0xFFFF, type, location);
149         if (p == NULL) {
150                 DEBUG(DEBUG_ERR, ("Could not find idr:%u\n",reqid));
151         }
152
153         return p;
154 }
155
156
157 void ctdb_reqid_remove(struct ctdb_context *ctdb, uint32_t reqid)
158 {
159         int ret;
160
161         ret = idr_remove(ctdb->idr, (reqid>>16)&0xFFFF);
162         if (ret != 0) {
163                 DEBUG(DEBUG_ERR, ("Removing idr that does not exist\n"));
164         }
165 }
166
167
168 /*
169   form a ctdb_rec_data record from a key/data pair
170   
171   note that header may be NULL. If not NULL then it is included in the data portion
172   of the record
173  */
174 struct ctdb_rec_data *ctdb_marshall_record(TALLOC_CTX *mem_ctx, uint32_t reqid, 
175                                            TDB_DATA key, 
176                                            struct ctdb_ltdb_header *header,
177                                            TDB_DATA data)
178 {
179         size_t length;
180         struct ctdb_rec_data *d;
181
182         length = offsetof(struct ctdb_rec_data, data) + key.dsize + 
183                 data.dsize + (header?sizeof(*header):0);
184         d = (struct ctdb_rec_data *)talloc_size(mem_ctx, length);
185         if (d == NULL) {
186                 return NULL;
187         }
188         d->length = length;
189         d->reqid = reqid;
190         d->keylen = key.dsize;
191         memcpy(&d->data[0], key.dptr, key.dsize);
192         if (header) {
193                 d->datalen = data.dsize + sizeof(*header);
194                 memcpy(&d->data[key.dsize], header, sizeof(*header));
195                 memcpy(&d->data[key.dsize+sizeof(*header)], data.dptr, data.dsize);
196         } else {
197                 d->datalen = data.dsize;
198                 memcpy(&d->data[key.dsize], data.dptr, data.dsize);
199         }
200         return d;
201 }
202
203
204 /* helper function for marshalling multiple records */
205 struct ctdb_marshall_buffer *ctdb_marshall_add(TALLOC_CTX *mem_ctx, 
206                                                struct ctdb_marshall_buffer *m,
207                                                uint64_t db_id,
208                                                uint32_t reqid,
209                                                TDB_DATA key,
210                                                struct ctdb_ltdb_header *header,
211                                                TDB_DATA data)
212 {
213         struct ctdb_rec_data *r;
214         size_t m_size, r_size;
215         struct ctdb_marshall_buffer *m2;
216
217         r = ctdb_marshall_record(mem_ctx, reqid, key, header, data);
218         if (r == NULL) {
219                 talloc_free(m);
220                 return NULL;
221         }
222
223         if (m == NULL) {
224                 m = talloc_zero_size(mem_ctx, offsetof(struct ctdb_marshall_buffer, data));
225                 if (m == NULL) {
226                         return NULL;
227                 }
228                 m->db_id = db_id;
229         }
230
231         m_size = talloc_get_size(m);
232         r_size = talloc_get_size(r);
233
234         m2 = talloc_realloc_size(mem_ctx, m,  m_size + r_size);
235         if (m2 == NULL) {
236                 talloc_free(m);
237                 return NULL;
238         }
239
240         memcpy(m_size + (uint8_t *)m2, r, r_size);
241
242         talloc_free(r);
243
244         m2->count++;
245
246         return m2;
247 }
248
249 /* we've finished marshalling, return a data blob with the marshalled records */
250 TDB_DATA ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
251 {
252         TDB_DATA data;
253         data.dptr = (uint8_t *)m;
254         data.dsize = talloc_get_size(m);
255         return data;
256 }
257
258 /* 
259    loop over a marshalling buffer 
260    
261      - pass r==NULL to start
262      - loop the number of times indicated by m->count
263 */
264 struct ctdb_rec_data *ctdb_marshall_loop_next(struct ctdb_marshall_buffer *m, struct ctdb_rec_data *r,
265                                               uint32_t *reqid,
266                                               struct ctdb_ltdb_header *header,
267                                               TDB_DATA *key, TDB_DATA *data)
268 {
269         if (r == NULL) {
270                 r = (struct ctdb_rec_data *)&m->data[0];
271         } else {
272                 r = (struct ctdb_rec_data *)(r->length + (uint8_t *)r);
273         }
274
275         if (reqid != NULL) {
276                 *reqid = r->reqid;
277         }
278         
279         if (key != NULL) {
280                 key->dptr   = &r->data[0];
281                 key->dsize  = r->keylen;
282         }
283         if (data != NULL) {
284                 data->dptr  = &r->data[r->keylen];
285                 data->dsize = r->datalen;
286                 if (header != NULL) {
287                         data->dptr += sizeof(*header);
288                         data->dsize -= sizeof(*header);
289                 }
290         }
291
292         if (header != NULL) {
293                 if (r->datalen < sizeof(*header)) {
294                         return NULL;
295                 }
296                 *header = *(struct ctdb_ltdb_header *)&r->data[r->keylen];
297         }
298
299         return r;
300 }
301
302
303 #if HAVE_SCHED_H
304 #include <sched.h>
305 #endif
306
307 /*
308   if possible, make this task real time
309  */
310 void ctdb_set_scheduler(struct ctdb_context *ctdb)
311 {
312 #if HAVE_SCHED_SETSCHEDULER     
313         struct sched_param p;
314         if (ctdb->saved_scheduler_param == NULL) {
315                 ctdb->saved_scheduler_param = talloc_size(ctdb, sizeof(p));
316         }
317         
318         if (sched_getparam(0, (struct sched_param *)ctdb->saved_scheduler_param) == -1) {
319                 DEBUG(DEBUG_ERR,("Unable to get old scheduler params\n"));
320                 return;
321         }
322
323         p = *(struct sched_param *)ctdb->saved_scheduler_param;
324         p.sched_priority = 1;
325
326         if (sched_setscheduler(0, SCHED_FIFO, &p) == -1) {
327                 DEBUG(DEBUG_CRIT,("Unable to set scheduler to SCHED_FIFO (%s)\n", 
328                          strerror(errno)));
329         } else {
330                 DEBUG(DEBUG_NOTICE,("Set scheduler to SCHED_FIFO\n"));
331         }
332 #endif
333 }
334
335 /*
336   restore previous scheduler parameters
337  */
338 void ctdb_restore_scheduler(struct ctdb_context *ctdb)
339 {
340 #if HAVE_SCHED_SETSCHEDULER     
341         if (ctdb->saved_scheduler_param == NULL) {
342                 ctdb_fatal(ctdb, "No saved scheduler parameters\n");
343         }
344         if (sched_setscheduler(0, SCHED_OTHER, (struct sched_param *)ctdb->saved_scheduler_param) == -1) {
345                 ctdb_fatal(ctdb, "Unable to restore old scheduler parameters\n");
346         }
347 #endif
348 }
349
350 void set_nonblocking(int fd)
351 {
352         unsigned v;
353         v = fcntl(fd, F_GETFL, 0);
354         fcntl(fd, F_SETFL, v | O_NONBLOCK);
355 }
356
357 void set_close_on_exec(int fd)
358 {
359         unsigned v;
360         v = fcntl(fd, F_GETFD, 0);
361         fcntl(fd, F_SETFD, v | FD_CLOEXEC);
362 }
363
364
365 /*
366   parse a ip:num pair with the given separator
367  */
368 static bool parse_ip_num(const char *s, struct in_addr *addr, unsigned *num, const char sep)
369 {
370         const char *p;
371         char *endp = NULL;
372         char buf[16];
373
374         p = strchr(s, sep);
375         if (p == NULL) {
376                 return false;
377         }
378
379         if (p - s > 15) {
380                 return false;
381         }
382
383         *num = strtoul(p+1, &endp, 10);
384         if (endp == NULL || *endp != 0) {
385                 /* trailing garbage */
386                 return false;
387         }
388
389         strlcpy(buf, s, 1+p-s);
390
391         if (inet_aton(buf, addr) == 0) {
392                 return false;
393         }
394
395         return true;
396 }
397
398
399 static bool parse_ipv4(const char *s, unsigned port, ctdb_sock_addr *saddr)
400 {
401         saddr->ip.sin_family = AF_INET;
402         saddr->ip.sin_port   = htons(port);
403
404         if (inet_pton(AF_INET, s, &saddr->ip.sin_addr) != 1) {
405                 DEBUG(DEBUG_ERR, (__location__ " Failed to translate %s into sin_addr\n", s));
406                 return false;
407         }
408
409         return true;
410 }
411
412 static bool parse_ipv6(const char *s, unsigned port, ctdb_sock_addr *saddr)
413 {
414         saddr->ip6.sin6_family   = AF_INET6;
415         saddr->ip6.sin6_port     = htons(port);
416         saddr->ip6.sin6_flowinfo = 0;
417         saddr->ip6.sin6_scope_id = 0;
418
419         if (inet_pton(AF_INET6, s, &saddr->ip6.sin6_addr) != 1) {
420                 DEBUG(DEBUG_ERR, (__location__ " Failed to translate %s into sin6_addr\n", s));
421                 return false;
422         }
423
424         return true;
425 }
426 /*
427   parse a ip:port pair
428  */
429 bool parse_ip_port(const char *addr, ctdb_sock_addr *saddr)
430 {
431         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
432         char *s, *p;
433         unsigned port;
434         char *endp = NULL;
435         bool ret;
436
437         s = talloc_strdup(tmp_ctx, addr);
438         if (s == NULL) {
439                 DEBUG(DEBUG_ERR, (__location__ " Failed strdup()\n"));
440                 talloc_free(tmp_ctx);
441                 return false;
442         }
443
444         p = rindex(s, ':');
445         if (p == NULL) {
446                 DEBUG(DEBUG_ERR, (__location__ " This addr: %s does not contain a port number\n", s));
447                 talloc_free(tmp_ctx);
448                 return false;
449         }
450
451         port = strtoul(p+1, &endp, 10);
452         if (endp == NULL || *endp != 0) {
453                 /* trailing garbage */
454                 DEBUG(DEBUG_ERR, (__location__ " Trailing garbage after the port in %s\n", s));
455                 talloc_free(tmp_ctx);
456                 return false;
457         }
458         *p = 0;
459
460
461         /* now is this a ipv4 or ipv6 address ?*/
462         p = index(s, ':');
463         if (p == NULL) {
464                 ret = parse_ipv4(s, port, saddr);
465         } else {
466                 ret = parse_ipv6(s, port, saddr);
467         }
468
469         talloc_free(tmp_ctx);
470         return ret;
471 }
472
473 /*
474   parse an ip
475  */
476 bool parse_ip(const char *addr, ctdb_sock_addr *saddr)
477 {
478         char *p;
479         bool ret;
480
481         /* now is this a ipv4 or ipv6 address ?*/
482         p = index(addr, ':');
483         if (p == NULL) {
484                 ret = parse_ipv4(addr, 0, saddr);
485         } else {
486                 ret = parse_ipv6(addr, 0, saddr);
487         }
488
489         return ret;
490 }
491
492 /*
493   parse a ip/mask pair
494  */
495 bool parse_ip_mask(const char *s, struct sockaddr_in *ip, unsigned *mask)
496 {
497         ZERO_STRUCT(*ip);
498
499         if (!parse_ip_num(s, &ip->sin_addr, mask, '/')) {
500                 return false;
501         }
502         if (*mask > 32) {
503                 return false;
504         }
505         ip->sin_family = AF_INET;
506         ip->sin_port   = 0;
507         return true;
508 }
509
510 /*
511   compare two sockaddr_in structures - matching only on IP
512  */
513 bool ctdb_same_ipv4(const struct sockaddr_in *ip1, const struct sockaddr_in *ip2)
514 {
515         return ip1->sin_family == ip2->sin_family &&
516                 ip1->sin_addr.s_addr == ip2->sin_addr.s_addr;
517 }
518
519 bool ctdb_same_ip(ctdb_sock_addr *ip1, ctdb_sock_addr *ip2)
520 {
521         if (ip1->sa.sa_family != ip2->sa.sa_family) {
522                 return false;
523         }
524
525         switch (ip1->sa.sa_family) {
526         case AF_INET:
527                 return ip1->ip.sin_addr.s_addr == ip2->ip.sin_addr.s_addr;
528         case AF_INET6:
529                 return !memcmp(&ip1->ip6.sin6_addr.s6_addr[0],
530                                 &ip2->ip6.sin6_addr.s6_addr[0],
531                                 16);
532         default:
533                 DEBUG(DEBUG_ERR, (__location__ " CRITICAL Can not compare sockaddr structures of type %u\n", ip1->sa.sa_family));
534                 return false;
535         }
536
537         return true;
538 }
539
540 /*
541   compare two sockaddr_in structures
542  */
543 bool ctdb_same_sockaddr(const struct sockaddr_in *ip1, const struct sockaddr_in *ip2)
544 {
545         return ctdb_same_ipv4(ip1, ip2) && ip1->sin_port == ip2->sin_port;
546 }
547
548
549
550 void ctdb_block_signal(int signum)
551 {
552         sigset_t set;
553         sigemptyset(&set);
554         sigaddset(&set,signum);
555         sigprocmask(SIG_BLOCK,&set,NULL);
556 }
557
558 void ctdb_unblock_signal(int signum)
559 {
560         sigset_t set;
561         sigemptyset(&set);
562         sigaddset(&set,signum);
563         sigprocmask(SIG_UNBLOCK,&set,NULL);
564 }