int
main(int argc, char** argv)
{
  my_progname = "ndb_pack_frm";
  int ret;

  ndb_init();
  ndb_opt_set_usage_funcs(short_usage_sub, usage);
  ret = handle_options(&argc, &argv, my_long_options, ndb_std_get_one_option);
 if (ret != 0)
    return NDBT_WRONGARGS;

  for (int i = 0; i < argc; i++)
  {
    ret = dofile(argv[i]);
    if (ret != 0)
      return NDBT_FAILED;
  }

  return NDBT_OK;
}
Ejemplo n.º 2
0
int main(int argc, char** argv){
  NDB_INIT(argv[0]);
  load_defaults("my",load_default_groups,&argc,&argv);
  const char* _hostName = NULL;

#ifndef DBUG_OFF
  opt_debug= "d:t:O,/tmp/ndb_waiter.trace";
#endif

  if (handle_options(&argc, &argv, my_long_options,
                     ndb_std_get_one_option))
    return NDBT_ProgramExit(NDBT_WRONGARGS);

  _hostName = argv[0];

  if (_hostName == 0)
    _hostName= opt_connect_str;

  enum ndb_mgm_node_status wait_status;
  if (_no_contact)
  {
    wait_status= NDB_MGM_NODE_STATUS_NO_CONTACT;
  }
  else if (_not_started)
  {
    wait_status= NDB_MGM_NODE_STATUS_NOT_STARTED;
  }
  else if (_single_user)
  {
    wait_status= NDB_MGM_NODE_STATUS_SINGLEUSER;
  }
  else 
  {
    wait_status= NDB_MGM_NODE_STATUS_STARTED;
  }

  if (waitClusterStatus(_hostName, wait_status) != 0)
    return NDBT_ProgramExit(NDBT_FAILED);
  return NDBT_ProgramExit(NDBT_OK);
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
    checkin_initialize();
    if( argc == 1 ) {
        printf("No option or keyword specified. Starting shell...\n");
        checkin_shell();
    }
    else if( argc > 1) {
        char *keyword = NULL;
        int arg_c = argc;
        char **arg_v = argv;
        /* not an option */
        if( argv[1][0] != '-' ) {
            keyword = argv[1];
            arg_c -= 1;
            arg_v = argv+1;
        }
        initialize_database_connection();
        handle_options(keyword, arg_c, arg_v);
    }
    checkin_terminate(0);
}
Ejemplo n.º 4
0
int
main(int argc, char *argv[])
{
  int i, r;

  progname = argv[0];
  for (i = 1; i < argc; i++) {
    r = handle_options(argv[i]);
    if (r == 1) i++;
    if (r > 0) break;
  }
  if (i == argc) fatal("no program to execute");

  if (!(current_dir = os_GetWorkingDir())) fatal("getcwd() failed");

  if (all_tests > 0) {
    if (!test_dir) fatal("--test-dir must be specified in --all-tests mode");
    if (!test_pattern || !*test_pattern) fatal("--test-pattern must be specified in --all-tests mode");
    return run_all_tests(argc - i, argv + i);
  }

  return run_program(argc - i, argv + i, NULL, NULL);
}
Ejemplo n.º 5
0
int
main(int argc, char** argv)
{
  my_progname = "ndb_index_stat";
  int ret;

  ndb_init();
  ndb_opt_set_usage_funcs(short_usage_sub, usage);
  ret = handle_options(&argc, &argv, my_long_options, ndb_std_get_one_option);
  if (ret != 0 || checkopts(argc, argv) != 0)
    return NDBT_ProgramExit(NDBT_WRONGARGS);

  setOutputLevel(_verbose ? 2 : 0);

  unsigned seed = (unsigned)time(0);
  g_info << "random seed " << seed << endl;
  ndb_srand(seed);

  ret = doall();
  if (ret == -1)
    return NDBT_ProgramExit(NDBT_FAILED);
  return NDBT_ProgramExit(NDBT_OK);
}
Ejemplo n.º 6
0
int main(int argc, char** argv){
  NDB_INIT(argv[0]);
  const char* _tabname;
  ndb_opt_set_usage_funcs(short_usage_sub, usage);
  ndb_load_defaults(NULL,load_default_groups,&argc,&argv);
  int ho_error;
#ifndef DBUG_OFF
  opt_debug= "d:t:O,/tmp/ndb_show_tables.trace";
#endif
  if ((ho_error=handle_options(&argc, &argv, my_long_options,
			       ndb_std_get_one_option)))
    return NDBT_ProgramExit(NDBT_WRONGARGS);
  _tabname = argv[0];

  ndb_cluster_connection = new Ndb_cluster_connection(opt_ndb_connectstring,
                                                      opt_ndb_nodeid);
  if (ndb_cluster_connection == NULL)
    fatal("Unable to create cluster connection");

  ndb_cluster_connection->set_name("ndb_show_tables");
  if (ndb_cluster_connection->connect(12,5,1))
    fatal("Unable to connect to management server.");
  if (ndb_cluster_connection->wait_until_ready(30,0) < 0)
    fatal("Cluster nodes not ready in 30 seconds.");

  ndb = new Ndb(ndb_cluster_connection, _dbname);
  if (ndb->init() != 0)
    fatal("init");
  dic = ndb->getDictionary();
  for (int i = 0; _loops == 0 || i < _loops; i++) {
    list(_tabname, (NdbDictionary::Object::Type)_type);
  }
  delete ndb;
  delete ndb_cluster_connection;
  return NDBT_ProgramExit(NDBT_OK);
}
Ejemplo n.º 7
0
int main(int argc, char** argv)

