Cli.cc 39 KB
Newer Older
Elemer Lelik's avatar
Elemer Lelik committed
1
/******************************************************************************
balaskoa's avatar
balaskoa committed
2
 * Copyright (c) 2000-2020 Ericsson Telecom AB
Elemer Lelik's avatar
Elemer Lelik committed
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v2.0
Elemer Lelik's avatar
Elemer Lelik committed
5
 * which accompanies this distribution, and is available at
6
 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
Elemer Lelik's avatar
Elemer Lelik committed
7
8
9
 *
 * Contributors:
 *   Balasko, Jeno
10
 *   Baranyi, Botond
Elemer Lelik's avatar
Elemer Lelik committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 *   Bene, Tamas
 *   Beres, Szabolcs
 *   Delic, Adam
 *   Forstner, Matyas
 *   Gecse, Roland
 *   Kovacs, Ferenc
 *   Lovassy, Arpad
 *   Raduly, Csaba
 *   Szabados, Kristof
 *   Szabo, Janos Zoltan – initial implementation
 *   Szalai, Gabor
 *   Zalanyi, Balazs Andor
 *   Roland Gecse - author
 *
 ******************************************************************************/
Elemer Lelik's avatar
Elemer Lelik committed
26
27
28
29
30
31
32
33
//
// Description:           Implementation file for Cli
//
//----------------------------------------------------------------------------
#include "Cli.h"
#include "../mctr/MainController.h"

#include <stdio.h>
34
#include <readline.h>
Elemer Lelik's avatar
Elemer Lelik committed
35
36
37
38
39
40
41
42
43
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#include <arpa/inet.h>
#include "../../common/version_internal.h"
#include "../../common/memory.h"
#include "../../common/config_preproc.h"
44
#include "../../core/DebugCommands.hh"
Elemer Lelik's avatar
Elemer Lelik committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

#define PROMPT "MC2> "
#define CMTC_TEXT "cmtc"
#define SMTC_TEXT "smtc"
#define EMTC_TEXT "emtc"
#define STOP_TEXT "stop"
#define PAUSE_TEXT "pause"
#define CONTINUE_TEXT "continue"
#define INFO_TEXT "info"
#define HELP_TEXT "help"
#define RECONF_TEXT "reconf"
#define LOG_TEXT "log"
#define SHELL_TEXT "!"
#define EXIT_TEXT "quit"
#define EXIT_TEXT2 "exit"
60
#define BATCH_TEXT "batch"
Elemer Lelik's avatar
Elemer Lelik committed
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
#define SHELL_ESCAPE '!'
#define TTCN3_HISTORY_FILENAME ".ttcn3_history"

using mctr::MainController;
using namespace cli;

/**
 * shell_mode == TRUE while editing a command line that is passed to the shell
 */
static boolean shell_mode;

struct Command {
  const char *name;
  callback_t callback_function;
  const char *synopsis;
  const char *description;
};

static const Command command_list[] = {
  { CMTC_TEXT, &Cli::cmtcCallback, CMTC_TEXT " [hostname]",
    "Create the MTC." },
  { SMTC_TEXT, &Cli::smtcCallback,
    SMTC_TEXT " [module_name[[.control]|.testcase_name|.*]",
    "Start MTC with control part, test case or all test cases." },
  { STOP_TEXT, &Cli::stopCallback, STOP_TEXT,
    "Stop test execution." },
  { PAUSE_TEXT, &Cli::pauseCallback, PAUSE_TEXT " [on|off]",
    "Set whether to interrupt test execution after each "
    "test case." },
  { CONTINUE_TEXT, &Cli::continueCallback, CONTINUE_TEXT,
    "Resumes interrupted test execution." },
  { EMTC_TEXT, &Cli::emtcCallback, EMTC_TEXT, "Terminate MTC." },
  { LOG_TEXT, &Cli::logCallback, LOG_TEXT " [on|off]",
    "Enable/disable console logging." },
  { INFO_TEXT, &Cli::infoCallback, INFO_TEXT,
    "Display test configuration information." },
  { RECONF_TEXT, &Cli::reconfCallback, RECONF_TEXT " [config_file]",
    "Reload configuration file." },
  { HELP_TEXT, &Cli::helpCallback, HELP_TEXT " <command>",
    "Display help on command." },
  { SHELL_TEXT, &Cli::shellCallback, SHELL_TEXT "[shell cmds]",
    "Execute commands in subshell." },
  { EXIT_TEXT, &Cli::exitCallback, EXIT_TEXT, "Exit Main Controller." },
  { EXIT_TEXT2, &Cli::exitCallback, EXIT_TEXT2, "Exit Main Controller." },
105
106
  { BATCH_TEXT, &Cli::executeBatchFile, BATCH_TEXT " <batch_file>",
    "Run commands from batch file." },
Elemer Lelik's avatar
Elemer Lelik committed
107
108
109
  { NULL, NULL, NULL, NULL }
};

