summaryrefslogtreecommitdiffstats
blob: d420c96b1362305e1102ac6e070d206511293f9c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*
 * ctoolsprof_srv_main.c
 *
 * Ctools Profiler Server Implementation
 *
 * Copyright (C) 2013 Texas Instruments Incorporated - http://www.ti.com/ 
 * 
 * 
 *  Redistribution and use in source and binary forms, with or without 
 *  modification, are permitted provided that the following conditions 
 *  are met:
 *
 *    Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the 
 *    documentation and/or other materials provided with the   
 *    distribution.
 *
 *    Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <getopt.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "error_handler.h"
#include "logging.h"
#include "socket.h"
#include "command_handler.h"
#include "remote_commands.h"
#include "signal_handler.h"
#include "etb_handler.h"
#include "ctoolsprof.h"

const int g_major_version = 1;
const int g_minor_version = 1;
const int g_copyright_year = 2013;

FILE *g_stdout;
FILE *g_stderr;
char * g_whoami;

/* This is used by error_handler.c to determine if an error causes
 * program exit or decides based on if the error is fatal or not.
 */
bool g_interactive_mode = false;

/* This is used to enable sending the server state over a named pipe */
bool g_fifo_used = false;
bool g_fifo_enabled = false;
int g_fifo_fd = -1;
static char * fifo_filename = "ctprof_fifo";

/* g_terminate is used to terminate the server on a disconnect from the client.
 * AND it will not allow g_fifo_enabled to be set false (which causes
 * the server to block trying to open the pipe again).
 */
bool g_terminate = false;
static const char msg_terminate[] = "client terminate\n";

static int cmd_port = 54242;
static int etb_port = 54243;
//static int log_port = 54244;

/* Global server state initialization*/
monitor_state_t global_state = {
    .delay_active = false,
    .duration_active = false,
    .signal_active = false,
    .etb_active = false,
    .socket_disconnect = true,
    .etb_mode = 0,
    .recording = STATE_UNINITIALIZED
};

static int cmd_socket;
static int etb_socket;


/***************************************************************************** 
 *  Private functions
 *****************************************************************************/

/***************************************************************************** 
 *  socket_connect()
 *
 *  This function called by main to open the command and etb sockets with the
 *  client (running on the host).
 *
 *  - Initialize the socket tables.
 *  - Create command and etb ports. This binds, listens for the client and then
 *    accepts the 
 *  - Make each port non-blocking and register with their handler functions.
 *  - Set the global socket disconnect state to false.
 *  
 *****************************************************************************/

static void socket_connect(void)
{
    LOGFUNC();

    /* Initialize the socket tables */
    socket_open();
    fprintf(g_stdout, "%s:Waiting for client to connect\n", g_whoami);

    /* Configure a socket port and wait until client connects */   
    cmd_socket = socket_server_create(cmd_port);
    fprintf(g_stdout, "%s:Client command port connected\n", g_whoami);

    /* Optimize the command socket for server operation. */
    socket_command_optimize(cmd_socket);

    etb_socket = socket_server_create(etb_port);
    fprintf(g_stdout, "%s:Client etb service port connected\n", g_whoami);

    
    /* Make the command socket non-blocking so we don't 
     * wait on writes to complete. Add command socket to
     * list of read file descriptors to socket_wait() to wait on.
     */
    socket_set_nonblocking(cmd_socket);
    bool is_read_socket = true;
    socket_add_list(cmd_socket, is_read_socket);

    /* Register the command socket with the command handler */
    command_init(cmd_socket);

    /* Make the etb socket non-blocking and register the 
     * etb socket with the etb_handler.
     * Note - unlike the command socket, no need to add
     * the etb socket to the list of sockets to check by 
     * socket_wait() until there is some ETB data available.
     */
    socket_set_nonblocking(etb_socket);
    etb_init(etb_socket); 

    global_state.socket_disconnect = false;

}

/***************************************************************************** 
 *  clean_up_socket()
 *
 *  This function called by main when main detects a socket disconnect. Normally
 *  a socket disconnect only occurs when the client terminates.
 *  
 *****************************************************************************/
static void clean_up_socket(void)
{

    LOGFUNC();

    socket_remove_list(cmd_socket);
    socket_remove_list(etb_socket);
    socket_close(cmd_socket);
    socket_close(etb_socket);

}

/***************************************************************************** 
 *  Public functions
 *****************************************************************************/