{

	tall_bts_ctx = talloc_named_const(NULL, 1, "softBTS");

	handle_options(argc, argv);
	set_globals();
	bts_core_set_rlimits();
	daemonize();
	/* Initialize */
	srand(time(NULL));
	telnet_init(TELNET_PORT);
	
	
	socket_init(&oml.addr, &oml.socket, BSC_OML_PORT);
	socket_init(&rsl.addr, &rsl.socket, BSC_RSL_PORT);	
	trx_socket_init(TRX_PORT);

	while(1){
		socket_select_main(0);

	}
}
Ejemplo n.º 8
0
Archivo: main.c Proyecto: ralt/soach
int main(int argc, char* argv[])
{
	char* fvalue = NULL;

	if (argc < 2) {
		presentation();
		return EXIT_SUCCESS;
	}

	if (!handle_options(&fvalue, argc, argv)) {
		return EXIT_FAILURE;
	}

	struct SOACH_route_vector* routes =
		malloc(sizeof(struct SOACH_route_vector));
	if (routes == NULL) {
		fprintf(stderr, "%s\n", strerror(errno));
		return EXIT_FAILURE;
	}

	SOACH_route_vector_init(routes, DEFAULT_ROUTES_CAPACITY);

	if (!SOACH_conf_read(fvalue, routes)) {
		return EXIT_FAILURE;
	}

	for (int i = 0; i < routes->size; i++) {
		struct SOACH_route route = *SOACH_route_vector_get(routes, i);
		fprintf(stdout, "Route: %s, Service: %s\n", route.route,
				route.service);
	}

	SOACH_route_vector_free(routes);

	return EXIT_SUCCESS;
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
  char self_name[FN_REFLEN];

  MY_INIT(argv[0]);

#if __WIN__
  if (GetModuleFileName(NULL, self_name, FN_REFLEN) == 0)
#endif
  {
    strncpy(self_name, argv[0], FN_REFLEN);
  }

  if (init_dynamic_string(&ds_args, "", 512, 256) ||
      init_dynamic_string(&conn_args, "", 512, 256))
    die("Out of memory");

  if (load_defaults("my", load_default_groups, &argc, &argv))
    die(NULL);
  defaults_argv= argv; /* Must be freed by 'free_defaults' */

  if (handle_options(&argc, &argv, my_long_options, get_one_option))
    die(NULL);
  if (debug_info_flag)
    my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
  if (debug_check_flag)
    my_end_arg= MY_CHECK_ERROR;

  if (tty_password)
  {
    opt_password= get_tty_password(NullS);
    /* add password to defaults file */
    dynstr_append_os_quoted(&ds_args, "--password="******" ");
  }
  /* add user to defaults file */
  dynstr_append_os_quoted(&ds_args, "--user="******" ");

  /* Find mysql */
  find_tool(mysql_path, IF_WIN("mysql.exe", "mysql"), self_name);

  if (!opt_systables_only)
  {
    /* Find mysqlcheck */
    find_tool(mysqlcheck_path, IF_WIN("mysqlcheck.exe", "mysqlcheck"), self_name);
  }
  else
  {
    if (!opt_silent)
      printf("The --upgrade-system-tables option was used, databases won't be touched.\n");
  }

  /*
    Read the mysql_upgrade_info file to check if mysql_upgrade
    already has been run for this installation of MySQL
  */
  if (!opt_force && upgrade_already_done())
  {
    printf("This installation of MySQL is already upgraded to %s, "
           "use --force if you still need to run mysql_upgrade\n",
           MYSQL_SERVER_VERSION);
    die(NULL);
  }

  if (opt_version_check && check_version_match())
    die("Upgrade failed");

  /*
    Run "mysqlcheck" and "mysql_fix_privilege_tables.sql"
  */
  if ((!opt_systables_only &&
       (run_mysqlcheck_fixnames() || run_mysqlcheck_upgrade())) ||
      run_sql_fix_privilege_tables())
  {
    /*
      The upgrade failed to complete in some way or another,
      significant error message should have been printed to the screen
    */
    die("Upgrade failed" );
  }
  verbose("OK");

  /* Create a file indicating upgrade has been performed */
  create_mysql_upgrade_info_file();

  free_used_memory();
  my_end(my_end_arg);
  exit(0);
}
Ejemplo n.º 10
0
int
main(int argc, char *argv[])
{
  Font font;
  ttfinfo *ti;


#ifdef MIKTEX
  miktex_initialize();
#endif

  init_font_structure(&font);

  TeX_search_init(argv[0], "ttf2tfm", "TTF2TFM");

  if (argc == 1)
  {
    fputs("ttf2tfm: Need at least one file argument.\n", stderr);
    fputs("Try `ttf2tfm --help' for more information.\n", stderr);
    exit(1);
  }
  if (argc == 2)
  {
    if (strcmp(argv[1], "--help") == 0)
      usage();
    else if (strcmp(argv[1], "--version") == 0)
      version();
  }

  handle_options(argc, argv, &font);

  if (font.sfdname)
  {
    while (get_sfd(&font, True))
    {
      char *temp, *ttemp;
      int i, start, end, len;


      get_tfm_fullname(&font);

      /*
       *   Extract base name of sfd file.
       */

      temp = newstring(font.sfdname);
      len = strlen(temp);

      start = 0;
      for (i = len - 1; i >= 0; i--)
        if (temp[i] == '/' || temp[i] == ':' || temp[i] == '\\')
        {
          start = i + 1;
          break;
        }

      end = len;
      for (i = len - 1; i >= 0; i--)
        if (temp[i] == '.')
        {
          end = i;
          break;
        }
      temp[end] = '\0';

      ttemp = (char *)mymalloc(strlen(temp + start) + 4 + 1);
      sprintf(ttemp, "CJK-%s", temp + start);
      font.codingscheme = ttemp;
      free(temp);

      readttf(&font, quiet, True);
      if (font.replacements)
        warning("Replacement glyphs will be ignored.");

      /* second try to get an xheight value */
      if (font.xheight == 0)
      {
        if (NULL != (ti = findadobe("x", font.charlist)))
          font.xheight = ti->ury;
        else if (font.pid == 3 && font.eid == 1 &&
                 NULL != (ti = findadobe(".c0x78", font.charlist)))
          font.xheight = ti->ury;
        else
          font.xheight = 400;
      }

      if (NULL != (ti = findadobe("space", font.charlist)))
        font.fontspace = ti->width;
      else if (NULL != (ti = findadobe(".c0x20", font.charlist)))
        font.fontspace = ti->width;
      else
        font.fontspace = transform(500, 0, font.efactor, font.slant);

      if (font.ligname)
        get_sfd(&font, False); /* read sfd files for ligatures */

      if (buildtfm(&font))
      {
        writetfm(&font);
        if (font.write_enc)
          writeenc(&font);
        if (font.vplout)
          add_subfont_list(&font);
      }
    }

    close_sfd();

    if (font.vplout)
    {
      writeovp(&font);
      fclose(font.vplout);
      release_subfont_list(&font);
    }
  }
  else
  {
    get_tfm_fullname(&font);

    readttf(&font, quiet, False);
    replace_glyphs(&font);

    /* second try to get an xheight value */
    if (font.xheight == 0)
    {
      if (NULL != (ti = findadobe("x", font.charlist)))
        font.xheight = ti->ury;
      else if (font.pid == 3 && font.eid == 1 &&
               NULL != (ti = findadobe(".c0x78", font.charlist)))
        font.xheight = ti->ury;
      else
        font.xheight = 400;
    }

    if (NULL != (ti = findadobe("space", font.charlist)))
      font.fontspace = ti->width;
    else if (NULL != (ti = findadobe(".c0x20", font.charlist)))
      font.fontspace = ti->width;
    else
      font.fontspace = transform(500, 0, font.efactor, font.slant);

    handlereencoding(&font);

    buildtfm(&font);
    writetfm(&font);
  }

  if (makevpl)
  {
    assignchars(&font);
    if (makevpl > 1)
      upmap(&font);
    writevpl(&font, makevpl, forceoctal);
    fclose(font.vplout);
  }

  consttfonts(&font);

  exit(0);      /* for safety reasons */
  return 0;     /* never reached */
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
	int rc;

	struct cmdline_cfg _ccfg;
	struct cmdline_cfg *ccfg = &_ccfg;
	memset(ccfg, '\0', sizeof(*ccfg));
	ccfg->config_file = "./gtphub.conf";
	ccfg->restart_counter_file = "./gtphub_restart_count";

	struct gtphub_cfg _cfg;
	struct gtphub_cfg *cfg = &_cfg;
	memset(cfg, '\0', sizeof(*cfg));

	struct gtphub _hub;
	struct gtphub *hub = &_hub;

	osmo_gtphub_ctx = talloc_named_const(NULL, 0, "osmo_gtphub");
	msgb_talloc_ctx_init(osmo_gtphub_ctx, 0);

	signal(SIGINT, &signal_handler);
	signal(SIGABRT, &signal_handler);
	signal(SIGUSR1, &signal_handler);
	signal(SIGUSR2, &signal_handler);
	osmo_init_ignore_signals();

	osmo_init_logging(&gtphub_log_info);

	vty_info.copyright = gtphub_copyright;
	vty_init(&vty_info);
	logging_vty_add_cmds(&gtphub_log_info);
        gtphub_vty_init(hub, cfg);

	rate_ctr_init(osmo_gtphub_ctx);

	handle_options(ccfg, argc, argv);

	rc = gtphub_cfg_read(cfg, ccfg->config_file);
	if (rc < 0) {
		LOGP(DGTPHUB, LOGL_FATAL, "Cannot parse config file '%s'\n",
		     ccfg->config_file);
		exit(2);
	}

	/* start telnet after reading config for vty_get_bind_addr() */
	rc = telnet_init_dynif(osmo_gtphub_ctx, 0, vty_get_bind_addr(),
			       OSMO_VTY_PORT_GTPHUB);
	if (rc < 0)
		exit(1);

	if (gtphub_start(hub, cfg,
			 next_restart_count(ccfg->restart_counter_file))
	    != 0)
		return -1;

	log_cfg(cfg);

	if (ccfg->daemonize) {
		rc = osmo_daemonize();
		if (rc < 0) {
			LOGP(DGTPHUB, LOGL_FATAL, "Error during daemonize");
			exit(1);
		}
	}

	while (1) {
		rc = osmo_select_main(0);
		if (rc < 0)
			exit(3);
	}

	/* not reached */
	exit(0);
}
Ejemplo n.º 12
0
Archivo: git.c Proyecto: SRabbelier/git
int main(int argc, const char **argv)
{
	const char *cmd;

	startup_info = &git_startup_info;

	cmd = git_extract_argv0_path(argv[0]);
	if (!cmd)
		cmd = "git-help";

	/*
	 * "git-xxxx" is the same as "git xxxx", but we obviously:
	 *
	 *  - cannot take flags in between the "git" and the "xxxx".
	 *  - cannot execute it externally (since it would just do
	 *    the same thing over again)
	 *
	 * So we just directly call the internal command handler, and
	 * die if that one cannot handle it.
	 */
	if (!prefixcmp(cmd, "git-")) {
		cmd += 4;
		argv[0] = cmd;
		handle_internal_command(argc, argv);
		die("cannot handle %s internally", cmd);
	}

	/* Look for flags.. */
	argv++;
	argc--;
	handle_options(&argv, &argc, NULL);
	if (argc > 0) {
		if (!prefixcmp(argv[0], "--"))
			argv[0] += 2;
	} else {
		/* The user didn't specify a command; give them help */
		commit_pager_choice();
		printf("usage: %s\n\n", git_usage_string);
		list_common_cmds_help();
		printf("\n%s\n", git_more_info_string);
		exit(1);
	}
	cmd = argv[0];

	/*
	 * We use PATH to find git commands, but we prepend some higher
	 * precedence paths: the "--exec-path" option, the GIT_EXEC_PATH
	 * environment, and the $(gitexecdir) from the Makefile at build
	 * time.
	 */
	setup_path();

	while (1) {
		static int done_help = 0;
		static int was_alias = 0;
		was_alias = run_argv(&argc, &argv);
		if (errno != ENOENT)
			break;
		if (was_alias) {
			fprintf(stderr, "Expansion of alias '%s' failed; "
				"'%s' is not a git command\n",
				cmd, argv[0]);
			exit(1);
		}
		if (!done_help) {
			cmd = argv[0] = help_unknown_cmd(cmd);
			done_help = 1;
		} else
			break;
	}

	fprintf(stderr, "Failed to run command '%s': %s\n",
		cmd, strerror(errno));

	return 1;
}
Ejemplo n.º 13
0
int main(int argc, const char **argv)
{
	const char *cmd;

	cmd = perf_extract_argv0_path(argv[0]);
	if (!cmd)
		cmd = "perf-help";
	
	debugfs_mount(NULL);
	if (!prefixcmp(cmd, "perf-")) {
		cmd += 5;
		argv[0] = cmd;
		handle_internal_command(argc, argv);
		die("cannot handle %s internally", cmd);
	}

	
	argv++;
	argc--;
	handle_options(&argv, &argc, NULL);
	commit_pager_choice();
	set_buildid_dir();

	if (argc > 0) {
		if (!prefixcmp(argv[0], "--"))
			argv[0] += 2;
	} else {
		
		printf("\n usage: %s\n\n", perf_usage_string);
		list_common_cmds_help();
		printf("\n %s\n\n", perf_more_info_string);
		exit(1);
	}
	cmd = argv[0];

	setup_path();
	pthread__block_sigwinch();

	while (1) {
		static int done_help;
		static int was_alias;

		was_alias = run_argv(&argc, &argv);
		if (errno != ENOENT)
			break;

		if (was_alias) {
			fprintf(stderr, "Expansion of alias '%s' failed; "
				"'%s' is not a perf-command\n",
				cmd, argv[0]);
			exit(1);
		}
		if (!done_help) {
			cmd = argv[0] = help_unknown_cmd(cmd);
			done_help = 1;
		} else
			break;
	}

	fprintf(stderr, "Failed to run command '%s': %s\n",
		cmd, strerror(errno));

	return 1;
}
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
  char self_name[FN_REFLEN];

  MY_INIT(argv[0]);

#if __WIN__
  if (GetModuleFileName(NULL, self_name, FN_REFLEN) == 0)
#endif
  {
    strncpy(self_name, argv[0], FN_REFLEN);
  }

  if (init_dynamic_string(&ds_args, "", 512, 256) ||
      init_dynamic_string(&conn_args, "", 512, 256))
    die("Out of memory");

  if (load_defaults("my", load_default_groups, &argc, &argv))
    die(NULL);
  defaults_argv= argv; /* Must be freed by 'free_defaults' */

  if (handle_options(&argc, &argv, my_long_options, get_one_option))
    die(NULL);
  if (debug_info_flag)
    my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
  if (debug_check_flag)
    my_end_arg= MY_CHECK_ERROR;

  if (tty_password)
  {
    opt_password= get_tty_password(NullS);
    /* add password to defaults file */
    dynstr_append_os_quoted(&ds_args, "--password="******" ");
  }
  /* add user to defaults file */
  dynstr_append_os_quoted(&ds_args, "--user="******" ");

  /* Find mysql */
  find_tool(mysql_path, IF_WIN("mysql.exe", "mysql"), self_name);

  /* Find mysqlcheck */
  find_tool(mysqlcheck_path, IF_WIN("mysqlcheck.exe", "mysqlcheck"), self_name);

  if (opt_systables_only && !opt_silent)
    printf("The --upgrade-system-tables option was used, user tables won't be touched.\n");


  /*
    Read the mysql_upgrade_info file to check if mysql_upgrade
    already has been run for this installation of MySQL
  */
  if (!opt_force && upgrade_already_done())
  {
    printf("This installation of MySQL is already upgraded to %s, "
           "use --force if you still need to run mysql_upgrade\n",
           MYSQL_SERVER_VERSION);
    goto end;
  }

  if (opt_version_check && check_version_match())
    die("Upgrade failed");

  upgrade_from_mysql= is_mysql();

  /*
    Run "mysqlcheck" and "mysql_fix_privilege_tables.sql"
  */
  if (run_mysqlcheck_upgrade(TRUE) ||
      run_mysqlcheck_views() ||
      run_sql_fix_privilege_tables() ||
      run_mysqlcheck_fixnames() ||
      run_mysqlcheck_upgrade(FALSE))
    die("Upgrade failed" );

  verbose("Phase %d/%d: Running 'FLUSH PRIVILEGES'", ++phase, phases_total);
  if (run_query("FLUSH PRIVILEGES", NULL, TRUE))
    die("Upgrade failed" );

  verbose("OK");

  /* Create a file indicating upgrade has been performed */
  create_mysql_upgrade_info_file();

  DBUG_ASSERT(phase == phases_total);