110
111
112
113
114
115
116
117
118
119
struct DebugCommand {
  const char *name;
  int commandID;
  const char *synopsis;
  const char *description;
};

static const DebugCommand debug_command_list[] = {
  { D_SWITCH_TEXT, D_SWITCH, D_SWITCH_TEXT " on|off",
    "Switch the debugger on or off." },
120
  { D_SET_BREAKPOINT_TEXT, D_SET_BREAKPOINT,
121
    D_SET_BREAKPOINT_TEXT " <module> <line>|<function> [<batch_file>]",
122
    "Add a breakpoint at the specified location, or change the batch file of "
123
    "an existing breakpoint." },
124
  { D_REMOVE_BREAKPOINT_TEXT, D_REMOVE_BREAKPOINT,
125
126
127
    D_REMOVE_BREAKPOINT_TEXT " all|<module> [all|<line>|<function>]",
    "Remove a breakpoint, or all breakpoints from a module, or all breakpoints "
    "from all modules." },
128
129
130
131
  { D_SET_AUTOMATIC_BREAKPOINT_TEXT, D_SET_AUTOMATIC_BREAKPOINT,
    D_SET_AUTOMATIC_BREAKPOINT_TEXT " error|fail on|off [<batch_file>]",
    "Switch an automatic breakpoint (truggered by an event) on or off, and/or "
    "change its batch file." },
132
133
134
  { D_SET_OUTPUT_TEXT, D_SET_OUTPUT,
    D_SET_OUTPUT_TEXT " console|file|both [file_name]",
    "Set the output of the debugger." },
135
136
137
138
  { D_SET_GLOBAL_BATCH_FILE_TEXT, D_SET_GLOBAL_BATCH_FILE,
    D_SET_GLOBAL_BATCH_FILE_TEXT " on|off [batch_file_name]",
    "Set whether a batch file should be executed automatically when test execution "
    "is halted (breakpoint-specific batch files override this setting)." },
139
140
141
  { D_FUNCTION_CALL_CONFIG_TEXT, D_FUNCTION_CALL_CONFIG,
    D_FUNCTION_CALL_CONFIG_TEXT " file|<limit>|all [<file_name>]",
    "Configure the storing of function call data." },
142
143
144
145
  { D_PRINT_SETTINGS_TEXT, D_PRINT_SETTINGS, D_PRINT_SETTINGS_TEXT,
    "Prints the debugger's settings." },
  { D_LIST_COMPONENTS_TEXT, D_LIST_COMPONENTS, D_LIST_COMPONENTS_TEXT,
    "List the test components currently running debuggable code." },
146
  { D_SET_COMPONENT_TEXT, D_SET_COMPONENT,
147
    D_SET_COMPONENT_TEXT " <component name>|<component_reference>",
148
149
150
151
152
153
    "Set the test component to print debug information from." },
  { D_PRINT_CALL_STACK_TEXT, D_PRINT_CALL_STACK, D_PRINT_CALL_STACK_TEXT,
    "Print call stack." },
  { D_SET_STACK_LEVEL_TEXT, D_SET_STACK_LEVEL, D_SET_STACK_LEVEL_TEXT " <level>",
    "Set the stack level to print debug information from." },
  { D_LIST_VARIABLES_TEXT, D_LIST_VARIABLES,
154
    D_LIST_VARIABLES_TEXT " [local|global|comp|all] [pattern]",
155
156
    "List variable names." },
  { D_PRINT_VARIABLE_TEXT, D_PRINT_VARIABLE,
157
158
159
    D_PRINT_VARIABLE_TEXT " <variable_name>|$ [{ <variable_name>|$}]",
    "Print current value of one or more variables ('$' is substituted with the "
    "result of the last " D_LIST_VARIABLES_TEXT " command)." },
160
161
162
  { D_OVERWRITE_VARIABLE_TEXT, D_OVERWRITE_VARIABLE,
    D_OVERWRITE_VARIABLE_TEXT " <variable_name> <value>",
    "Overwrite the current value of a variable." },
163
164
165
  { D_PRINT_FUNCTION_CALLS_TEXT, D_PRINT_FUNCTION_CALLS,
    D_PRINT_FUNCTION_CALLS_TEXT " [all|<amount>]",
    "Print function call data." },
166
167
168
169
170
171
172
  { D_STEP_OVER_TEXT, D_STEP_OVER, D_STEP_OVER_TEXT,
    "Resume test execution until the next line of code (in this function or the "
    "caller function)." },
  { D_STEP_INTO_TEXT, D_STEP_INTO, D_STEP_INTO_TEXT,
    "Resume test execution until the next line of code (on any stack level)." },
  { D_STEP_OUT_TEXT, D_STEP_OUT, D_STEP_OUT_TEXT,
    "Resume test execution until the next line of code in the caller function." },
173
174
  { D_RUN_TO_CURSOR_TEXT, D_RUN_TO_CURSOR,
    D_RUN_TO_CURSOR_TEXT " <module> <line>|<function>",
175
176
177
178
179
180
181
182
    "Resume test execution until the specified location." },
  { D_HALT_TEXT, D_HALT, D_HALT_TEXT, "Halt test execution." },
  { D_CONTINUE_TEXT, D_CONTINUE, D_CONTINUE_TEXT, "Resume halted test execution." },
  { D_EXIT_TEXT, D_EXIT, D_EXIT_TEXT " test|all",
    "Exit the current test or the execution of all tests." },
  { NULL, D_ERROR, NULL, NULL }
};

