Statistics
| Branch: | Tag: | Revision:

root / xseg / peers / user / peer.c @ 59da5107

History | View | Annotate | Download (21.9 kB)

1
/*
2
 * Copyright 2012 GRNET S.A. All rights reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or
5
 * without modification, are permitted provided that the following
6
 * conditions are met:
7
 *
8
 *   1. Redistributions of source code must retain the above
9
 *      copyright notice, this list of conditions and the following
10
 *      disclaimer.
11
 *   2. Redistributions in binary form must reproduce the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer in the documentation and/or other materials
14
 *      provided with the distribution.
15
 *
16
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
 * POSSIBILITY OF SUCH DAMAGE.
28
 *
29
 * The views and conclusions contained in the software and
30
 * documentation are those of the authors and should not be
31
 * interpreted as representing official policies, either expressed
32
 * or implied, of GRNET S.A.
33
 */
34

    
35
#define _GNU_SOURCE
36
#include <stdio.h>
37
#include <stdlib.h>
38
#include <sys/types.h>
39
#include <unistd.h>
40
#include <sys/syscall.h>
41
#include <sys/time.h>
42
#include <signal.h>
43
#include <sys/stat.h>
44
#include <fcntl.h>
45
#include <errno.h>
46

    
47
#ifdef MT
48
#include <pthread.h>
49
#endif
50

    
51
#include <xseg/xseg.h>
52
#include <peer.h>
53

    
54
#ifdef MT
55
#define PEER_TYPE "pthread"
56
#else
57
#define PEER_TYPE "posix"
58
#endif
59

    
60
//FIXME this should not be defined here probably
61
#define MAX_SPEC_LEN 128
62
#define MAX_PIDFILE_LEN 512
63

    
64
volatile unsigned int terminated = 0;
65
unsigned int verbose = 0;
66
struct log_ctx lc;
67
#ifdef ST_THREADS
68
uint32_t ta = 0;
69
#endif
70

    
71
#ifdef MT
72
struct peerd *global_peer;
73

    
74
struct thread {
75
        struct peerd *peer;
76
        pthread_t tid;
77
        pthread_cond_t cond;
78
        pthread_mutex_t lock;
79
        int thread_no;
80
        void (*func)(void *arg);
81
        void *arg;
82
};
83

    
84
inline static struct thread* alloc_thread(struct peerd *peer)
85
{
86
        xqindex idx = xq_pop_head(&peer->threads, 1);
87
        if (idx == Noneidx)
88
                return NULL;
89
        return peer->thread + idx;
90
}
91

    
92
inline static void free_thread(struct peerd *peer, struct thread *t)
93
{
94
        xqindex idx = t - peer->thread;
95
        xq_append_head(&peer->threads, idx, 1);
96
}
97

    
98

    
99
inline static void __wake_up_thread(struct thread *t)
100
{
101
        pthread_mutex_lock(&t->lock);
102
        pthread_cond_signal(&t->cond);
103
        pthread_mutex_unlock(&t->lock);
104
}
105

    
106
inline static void wake_up_thread(struct thread* t)
107
{
108
        if (t){
109
                __wake_up_thread(t);
110
        }
111
}
112

    
113
inline static int wake_up_next_thread(struct peerd *peer)
114
{
115
        return (xseg_signal(peer->xseg, peer->portno_start));
116
}
117
#endif
118

    
119
/*
120
 * extern is needed if this function is going to be called by another file
121
 * such as bench-xseg.c
122
 */