end:
  free_used_memory();
  my_end(my_end_arg);
  exit(0);
}
Ejemplo n.º 15
0
Archivo: git.c Proyecto: benpeart/git
int cmd_main(int argc, const char **argv)
{
	const char *cmd;
	int done_help = 0;

	cmd = argv[0];
	if (!cmd)
		cmd = "git-help";
	else {
		const char *slash = find_last_dir_sep(cmd);
		if (slash)
			cmd = slash + 1;
	}

	/*
	 * wait_for_pager_atexit will close stdout/stderr so it needs to be
	 * registered first so that it will execute last and not close the
	 * handles until all other atexit handlers have finished
	 */
	atexit(wait_for_pager_atexit);
	trace_command_performance(argv);
	atexit(post_command_hook_atexit);

	/*
	 * "git-xxxx" is the same as "git xxxx", but we obviously:
	 *
	 *  - cannot take flags in between the "git" and the "xxxx".
	 *  - cannot execute it externally (since it would just do
	 *    the same thing over again)
	 *
	 * So we just directly call the builtin handler, and die if
	 * that one cannot handle it.
	 */
	if (skip_prefix(cmd, "git-", &cmd)) {
		argv[0] = cmd;
		handle_builtin(argc, argv);
		die("cannot handle %s as a builtin", cmd);
	}

	/* Look for flags.. */
	argv++;
	argc--;
	handle_options(&argv, &argc, NULL);
	if (argc > 0) {
		/* translate --help and --version into commands */
		skip_prefix(argv[0], "--", &argv[0]);
	} else {
		/* The user didn't specify a command; give them help */
		commit_pager_choice();
		if (run_pre_command_hook(argv))
			die("pre-command hook aborted command");
		printf("usage: %s\n\n", git_usage_string);
		list_common_cmds_help();
		printf("\n%s\n", _(git_more_info_string));
		exit_code = 1;
		run_post_command_hook();
		exit(exit_code);
	}
	cmd = argv[0];

	/*
	 * We use PATH to find git commands, but we prepend some higher
	 * precedence paths: the "--exec-path" option, the GIT_EXEC_PATH
	 * environment, and the $(gitexecdir) from the Makefile at build
	 * time.
	 */
	setup_path();

	while (1) {
		int was_alias = run_argv(&argc, &argv);
		if (errno != ENOENT)
			break;
		if (was_alias) {
			fprintf(stderr, _("expansion of alias '%s' failed; "
					  "'%s' is not a git command\n"),
				cmd, argv[0]);
			exit(1);
		}
		if (!done_help) {
			cmd = argv[0] = help_unknown_cmd(cmd);
			done_help = 1;
		} else
			break;
	}

	fprintf(stderr, _("failed to run command '%s': %s\n"),
		cmd, strerror(errno));

	return 1;
}
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
	struct gsm_network dummy_network;
	int rc;

	tall_bsc_ctx = talloc_named_const(NULL, 0, "osmo_sgsn");
	tall_msgb_ctx = talloc_named_const(tall_bsc_ctx, 0, "msgb");

	signal(SIGINT, &signal_handler);
	signal(SIGABRT, &signal_handler);
	signal(SIGUSR1, &signal_handler);
	signal(SIGUSR2, &signal_handler);

	osmo_init_ignore_signals();
	osmo_init_logging(&gprs_log_info);

	vty_info.copyright = openbsc_copyright;
	vty_init(&vty_info);
	logging_vty_add_cmds(&gprs_log_info);
        sgsn_vty_init();

	handle_options(argc, argv);

	rate_ctr_init(tall_bsc_ctx);
	rc = telnet_init(tall_bsc_ctx, &dummy_network, 4245);
	if (rc < 0)
		exit(1);

	gprs_ns_set_log_ss(DNS);
	bssgp_set_log_ss(DBSSGP);

	sgsn_nsi = gprs_ns_instantiate(&sgsn_ns_cb, tall_bsc_ctx);
	if (!sgsn_nsi) {
		LOGP(DGPRS, LOGL_ERROR, "Unable to instantiate NS\n");
		exit(1);
	}
	bssgp_nsi = sgsn_inst.cfg.nsi = sgsn_nsi;

	gprs_llc_init("/usr/local/lib/osmocom/crypt/");

	gprs_ns_vty_init(bssgp_nsi);
	bssgp_vty_init();
	gprs_llc_vty_init();
	gprs_sndcp_vty_init();
	/* FIXME: register signal handler for SS_L_NS */

	rc = sgsn_parse_config(sgsn_inst.config_file, &sgsn_inst.cfg);
	if (rc < 0) {
		LOGP(DGPRS, LOGL_FATAL, "Cannot parse config file\n");
		exit(2);
	}

	rc = sgsn_gtp_init(&sgsn_inst);
	if (rc) {
		LOGP(DGPRS, LOGL_FATAL, "Cannot bind/listen on GTP socket\n");
		exit(2);
	}

	rc = gprs_ns_nsip_listen(sgsn_nsi);
	if (rc < 0) {
		LOGP(DGPRS, LOGL_FATAL, "Cannot bind/listen on NSIP socket\n");
		exit(2);
	}

	rc = gprs_ns_frgre_listen(sgsn_nsi);
	if (rc < 0) {
		LOGP(DGPRS, LOGL_FATAL, "Cannot bind/listen GRE "
			"socket. Do you have CAP_NET_RAW?\n");
		exit(2);
	}

	if (daemonize) {
		rc = osmo_daemonize();
		if (rc < 0) {
			perror("Error during daemonize");
			exit(1);
		}
	}

	while (1) {
		rc = osmo_select_main(0);
		if (rc < 0)
			exit(3);
	}

	/* not reached */
	exit(0);
}
Ejemplo n.º 17
0
int NDBT_TestSuite::execute(int argc, const char** argv){
  int res = NDBT_FAILED;
  /* Arguments:
       Run only a subset of tests
       -n testname Which test to run
       Recommendations to test functions:
       --records Number of records to use(default: 10000)
       --loops Number of loops to execute in the test(default: 100)

       Other parameters should:
       * be calculated from the above two parameters 
       * be divided into different test cases, ex. one testcase runs
         with FragmentType = Single and another perfoms the same 
         test with FragmentType = Large
       * let the test case iterate over all/subset of appropriate parameters
         ex. iterate over FragmentType = Single to FragmentType = AllLarge

       Remeber that the intention is that it should be _easy_ to run 
       a complete test suite without any greater knowledge of what 
       should be tested ie. keep arguments at a minimum
  */

  char **_argv= (char **)argv;

  if (!my_progname)
    my_progname= _argv[0];

  ndb_opt_set_usage_funcs(short_usage_sub, usage);

  ndb_load_defaults(NULL, load_default_groups,&argc,&_argv);
  // Save pointer to memory allocated by 'ndb_load_defaults'
  char** defaults_argv= _argv;

  int ho_error;
#ifndef DBUG_OFF
  opt_debug= "d:t:i:F:L";
#endif
  if ((ho_error=handle_options(&argc, &_argv, my_long_options,
			       ndb_std_get_one_option)))
  {
    usage();
    ndb_free_defaults(defaults_argv);
    return NDBT_ProgramExit(NDBT_WRONGARGS);
  }

  if (opt_verbose)
    setOutputLevel(2); // Show g_info
  else 
    setOutputLevel(0); // Show only g_err ?

  records = opt_records;
  loops = opt_loops;
  timer = opt_timer;
  if (opt_nologging)
    setLogging(false);
  temporaryTables = opt_temporary;
  m_noddl = opt_noddl;
  m_forceShort = opt_forceShort;

  if (opt_seed == 0)
  {
    opt_seed = (unsigned)NdbTick_CurrentMillisecond();
  }
  ndbout_c("random seed: %u", opt_seed);
  srand(opt_seed);
  srandom(opt_seed);

  global_flag_skip_invalidate_cache = 1;

  int num_tables= argc;
  if (argc == 0)
    num_tables = NDBT_Tables::getNumTables();

  for(int i = 0; i<num_tables; i++)
  {
    if (argc == 0)
      m_tables_in_test.push_back(NDBT_Tables::getTable(i)->getName());
    else
      m_tables_in_test.push_back(_argv[i]);
  }

  if (m_createTable)
  {
    for (unsigned t = 0; t < tests.size(); t++)
    {
      const char* createFuncName= NULL;
      NDBT_TESTFUNC* createFunc= NULL;
      const char* dropFuncName= NULL;
      NDBT_TESTFUNC* dropFunc= NULL;

      if (!m_noddl)
      {
        createFuncName= m_createAll ? "runCreateTable" : "runCreateTable";
        createFunc=   m_createAll ? &runCreateTables : &runCreateTable;
        dropFuncName= m_createAll ? "runDropTables" : "runDropTable";
        dropFunc= m_createAll ? &runDropTables : &runDropTable;
      }
      else
      {
        /* No DDL allowed, so we substitute 'do nothing' variants
         * of the create + drop table test procs
         */
        createFuncName= "runCheckTableExists";
        createFunc= &runCheckTableExists;
        dropFuncName= "runEmptyDropTable";
        dropFunc= &runEmptyDropTable;
      }

      NDBT_TestCaseImpl1* pt= (NDBT_TestCaseImpl1*)tests[t];
      NDBT_Initializer* pti =
        new NDBT_Initializer(pt,
                             createFuncName,
                             *createFunc);
      pt->addInitializer(pti, true);
      NDBT_Finalizer* ptf =
        new NDBT_Finalizer(pt,
                           dropFuncName,
                           *dropFunc);
      pt->addFinalizer(ptf);
    }

    for (unsigned t = 0; t < explicitTests.size(); t++)
    {
      const char* createFuncName= NULL;
      NDBT_TESTFUNC* createFunc= NULL;
      const char* dropFuncName= NULL;
      NDBT_TESTFUNC* dropFunc= NULL;

      if (!m_noddl)
      {
        createFuncName= m_createAll ? "runCreateTable" : "runCreateTable";
        createFunc=   m_createAll ? &runCreateTables : &runCreateTable;
        dropFuncName= m_createAll ? "runDropTables" : "runDropTable";
        dropFunc= m_createAll ? &runDropTables : &runDropTable;
      }
      else
      {
        /* No DDL allowed, so we substitute 'do nothing' variants
         * of the create + drop table test procs
         */
        createFuncName= "runCheckTableExists";
        createFunc= &runCheckTableExists;
        dropFuncName= "runEmptyDropTable";
        dropFunc= &runEmptyDropTable;
      }

      NDBT_TestCaseImpl1* pt= (NDBT_TestCaseImpl1*)explicitTests[t];
      NDBT_Initializer* pti =
        new NDBT_Initializer(pt,
                             createFuncName,
                             *createFunc);
      pt->addInitializer(pti, true);
      NDBT_Finalizer* ptf =
        new NDBT_Finalizer(pt,
                           dropFuncName,
                           *dropFunc);
      pt->addFinalizer(ptf);
    }
  }

  if (opt_print == true){
    printExecutionTree();
    ndb_free_defaults(defaults_argv);
    return 0;
  }

  if (opt_print_html == true){
    printExecutionTreeHTML();
    ndb_free_defaults(defaults_argv);
    return 0;
  }

  if (opt_print_cases == true){
    printCases();
    ndb_free_defaults(defaults_argv);
    return 0;
  }

  Ndb_cluster_connection con(opt_ndb_connectstring, opt_ndb_nodeid);
  if(m_connect_cluster && con.connect(12, 5, 1))
  {
    ndb_free_defaults(defaults_argv);
    return NDBT_ProgramExit(NDBT_FAILED);
  }

  if(argc == 0){
    // No table specified
    res = executeAll(con, opt_testname);
  } else {
    testSuiteTimer.doStart(); 
    for(int i = 0; i<argc; i++){
      executeOne(con, _argv[i], opt_testname);
    }
    testSuiteTimer.doStop();
    res = report(opt_testname);
  }

  ndb_free_defaults(defaults_argv);
  return NDBT_ProgramExit(res);
}
Ejemplo n.º 18
0
static void add_offset(int argc, char *argv[])
{
  char *input_filename;
  int next_arg;
  int force;
  char cmd[1024];
  char tmp_filename[1024];
  carmen_FILE *fp_in, *fp_out;
  carmen_global_offset_t offset;
  int system_err;
  int num_args;
  int response;

  next_arg = handle_options(argc, argv, &force);
  next_arg++;

  num_args = argc - next_arg;

  if(num_args != 4) {
    carmen_warn("\nError: wrong number of parameters.\n");    
    carmen_warn("\nUsage: %s <mapfilename> <x> <y> <theta>\n",
		argv[0]);
    carmen_warn("       <theta> should be given in degrees.\n");
  }
     
  input_filename = check_mapfile(argv[next_arg]);
  next_arg++;

  if(!carmen_map_file(input_filename))
    carmen_die("Error: %s does not appear to be a valid carmen map file;\n" 
	       "if it is gzipped, make sure it has a \".gz\" extension.\n",
	       input_filename);

  if(carmen_map_chunk_exists(input_filename, CARMEN_MAP_GLOBAL_OFFSET_CHUNK)) {
    carmen_warn("Offset chunk exists already. Replace? [y/n] ");
    response = getchar();
    if (tolower(response) != 'y')
      exit(0);
    carmen_warn("Replacing...\n");
  }

  offset.x = atof(argv[next_arg]);
  offset.y = atof(argv[next_arg+1]);
  offset.theta = carmen_degrees_to_radians(atof(argv[next_arg+2]));

  fprintf(stderr, "Set (%s %s %s) to (%.2f m, %.2f m, %.2f rad)\n", 
	  argv[next_arg], argv[next_arg+1], argv[next_arg+2], 
	  offset.x, offset.y, offset.theta);
  
  fp_in = carmen_fopen(input_filename, "r");
  if(fp_in == NULL)
    carmen_die_syserror("Error: file %s could not be opened for reading", 
			input_filename);
  
  strcpy(tmp_filename, "/tmp/newmapXXXXXX");
  system_err = mkstemp(tmp_filename);
  if (system_err == -1) 
    carmen_die_syserror("I need to create a temporary file in /tmp, but I "
			"can't for the\n following reason\n");
  
  fp_out = carmen_fopen(tmp_filename, "w");
  if(fp_out == NULL)
    carmen_die_syserror("Error: file could not be opened for writing");

  if(carmen_map_strip(fp_in, fp_out, CARMEN_MAP_GLOBAL_OFFSET_CHUNK) < 0)
     carmen_die("Error: could not strip global offset from map file.\n");
  if(carmen_map_write_global_offset_chunk(fp_out, &offset) < 0)
    carmen_die("Error: could not write offset chunk.\n");

  carmen_fclose(fp_in);
  carmen_fclose(fp_out);

  sprintf(cmd, "mv -f %s %s", tmp_filename, input_filename);
  system_err = system(cmd);
  if (system_err != 0) 
    carmen_die("I created a temporary file contained the map with the new "
	       "place name\nat %s. I tried to copy the new file onto your "
	       "old file, but the copy\nfailed for the following reason: %s\n"
	       "\n"
	       "You will have to copy the new file over yourself.\n", 
	       tmp_filename, strerror(errno));
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
	struct gprs_rlcmac_bts *bts;
	int rc;

	tall_pcu_ctx = talloc_named_const(NULL, 1, "Osmo-PCU context");
	if (!tall_pcu_ctx)
		return -ENOMEM;
	bv_tall_ctx = tall_pcu_ctx;

	bts = gprs_rlcmac_bts = talloc_zero(tall_pcu_ctx,
						struct gprs_rlcmac_bts);
	if (!gprs_rlcmac_bts)
		return -ENOMEM;
	bts->fc_interval = 1;
	bts->initial_cs_dl = bts->initial_cs_ul = 1;
	bts->cs1 = 1;
	bts->t3142 = 20;
	bts->t3169 = 5;
	bts->t3191 = 5;
	bts->t3193_msec = 100;
	bts->t3195 = 5;
	bts->n3101 = 10;
	bts->n3103 = 4;
	bts->n3105 = 8;
	bts->alpha = 0; /* a = 0.0 */

	msgb_set_talloc_ctx(tall_pcu_ctx);

	osmo_init_logging(&gprs_log_info);

	vty_init(&pcu_vty_info);
	pcu_vty_init(&gprs_log_info);

	handle_options(argc, argv);
	if ((!!spoof_mcc) + (!!spoof_mnc) == 1) {
		fprintf(stderr, "--mcc and --mnc must be specified "
			"together.\n");
		exit(0);
	}

	rc = vty_read_config_file(config_file, NULL);
	if (rc < 0 && config_given) {
		fprintf(stderr, "Failed to parse the config file: '%s'\n",
			config_file);
		exit(1);
	}
	if (rc < 0)
		fprintf(stderr, "No config file: '%s' Using default config.\n",
			config_file);

	rc = telnet_init(tall_pcu_ctx, NULL, 4240);
	if (rc < 0) {
		fprintf(stderr, "Error initializing telnet\n");
		exit(1);
	}

	if (!bts->alloc_algorithm)
		bts->alloc_algorithm = alloc_algorithm_b;

	rc = pcu_l1if_open();

	if (rc < 0)
		return rc;

	signal(SIGINT, sighandler);
	signal(SIGHUP, sighandler);
	signal(SIGTERM, sighandler);
	signal(SIGPIPE, sighandler);
	signal(SIGABRT, sighandler);
	signal(SIGUSR1, sighandler);
	signal(SIGUSR2, sighandler);

	while (!quit) {
		osmo_gsm_timers_check();
		osmo_gsm_timers_prepare();
		osmo_gsm_timers_update();

		osmo_select_main(0);
#ifdef DEBUG_DIAGRAM
		gettimeofday(&diagram_time, NULL);
#endif
	}

	telnet_exit();

	pcu_l1if_close();

	talloc_free(gprs_rlcmac_bts);

	talloc_report_full(tall_pcu_ctx, stderr);
	talloc_free(tall_pcu_ctx);

	return 0;
}
Ejemplo n.º 20
0
static void add_place(int argc, char *argv[])
{
  char *input_filename;
  int next_arg;
  int force;
  char cmd[1024];
  char tmp_filename[1024];
  carmen_FILE *fp_in, *fp_out;
  carmen_map_placelist_t place_list;
  carmen_place_p places;
  int system_err;
  int num_args;

  next_arg = handle_options(argc, argv, &force);
  next_arg++;

  num_args = argc - next_arg;

  if(num_args != 4 && num_args != 5 && num_args != 8) {
    carmen_warn("\nError: wrong number of parameters.\n");    
    carmen_warn("\nUsage: %s <mapfilename> <placename> <place params>\n",
		argv[0]);
    carmen_warn("       2, 3, or 6 place parameters can be given.\n");
  }
     
  input_filename = check_mapfile(argv[next_arg]);
  next_arg++;

  if(!carmen_map_file(input_filename))
    carmen_die("Error: %s does not appear to be a valid carmen map file;\n" 
	       "if it is gzipped, make sure it has a \".gz\" extension.\n",
	       input_filename);

  if(!carmen_map_chunk_exists(input_filename, CARMEN_MAP_PLACES_CHUNK)) {
    place_list.num_places = 1;
    place_list.places = (carmen_place_p)calloc(1, sizeof(carmen_place_t)); 
    carmen_test_alloc(place_list.places);
  } else {
    carmen_map_read_places_chunk(input_filename, &place_list);
    place_list.num_places++;
    place_list.places = (carmen_place_p)realloc
      (place_list.places, sizeof(carmen_place_t) * place_list.num_places); 
    /* check_alloc checked */
  }
  carmen_test_alloc(place_list.places);

  places = place_list.places;

  if(num_args == 4) {
    strcpy(places[place_list.num_places - 1].name, argv[next_arg]);
    places[place_list.num_places - 1].type = CARMEN_NAMED_POSITION_TYPE;
    places[place_list.num_places - 1].x = atof(argv[next_arg+1]);
    places[place_list.num_places - 1].y = atof(argv[next_arg+2]);
  }
  else if(num_args == 5) {
    strcpy(places[place_list.num_places - 1].name, argv[next_arg]);
    places[place_list.num_places - 1].type = CARMEN_NAMED_POSE_TYPE;
    places[place_list.num_places - 1].x = atof(argv[next_arg+1]);
    places[place_list.num_places - 1].y = atof(argv[next_arg+2]);
    places[place_list.num_places - 1].theta = 
      carmen_degrees_to_radians(atof(argv[next_arg+3]));
    fprintf(stderr, "Set (%s %s %s) to (%f.2m, %f.2m, %f.2 rad)\n", argv[4],
	    argv[5], argv[6], places[place_list.num_places - 1].x, 
	    places[place_list.num_places - 1].y,
	    places[place_list.num_places - 1].theta);
  }
  else {
    strcpy(places[place_list.num_places - 1].name, argv[next_arg]);
    places[place_list.num_places - 1].type = CARMEN_LOCALIZATION_INIT_TYPE;
    places[place_list.num_places - 1].x = atof(argv[next_arg+1]);
    places[place_list.num_places - 1].y = atof(argv[next_arg+2]);
    places[place_list.num_places - 1].theta = 
      carmen_degrees_to_radians(atof(argv[next_arg+3]));
    places[place_list.num_places - 1].x_std = atof(argv[next_arg+4]);
    places[place_list.num_places - 1].y_std = atof(argv[next_arg+5]);
    places[place_list.num_places - 1].theta_std = 
      carmen_degrees_to_radians(atof(argv[next_arg+6]));

    fprintf(stderr, "Set (%s %s %s %s %s %s) to:\n(%f.2m +/- %f.2m, %f.2m "
	    "+/- %f.2m, %f.2 +/- %f.2 rad)\n", 
	    argv[next_arg+1], argv[next_arg+2], argv[next_arg+3], 
	    argv[next_arg+4], argv[next_arg+5], argv[next_arg+6], 
	    places[place_list.num_places - 1].x, 
	    places[place_list.num_places - 1].x_std, 
	    places[place_list.num_places - 1].y, 
	    places[place_list.num_places - 1].y_std,
	    places[place_list.num_places - 1].theta, 
	    places[place_list.num_places - 1].theta_std);    
  }
  
  fp_in = carmen_fopen(input_filename, "r");
  if(fp_in == NULL)
    carmen_die_syserror("Error: file %s could not be opened for reading", 
			input_filename);
  
  strcpy(tmp_filename, "/tmp/newmapXXXXXX");
  system_err = mkstemp(tmp_filename);
  if (system_err == -1) 
    carmen_die_syserror("I need to create a temporary file in /tmp, but I "
			"can't for the\n following reason\n");
  
  fp_out = carmen_fopen(tmp_filename, "w");
  if(fp_out == NULL)
    carmen_die_syserror("Error: file could not be opened for writing");

  if(carmen_map_strip(fp_in, fp_out, CARMEN_MAP_PLACES_CHUNK) < 0)
    carmen_die("Error: could not strip places from map file.\n");
  if(carmen_map_write_places_chunk(fp_out, place_list.places, 
				   place_list.num_places) < 0)
    carmen_die("Error: could not write places chunk.\n");

  carmen_fclose(fp_in);
  carmen_fclose(fp_out);

  sprintf(cmd, "mv -f %s %s", tmp_filename, input_filename);
  system_err = system(cmd);
  if (system_err != 0) 
    carmen_die("I created a temporary file contained the map with the new "
	       "place name\nat %s. I tried to copy the new file onto your "
	       "old file, but the copy\nfailed for the following reason: %s\n"
	       "\n"
	       "You will have to copy the new file over yourself.\n", 
	       tmp_filename, strerror(errno));
}
Ejemplo n.º 21
0
static void minimize(int argc, char *argv[])
{
  char *input_filename, *output_filename;
  int next_arg;
  carmen_FILE *in_fp, *out_fp;

  int ret_val;
  carmen_map_t map;
  int x_offset, y_offset;
  carmen_offlimits_list_t offlimits_list;
  carmen_map_placelist_t places;
  int force;
  int previous_num_places;

  next_arg = handle_options(argc, argv, &force);
  next_arg++;

  if(argc - next_arg != 2) {
    carmen_warn("\nError: wrong number of parameters.\n");    
    carmen_die("\nUsage: %s minimize <in map filename> <out map filename>\n\n",
	       argv[0]);
  }

  input_filename = check_mapfile(argv[next_arg]);
  output_filename = check_output(argv[next_arg+1], force);

  /*
   * Read the gridmap, places and offlimits chunks and minimize them
   */ 

  if (carmen_map_read_gridmap_chunk(input_filename, &map) < 0) {
    carmen_die_syserror("Couldn't read GRIDMAP_CHUNK from %s", input_filename);
  }

  carmen_warn("Map size was %d x %d, ",map.config.x_size, map.config.y_size);

  carmen_minimize_gridmap(&map, &x_offset, &y_offset);

  carmen_warn("is now %d x %d (offset %d, %d)\n", map.config.x_size, 
	      map.config.y_size, x_offset, y_offset);


  ret_val = carmen_map_chunk_exists(input_filename, 
				    CARMEN_MAP_OFFLIMITS_CHUNK);
  if (ret_val > 0) {
    ret_val = carmen_map_read_offlimits_chunk
      (input_filename, &(offlimits_list.offlimits), 
       &(offlimits_list.list_length));
    if (ret_val < 0)
      carmen_die_syserror("Couldn't read OFFLIMITS_CHUNK in %s",
			  input_filename);

    carmen_minimize_offlimits(&offlimits_list, x_offset*map.config.resolution, 
			      y_offset*map.config.resolution);
  } else
    offlimits_list.list_length = 0;

  ret_val = carmen_map_chunk_exists(input_filename, CARMEN_MAP_PLACES_CHUNK);
  if (ret_val > 0) {
    ret_val = carmen_map_read_places_chunk(input_filename, &places);
    if (ret_val < 0)
      carmen_die_syserror("Couldn't read PLACES_CHUNK in %s", input_filename);

    previous_num_places = places.num_places;
    carmen_minimize_places(&places, x_offset*map.config.resolution, 
			   y_offset*map.config.resolution, 
			   map.config.x_size*map.config.resolution,
			   map.config.y_size*map.config.resolution);
    if (places.num_places < previous_num_places)
      carmen_warn("%d place locations were dropped from the map after "
		  "minimization.\n", previous_num_places-places.num_places);
  } else
    places.num_places = 0;

  /*
   * Pass everything else through untouched, and then write the rotated
   * chunks at the end.
   */


  in_fp = carmen_fopen(input_filename, "r");
  if (in_fp == NULL)
    carmen_die_syserror("Couldn't open %s for reading", input_filename);

  out_fp = carmen_fopen(output_filename, "w");
  if (out_fp == NULL)
    carmen_die_syserror("Couldn't open %s for writing", output_filename);
  
  if (carmen_map_vstrip(in_fp, out_fp, 3, CARMEN_MAP_GRIDMAP_CHUNK,
			CARMEN_MAP_OFFLIMITS_CHUNK, 
			CARMEN_MAP_PLACES_CHUNK) < 0) 
    carmen_die_syserror("Couldn't strip map to %s", output_filename);
  

  if (carmen_map_write_gridmap_chunk(out_fp, map.map, map.config.x_size, 
				     map.config.y_size, 
				     map.config.resolution) < 0)
    carmen_die_syserror("Couldn't write gridmap to %s", output_filename);

  if (offlimits_list.list_length > 0) {
    if (carmen_map_write_offlimits_chunk(out_fp, offlimits_list.offlimits,
					 offlimits_list.list_length) < 0)
      carmen_die_syserror("Couldn't write offlimits list to %s", 
			  output_filename);
  }

  if (places.num_places > 0) {
    if (carmen_map_write_places_chunk(out_fp, places.places,
				      places.num_places) < 0)
      carmen_die_syserror("Couldn't write places list to %s", output_filename);
  }

  carmen_fclose(in_fp);
  carmen_fclose(out_fp);
}
Ejemplo n.º 22
0
static void rotate(int argc, char *argv[])
{
  int force;
  char *input_filename, *output_filename;
  int next_arg;

  carmen_FILE *in_fp, *out_fp;
  int ret_val;
  carmen_map_t map;
  int rotation = 0;
  double remain;
  int degrees_angle;
  carmen_offlimits_list_t offlimits_list;
  carmen_map_placelist_t places_list;

  next_arg = handle_options(argc, argv, &force);
  next_arg++;

  if(argc - next_arg != 4) {
    carmen_warn("\nError: wrong number of parameters.\n");    
    carmen_die("\nUsage: %s rotate <rotation in degrees> <in map filename> "
	       "<out map filename>\n\n", argv[0]);
  }

  degrees_angle = (int)(atof(argv[next_arg]) / 90);
  remain = fabs(degrees_angle*90 - atof(argv[next_arg]));
  if (carmen_radians_to_degrees(remain) > 2)
    carmen_die("Rotations only supported in increments of 90 degrees.\n");
  else
    rotation = (int)atof(argv[next_arg]) / 90;

  input_filename = check_mapfile(argv[next_arg+1]);
  output_filename = check_output(argv[next_arg+2], force);

  carmen_warn("Rotating by %d degrees\n", rotation*90);

  /*
   * Read the gridmap, places and offlimits chunks and rotate them
   */ 

  ret_val = carmen_map_chunk_exists(input_filename, CARMEN_MAP_GRIDMAP_CHUNK);
  if (ret_val < 0)    
    carmen_die_syserror("Couldn't check existence of GRIDMAP_CHUNK in %s", 
			input_filename);
  
  if (carmen_map_read_gridmap_chunk(input_filename, &map) < 0)
    carmen_die_syserror("Couldn't read GRIDMAP_CHUNK from %s", input_filename);

  carmen_rotate_gridmap(&map, rotation);

  ret_val = carmen_map_chunk_exists(input_filename, 
				    CARMEN_MAP_OFFLIMITS_CHUNK);
  if (ret_val > 0) {
    ret_val = carmen_map_read_offlimits_chunk
      (input_filename, &(offlimits_list.offlimits), 
       &(offlimits_list.list_length));

    if (ret_val < 0)
      carmen_die_syserror("Couldn't read OFFLIMITS_CHUNK in %s",
			  input_filename);

    carmen_rotate_offlimits(map.config, &offlimits_list, rotation);
  } else
    offlimits_list.list_length = 0;

  ret_val = carmen_map_chunk_exists(input_filename, CARMEN_MAP_PLACES_CHUNK);
  if (ret_val > 0) {
    ret_val = carmen_map_read_places_chunk(input_filename, &places_list);
    if (ret_val < 0)
      carmen_die_syserror("Couldn't read PLACES_CHUNK in %s", input_filename);

    carmen_rotate_places(map.config, &places_list, rotation);
  } else
    places_list.num_places = 0;


  /*
   * Pass everything else through untouched, and then write the rotated
   * chunks at the end.
   */

  in_fp = carmen_fopen(input_filename, "r");
  if (in_fp == NULL)
    carmen_die_syserror("Couldn't open %s for reading", input_filename);

  out_fp = carmen_fopen(output_filename, "w");
  if (out_fp == NULL)
    carmen_die_syserror("Couldn't open %s for writing", output_filename);
  
  if (carmen_map_vstrip(in_fp, out_fp, 3, CARMEN_MAP_GRIDMAP_CHUNK,
			CARMEN_MAP_OFFLIMITS_CHUNK, 
			CARMEN_MAP_PLACES_CHUNK) < 0) 
    carmen_die_syserror("Couldn't strip map to %s", output_filename);

  if (carmen_map_write_gridmap_chunk(out_fp, map.map, map.config.x_size, 
				     map.config.y_size, 
				     map.config.resolution) < 0)
    carmen_die_syserror("Couldn't write gridmap to %s", output_filename);

  if (offlimits_list.list_length > 0) {
    if (carmen_map_write_offlimits_chunk(out_fp, offlimits_list.offlimits,
					 offlimits_list.list_length) < 0)
      carmen_die_syserror("Couldn't write offlimits list to %s", 
			  output_filename);
  }

  if (places_list.num_places > 0) {
    if (carmen_map_write_places_chunk(out_fp, places_list.places, 
				      places_list.num_places) < 0)
      carmen_die_syserror("Couldn't write places list to %s", output_filename);
  }

  carmen_fclose(in_fp);
  carmen_fclose(out_fp);
}
Ejemplo n.º 23
0
int main(int argc,char *argv[])
{
  int error=0, subkeys;
  uint keylen, keylen2=0, inx, doc_cnt=0;
  float weight= 1.0;
  double gws, min_gws=0, avg_gws=0;
  MI_INFO *info;
  char buf[MAX_LEN], buf2[MAX_LEN], buf_maxlen[MAX_LEN], buf_min_gws[MAX_LEN];
  ulong total=0, maxlen=0, uniq=0, max_doc_cnt=0;
  struct { MI_INFO *info; } aio0, *aio=&aio0; /* for GWS_IN_USE */

  MY_INIT(argv[0]);

  memset(&main_thread_keycache_var, 0, sizeof(st_keycache_thread_var));
  mysql_cond_init(PSI_NOT_INSTRUMENTED,
                  &main_thread_keycache_var.suspend);

  if ((error= handle_options(&argc, &argv, my_long_options, get_one_option)))
    exit(error);
  if (count || dump)
    verbose=0;
  if (!count && !dump && !lstats && !query)
    stats=1;

  if (verbose)
    setbuf(stdout,NULL);

  if (argc < 2)
    usage();

  {
    char *end;
    inx= (uint) my_strtoll(argv[1], &end, 10);
    if (*end)
      usage();
  }

  init_key_cache(dflt_key_cache,MI_KEY_BLOCK_LENGTH,USE_BUFFER_INIT, 0, 0);

  if (!(info=mi_open(argv[0], O_RDONLY,
                     HA_OPEN_ABORT_IF_LOCKED|HA_OPEN_FROM_SQL_LAYER)))
  {
    error=my_errno();
    goto err;
  }

  *buf2=0;
  aio->info=info;

  if ((inx >= info->s->base.keys) ||
      !(info->s->keyinfo[inx].flag & HA_FULLTEXT))
  {
    printf("Key %d in table %s is not a FULLTEXT key\n", inx, info->filename);
    goto err;
  }

  mi_lock_database(info, F_EXTRA_LCK);

  info->lastpos= HA_OFFSET_ERROR;
  info->update|= HA_STATE_PREV_FOUND;

  while (!(error=mi_rnext(info,NULL,inx)))
  {
    keylen=*(info->lastkey);

    subkeys=ft_sintXkorr(info->lastkey+keylen+1);
    if (subkeys >= 0)
      ft_floatXget(weight, info->lastkey+keylen+1);

    my_snprintf(buf,MAX_LEN,"%.*s",(int) keylen,info->lastkey+1);
    my_casedn_str(default_charset_info,buf);
    total++;
    lengths[keylen]++;

    if (count || stats)
    {
      if (strcmp(buf, buf2))
      {
        if (*buf2)
        {
          uniq++;
          avg_gws+=gws=GWS_IN_USE;
          if (count)
            printf("%9u %20.7f %s\n",doc_cnt,gws,buf2);
          if (maxlen<keylen2)
          {
            maxlen=keylen2;
            my_stpcpy(buf_maxlen, buf2);
          }
          if (max_doc_cnt < doc_cnt)
          {
            max_doc_cnt=doc_cnt;
            my_stpcpy(buf_min_gws, buf2);
            min_gws=gws;
          }
        }
        my_stpcpy(buf2, buf);
        keylen2=keylen;
        doc_cnt=0;
      }
      doc_cnt+= (subkeys >= 0 ? 1 : -subkeys);
    }
    if (dump)
    {
      if (subkeys>=0)
        printf("%9lx %20.7f %s\n", (long) info->lastpos,weight,buf);
      else
        printf("%9lx => %17d %s\n",(long) info->lastpos,-subkeys,buf);
    }
    if (verbose && (total%HOW_OFTEN_TO_WRITE)==0)
      printf("%10ld\r",total);
  }
  mi_lock_database(info, F_UNLCK);

  if (count || stats)
  {
    if (*buf2)
    {
      uniq++;
      avg_gws+=gws=GWS_IN_USE;
      if (count)
        printf("%9u %20.7f %s\n",doc_cnt,gws,buf2);
      if (maxlen<keylen2)
      {
        maxlen=keylen2;
        my_stpcpy(buf_maxlen, buf2);
      }
      if (max_doc_cnt < doc_cnt)
      {
        max_doc_cnt=doc_cnt;
        my_stpcpy(buf_min_gws, buf2);
        min_gws=gws;
      }
    }
  }

  if (stats)
  {
    count=0;
    for (inx=0;inx<256;inx++)
    {
      count+=lengths[inx];
      if ((ulong) count >= total/2)
        break;
    }
    printf("Total rows: %lu\nTotal words: %lu\n"
           "Unique words: %lu\nLongest word: %lu chars (%s)\n"
           "Median length: %u\n"
           "Average global weight: %f\n"
           "Most common word: %lu times, weight: %f (%s)\n",
           (long) info->state->records, total, uniq, maxlen, buf_maxlen,
           inx, avg_gws/uniq, max_doc_cnt, min_gws, buf_min_gws);
  }
  if (lstats)
  {
    count=0;
    for (inx=0; inx<256; inx++)
    {
      count+=lengths[inx];
      if (count && lengths[inx])
        printf("%3u: %10lu %5.2f%% %20lu %4.1f%%\n", inx,
               (ulong) lengths[inx],100.0*lengths[inx]/total,(ulong) count,
               100.0*count/total);
    }
  }

err:
  if (error && error != HA_ERR_END_OF_FILE)
    printf("got error %d\n",my_errno());
  if (info)
    mi_close(info);
  mysql_cond_destroy(&main_thread_keycache_var.suspend);
  return 0;
}
Ejemplo n.º 24
0
int
main (int argc, char **argv)
{
  int i;
  char **argv_copy;
  const char *startup_id, *display_name;
  GdkDisplay *display;
  TerminalOptions *options;
  TerminalFactory *factory;
  GError *error = NULL;
  char *working_directory;
  int exit_code = EXIT_FAILURE;

  setlocale (LC_ALL, "");

  terminal_i18n_init (TRUE);

  _terminal_debug_init ();

  /* Make a NULL-terminated copy since we may need it later */
  argv_copy = g_new (char *, argc + 1);
  for (i = 0; i < argc; ++i)
    argv_copy [i] = argv [i];
  argv_copy [i] = NULL;

  startup_id = g_getenv ("DESKTOP_STARTUP_ID");

  working_directory = g_get_current_dir ();

  options = terminal_options_parse (working_directory,
                                    startup_id,
                                    &argc, &argv,
                                    &error);
  if (options == NULL) {
    g_printerr (_("Failed to parse arguments: %s\n"), error->message);
    g_error_free (error);
    g_free (working_directory);
    g_free (argv_copy);
    exit (EXIT_FAILURE);
  }

  g_set_application_name (_("Terminal"));

  /* Do this here so that gdk_display is initialized */
  if (options->startup_id == NULL)
    terminal_client_get_fallback_startup_id (&options->startup_id);

  display = gdk_display_get_default ();
  display_name = gdk_display_get_name (display);
  options->display_name = g_strdup (display_name);

  factory = terminal_factory_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                                     G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
                                                     G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
                                                     options->server_app_id ? options->server_app_id 
                                                                            : TERMINAL_APPLICATION_ID,
                                                     TERMINAL_FACTORY_OBJECT_PATH,
                                                     NULL /* cancellable */,
                                                     &error);
  if (factory == NULL) {
    g_dbus_error_strip_remote_error (error);
    g_printerr ("Error constructing proxy for %s:%s: %s\n", 
                options->server_app_id ? options->server_app_id : TERMINAL_APPLICATION_ID,
                TERMINAL_FACTORY_OBJECT_PATH,
                error->message);
    g_error_free (error);
    goto out;
  }

  if (!handle_options (factory, options, &error)) {
    g_dbus_error_strip_remote_error (error);
    g_printerr ("Failed to handle arguments: %s\n", error->message);
  } else {
    exit_code = EXIT_SUCCESS;
  }

  g_object_unref (factory);