Elemer Lelik's avatar
Elemer Lelik committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
Cli::Cli()
{
  loggingEnabled = TRUE;
  exitFlag = FALSE;
  waitState = WAIT_NOTHING;
  executeListIndex = 0;

  if (pthread_mutex_init(&mutex, NULL)) {
    perror("Cli::Cli: pthread_mutex_init failed.");
    exit(EXIT_FAILURE);
  }
  if (pthread_cond_init(&cond, NULL)) {
    perror("Cli::Cli: pthread_cond_init failed.");
    exit(EXIT_FAILURE);
  }
198
  cfg_file_name = NULL;
Elemer Lelik's avatar
Elemer Lelik committed
199
200
201
202
203
204
}

Cli::~Cli()
{
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond);
205
  Free(cfg_file_name);
Elemer Lelik's avatar
Elemer Lelik committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
}

//----------------------------------------------------------------------------
// MANDATORY

int Cli::enterLoop(int argc, char *argv[])
{
  // Parameter check: mctr [config file name]
  if (argc > 2) {
    printUsage(argv[0]);
    return EXIT_FAILURE;
  }

  printWelcome();

  if (argc == 2) {
222
223
224
    cfg_file_name = mcopystr(argv[1]);
    printf("Using configuration file: %s\n", cfg_file_name);
    if (process_config_read_file(cfg_file_name, &mycfg)) {
Elemer Lelik's avatar
Elemer Lelik committed
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
      puts("Error was found in the configuration file. Exiting.");
      cleanUp();
      return EXIT_FAILURE;
    }
    else {
      MainController::set_kill_timer(mycfg.kill_timer);

      for (int i = 0; i < mycfg.group_list_len; ++i) {
        MainController::add_host(mycfg.group_list[i].group_name,
          mycfg.group_list[i].host_name);
      }

      for (int i = 0; i < mycfg.component_list_len; ++i) {
        MainController::assign_component(mycfg.component_list[i].host_or_group,
          mycfg.component_list[i].component);
      }
    }
  }

  int ret_val;
  if (mycfg.num_hcs <= 0) ret_val = interactiveMode();
  else ret_val = batchMode();

  cleanUp();
  return ret_val;
}

//----------------------------------------------------------------------------
// MANDATORY

void Cli::status_change()
{
  lock();
  if (waitState != WAIT_NOTHING && conditionHolds(waitState)) {
    waitState = WAIT_NOTHING;
    signal();
  }
  unlock();
}

//----------------------------------------------------------------------------
// MANDATORY

void Cli::error(int /*severity*/, const char *message)
{
  printf("Error: %s\n", message);
  fflush(stdout);
  // TODO: Error handling based on the MC state where the error happened
}

//----------------------------------------------------------------------------
// MANDATORY

void Cli::notify(const struct timeval *timestamp, const char *source,
  int /*severity*/, const char *message)
{
  if (loggingEnabled)
  {
    switch(mycfg.tsformat){
      case TSF_TIME:       // handled together
      case TSF_DATE_TIME:
        {
          time_t tv_sec = timestamp->tv_sec;
          struct tm *lt = localtime(&tv_sec);
          if (lt == NULL) {
            printf("localtime() call failed.");
            printf("%s: %s\n", source, message);
            fflush(stdout);
            break;
          }
          if (mycfg.tsformat == TSF_TIME) {
            printf("%02d:%02d:%02d.%06ld %s: %s\n",
                  lt->tm_hour, lt->tm_min, lt->tm_sec, timestamp->tv_usec,source, message);
          } else {
            static const char * const month_names[] = { "Jan", "Feb", "Mar",
              "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            printf("%4d/%s/%02d %02d:%02d:%02d.%06ld  %s: %s\n",
                             lt->tm_year + 1900, month_names[lt->tm_mon],
                             lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec,
                             timestamp->tv_usec
                             ,source, message);
          }
        }
        fflush(stdout);
        break;
      case TSF_SEC:
311
        printf("%ld.%06ld %s: %s\n", static_cast<long>( timestamp->tv_sec ), timestamp->tv_usec, source, message);
Elemer Lelik's avatar
Elemer Lelik committed
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
        fflush(stdout);
      
        break;
      default:
        printf("%s: %s\n", source, message);
        fflush(stdout);
        break;
    }
  }
}