123

    
124
void signal_handler(int signal)
125
{
126
        XSEGLOG2(&lc, I, "Caught signal. Terminating gracefully");
127
        terminated = 1;
128
#ifdef MT
129
        wake_up_next_thread(global_peer);
130
#endif
131
}
132

    
133
void renew_logfile(int signal)
134
{
135
        XSEGLOG2(&lc, I, "Caught signal. Renewing logfile");
136
        renew_logctx(&lc, NULL, verbose, NULL, REOPEN_FILE);
137
}
138

    
139
static int setup_signals(struct peerd *peer)
140
{
141
        int r;
142
        struct sigaction sa;
143
#ifdef MT
144
        global_peer = peer;
145
#endif
146
        sigemptyset(&sa.sa_mask);
147
        sa.sa_flags = 0;
148
        sa.sa_handler = signal_handler;
149
        r = sigaction(SIGTERM, &sa, NULL);
150
        if (r < 0)
151
                return r;
152
        r = sigaction(SIGINT, &sa, NULL);
153
        if (r < 0)
154
                return r;
155
        r = sigaction(SIGQUIT, &sa, NULL);
156
        if (r < 0)
157
                return r;
158

    
159
        sa.sa_handler = renew_logfile;
160
        r = sigaction(SIGUSR1, &sa, NULL);
161
        if (r < 0)
162
                return r;
163

    
164
        return r;
165
}
166

    
167
inline int canDefer(struct peerd *peer)
168
{
169
        return !(peer->defer_portno == NoPort);
170
}
171

    
172
void print_req(struct xseg *xseg, struct xseg_request *req)
173
{
174
        char target[64], data[64];
175
        char *req_target, *req_data;
176
        unsigned int end = (req->targetlen> 63) ? 63 : req->targetlen;
177
        req_target = xseg_get_target(xseg, req);
178
        req_data = xseg_get_data(xseg, req);
179

    
180
        if (1) {
181
                strncpy(target, req_target, end);
182
                target[end] = 0;
183
                strncpy(data, req_data, 63);
184
                data[63] = 0;
185
                printf("req id:%lu, op:%u %llu:%lu serviced: %lu, reqstate: %u\n"
186
                                "src: %u, st: %u, dst: %u dt: %u\n"
187
                                "target[%u]:'%s', data[%llu]:\n%s------------------\n\n",
188
                                (unsigned long)(req),
189
                                (unsigned int)req->op,
190
                                (unsigned long long)req->offset,
191
                                (unsigned long)req->size,
192
                                (unsigned long)req->serviced,
193
                                (unsigned int)req->state,
194
                                (unsigned int)req->src_portno,
195
                                (unsigned int)req->src_transit_portno,
196
                                (unsigned int)req->dst_portno,
197
                                (unsigned int)req->dst_transit_portno,
198
                                (unsigned int)req->targetlen, target,
199
                                (unsigned long long)req->datalen, data);
200
        }
201
}
202
void log_pr(char *msg, struct peer_req *pr)
203
{
204
        char target[64], data[64];
205
        char *req_target, *req_data;
206
        struct peerd *peer = pr->peer;
207
        struct xseg *xseg = pr->peer->xseg;
208
        req_target = xseg_get_target(xseg, pr->req);
209
        req_data = xseg_get_data(xseg, pr->req);
210
        /* null terminate name in case of req->target is less than 63 characters,
211
         * and next character after name (aka first byte of next buffer) is not
212
         * null
213
         */
214
        unsigned int end = (pr->req->targetlen> 63) ? 63 : pr->req->targetlen;
215
        if (verbose) {
216
                strncpy(target, req_target, end);
217
                target[end] = 0;
218
                strncpy(data, req_data, 63);
219
                data[63] = 0;
220
                printf("%s: req id:%u, op:%u %llu:%lu serviced: %lu, retval: %lu, reqstate: %u\n"
221
                                "target[%u]:'%s', data[%llu]:\n%s------------------\n\n",
222
                                msg,
223
                                (unsigned int)(pr - peer->peer_reqs),
224
                                (unsigned int)pr->req->op,
225
                                (unsigned long long)pr->req->offset,
226
                                (unsigned long)pr->req->size,
227
                                (unsigned long)pr->req->serviced,
228
                                (unsigned long)pr->retval,
229
                                (unsigned int)pr->req->state,
230
                                (unsigned int)pr->req->targetlen, target,
231
                                (unsigned long long)pr->req->datalen, data);
232
        }
233
}
234

    
235
/*
236
 * free_reqs is a queue that simply contains pointer offsets to the peer_reqs
237
 * queue. If a pointer from peer_reqs is popped, we are certain that the
238
 * associated memory in peer_reqs is free to use
239
 */