out:
  terminal_options_free (options);
  g_free (working_directory);
  g_free (argv_copy);

  return exit_code;
}
Ejemplo n.º 25
0
int
main(int argc, char** argv)
{
  NDB_INIT(argv[0]);
  const char *load_default_groups[]= { "mysql_cluster",0 };
  load_defaults("my",load_default_groups,&argc,&argv);

  int ho_error;
#ifndef DBUG_OFF
  opt_debug= "d:t:F:L";
#endif
  if ((ho_error=handle_options(&argc, &argv, my_long_options, 
			       ndb_std_get_one_option)))
    return NDBT_ProgramExit(NDBT_WRONGARGS);

  DBUG_ENTER("main");
  Ndb_cluster_connection con(opt_connect_str);
  if(con.connect(12, 5, 1))
  {
    DBUG_RETURN(NDBT_ProgramExit(NDBT_FAILED));
  }
  

  Ndb ndb(&con,_dbname);
  ndb.init();
  while (ndb.waitUntilReady() != 0);

  NdbDictionary::Dictionary * dict = ndb.getDictionary();
  int no_error= 1;
  int i;

  // create all tables
  Vector<const NdbDictionary::Table*> pTabs;
  if (argc == 0)
  {
    NDBT_Tables::dropAllTables(&ndb);
    NDBT_Tables::createAllTables(&ndb);
    for (i= 0; no_error && i < NDBT_Tables::getNumTables(); i++)
    {
      const NdbDictionary::Table *pTab= dict->getTable(NDBT_Tables::getTable(i)->getName());
      if (pTab == 0)
      {
	ndbout << "Failed to create table" << endl;
	ndbout << dict->getNdbError() << endl;
	no_error= 0;
	break;
      }
      pTabs.push_back(pTab);
    }
  }
  else
  {
    for (i= 0; no_error && argc; argc--, i++)
    {
      dict->dropTable(argv[i]);
      NDBT_Tables::createTable(&ndb, argv[i]);
      const NdbDictionary::Table *pTab= dict->getTable(argv[i]);
      if (pTab == 0)
      {
	ndbout << "Failed to create table" << endl;
	ndbout << dict->getNdbError() << endl;
	no_error= 0;
	break;
      }
      pTabs.push_back(pTab);
    }
  }
  pTabs.push_back(NULL);

  // create an event for each table
  for (i= 0; no_error && pTabs[i]; i++)
  {
    HugoTransactions ht(*pTabs[i]);
    if (ht.createEvent(&ndb)){
      no_error= 0;
      break;
    }
  }

  // create an event operation for each event
  Vector<NdbEventOperation *> pOps;
  for (i= 0; no_error && pTabs[i]; i++)
  {
    char buf[1024];
    sprintf(buf, "%s_EVENT", pTabs[i]->getName());
    NdbEventOperation *pOp= ndb.createEventOperation(buf, 1000);
    if ( pOp == NULL )
    {
      no_error= 0;
      break;
    }
    pOps.push_back(pOp);
  }

  // get storage for each event operation
  for (i= 0; no_error && pTabs[i]; i++)
  {
    int n_columns= pTabs[i]->getNoOfColumns();
    for (int j = 0; j < n_columns; j++) {
      pOps[i]->getValue(pTabs[i]->getColumn(j)->getName());
      pOps[i]->getPreValue(pTabs[i]->getColumn(j)->getName());
    }
  }

  // start receiving events
  for (i= 0; no_error && pTabs[i]; i++)
  {
    if ( pOps[i]->execute() )
    {
      no_error= 0;
      break;
    }
  }

  // create a "shadow" table for each table
  Vector<const NdbDictionary::Table*> pShadowTabs;
  for (i= 0; no_error && pTabs[i]; i++)
  {
    char buf[1024];
    sprintf(buf, "%s_SHADOW", pTabs[i]->getName());

    dict->dropTable(buf);
    if (dict->getTable(buf))
    {
      no_error= 0;
      break;
    }

    NdbDictionary::Table table_shadow(*pTabs[i]);
    table_shadow.setName(buf);
    dict->createTable(table_shadow);
    pShadowTabs.push_back(dict->getTable(buf));
    if (!pShadowTabs[i])
    {
      no_error= 0;
      break;
    }
  }

  // create a hugo operation per table
  Vector<HugoOperations *> hugo_ops;
  for (i= 0; no_error && pTabs[i]; i++)
  {
    hugo_ops.push_back(new HugoOperations(*pTabs[i]));
  }

  int n_records= 3;
  // insert n_records records per table
  do {
    if (start_transaction(&ndb, hugo_ops))
    {
      no_error= 0;
      break;
    }
    for (i= 0; no_error && pTabs[i]; i++)
    {
      hugo_ops[i]->pkInsertRecord(&ndb, 0, n_records);
    }
    if (execute_commit(&ndb, hugo_ops))
    {
      no_error= 0;
      break;
    }
    if(close_transaction(&ndb, hugo_ops))
    {
      no_error= 0;
      break;
    }
  } while(0);

  // copy events and verify
  do {
    if (copy_events(&ndb) < 0)
    {
      no_error= 0;
      break;
    }
    if (verify_copy(&ndb, pTabs, pShadowTabs))
    {
      no_error= 0;
      break;
    }
  } while (0);

  // update n_records-1 records in first table
  do {
    if (start_transaction(&ndb, hugo_ops))
    {
      no_error= 0;
      break;
    }

    hugo_ops[0]->pkUpdateRecord(&ndb, n_records-1);

    if (execute_commit(&ndb, hugo_ops))
    {
      no_error= 0;
      break;
    }
    if(close_transaction(&ndb, hugo_ops))
    {
      no_error= 0;
      break;
    }
  } while(0);

  // copy events and verify
  do {
    if (copy_events(&ndb) < 0)
    {
      no_error= 0;
      break;
    }
    if (verify_copy(&ndb, pTabs, pShadowTabs))
    {
      no_error= 0;
      break;
    }
  } while (0);


  {
    NdbRestarts restarts;
    for (int j= 0; j < 10; j++)
    {
      // restart a node
      if (no_error)
      {
	int timeout = 240;
	if (restarts.executeRestart("RestartRandomNodeAbort", timeout))
	{
	  no_error= 0;
	  break;
	}
      }

      // update all n_records records on all tables
      if (start_transaction(&ndb, hugo_ops))
      {
	no_error= 0;
	break;
      }

      for (int r= 0; r < n_records; r++)
      {
	for (i= 0; pTabs[i]; i++)
	{
	  hugo_ops[i]->pkUpdateRecord(&ndb, r);
	}
      }
      if (execute_commit(&ndb, hugo_ops))
      {
	no_error= 0;
	break;
      }
      if(close_transaction(&ndb, hugo_ops))
      {
	no_error= 0;
	break;
      }

      // copy events and verify
      if (copy_events(&ndb) < 0)
      {
	no_error= 0;
	break;
      }
      if (verify_copy(&ndb, pTabs, pShadowTabs))
      {
	no_error= 0;
	break;
      }
    }
  }

  // drop the event operations
  for (i= 0; i < (int)pOps.size(); i++)
  {
    if (ndb.dropEventOperation(pOps[i]))
    {
      no_error= 0;
    }
  }

  if (no_error)
    DBUG_RETURN(NDBT_ProgramExit(NDBT_OK));
  DBUG_RETURN(NDBT_ProgramExit(NDBT_FAILED));
}
Ejemplo n.º 26
0
int main(int argc, char** argv) {
    NDB_INIT(argv[0]);

    load_defaults("my",load_default_groups,&argc,&argv);
    int ho_error;
#ifndef DBUG_OFF
    opt_debug= "d:t:O,/tmp/ndb_mgm.trace";
#endif
    if ((ho_error=handle_options(&argc, &argv, my_long_options,
                                 ndb_std_get_one_option)))
        exit(ho_error);

    char buf[MAXHOSTNAMELEN+10];
    if(argc == 1) {
        BaseString::snprintf(buf, sizeof(buf), "%s",  argv[0]);
        opt_connect_str= buf;
    } else if (argc >= 2) {
        BaseString::snprintf(buf, sizeof(buf), "%s:%s",  argv[0], argv[1]);
        opt_connect_str= buf;
    }

    if (!isatty(0) || opt_execute_str)
    {
        prompt= 0;
    }

    signal(SIGPIPE, handler);
    com = new Ndb_mgmclient(opt_connect_str,1);
    int ret= 0;
    BaseString histfile;
    if (!opt_execute_str)
    {
#ifdef HAVE_READLINE
        char *histfile_env= getenv("NDB_MGM_HISTFILE");
        if (histfile_env)
            histfile.assign(histfile_env,strlen(histfile_env));
        else if(getenv("HOME"))
        {
            histfile.assign(getenv("HOME"),strlen(getenv("HOME")));
            histfile.append("/.ndb_mgm_history");
        }
        if (histfile.length())
            read_history(histfile.c_str());
#endif

        ndbout << "-- NDB Cluster -- Management Client --" << endl;
        while(read_and_execute(_try_reconnect));

#ifdef HAVE_READLINE
        if (histfile.length())
        {
            BaseString histfile_tmp;
            histfile_tmp.assign(histfile);
            histfile_tmp.append(".TMP");
            if(!write_history(histfile_tmp.c_str()))
                my_rename(histfile_tmp.c_str(), histfile.c_str(), MYF(MY_WME));
        }
#endif
    }
    else
    {
        com->execute(opt_execute_str,_try_reconnect, 0, &ret);
    }
    delete com;

    ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
    return ret;
}
Ejemplo n.º 27
0
Archivo: git.c Proyecto: benpeart/git
static int handle_alias(int *argcp, const char ***argv)
{
	int envchanged = 0, ret = 0, saved_errno = errno;
	int count, option_count;
	const char **new_argv;
	const char *alias_command;
	char *alias_string;

	alias_command = (*argv)[0];
	alias_string = alias_lookup(alias_command);
	if (alias_string) {
		if (alias_string[0] == '!') {
			struct child_process child = CHILD_PROCESS_INIT;
			int nongit_ok;

			/* Aliases expect GIT_PREFIX, GIT_DIR etc to be set */
			setup_git_directory_gently(&nongit_ok);

			commit_pager_choice();

			child.use_shell = 1;
			argv_array_push(&child.args, alias_string + 1);
			argv_array_pushv(&child.args, (*argv) + 1);

			ret = run_command(&child);
			if (ret >= 0)   /* normal exit */
				exit(ret);

			die_errno("while expanding alias '%s': '%s'",
			    alias_command, alias_string + 1);
		}
		count = split_cmdline(alias_string, &new_argv);
		if (count < 0)
			die("Bad alias.%s string: %s", alias_command,
			    split_cmdline_strerror(count));
		option_count = handle_options(&new_argv, &count, &envchanged);
		if (envchanged)
			die("alias '%s' changes environment variables.\n"
				 "You can use '!git' in the alias to do this",
				 alias_command);
		memmove(new_argv - option_count, new_argv,
				count * sizeof(char *));
		new_argv -= option_count;

		if (count < 1)
			die("empty alias for %s", alias_command);

		if (!strcmp(alias_command, new_argv[0]))
			die("recursive alias: %s", alias_command);

		trace_argv_printf(new_argv,
				  "trace: alias expansion: %s =>",
				  alias_command);

		REALLOC_ARRAY(new_argv, count + *argcp);
		/* insert after command name */
		memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);

		*argv = new_argv;
		*argcp += count - 1;

		ret = 1;
	}

	errno = saved_errno;

	return ret;
}
Ejemplo n.º 28
0
static int handle_alias(int *argcp, const char ***argv)
{
	int envchanged = 0, ret = 0, saved_errno = errno;
	int count, option_count;
	const char **new_argv;
	const char *alias_command;
	char *alias_string;

	alias_command = (*argv)[0];
	alias_string = alias_lookup(alias_command);
	if (alias_string) {
		if (alias_string[0] == '!') {
			if (*argcp > 1) {
				struct strbuf buf;

				strbuf_init(&buf, PATH_MAX);
				strbuf_addstr(&buf, alias_string);
				sq_quote_argv(&buf, (*argv) + 1, PATH_MAX);
				free(alias_string);
				alias_string = buf.buf;
			}
			ret = system(alias_string + 1);
			if (ret >= 0 && WIFEXITED(ret) &&
			    WEXITSTATUS(ret) != 127)
				exit(WEXITSTATUS(ret));
			die("Failed to run '%s' when expanding alias '%s'",
			    alias_string + 1, alias_command);
		}
		count = split_cmdline(alias_string, &new_argv);
		if (count < 0)
			die("Bad alias.%s string", alias_command);
		option_count = handle_options(&new_argv, &count, &envchanged);
		if (envchanged)
			die("alias '%s' changes environment variables\n"
				 "You can use '!perf' in the alias to do this.",
				 alias_command);
		memmove(new_argv - option_count, new_argv,
				count * sizeof(char *));
		new_argv -= option_count;

		if (count < 1)
			die("empty alias for %s", alias_command);

		if (!strcmp(alias_command, new_argv[0]))
			die("recursive alias: %s", alias_command);

		new_argv = realloc(new_argv, sizeof(char *) *
				    (count + *argcp + 1));
		
		memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);
		new_argv[count + *argcp] = NULL;

		*argv = new_argv;
		*argcp += count - 1;

		ret = 1;
	}

	errno = saved_errno;

	return ret;
}
Ejemplo n.º 29
0
/*
 *  MAIN 
 */