//----------------------------------------------------------------------------
// PRIVATE

void Cli::cleanUp()
{
}

//----------------------------------------------------------------------------
// PRIVATE

void Cli::printWelcome()
{
  printf("\n"
    "*************************************************************************\n"
    "* TTCN-3 Test Executor - Main Controller 2                              *\n"
    "* Version: %-40s                     *\n"
balaskoa's avatar
balaskoa committed
339
    "* Copyright (c) 2000-2020 Ericsson Telecom AB                           *\n"
Elemer Lelik's avatar
Elemer Lelik committed
340
    "* All rights reserved. This program and the accompanying materials      *\n"
341
    "* are made available under the terms of the Eclipse Public License v2.0 *\n"
Elemer Lelik's avatar
Elemer Lelik committed
342
    "* which accompanies this distribution, and is available at              *\n"
balaskoa's avatar
balaskoa committed
343
    "* https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html            *\n"
Elemer Lelik's avatar
Elemer Lelik committed
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
    "*************************************************************************\n"
    "\n", PRODUCT_NUMBER);
}

void Cli::printUsage(const char *prg_name)
{
  fprintf(stderr,
    "TTCN-3 Test Executor - Main Controller 2\n"
    "Version: " PRODUCT_NUMBER "\n\n"
    "usage: %s [configuration_file]\n"
    "where: the optional 'configuration_file' parameter specifies the name "
    "and\nlocation of the main controller configuration file"
    "\n", prg_name);
}

//----------------------------------------------------------------------------
// PRIVATE

int Cli::interactiveMode()
{
  // Initialize history library
  using_history();
  // Tailor $HOME/...
  const char *home_directory = getenv("HOME");
  if(home_directory == NULL)
    home_directory = ".";
  char *ttcn3_history_filename = mprintf("%s/%s", home_directory,
    TTCN3_HISTORY_FILENAME);
  // Read history from file, don't bother if it does not exist!
  read_history(ttcn3_history_filename);
  // Set our own command completion function
375
#ifdef OLD_LIBEDIT
376
377
  rl_completion_entry_function = (Function*)completeCommand;
#else
378
  rl_completion_entry_function = completeCommand;
379
#endif
Elemer Lelik's avatar
Elemer Lelik committed
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
  // Override rl_getc() in order to detect shell mode
  rl_getc_function = getcWithShellDetection;

  // TCP listen port parameter, returns TCP port on which it listens!
  // Returns 0 on error.
  if (MainController::start_session(mycfg.local_addr, mycfg.tcp_listen_port,
    mycfg.unix_sockets_enabled) == 0) {
    puts("Initialization of TCP server failed. Exiting.");
    Free(ttcn3_history_filename);
    return EXIT_FAILURE;
  }

  do {
    char *line_read = readline(PROMPT);
    if (line_read != NULL) {
      shell_mode = FALSE;
      stripLWS(line_read);
      if (*line_read) {
        add_history(line_read); // history maintains its own copy
        // process and free line
        processCommand(line_read);
        free(line_read);
        line_read = NULL;
      }
    } else {
      // EOF was received
      puts("exit");
      exitCallback("");
    }
  } while (!exitFlag);

  if (write_history(ttcn3_history_filename))
    perror("Could not save history.");
  Free(ttcn3_history_filename);

  return EXIT_SUCCESS;
}