240
inline struct peer_req *alloc_peer_req(struct peerd *peer)
241
{
242
        xqindex idx = xq_pop_head(&peer->free_reqs, 1);
243
        if (idx == Noneidx)
244
                return NULL;
245
        return peer->peer_reqs + idx;
246
}
247

    
248
inline void free_peer_req(struct peerd *peer, struct peer_req *pr)
249
{
250
        xqindex idx = pr - peer->peer_reqs;
251
        pr->req = NULL;
252
        xq_append_head(&peer->free_reqs, idx, 1);
253
}
254

    
255
struct timeval resp_start, resp_end, resp_accum = {0, 0};
256
uint64_t responds = 0;
257
void get_responds_stats(){
258
                printf("Time waiting respond %lu.%06lu sec for %llu times.\n",
259
                                //(unsigned int)(t - peer->thread),
260
                                resp_accum.tv_sec, resp_accum.tv_usec, (long long unsigned int) responds);
261
}
262

    
263
//FIXME error check
264
void fail(struct peerd *peer, struct peer_req *pr)
265
{
266
        struct xseg_request *req = pr->req;
267
        uint32_t p;
268
        XSEGLOG2(&lc, D, "failing req %u", (unsigned int) (pr - peer->peer_reqs));
269
        req->state |= XS_FAILED;
270
        //xseg_set_req_data(peer->xseg, pr->req, NULL);
271
        p = xseg_respond(peer->xseg, req, pr->portno, X_ALLOC);
272
        xseg_signal(peer->xseg, p);
273
        free_peer_req(peer, pr);
274
#ifdef MT
275
        wake_up_next_thread(peer);
276
#endif
277
}
278

    
279
//FIXME error check
280
void complete(struct peerd *peer, struct peer_req *pr)
281
{
282
        struct xseg_request *req = pr->req;
283
        uint32_t p;
284
        req->state |= XS_SERVED;
285
        //xseg_set_req_data(peer->xseg, pr->req, NULL);
286
        //gettimeofday(&resp_start, NULL);
287
        p = xseg_respond(peer->xseg, req, pr->portno, X_ALLOC);
288
        //gettimeofday(&resp_end, NULL);
289
        //responds++;
290
        //timersub(&resp_end, &resp_start, &resp_end);
291
        //timeradd(&resp_end, &resp_accum, &resp_accum);
292
        //printf("xseg_signal: %u\n", p);
293
        xseg_signal(peer->xseg, p);
294
        free_peer_req(peer, pr);
295
#ifdef MT
296
        wake_up_next_thread(peer);
297
#endif
298
}
299

    
300
static void handle_accepted(struct peerd *peer, struct peer_req *pr,
301
                                struct xseg_request *req)
302
{
303
        struct xseg_request *xreq = pr->req;
304
        //assert xreq == req;
305
        XSEGLOG2(&lc, D, "Handle accepted");
306
        xreq->serviced = 0;
307
        //xreq->state = XS_ACCEPTED;
308
        pr->retval = 0;
309
        dispatch(peer, pr, req, dispatch_accept);
310
}
311

    
312
static void handle_received(struct peerd *peer, struct peer_req *pr,
313
                                struct xseg_request *req)