int main(int argc, char** argv)
{

  NDB_INIT(argv[0]);

  load_defaults("my",load_default_groups,&argc,&argv);

  int ho_error;
#ifndef DBUG_OFF
  opt_debug= "d:t:O,/tmp/ndb_mgmd.trace";
#endif
  if ((ho_error=handle_options(&argc, &argv, my_long_options, 
			       ndb_std_get_one_option)))
    exit(ho_error);

start:
  glob= new MgmGlobals;

  /**
   * OSE specific. Enable shared ownership of file system resources. 
   * This is needed in order to use the cluster log since the events 
   * from the cluster is written from the 'ndb_receive'(NDBAPI) thread/process.
   */
#if defined NDB_OSE || defined NDB_SOFTOSE
  efs_segment_share();
#endif

  global_mgmt_server_check = 1;

  if (opt_interactive ||
      opt_non_interactive ||
      g_print_full_config) {
    opt_daemon= 0;
  }

  if (opt_mycnf && opt_config_filename)
  {
    ndbout_c("Both --mycnf and -f is not supported");
    return 0;
  }

  if (opt_mycnf == 0 && opt_config_filename == 0)
  {
    struct stat buf;
    if (stat("config.ini", &buf) != -1)
      opt_config_filename = "config.ini";
  }
  
  glob->socketServer = new SocketServer();

  MgmApiService * mapi = new MgmApiService();

  glob->mgmObject = new MgmtSrvr(glob->socketServer,
				 opt_config_filename,
				 opt_connect_str);

  if (g_print_full_config)
    goto the_end;

  if (glob->mgmObject->init())
    goto error_end;

  my_setwd(NdbConfig_get_path(0), MYF(0));

  glob->localNodeId= glob->mgmObject->getOwnNodeId();
  if (glob->localNodeId == 0) {
    goto error_end;
  }

  glob->port= glob->mgmObject->getPort();

  if (glob->port == 0)
    goto error_end;

  glob->interface_name = 0;
  glob->use_specific_ip = false;

  if(!glob->use_specific_ip){
    int count= 5; // no of retries for tryBind
    while(!glob->socketServer->tryBind(glob->port, glob->interface_name)){
      if (--count > 0) {
	NdbSleep_MilliSleep(1000);
	continue;
      }
      ndbout_c("Unable to setup port: %s:%d!\n"
	       "Please check if the port is already used,\n"
	       "(perhaps a ndb_mgmd is already running),\n"
	       "and if you are executing on the correct computer", 
	       (glob->interface_name ? glob->interface_name : "*"), glob->port);
      goto error_end;
    }
    free(glob->interface_name);
    glob->interface_name = 0;
  }

  if(!glob->socketServer->setup(mapi, &glob->port, glob->interface_name))
  {
    ndbout_c("Unable to setup management port: %d!\n"
	     "Please check if the port is already used,\n"
	     "(perhaps a ndb_mgmd is already running),\n"
	     "and if you are executing on the correct computer", 
	     glob->port);
    delete mapi;
    goto error_end;
  }

  if(!glob->mgmObject->check_start()){
    ndbout_c("Unable to check start management server.");
    ndbout_c("Probably caused by illegal initial configuration file.");
    goto error_end;
  }

  if (opt_daemon) {
    // Become a daemon
    char *lockfile= NdbConfig_PidFileName(glob->localNodeId);
    char *logfile=  NdbConfig_StdoutFileName(glob->localNodeId);
    NdbAutoPtr<char> tmp_aptr1(lockfile), tmp_aptr2(logfile);

    if (NdbDaemon_Make(lockfile, logfile, 0) == -1) {
      ndbout << "Cannot become daemon: " << NdbDaemon_ErrorText << endl;
      return 1;
    }
  }

#ifndef NDB_WIN32
  signal(SIGPIPE, SIG_IGN);
#endif
  {
    BaseString error_string;
    if(!glob->mgmObject->start(error_string)){
      ndbout_c("Unable to start management server.");
      ndbout_c("Probably caused by illegal initial configuration file.");
      ndbout_c(error_string.c_str());
      goto error_end;
    }
  }

  //glob->mgmObject->saveConfig();
  mapi->setMgm(glob->mgmObject);

  char msg[256];
  BaseString::snprintf(msg, sizeof(msg),
	   "NDB Cluster Management Server. %s", NDB_VERSION_STRING);
  ndbout_c(msg);
  g_eventLogger.info(msg);

  BaseString::snprintf(msg, 256, "Id: %d, Command port: %d",
	   glob->localNodeId, glob->port);
  ndbout_c(msg);
  g_eventLogger.info(msg);
  
  g_StopServer = false;
  g_RestartServer= false;
  glob->socketServer->startServer();

#if ! defined NDB_OSE && ! defined NDB_SOFTOSE
  if(opt_interactive) {
    BaseString con_str;
    if(glob->interface_name)
      con_str.appfmt("host=%s:%d", glob->interface_name, glob->port);
    else 
      con_str.appfmt("localhost:%d", glob->port);
    Ndb_mgmclient com(con_str.c_str(), 1);
    while(g_StopServer != true && read_and_execute(&com, "ndb_mgm> ", 1));
  } else 
#endif
  {
    while(g_StopServer != true)
      NdbSleep_MilliSleep(500);
  }

  if(g_RestartServer)
    g_eventLogger.info("Restarting server...");
  else
    g_eventLogger.info("Shutting down server...");
  glob->socketServer->stopServer();
  // We disconnect from the ConfigRetreiver mgmd when we delete glob below
  glob->socketServer->stopSessions(true);
  g_eventLogger.info("Shutdown complete");
 the_end:
  delete glob;
  if(g_RestartServer)
    goto start;
  ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  return 0;
 error_end:
  delete glob;
  ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  return 1;
}
Ejemplo n.º 30
0
Archivo: git.c Proyecto: SRabbelier/git
static int handle_alias(int *argcp, const char ***argv)
{
	int envchanged = 0, ret = 0, saved_errno = errno;
	const char *subdir;
	int count, option_count;
	const char **new_argv;
	const char *alias_command;
	char *alias_string;
	int unused_nongit;

	subdir = setup_git_directory_gently(&unused_nongit);

	alias_command = (*argv)[0];
	alias_string = alias_lookup(alias_command);
	if (alias_string) {
		if (alias_string[0] == '!') {
			commit_pager_choice();
			if (*argcp > 1) {
				struct strbuf buf;

				strbuf_init(&buf, PATH_MAX);
				strbuf_addstr(&buf, alias_string);
				sq_quote_argv(&buf, (*argv) + 1, PATH_MAX);
				free(alias_string);
				alias_string = buf.buf;
			}
			trace_printf("trace: alias to shell cmd: %s => %s\n",
				     alias_command, alias_string + 1);
			ret = system(alias_string + 1);
			if (ret >= 0 && WIFEXITED(ret) &&
			    WEXITSTATUS(ret) != 127)
				exit(WEXITSTATUS(ret));
			die("Failed to run '%s' when expanding alias '%s'",
			    alias_string + 1, alias_command);
		}
		count = split_cmdline(alias_string, &new_argv);
		if (count < 0)
			die("Bad alias.%s string: %s", alias_command,
			    split_cmdline_strerror(count));
		option_count = handle_options(&new_argv, &count, &envchanged);
		if (envchanged)
			die("alias '%s' changes environment variables\n"
				 "You can use '!git' in the alias to do this.",
				 alias_command);
		memmove(new_argv - option_count, new_argv,
				count * sizeof(char *));
		new_argv -= option_count;

		if (count < 1)
			die("empty alias for %s", alias_command);

		if (!strcmp(alias_command, new_argv[0]))
			die("recursive alias: %s", alias_command);

		trace_argv_printf(new_argv,
				  "trace: alias expansion: %s =>",
				  alias_command);

		new_argv = xrealloc(new_argv, sizeof(char *) *
				    (count + *argcp));
		/* insert after command name */
		memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);

		*argv = new_argv;
		*argcp += count - 1;

		ret = 1;
	}

	if (subdir && chdir(subdir))
		die_errno("Cannot change to '%s'", subdir);

	errno = saved_errno;

	return ret;
}