int Cli::batchMode()
{
  printf("Entering batch mode. Waiting for %d HC%s to connect...\n",
    mycfg.num_hcs, mycfg.num_hcs > 1 ? "s" : "");
  if (mycfg.execute_list_len <= 0) {
    puts("No [EXECUTE] section was given in the configuration file. "
      "Exiting.");
    return EXIT_FAILURE;
  }
  boolean error_flag = FALSE;
  // start to listen on TCP port
  if (MainController::start_session(mycfg.local_addr, mycfg.tcp_listen_port,
    mycfg.unix_sockets_enabled) == 0) {
    puts("Initialization of TCP server failed. Exiting.");
    return EXIT_FAILURE;
  }
  waitMCState(WAIT_HC_CONNECTED);
  // download config file
  MainController::configure(mycfg.config_read_buffer);
  waitMCState(WAIT_ACTIVE);
  if (MainController::get_state() != mctr::MC_ACTIVE) {
    puts("Error during initialization. Cannot continue in batch mode.");
    error_flag = TRUE;
  }
  if (!error_flag) {
    // create MTC on firstly connected HC
    MainController::create_mtc(0);
    waitMCState(WAIT_MTC_CREATED);
    if (MainController::get_state() != mctr::MC_READY) {
      puts("Creation of MTC failed. Cannot continue in batch mode.");
      error_flag = TRUE;
    }
  }
  if (!error_flag) {
    // execute each item of the list
    for (int i = 0; i < mycfg.execute_list_len; i++) {
      executeFromList(i);
      waitMCState(WAIT_MTC_READY);
      if (MainController::get_state() != mctr::MC_READY) {
        puts("MTC terminated unexpectedly. Cannot continue in batch "
          "mode.");
        error_flag = TRUE;
        break;
      }
    }
  }
  if (!error_flag) {
    // terminate the MTC
    MainController::exit_mtc();
    waitMCState(WAIT_MTC_TERMINATED);
  }
  // now MC must be in state MC_ACTIVE anyway
  // shutdown MC
  MainController::shutdown_session();
  waitMCState(WAIT_SHUTDOWN_COMPLETE);
  if (error_flag) return EXIT_FAILURE;
  else return EXIT_SUCCESS;
}

//----------------------------------------------------------------------------
// PRIVATE

void Cli::processCommand(char *line_read)
{
  for (const Command *command = command_list; command->name != NULL;
483
       command++) {
Elemer Lelik's avatar
Elemer Lelik committed
484
485
486
487
488
489
490
491
    size_t command_name_len = strlen(command->name);
    if (!strncmp(line_read, command->name, command_name_len)) {
      memset(line_read, ' ', command_name_len);
      stripLWS(line_read);
      (this->*command->callback_function)(line_read);
      return;
    }
  }
492
493
494
495
496
497
498
  for (const DebugCommand* command = debug_command_list; command->name != NULL;
       command++) {
    size_t command_name_len = strlen(command->name);
    if (!strncmp(line_read, command->name, command_name_len)) {
      memset(line_read, ' ', command_name_len);
      stripLWS(line_read);
      MainController::debug_command(command->commandID, line_read);
499
500
501
502
503
      if (waitState == WAIT_EXECUTE_LIST && command->commandID == D_EXIT &&
          !strcmp(line_read, "all")) {
        // stop executing the list from the config file
        waitState = WAIT_NOTHING;
      }
504
505
506
      return;
    }
  }
Elemer Lelik's avatar
Elemer Lelik committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  puts("Unknown command, try again...");
}

//----------------------------------------------------------------------------
// PRIVATE
// Create Main Test Component

void Cli::cmtcCallback(const char *arguments)
{
  int hostIndex;
  if(*arguments == 0) hostIndex = 0;
  else {
    hostIndex = getHostIndex(arguments);
    if (hostIndex < 0) return;
  }
  switch (MainController::get_state()) {
  case mctr::MC_LISTENING:
  case mctr::MC_LISTENING_CONFIGURED:
    puts("Waiting for HC to connect...");
    waitMCState(WAIT_HC_CONNECTED);
Kristof Szabados's avatar
Kristof Szabados committed
527
    //intentional fall through
Elemer Lelik's avatar
Elemer Lelik committed
528
529
530
531
532
533
534
  case mctr::MC_HC_CONNECTED:
    MainController::configure(mycfg.config_read_buffer);
    waitMCState(WAIT_ACTIVE);
    if (MainController::get_state() != mctr::MC_ACTIVE) {
      puts("Error during initialization. Cannot create MTC.");
      break;
    }
Kristof Szabados's avatar
Kristof Szabados committed
535
    //intentional fall through
Elemer Lelik's avatar
Elemer Lelik committed
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
  case mctr::MC_ACTIVE:
    MainController::create_mtc(hostIndex);
    waitMCState(WAIT_MTC_CREATED);
    break;
  default:
    puts("MTC already exists.");
  }
  fflush(stdout);
}

//----------------------------------------------------------------------------
// PRIVATE
// Start Main Test Component and execute the
// a) control part or testcase (or *) given in arguments
// b) EXECUTE part of supplied configuration file -- if arguments==NULL