314
{
315
        //struct xseg_request *req = pr->req;
316
        //assert req->state != XS_ACCEPTED;
317
        XSEGLOG2(&lc, D, "Handle received \n");
318
        dispatch(peer, pr, req, dispatch_receive);
319

    
320
}
321
struct timeval sub_start, sub_end, sub_accum = {0, 0};
322
uint64_t submits = 0;
323
void get_submits_stats(){
324
                printf("Time waiting submit %lu.%06lu sec for %llu times.\n",
325
                                //(unsigned int)(t - peer->thread),
326
                                sub_accum.tv_sec, sub_accum.tv_usec, (long long unsigned int) submits);
327
}
328

    
329
int submit_peer_req(struct peerd *peer, struct peer_req *pr)
330
{
331
        uint32_t ret;
332
        struct xseg_request *req = pr->req;
333
        // assert req->portno == peer->portno ?
334
        //TODO small function with error checking
335
        XSEGLOG2 (&lc, D, "submitting peer req %u\n", (unsigned int)(pr - peer->peer_reqs));
336
        ret = xseg_set_req_data(peer->xseg, req, (void *)(pr));
337
        if (ret < 0)
338
                return -1;
339
        //printf("pr: %x , req_data: %x \n", pr, xseg_get_req_data(peer->xseg, req));
340
        //gettimeofday(&sub_start, NULL);
341
        ret = xseg_submit(peer->xseg, req, pr->portno, X_ALLOC);
342
        //gettimeofday(&sub_end, NULL);
343
        //submits++;
344
        //timersub(&sub_end, &sub_start, &sub_end);
345
        //timeradd(&sub_end, &sub_accum, &sub_accum);
346
        if (ret == NoPort)
347
                return -1;
348
        xseg_signal(peer->xseg, ret);
349
        return 0;
350
}
351

    
352
int check_ports(struct peerd *peer)
353
{
354
        struct xseg *xseg = peer->xseg;
355
        xport portno_start = peer->portno_start;
356
        xport portno_end = peer->portno_end;
357
        struct xseg_request *accepted, *received;
358
        struct peer_req *pr;
359
        xport i;
360
        int  r, c = 0;
361

    
362
        for (i = portno_start; i <= portno_end; i++) {
363
                accepted = NULL;
364
                received = NULL;
365
                //Shouldn't we just leave?
366
                if (!isTerminate()) {
367
                        //Better way than alloc/free all the time?
368
                        //Cache the allocated peer_req?
369
                        pr = alloc_peer_req(peer);
370
                        if (pr) {
371
                                accepted = xseg_accept(xseg, i, X_NONBLOCK);
372
                                if (accepted) {
373
                                        pr->req = accepted;
374
                                        pr->portno = i;
375
                                        xseg_cancel_wait(xseg, i);
376
                                        handle_accepted(peer, pr, accepted);
377
                                        c = 1;
378
                                }
379
                                else {
380
                                        free_peer_req(peer, pr);
381
                                }
382
                        }
383
                }
384
                received = xseg_receive(xseg, i, X_NONBLOCK);
385
                if (received) {
386
                        r =  xseg_get_req_data(xseg, received, (void **) &pr);
387
                        if (r < 0 || !pr){
388
                                XSEGLOG2(&lc, W, "Received request with no pr data\n");
389
                                xport p = xseg_respond(peer->xseg, received, peer->portno_start, X_ALLOC);
390
                                if (p == NoPort){
391
                                        XSEGLOG2(&lc, W, "Could not respond stale request");
392
                                        xseg_put_request(xseg, received, portno_start);
393
                                        continue;
394
                                } else {
395
                                        xseg_signal(xseg, p);
396
                                }
397
                        } else {
398
                                //maybe perform sanity check for pr
399
                                xseg_cancel_wait(xseg, i);
400
                                handle_received(peer, pr, received);
401
                                c = 1;
402
                        }
403
                }
404
        }
405

    
406
        return c;
407
}
408

    
409
#ifdef MT
410
static void* thread_loop(void *arg)
411
{
412
        struct thread *t = (struct thread *) arg;
413
        struct peerd *peer = t->peer;
414
        struct xseg *xseg = peer->xseg;
415
        xport portno_start = peer->portno_start;
416
        xport portno_end = peer->portno_end;
417
        pid_t pid =syscall(SYS_gettid);
418
        uint64_t loops;
419
        uint64_t threshold=1000/(1 + portno_end - portno_start);
420

    
421
        XSEGLOG2(&lc, D, "thread %u\n",  (unsigned int) (t- peer->thread));
422
        XSEGLOG2(&lc, I, "Thread %u has tid %u.\n", (unsigned int) (t- peer->thread), pid);
423
        xseg_init_local_signal(xseg, peer->portno_start);
424
        for (;!(isTerminate() && xq_count(&peer->free_reqs) == peer->nr_ops);) {
425
                for(loops =  threshold; loops > 0; loops--) {
426
                        if (loops == 1)
427
                                xseg_prepare_wait(xseg, peer->portno_start);
428
                        if (check_ports(peer))
429
                                loops = threshold;
430
                }
431
                XSEGLOG2(&lc, I, "Thread %u goes to sleep\n", (unsigned int) (t- peer->thread));
432
                xseg_wait_signal(xseg, 10000000UL);
433
                xseg_cancel_wait(xseg, peer->portno_start);
434
                XSEGLOG2(&lc, I, "Thread %u woke up\n", (unsigned int) (t- peer->thread));
435
        }
436
        wake_up_next_thread(peer);
437
        custom_peer_finalize(peer);
438
        return NULL;
439
}
440

    
441
void *init_thread_loop(void *arg)
442
{
443
        struct thread *t = (struct thread *) arg;
444
        struct peerd *peer = t->peer;
445
        char *thread_id;
446
        int i;
447

    
448
        /*
449
         * We need an identifier for every thread that will spin in peerd_loop.
450
         * The following code is a way to create a string of this format:
451
         *                "Thread <num>"
452
         * minus the null terminator. What we do is we create this string with
453
         * snprintf and then resize it to exclude the null terminator with
454
         * realloc. Finally, the result string is passed to the (void *arg) field
455
         * of struct thread.
456
         *
457
         * Since the highest thread number can't be more than 5 digits, using 13
458
         * chars should be more than enough.
459
         */
460
        thread_id = malloc(13 * sizeof(char));
461
        snprintf(thread_id, 13, "Thread %ld", t - t->peer->thread);
462
        for (i = 0; thread_id[i]; i++) {}
463
        t->arg = (void *)realloc(thread_id, i-1);
464

    
465
        //Start thread loop
466
        (void)peer->peerd_loop(t);
467

    
468
        wake_up_next_thread(peer);
469
        custom_peer_finalize(peer);
470

    
471
        return NULL;
472
}
473

    
474
int peerd_start_threads(struct peerd *peer)
475
{
476
        int i;
477
        uint32_t nr_threads = peer->nr_threads;
478
        //TODO err check
479
        for (i = 0; i < nr_threads; i++) {
480
                peer->thread[i].func = NULL;
481
                peer->thread[i].arg = NULL;
482
                peer->thread[i].peer = peer;
483
                pthread_cond_init(&peer->thread[i].cond,NULL);
484
                pthread_mutex_init(&peer->thread[i].lock, NULL);
485
                pthread_create(&peer->thread[i].tid, NULL,
486
                                        init_thread_loop, (void *)(peer->thread + i));
487
        }
488

    
489
        if (peer->interactive_func)
490
                peer->interactive_func();
491
        for (i = 0; i < nr_threads; i++) {
492
                pthread_join(peer->thread[i].tid, NULL);
493
        }
494

    
495
        return 0;
496
}
497
#endif
498

    
499
void defer_request(struct peerd *peer, struct peer_req *pr)
500
{
501
        // assert canDefer(peer);
502
//        xseg_submit(peer->xseg, peer->defer_portno, pr->req);
503
//        xseg_signal(peer->xseg, peer->defer_portno);
504
//        free_peer_req(peer, pr);
505
}
506

    
507
/*
508
 * generic_peerd_loop is a general-purpose port-checker loop that is
509
 * suitable both for multi-threaded and single-threaded peers.
510
 */