/***************************************************************************** 
 *  main()
 *
 *  Main evaluates a set of simple command line parameters and then drops into
 *  an endless loop that processes client commands or returns trace data 
 *  (if available).  
 * 
 * TODO:
 * - Add command line option to send server logging data back to the client.
 *****************************************************************************/
 
int main(int argc, char *argv[])
{
    /* Initialize globals */
    g_stdout = stdout;
    g_stderr = stderr;
    g_whoami = argv[0];

    signal_handler_init(start_recording, stop_recording);

    /* evaluate command line */
    while (1) {
        struct option long_options[] = {
            {"port", required_argument, 0, 'p'},
            {"pipe", no_argument, 0,'P'},
            {"quiet", no_argument, 0,'q'},
            {"help", no_argument, 0, 'h'},
            {"logging", required_argument, 0, 'l'},
            {"version", no_argument, 0, 'v'},
            {"terminate", no_argument, 0, 't'}
        };

        char * short_options = "p:qhl:vPt";
        int option, option_index = 0;

        option = getopt_long(argc, argv, short_options, long_options, &option_index);
        
        /* No more options then all done */
        if (option == -1) break;

        switch (option) {
        case 'P':
        {
            struct stat fifo_stat;
            if (stat(fifo_filename, &fifo_stat) == 0) {
                if(!S_ISFIFO(fifo_stat.st_mode)) {
                    fprintf(g_stderr, "%s:%s already exists but is not a fifo",
                            g_whoami, fifo_filename);
                    err_handler(ERR_TYPE_SYSTEM, ERR_FIFO_MAKE);                   
                }
            } else {
                if (mkfifo(fifo_filename, 0666) == -1) {
                    fprintf(g_stderr, "%s:Can't make %s fifo file",
                            g_whoami, fifo_filename);
                    err_handler(ERR_TYPE_SYSTEM, ERR_FIFO_MAKE);
                }
            }

            g_fifo_used = true;
            g_fifo_enabled = false; 
            break;
        }
        case 'p':
            cmd_port = atoi(optarg);
            etb_port = cmd_port + 1;
//          log_port = cmd_port + 2;
            break;
        case 'q':
            g_stdout = fopen("/dev/null", "w");
            break;
        case '?': /* getopt did not understand the option */
        case 'h':
            fprintf(g_stdout, "Usage: %s [hlpPqv]\n", g_whoami);
            fprintf(g_stdout, " --help/-h               Print this\n");
            fprintf(g_stdout, " --logging/-l <level>    Enable logging to LOG_FILENAME\n");
            fprintf(g_stdout, "                         Level 0 - User information logging\n");
            fprintf(g_stdout, "                         Level 1 - Debug logging\n");
            fprintf(g_stdout, " --port/-p <ip port>     Set port value\n");
            fprintf(g_stdout, " --pipe/-P               Issue server recording state over a named pipe\n");
            fprintf(g_stdout, " --quiet/-q              Send stdout to /dev/null\n");
            fprintf(g_stdout, " --terminate/-t          Terminate server on disconnect from client\n");
            fprintf(g_stdout, " --version/-v            Print version\n");
            fprintf(g_stdout, "\n");
            exit(0);
        case 'l':
        {
            /* Yes, this looks a bit strange, but in order to use the same
             * log_handler for both server and client, must conform to argtable convention
             */
            int level[1] = {atoi(optarg)};
            log_handler((void **)&level, 1);
            if (level[1] == 0)
                fprintf(g_stdout, "%s:Logging level set to user info logging\n",
                        g_whoami);
            else
                fprintf(g_stdout, "%s:Logging level set to debug logging\n",
                        g_whoami);
            break;
        }
        case 't':
            g_terminate = true;
            break;
        case 'v':
            fprintf(g_stdout, "%s:version %d.%d\n", g_whoami, g_major_version,
                    g_minor_version);
            fprintf(g_stdout, "%s:Copyright (C) %d Texas Instruments, Inc.\n", 
                    g_whoami, g_copyright_year); 
            exit(0);
            break;
        default:
            err_handler(ERR_TYPE_LOCAL, ERR_PARSER);
        } /* End of switch */

    }

    socket_connect();

    /* This loop is the heart of the server! */
    do {

        /* If disconnected then try to reconnect - will stall here until a 
         * client connects.
         */
        if (global_state.socket_disconnect) {
            LOGMSG1("%s:socket disconnect detected. listening for client connection.", __func__);

            if (g_terminate) {
                if (g_fifo_enabled) {            
                    char * broken_pipe_msg = NULL;
                    remote_pipe_write(msg_terminate, strlen(msg_terminate), broken_pipe_msg);

                    LOGMSG1("%s:write to the pipe %s", __func__, msg_terminate);
                }

                clean_up();
                exit(0);
            } 

            socket_connect();
        }

        /* Open the fifo if required */
        if ((g_fifo_used == true) && (g_fifo_fd == -1)) {

            fprintf(g_stdout,"%s:Opening pipe for writing. " 
                             "Waiting on pipe to be open for reading.\n",
                             g_whoami);

            LOGMSG1("%s:Opening %s for writing.", __func__, fifo_filename);

            if ((g_fifo_fd = open(fifo_filename, O_WRONLY)) == -1) {
                fprintf(g_stderr, "%s:Can't open %s fifo file", g_whoami,
                        fifo_filename );
                err_handler(ERR_TYPE_SYSTEM, ERR_FIFO_OPEN);
            }

            fprintf(g_stdout,"%s:pipe open for reading\n", g_whoami);
            LOGMSG1("%s:%s open for reading", __func__, fifo_filename);
        }

        /* If the fifo is used (set by command line -P option) but it is not
         * enabled, time to enable it and send the first message (the server's pid).
         */
        if ((g_fifo_used == true) && (g_fifo_enabled == false)) {         
            g_fifo_enabled = true;

            /* First message written is this task's pid */
            pid_t mypid = getpid();

            char * broken_pipe_msg = "ctprof_srv's pid";
            remote_pipe_write((char *)&mypid, sizeof(pid_t), broken_pipe_msg);

            LOGMSG1("%s:write to the pipe %d", __func__, mypid);

            LOGMSG1("%s:wrote ctprof_srv pid %d to %s", __func__, mypid, fifo_filename);           
        }

#if DEBUG
        int state = 0;
        fprintf (g_stdout,"Processing ...|");
#endif
        /* This is the processing loop - socket_wait will wait for:
         * - A command socket message
         * - An empty etb socket that is ready for more trace data
         * - Or a timeout (socket_wait() returns 0 on a timeout)      
         */ 

        while (!socket_wait()) {
            /* socket_wait() timeout - go check for available trace data */
#if DEBUG
            state++;
            if (state == 1) fprintf (g_stdout, "\b/");
            else if (state == 2) fprintf (g_stdout, "\b-");
            else if (state == 3) fprintf (g_stdout, "\b\\"); 
            else if (state == 4) {fprintf (g_stdout, "\b|"); state = 0;}
            fflush(stdout);
#endif
            /* Don't want signals messing with our etb processing */
            signal_handler_block();

            if ((global_state.recording == STATE_RECORDING) 
                && (global_state.etb_active == true) 
                && (global_state.etb_mode == ETB_MODE_DRAIN)) {
               
                etb_add_queue(ETB_QUEUE_LIMIT);
                                  
            }

            signal_handler_unblock();
            
        }
        /* socket_wait() returned non-zero which means there is either a
         * command message ready to service or the etb socket is ready
         * for more data.
         */
#if DEBUG
        fprintf(g_stdout, "\r");
#endif
        /* Don't want signals messing with our command or etb processing. */
        signal_handler_block();

        /* If the command socket is on the read ready list, a command
         * message is ready to process.
         */
        if (socket_check_read_list(cmd_socket)) {
            command_process();

        }

        /* If the etb socket is on the write ready list, then more
         * etb data can be sent to the etb socket.
         */
        if (socket_check_write_list(etb_socket)) {
            etb_send_from_queue();
        }

        signal_handler_unblock();

        /* Check for a client disconnect. This can only happen from 
         * socket_recv_data() (see socket.c).
         */
        if (global_state.socket_disconnect) {
            clean_up_socket();
        }

    } while (1);
    
    socket_remove_list(cmd_socket);
    socket_close(cmd_socket);
 
}

/***************************************************************************** 
 *  clean_up()
 *
 *  This function is called to clean up any resources being used. It is called
 *  only by the error_handler.c when a fatal error is encountered, or when any
 *  error is encountered if not in interactive mode.  
 * 
 *****************************************************************************/
void clean_up(void)
{
    LOGFUNC();

    clean_up_socket();

    if (g_fifo_enabled) {
        close(g_fifo_fd);
    }

    if (g_fifo_used) {
        unlink(fifo_filename);
    }

}