void Cli::smtcCallback(const char *arguments)
{
  switch (MainController::get_state()) {
  case mctr::MC_LISTENING:
  case mctr::MC_LISTENING_CONFIGURED:
  case mctr::MC_HC_CONNECTED:
  case mctr::MC_ACTIVE:
    puts("MTC does not exist.");
    break;
  case mctr::MC_READY:
    if (*arguments == 0) {
      // Execute configuration file's execute section
      if (mycfg.execute_list_len > 0) {
        puts("Executing all items of [EXECUTE] section.");
        waitState = WAIT_EXECUTE_LIST;
        executeListIndex = 0;
        executeFromList(0);
      } else {
        puts("No [EXECUTE] section was given in the configuration "
          "file.");
      }
    } else { // Check the arguments
      size_t doti = 0, alen = strlen(arguments), state = 0;
      for (size_t r = 0; r < alen; r++) {
        switch (arguments[r]) {
        case '.':
          ++state;
          doti = r;
          break;
        case ' ':
        case '\t':
          state = 3;
        }
      }

      if(state > 1) { // incorrect argument
        puts("Incorrect argument format.");
        helpCallback(SMTC_TEXT);
      } else {
        if(state == 0) { // only modulename is given in arguments
          MainController::execute_control(arguments);
        } else { // modulename.something in arguments
          expstring_t arg_copy = mcopystr(arguments);
          arg_copy[doti++] = '\0';
          if (!strcmp(arg_copy + doti, "*"))
            MainController::execute_testcase(arg_copy, NULL);
          else if (!strcmp(arg_copy + doti, "control"))
            MainController::execute_control(arg_copy);
          else MainController::execute_testcase(arg_copy,
            arg_copy + doti);
          Free(arg_copy);
        }
      }
    }
    break;
  default:
    puts("MTC is busy.");
  }
  fflush(stdout);
}

//----------------------------------------------------------------------------
// PRIVATE
// Stops test execution

void Cli::stopCallback(const char *arguments)
{
  if (*arguments == 0) {
    switch (MainController::get_state()) {
    case mctr::MC_TERMINATING_TESTCASE:
    case mctr::MC_EXECUTING_CONTROL:
    case mctr::MC_EXECUTING_TESTCASE:
    case mctr::MC_PAUSED:
      MainController::stop_execution();
      if (waitState == WAIT_EXECUTE_LIST) waitState = WAIT_NOTHING;
      break;
    default:
      puts("Tests are not running.");
    }
  } else helpCallback(STOP_TEXT);
}

//----------------------------------------------------------------------------
// PRIVATE
// Sets whether to interrupt test execution after testcase

void Cli::pauseCallback(const char *arguments)
{
  if (arguments[0] != '\0') {
    if (!strcmp(arguments, "on")) {
      if (!MainController::get_stop_after_testcase()) {
        MainController::stop_after_testcase(TRUE);
        puts("Pause function is enabled. "
          "Execution will stop at the end of each testcase.");
      } else puts("Pause function is already enabled.");
    } else if (!strcmp(arguments, "off")) {
      if (MainController::get_stop_after_testcase()) {
        MainController::stop_after_testcase(FALSE);
        puts("Pause function is disabled. "
          "Execution will continue at the end of each testcase.");
      } else puts("Pause function is already disabled.");
    } else helpCallback(PAUSE_TEXT);
  } else printf("Pause function is %s.\n",
    MainController::get_stop_after_testcase() ? "enabled" : "disabled");
}

//----------------------------------------------------------------------------
// PRIVATE
// Resumes interrupted test execution

void Cli::continueCallback(const char *arguments)
{
  if (*arguments == 0) {
    switch (MainController::get_state()) {
    case mctr::MC_TERMINATING_TESTCASE:
    case mctr::MC_EXECUTING_CONTROL:
    case mctr::MC_EXECUTING_TESTCASE:
      puts("Execution is not paused.");
      break;
    case mctr::MC_PAUSED:
      MainController::continue_testcase();
      break;
    default:
      puts("Tests are not running.");
    }
  } else helpCallback(CONTINUE_TEXT);
}

//----------------------------------------------------------------------------
// PRIVATE
// Exit Main Test Component

void Cli::emtcCallback(const char *arguments)
{
  if(*arguments == 0) {
    switch (MainController::get_state()) {
    case mctr::MC_LISTENING:
    case mctr::MC_LISTENING_CONFIGURED:
    case mctr::MC_HC_CONNECTED:
    case mctr::MC_ACTIVE:
      puts("MTC does not exist.");
      break;
    case mctr::MC_READY:
      MainController::exit_mtc();
      waitMCState(WAIT_MTC_TERMINATED);
      break;
    default:
      puts("MTC cannot be terminated.");
    }
  } else {
    helpCallback(EMTC_TEXT);
  }
}

//----------------------------------------------------------------------------
// PRIVATE
// Controls console logging