511
static int generic_peerd_loop(void *arg)
512
{
513
#ifdef MT
514
        struct thread *t = (struct thread *) arg;
515
        struct peerd *peer = t->peer;
516
        char *id = t->arg;
517
#else
518
        struct peerd *peer = (struct peerd *) arg;
519
        char id[4] = {'P','e','e','r'};
520
#endif
521
        struct xseg *xseg = peer->xseg;
522
        xport portno_start = peer->portno_start;
523
        xport portno_end = peer->portno_end;
524
        pid_t pid = syscall(SYS_gettid);
525
        uint64_t threshold=1000/(1 + portno_end - portno_start);
526
        uint64_t loops;
527

    
528
        XSEGLOG2(&lc, I, "%s has tid %u.\n", id, pid);
529
        xseg_init_local_signal(xseg, peer->portno_start);
530
        for (;!(isTerminate() && xq_count(&peer->free_reqs) == peer->nr_ops);) {
531
#ifdef MT
532
                if (t->func) {
533
                        XSEGLOG2(&lc, D, "%s executes function\n", id);
534
                        xseg_cancel_wait(xseg, peer->portno_start);
535
                        t->func(t->arg);
536
                        t->func = NULL;
537
                        t->arg = NULL;
538
                        continue;
539
                }
540
#endif
541
                //Heart of peerd_loop. This loop is common for everyone.
542
                for(loops = threshold; loops > 0; loops--) {
543
                        if (check_ports(peer))
544
                                loops = threshold;
545
                }
546
                xseg_prepare_wait(xseg, peer->portno_start);
547
#ifdef ST_THREADS
548
                if (ta){
549
                        st_sleep(0);
550
                        continue;
551
                }
552
#endif
553
                XSEGLOG2(&lc, I, "%s goes to sleep\n", id);
554
                xseg_wait_signal(xseg, 10000000UL);
555
                xseg_cancel_wait(xseg, peer->portno_start);
556
                XSEGLOG2(&lc, I, "%s woke up\n", id);
557
        }
558
        return 0;
559
}
560

    
561
static int init_peerd_loop(struct peerd *peer)
562
{
563
        struct xseg *xseg = peer->xseg;
564

    
565
        peer->peerd_loop(peer);
566
        custom_peer_finalize(peer);
567
        xseg_quit_local_signal(xseg, peer->portno_start);
568

    
569
        return 0;
570
}
571

    
572
static struct xseg *join(char *spec)
573
{
574
        struct xseg_config config;
575
        struct xseg *xseg;
576

    
577
        (void)xseg_parse_spec(spec, &config);
578
        xseg = xseg_join(config.type, config.name, PEER_TYPE, NULL);
579
        if (xseg)
580
                return xseg;
581

    
582
        (void)xseg_create(&config);
583
        return xseg_join(config.type, config.name, PEER_TYPE, NULL);
584
}
585

    
586
static struct peerd* peerd_init(uint32_t nr_ops, char* spec, long portno_start,
587
                        long portno_end, uint32_t nr_threads, uint32_t defer_portno)