void Cli::logCallback(const char *arguments)
{
  if (arguments[0] != '\0') {
    if (!strcmp(arguments, "on")) {
      loggingEnabled = TRUE;
      puts("Console logging is enabled.");
    } else if (!strcmp(arguments, "off")) {
      loggingEnabled = FALSE;
      puts("Console logging is disabled.");
    } else helpCallback(LOG_TEXT);
  } else printf("Console logging is %s.\n",
    loggingEnabled ? "enabled" : "disabled");
}

//----------------------------------------------------------------------------
// PRIVATE
// Print connection information

void Cli::infoCallback(const char *arguments)
{
  if (*arguments == 0) printInfo();
  else helpCallback(INFO_TEXT);
}

//----------------------------------------------------------------------------
// PRIVATE
// Reconfigure MC and HCs

void Cli::reconfCallback(const char *arguments)
{
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
  if (!MainController::start_reconfiguring()) {
    return;
  }
  if (*arguments != 0) {
    Free(cfg_file_name);
    cfg_file_name = mcopystr(arguments);
  }
  
  printf("Using configuration file: %s\n", cfg_file_name);
  if (process_config_read_file(cfg_file_name, &mycfg)) {
    puts("Error was found in the configuration file. Exiting.");
    cleanUp();
    puts("exit");
    exitCallback("");
  }
  else {
    MainController::set_kill_timer(mycfg.kill_timer);

    for (int i = 0; i < mycfg.group_list_len; ++i) {
      MainController::add_host(mycfg.group_list[i].group_name,
        mycfg.group_list[i].host_name);
    }

    for (int i = 0; i < mycfg.component_list_len; ++i) {
      MainController::assign_component(mycfg.component_list[i].host_or_group,
        mycfg.component_list[i].component);
    }
    
    if (MainController::get_state() == mctr::MC_RECONFIGURING) {
      MainController::configure(mycfg.config_read_buffer);
    }
Elemer Lelik's avatar
Elemer Lelik committed
771
772
773
774
775
776
777
778
779
780
781
782
783
  }
}

//----------------------------------------------------------------------------
// PRIVATE
// Print general help or help on command usage to console

void Cli::helpCallback(const char *arguments)
{
  if (*arguments == 0) {
    puts("Help is available for the following commands:");
    for (const Command *command = command_list;
      command->name != NULL; command++) {
784
      printf("%s ", command->name);
Elemer Lelik's avatar
Elemer Lelik committed
785
    }
786
787
    for (const DebugCommand *command = debug_command_list;
         command->name != NULL; command++) {
788
      printf("%s ", command->name);
789
    }
Elemer Lelik's avatar
Elemer Lelik committed
790
791
792
793
794
795
796
797
798
799
800
801
    putchar('\n');
  } else {
    for (const Command *command = command_list;
      command->name != NULL; command++) {
      if (!strncmp(arguments, command->name,
        strlen(command->name))) {
        printf("%s usage: %s\n%s\n", command->name,
          command->synopsis,
          command->description);
        return;
      }
    }
802
803
804
805
806
807
808
809
810
811
    for (const DebugCommand *command = debug_command_list;
         command->name != NULL; command++) {
      if (!strncmp(arguments, command->name,
        strlen(command->name))) {
        printf("%s usage: %s\n%s\n", command->name,
          command->synopsis,
          command->description);
        return;
      }
    }
Elemer Lelik's avatar
Elemer Lelik committed
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
    printf("No help for %s.\n", arguments);
  }
}

//----------------------------------------------------------------------------
// PRIVATE
// Pass command to shell

void Cli::shellCallback(const char *arguments)
{
  if(system(arguments) == -1) {
    perror("Error executing command in subshell.");
  }
}

//----------------------------------------------------------------------------
// PRIVATE
// User initiated MC termination, exits the program.
// Save history into file and terminate CLI session.

void Cli::exitCallback(const char *arguments)
{
  if (*arguments == 0) {
    switch (MainController::get_state()) {
    case mctr::MC_READY:
837
    case mctr::MC_RECONFIGURING:
Elemer Lelik's avatar
Elemer Lelik committed
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
      MainController::exit_mtc();
      waitMCState(WAIT_MTC_TERMINATED);
    case mctr::MC_LISTENING:
    case mctr::MC_LISTENING_CONFIGURED:
    case mctr::MC_HC_CONNECTED:
    case mctr::MC_ACTIVE:
      MainController::shutdown_session();
      waitMCState(WAIT_SHUTDOWN_COMPLETE);
      exitFlag = TRUE;
      break;
    default:
      puts("Cannot exit until execution is finished.");
    }
  } else {
    helpCallback(EXIT_TEXT);
  }
}

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
void Cli::executeBatchFile(const char* filename)
{
  FILE* fp = fopen(filename, "r");
  if (fp == NULL) {
    printf("Failed to open file '%s' for reading.\n", filename);
    return;
  }
  else {
    printf("Executing batch file '%s'.\n", filename);
  }
  char line[1024];
  while (fgets(line, sizeof(line), fp) != NULL) {
    size_t len = strlen(line);
    if (line[len - 1] == '\n') {
      line[len - 1] = '\0';
      --len;
    }
    if (len != 0) {
      printf("%s\n", line);
      processCommand(line);
    }
  }
  if (!feof(fp)) {
    printf("Error occurred while reading batch file '%s' (error code: %d).\n",
      filename, ferror(fp));
  }
  fclose(fp);
}

Elemer Lelik's avatar
Elemer Lelik committed
885
886
887
888
889
890
891
892
//----------------------------------------------------------------------------
// PRIVATE
// Command completion function implementation for readline() library.
// Heavily uses the ``static Command command_list[]'' array!

char *Cli::completeCommand(const char *prefix, int state)
{
  static int command_index;
893
  static int debug_command_index;
Elemer Lelik's avatar
Elemer Lelik committed
894
895
896
897
898
899
900
901
  static size_t prefix_len;
  const char *command_name;

  if(shell_mode)
    return rl_filename_completion_function(prefix, state);

  if(state == 0) {
    command_index = 0;
902
    debug_command_index = 0;
Elemer Lelik's avatar
Elemer Lelik committed
903
904
905
906
907
908
909
910
911
912
    prefix_len = strlen(prefix);
  }

  while((command_name = command_list[command_index].name)) {
    ++command_index;
    if(strncmp(prefix, command_name, prefix_len) == 0) {
      // Must allocate buffer for returned string (readline frees it)
      return strdup(command_name);
    }
  }
913
914
915
916
917
918
919
920
  
  while ((command_name = debug_command_list[debug_command_index].name)) {
    ++debug_command_index;
    if (strncmp(prefix, command_name, prefix_len) == 0) {
      // Must allocate buffer for returned string (readline frees it)
      return strdup(command_name);
    }
  }
Elemer Lelik's avatar
Elemer Lelik committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
  // No match found
  return NULL;
}

//----------------------------------------------------------------------------
// PRIVATE
// Character input function implementation for readline() library.

int Cli::getcWithShellDetection(FILE *fp)
{
  int input_char = getc(fp);
  if(input_char == SHELL_ESCAPE)
    shell_mode = TRUE;
  return input_char;
}


//----------------------------------------------------------------------------
// PRIVATE

void Cli::stripLWS(char *input_text)
{
  if(input_text == NULL) {
    puts("stripLWS() called with NULL.");
    exit(EXIT_FAILURE); // This shall never happen
  }
  size_t head_index, tail_index, input_len = strlen(input_text);
  if(input_len < 1) return;
  for(head_index = 0; isspace(input_text[head_index]); head_index++) ;
  for(tail_index = input_len - 1; tail_index >= head_index &&
  isspace(input_text[tail_index]); tail_index--) ;
  size_t output_len = tail_index - head_index + 1;
  memmove(input_text, input_text + head_index, output_len);
  memset(input_text + output_len, 0, input_len - output_len);
}

const char *Cli::verdict2str(verdicttype verdict)
{
  switch (verdict) {
  case NONE:
    return "none";
  case PASS:
    return "pass";
  case INCONC:
    return "inconc";
  case FAIL:
    return "fail";
  case ERROR:
    return "error";
  default:
    return "unknown";
  }
}

//----------------------------------------------------------------------------
// PRIVATE

void Cli::printInfo()
{
  puts("MC information:");
  printf(" MC state: %s\n",
    MainController::get_mc_state_name(MainController::get_state()));
  puts(" host information:");
  int host_index = 0;
  for ( ; ; host_index++) {
    mctr::host_struct *host = MainController::get_host_data(host_index);
    if (host != NULL) {
      printf("  - %s", host->hostname);
      const char *ip_addr = host->ip_addr->get_addr_str();
      // if the hostname differs from the IP address
      // (i.e. the host has a DNS entry)
      if (strcmp(ip_addr, host->hostname)) printf(" [%s]", ip_addr);
      // if the local hostname differs from the prefix of the DNS name
      if (strncmp(host->hostname, host->hostname_local,
        strlen(host->hostname_local)))
        printf(" (%s)", host->hostname_local);
      puts(":");
      printf("     operating system: %s %s on %s\n", host->system_name,
        host->system_release, host->machine_type);
      printf("     HC state: %s\n",
For faster browsing, not all history is shown. View entire blame