588
{
589
        int i;
590
        struct peerd *peer;
591
        struct xseg_port *port;
592
        void *sd = NULL;
593
        xport p;
594

    
595
#ifdef ST_THREADS
596
        st_init();
597
#endif
598
        peer = malloc(sizeof(struct peerd));
599
        if (!peer) {
600
                perror("malloc");
601
                return NULL;
602
        }
603
        peer->nr_ops = nr_ops;
604
        peer->defer_portno = defer_portno;
605
#ifdef MT
606
        peer->nr_threads = nr_threads;
607
        peer->thread = calloc(nr_threads, sizeof(struct thread));
608
        if (!peer->thread)
609
                goto malloc_fail;
610
#endif
611
        peer->peer_reqs = calloc(nr_ops, sizeof(struct peer_req));
612
        if (!peer->peer_reqs){
613
malloc_fail:
614
                perror("malloc");
615
                return NULL;
616
        }
617

    
618
        if (!xq_alloc_seq(&peer->free_reqs, nr_ops, nr_ops))
619
                goto malloc_fail;
620
#ifdef MT
621
        if (!xq_alloc_empty(&peer->threads, nr_threads))
622
                goto malloc_fail;
623
#endif
624
        if (xseg_initialize()){
625
                printf("cannot initialize library\n");
626
                return NULL;
627
        }
628
        peer->xseg = join(spec);
629
        if (!peer->xseg)
630
                return NULL;
631

    
632
        peer->portno_start = (xport) portno_start;
633
        peer->portno_end= (xport) portno_end;
634

    
635
        /*
636
         * Start binding ports from portno_start to portno_end.
637
         * The first port we bind will have its signal_desc initialized by xseg
638
         * and the same signal_desc will be used for all the other ports.
639
         */
640
        for (p = peer->portno_start; p <= peer->portno_end; p++) {
641
                port = xseg_bind_port(peer->xseg, p, sd);
642
                if (!port){
643
                        printf("cannot bind to port %u\n", (unsigned int) p);
644
                        return NULL;
645
                }
646
                if (p == peer->portno_start)
647
                        sd = xseg_get_signal_desc(peer->xseg, port);
648
        }
649

    
650
        printf("Peer on ports  %u-%u\n", peer->portno_start, peer->portno_end);
651

    
652
        for (i = 0; i < nr_ops; i++) {
653
                peer->peer_reqs[i].peer = peer;
654
                peer->peer_reqs[i].req = NULL;
655
                peer->peer_reqs[i].retval = 0;
656
                peer->peer_reqs[i].priv = NULL;
657
                peer->peer_reqs[i].portno = NoPort;
658

    
659
        //Plug default peerd_loop. This can change later on by custom_peer_init.
660
        peer->peerd_loop = generic_peerd_loop;
661

    
662
#ifdef ST_THREADS
663
                peer->peer_reqs[i].cond = st_cond_new(); //FIXME err check
664
#endif
665
        }
666
#ifdef MT
667
        peer->interactive_func = NULL;
668
#endif
669
        return peer;
670
}
671

    
672
int pidfile_remove(char *path, int fd)
673
{
674
        close(fd);
675
        return (unlink(path));
676
}
677

    
678
int pidfile_write(int pid_fd)
679
{
680
        char buf[16];
681
        snprintf(buf, sizeof(buf), "%ld", syscall(SYS_gettid));
682
        buf[15] = 0;
683

    
684
        lseek(pid_fd, 0, SEEK_SET);
685
        int ret = write(pid_fd, buf, strlen(buf));
686
        return ret;
687
}
688

    
689
int pidfile_read(char *path, pid_t *pid)
690
{
691
        char buf[16], *endptr;
692
        *pid = 0;
693

    
694
        int fd = open(path, O_RDONLY);
695
        if (fd < 0)
696
                return -1;
697
        int ret = read(fd, buf, 15);
698
        buf[15]=0;
699
        close(fd);
700
        if (ret < 0)
701
                return -1;
702
        else{
703
                *pid = strtol(buf, &endptr, 10);
704
                if (endptr != &buf[ret]){
705
                        *pid = 0;
706
                        return -1;
707
                }
708
        }
709
        return 0;
710
}
711

    
712
int pidfile_open(char *path, pid_t *old_pid)
713
{
714
        //nfs version > 3
715
        int fd = open(path, O_CREAT|O_EXCL|O_WRONLY, S_IWUSR);
716
        if (fd < 0){
717
                if (errno == EEXIST)
718
                        pidfile_read(path, old_pid);
719
        }
720
        return fd;
721
}
722

    
723
void usage(char *argv0)
724
{
725
        fprintf(stderr, "Usage: %s [general options] [custom peer options]\n\n", argv0);
726
        fprintf(stderr, "General peer options:\n"
727
                "  Option      | Default | \n"
728
                "  --------------------------------------------\n"
729
                "    -g        | None    | Segment spec to join\n"
730
                "    -sp       | NoPort  | Start portno to bind\n"
731
                "    -ep       | NoPort  | End portno to bind\n"
732
                "    -p        | NoPort  | Portno to bind\n"
733
                "    -n        | 16      | Number of ops\n"
734
                "    -v        | 0       | Verbosity level\n"
735
                "    -l        | None    | Logfile \n"
736
                "    -d        | No      | Daemonize \n"
737
                "    --pidfile | None    | Pidfile \n"
738
#ifdef MT
739
                "    -t        | No      | Number of threads \n"
740
#endif
741
                "\n"
742
               );
743
        custom_peer_usage();
744
}
745

    
746
int main(int argc, char *argv[])
747
{
748
        struct peerd *peer = NULL;
749
        //parse args
750
        int r;
751
        long portno_start = -1, portno_end = -1, portno = -1;
752

    
753
        //set defaults here
754
        int daemonize = 0, help = 0;
755
        uint32_t nr_ops = 16;
756
        uint32_t nr_threads = 1;
757
        unsigned int debug_level = 0;
758
        uint32_t defer_portno = NoPort;
759
        pid_t old_pid;
760
        int pid_fd = -1;
761

    
762
        char spec[MAX_SPEC_LEN + 1];
763
        char logfile[MAX_LOGFILE_LEN + 1];
764
        char pidfile[MAX_PIDFILE_LEN + 1];
765

    
766
        logfile[0] = 0;
767
        pidfile[0] = 0;
768
        spec[0] = 0;
769

    
770
        //capture here -g spec, -n nr_ops, -p portno, -t nr_threads -v verbose level
771
        // -dp xseg_portno to defer blocking requests
772
        // -l log file ?
773
        //TODO print messages on arg parsing error
774
        BEGIN_READ_ARGS(argc, argv);
775
        READ_ARG_STRING("-g", spec, MAX_SPEC_LEN);
776
        READ_ARG_ULONG("-sp", portno_start);
777
        READ_ARG_ULONG("-ep", portno_end);
778
        READ_ARG_ULONG("-p", portno);
779
        READ_ARG_ULONG("-n", nr_ops);
780
        READ_ARG_ULONG("-v", debug_level);
781
#ifdef MT
782
        READ_ARG_ULONG("-t", nr_threads);
783
#endif
784
//        READ_ARG_ULONG("-dp", defer_portno);
785
        READ_ARG_STRING("-l", logfile, MAX_LOGFILE_LEN);
786
        READ_ARG_BOOL("-d", daemonize);
787
        READ_ARG_BOOL("-h", help);
788
        READ_ARG_BOOL("--help", help);
789
        READ_ARG_STRING("--pidfile", pidfile, MAX_PIDFILE_LEN);
790
        END_READ_ARGS();
791

    
792
        if (help){
793
                usage(argv[0]);
794
                return 0;
795
        }
796

    
797
        r = init_logctx(&lc, argv[0], debug_level, logfile,
798
                        REDIRECT_STDOUT|REDIRECT_STDERR);
799
        if (r < 0){
800
                XSEGLOG("Cannot initialize logging to logfile");
801
                return -1;
802
        }
803
        XSEGLOG2(&lc, D, "Main thread has tid %ld.\n", syscall(SYS_gettid));
804

    
805
        if (pidfile[0]){
806
                pid_fd = pidfile_open(pidfile, &old_pid);
807
                if (pid_fd < 0) {
808
                        if (old_pid) {
809
                                XSEGLOG2(&lc, E, "Daemon already running, pid: %d.", old_pid);
810
                        } else {
811
                                XSEGLOG2(&lc, E, "Cannot open or create pidfile");
812
                        }
813
                        return -1;
814
                }
815
        }
816

    
817
        if (daemonize){
818
                if (daemon(0, 1) < 0){
819
                        XSEGLOG2(&lc, E, "Cannot daemonize");
820
                        r = -1;
821
                        goto out;
822
                }
823
        }
824

    
825
        pidfile_write(pid_fd);
826

    
827
        //TODO perform argument sanity checks
828
        verbose = debug_level;
829
        if (portno != -1) {
830
                portno_start = portno;
831
                portno_end = portno;
832
        }
833
        if (portno_start == -1 || portno_end == -1){
834
                XSEGLOG2(&lc, E, "Portno or {portno_start, portno_end} must be supplied");
835
                usage(argv[0]);
836
                r = -1;
837
                goto out;
838
        }
839

    
840
        peer = peerd_init(nr_ops, spec, portno_start, portno_end, nr_threads, defer_portno);
841
        if (!peer){
842
                r = -1;
843
                goto out;
844
        }
845
        setup_signals(peer);
846
        r = custom_peer_init(peer, argc, argv);
847
        if (r < 0)
848
                goto out;
849
#if defined(MT)
850
        //TODO err check
851
        peerd_start_threads(peer);
852
#elif defined(ST_THREADS)
853
        st_thread_t st = st_thread_create(init_peerd_loop, peer, 1, 0);
854
        r = st_thread_join(st, NULL);
855
#else
856
        r = init_peerd_loop(peer);
857
#endif
858
out:
859
        if (pid_fd > 0)
860
                pidfile_remove(pidfile, pid_fd);
861
        return r;
862
}