示例#1
0
int main(void)
{
    apr_status_t rv;
    apr_pool_t *pool;
    char errmsg[200];

    apr_initialize();

    printf("APR Shared Memory Test\n");
    printf("======================\n\n");

    printf("Initializing the pool............................");
    if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
        printf("could not initialize pool\n");
        exit(-1);
    }
    printf("OK\n");

    rv = test_anon(pool);
    if (rv != APR_SUCCESS) {
        if (rv == APR_ENOTIMPL) {
            printf("Anonymous shared memory unavailable on this platform.\n");
        }
        else {
            printf("Anonymous shared memory test FAILED: [%d] %s\n",
                   rv, apr_strerror(rv, errmsg, sizeof(errmsg)));
            exit(-2);
        }
    }
    printf("Anonymous shared memory test passed!\n");

    if ((rv = test_named(pool)) != APR_SUCCESS) {
        printf("Name-based shared memory test FAILED: [%d] %s \n",
               rv, apr_strerror(rv, errmsg, sizeof(errmsg)));
        exit(-3);
    }
    printf("Named shared memory test passed!\n");

    return 0;
}
示例#2
0
int sha1_file(const std::string& filename, std::string& checksum, bool binary)
{
  apr_initialize();
  apr_pool_t* pool;
  apr_pool_create(&pool, NULL);
  
  apr_file_t* in;
  apr_int32_t flags = (binary ? APR_READ | APR_BINARY : APR_READ);
  apr_file_open(&in, filename.c_str(), flags, APR_OS_DEFAULT, pool);
  
  char buffer[512];
  memset(buffer, 0, sizeof(buffer));
  apr_size_t bytes_read = 0;
  apr_file_read_full(in, buffer, 512, &bytes_read);
  apr_file_close(in);
  
  unsigned char digest[APR_SHA1_DIGESTSIZE + 1];
  memset(digest, 0, APR_SHA1_DIGESTSIZE + 1);
  
  apr_sha1_ctx_t context;
  apr_sha1_init(&context);
  if(binary) apr_sha1_update_binary(&context, (const unsigned char*)buffer, bytes_read);
  else apr_sha1_update(&context, buffer, bytes_read);
  apr_sha1_final(digest, &context);
  
  std::ostringstream oss;
  for(int i = 0; i < APR_SHA1_DIGESTSIZE; i++)
  {
    unsigned short letter = digest[i];
    oss << std::hex << std::setw(2) << std::setfill('0') << letter;
  }
  
  checksum = oss.str();
  
  apr_pool_destroy(pool);
  apr_terminate();
  
  return 0;
}
				void Listener::StartThreads ()
				{
								apr_status_t rc;
								rc = apr_initialize ();
								rc == APR_SUCCESS || die (-2, "Could not initialize", rc);
								atexit (terminate);

								pthread_t threads[2];
								size_t stacksize;
								pthread_attr_t attr;
								pthread_attr_init(&attr);

								//https://computing.llnl.gov/tutorials/pthreads/
								struct thread_data thread_data_array[2];

								thread_data_array[0].thread_id = 0;	
								rc = pthread_create(&threads[0], NULL, DiscoveryThread, (void *) &thread_data_array[0] );
								thread_data_array[1].thread_id = 1;	
								rc = pthread_create(&threads[1], NULL, PuppetdThread, (void *) &thread_data_array[1] );
							

				}
示例#4
0
int
main(int argc, char **argv)
{
    filter_t       *filter;
    apr_pool_t     *root_pool;

    if (argc <= 1) {
        printf("Usage: %s <file>\n", argv[0]);
        exit(0);
    }

    apr_initialize();
    apr_pool_create(&root_pool, NULL);

    filter = filter_parse_config(root_pool, argv[1], 0);

    printf("Filter passed? %s\n", filter ? "yes" : "no");

    apr_pool_destroy(root_pool);
    apr_terminate();
    return 0;
}
示例#5
0
文件: echod.c 项目: XianliangJ/mtcp
int main(int argc, char **argv)
{
    apr_pool_t *pool;
    apr_int16_t theport = 4747;

    printf("APR Test Application: echod\n");

    apr_initialize();
    atexit(apr_terminate);

    apr_pool_create(&pool, NULL);

    if (argc >= 2) {
        printf("argc = %d, port = '%s'\n", argc, argv[1]);
        theport = atoi(argv[1]);
    }

    fprintf(stdout, "Starting to listen on port %d\n", theport);
    glassToWall(theport, pool);

    return 0;
}
示例#6
0
int main(int argc, const char * const *argv)
{
    int reader = 0;
    apr_status_t status;
    char optchar;
    const char *optarg;
    apr_getopt_t *opt;

    if (apr_initialize() != APR_SUCCESS)
        errmsg("Could not initialize APR.\n");
    atexit(apr_terminate);

    if (apr_pool_create(&pool, NULL) != APR_SUCCESS)
        errmsg("Could not create global pool.\n");

    if (apr_getopt_init(&opt, pool, argc, argv) != APR_SUCCESS)
        errmsg("Could not parse options.\n");

    while ((status = apr_getopt(opt, "rf:", &optchar, &optarg)) == APR_SUCCESS) {
        if (optchar == 'r')
            ++reader;
        else if (optchar == 'f')
            testfile = optarg;
    }
    if (status != APR_SUCCESS && status != APR_EOF) {
        char msgbuf[80];

        fprintf(stderr, "error: %s\n",
                apr_strerror(status, msgbuf, sizeof msgbuf));
        exit(1);
    }

    if (reader)
        do_read();
    else
        do_write();

    return 0;
}
示例#7
0
static void make_child(CuTest *tc, apr_proc_t **proc, apr_pool_t *p)
{
    apr_status_t rv;

    *proc = apr_pcalloc(p, sizeof(**proc));

    /* slight delay to allow things to settle */
    apr_sleep (1);

    rv = apr_proc_fork(*proc, p);
    if (rv == APR_INCHILD) {
        int i = 0;
        /* The parent process has setup all processes to call apr_terminate
         * at exit.  But, that means that all processes must also call
         * apr_initialize at startup.  You cannot have an unequal number
         * of apr_terminate and apr_initialize calls.  If you do, bad things
         * will happen.  In this case, the bad thing is that if the mutex
         * is a semaphore, it will be destroyed before all of the processes
         * die.  That means that the test will most likely fail.
         */
        apr_initialize();

        if (apr_proc_mutex_child_init(&proc_lock, NULL, p))
            exit(1);

        do {
            if (apr_proc_mutex_lock(proc_lock))
                exit(1);
            i++;
            *x = increment(*x);
            if (apr_proc_mutex_unlock(proc_lock))
                exit(1);
        } while (i < MAX_ITER);
        exit(0);
    } 

    CuAssert(tc, "fork failed", rv == APR_INPARENT);
}
示例#8
0
int
main(int argc, const char *argv[])
{
    int result = 0;
    apr_pool_t *mp;
    apr_status_t status;
    char next_char;
    Source *source = NULL;

    apr_initialize();

    status = apr_pool_create(&mp, NULL);
    handle_and_display_error(status);

    source_init(&source, mp);

    status = source_set_options(source, argc, argv, mp);
    handle_and_display_error(status);

    status = source_open(source, mp);
    handle_and_display_error(status);

    while (source_shift_character(source, &next_char) == APR_SUCCESS) {
        printf("%c", next_char);
    }

    goto cleanup;

error:
    result = 1;

cleanup:
    if (source) { source_cleanup(source); }
    apr_pool_destroy(mp);
    apr_terminate();

    return result;
}
示例#9
0
int main(int argc, const char * const *argv)
{
    apr_file_t *file;
    apr_status_t status;
    apr_pool_t *p;

    apr_initialize();
    apr_pool_create(&p, NULL);

    if (apr_file_open(&file, TESTFILE, APR_WRITE, APR_OS_DEFAULT, p) 
        != APR_SUCCESS) {
        
        exit(UNEXPECTED_ERROR);
    }
    status = apr_file_lock(file, APR_FLOCK_EXCLUSIVE | APR_FLOCK_NONBLOCK);
    if (status == APR_SUCCESS) {
        exit(SUCCESSFUL_READ);
    }
    if (APR_STATUS_IS_EAGAIN(status)) {
        exit(FAILED_READ);
    }
    exit(UNEXPECTED_ERROR);
}
示例#10
0
int main(int argc,char **argv) {
    apr_initialize();
    apr_pool_t *pool;
    apr_pool_create(&pool,NULL);
    apr_status_t st;

    apr_dbm_t *dbm;
    st=apr_dbm_open(&dbm,"friends",APR_DBM_RWCREATE,APR_OS_DEFAULT,pool);
    if(st != APR_SUCCESS) {
        fprintf(stderr,"apr_dbm_open : %d\n",st);
        return st;
    }

    apr_datum_t key,value;
    key.dptr="laomeng";
    key.dsize=strlen(key.dptr)+1;
    value.dptr="[email protected]";
    value.dsize=strlen(value.dptr)+1;

    st=apr_dbm_store(dbm,key,value);
    
    apr_datum_t pvalue;
    st=apr_dbm_fetch(dbm,key,&pvalue);
    
    printf("pvalue => %s\n",pvalue.dptr);
    printf(" value => %s\n",value.dptr);

    apr_dbm_close(dbm);
    



    apr_pool_destroy(pool);
    apr_terminate();
    return 0;
}
示例#11
0
文件: teeterl.c 项目: aidanhs/teeterl
apr_status_t teeterl_init()
{
	xmod_bin_t *mp, *me;

	apr_initialize();
	atexit(apr_terminate);

	apr_pool_create(&g_mempool, 0);
	g_xpool = xpool_make(g_mempool);

	atoms_create(&g_atoms, g_mempool);
	g_base = code_base_make(g_mempool);

	module_bins = apr_array_make(g_mempool, 8, sizeof(xmod_bin_t));

	//teeterl_add_mod(init_xmod_bin);
	//...
#include "premods.inc"

	//preload all modules registered to date
	mp = (xmod_bin_t *)module_bins->elts;
	me = mp + module_bins->nelts;
	while (mp < me)
	{
		atom_cache_t *cache = atom_cache_make(g_xpool);
		term_t code = unpack_term(mp->data, mp->size, cache, g_atoms, g_xpool);

		mp->is_preloaded = 1;
		if (!code_base_load2(g_base, code))
			return APR_EBADF;

		mp++;
	}
	
	return APR_SUCCESS;
}
示例#12
0
Ganglia_pool
Ganglia_pool_create( Ganglia_pool p )
{
  apr_status_t status;
  apr_pool_t *pool=NULL, *parent=(apr_pool_t*)p;

  if(!libgmond_apr_lib_initialized)
    {
      status = apr_initialize();
      if(status != APR_SUCCESS)
        {
          return NULL;
        }
      libgmond_apr_lib_initialized = 1;
      atexit(apr_terminate);
    }

  status = apr_pool_create( &pool, parent );
  if(status != APR_SUCCESS)
    {
      return NULL;
    }
  return (Ganglia_pool)pool;
}
示例#13
0
文件: SVN.c 项目: omf/iosvnnative
int SVN_init(void)
{
    if(!svn_data.initialized) {
    	apr_status_t aprsts;
	    apr_allocator_t *allocator;

	    printf("SVN_init\n");

        if(APR_SUCCESS != apr_initialize()) {
		    printf("<SVN_init> error apr_initialize\n");
		    return FALSE;
	    }

	    if(APR_SUCCESS != (aprsts = apr_allocator_create(&allocator))) {
		    printf("<SVN_init> error apr_allocator_create\n");
		    return FALSE;
	    }

	    svn_data.allocator = allocator;
	    svn_data.pool = svn_pool_create_ex(NULL, allocator);
        svn_data.initialized = TRUE;
    }	
	return TRUE;	
}
示例#14
0
int main(int argc, const char **argv)
{
    apr_status_t status;
    apr_pool_t *pool;
    serf_bucket_alloc_t *bkt_alloc;
    serf_context_t *context;
    serf_connection_t **connections;
    app_baton_t app_ctx;
    handler_baton_t handler_ctx;
    serf_bucket_t *req_hdrs = NULL;
    apr_uri_t url;
    const char *proxy = NULL;
    const char *raw_url, *method, *req_body_path = NULL;
    int count, inflight, conn_count;
    int i;
    int print_headers, debug;
    const char *username = NULL;
    const char *password = "";
    const char *pem_path = NULL, *pem_pwd = NULL;
    apr_getopt_t *opt;
    int opt_c;
    const char *opt_arg;

    apr_initialize();
    atexit(apr_terminate);

    apr_pool_create(&pool, NULL);
    /* serf_initialize(); */
    bkt_alloc = serf_bucket_allocator_create(pool, NULL, NULL);

    /* Default to one round of fetching with no limit to max inflight reqs. */
    count = 1;
    inflight = 0;
    conn_count = 1;
    /* Default to GET. */
    method = "GET";
    /* Do not print headers by default. */
    print_headers = 0;
    /* Do not debug by default. */
    debug = 0;

    
    apr_getopt_init(&opt, pool, argc, argv);
    while ((status = apr_getopt_long(opt, options, &opt_c, &opt_arg)) ==
           APR_SUCCESS) {

        switch (opt_c) {
        case 'U':
            username = opt_arg;
            break;
        case 'P':
            password = opt_arg;
            break;
        case 'd':
            debug = 1;
            break;
        case 'f':
            req_body_path = opt_arg;
            break;
        case 'h':
            print_usage(pool);
            exit(0);
            break;
        case 'H':
            print_headers = 1;
            break;
        case 'm':
            method = opt_arg;
            break;
        case 'n':
            errno = 0;
            count = apr_strtoi64(opt_arg, NULL, 10);
            if (errno) {
                printf("Problem converting number of times to fetch URL (%d)\n",
                       errno);
                return errno;
            }
            break;
        case 'c':
            errno = 0;
            conn_count = apr_strtoi64(opt_arg, NULL, 10);
            if (errno) {
                printf("Problem converting number of concurrent connections to use (%d)\n",
                       errno);
                return errno;
            }

            if (conn_count <= 0) {
                printf("Invalid number of concurrent connections to use (%d)\n",
                       conn_count);
                return 1;
            }
            break;
        case 'x':
            errno = 0;
            inflight = apr_strtoi64(opt_arg, NULL, 10);
            if (errno) {
                printf("Problem converting number of requests to have outstanding (%d)\n",
                       errno);
                return errno;
            }
            break;
        case 'p':
            proxy = opt_arg;
            break;
        case 'r':
            {
                char *sep;
                char *hdr_val;

                if (req_hdrs == NULL) {
                    /* first request header, allocate bucket */
                    req_hdrs = serf_bucket_headers_create(bkt_alloc);
                }
                sep = strchr(opt_arg, ':');
                if ((sep == NULL) || (sep == opt_arg) || (strlen(sep) <= 1)) {
                    printf("Invalid request header string (%s)\n", opt_arg);
                    return EINVAL;
                }
                hdr_val = sep + 1;
                while (*hdr_val == ' ') {
                    hdr_val++;
                }
                serf_bucket_headers_setx(req_hdrs, opt_arg, (sep - opt_arg), 1,
                                         hdr_val, strlen(hdr_val), 1);
            }
            break;
        case CERTFILE:
            pem_path = opt_arg;
            break;
        case CERTPWD:
            pem_pwd = opt_arg;
            break;
        case 'v':
            puts("Serf version: " SERF_VERSION_STRING);
            exit(0);
        default:
            break;
        }
    }

    if (opt->ind != opt->argc - 1) {
        print_usage(pool);
        exit(-1);
    }

    raw_url = argv[opt->ind];

    apr_uri_parse(pool, raw_url, &url);
    if (!url.port) {
        url.port = apr_uri_port_of_scheme(url.scheme);
    }
    if (!url.path) {
        url.path = "/";
    }

    if (strcasecmp(url.scheme, "https") == 0) {
        app_ctx.using_ssl = 1;
    }
    else {
        app_ctx.using_ssl = 0;
    }

    if (strcasecmp(method, "HEAD") == 0) {
        app_ctx.head_request = 1;
    }
    else {
        app_ctx.head_request = 0;
    }

    app_ctx.hostinfo = url.hostinfo;
    app_ctx.pem_path = pem_path;
    app_ctx.pem_pwd = pem_pwd;

    context = serf_context_create(pool);
    app_ctx.serf_ctx = context;

    if (proxy)
    {
        apr_sockaddr_t *proxy_address = NULL;
        apr_port_t proxy_port;
        char *proxy_host;
        char *proxy_scope;

        status = apr_parse_addr_port(&proxy_host, &proxy_scope, &proxy_port, proxy, pool);
        if (status)
        {
            printf("Cannot parse proxy hostname/port: %d\n", status);
            apr_pool_destroy(pool);
            exit(1);
        }

        if (!proxy_host)
        {
            printf("Proxy hostname must be specified\n");
            apr_pool_destroy(pool);
            exit(1);
        }

        if (!proxy_port)
        {
            printf("Proxy port must be specified\n");
            apr_pool_destroy(pool);
            exit(1);
        }

        status = apr_sockaddr_info_get(&proxy_address, proxy_host, APR_UNSPEC,
                                       proxy_port, 0, pool);

        if (status)
        {
            printf("Cannot resolve proxy address '%s': %d\n", proxy_host, status);
            apr_pool_destroy(pool);
            exit(1);
        }

        serf_config_proxy(context, proxy_address);
    }

    if (username)
    {
        serf_config_authn_types(context, SERF_AUTHN_ALL);
    }
    else
    {
        serf_config_authn_types(context, SERF_AUTHN_NTLM | SERF_AUTHN_NEGOTIATE);
    }

    serf_config_credentials_callback(context, credentials_callback);

    /* Setup debug logging */
    if (debug)
    {
        serf_log_output_t *output;
        apr_status_t status;

        status = serf_logging_create_stream_output(&output,
                                                   context,
                                                   SERF_LOG_DEBUG,
                                                   SERF_LOGCOMP_ALL_MSG,
                                                   SERF_LOG_DEFAULT_LAYOUT,
                                                   stderr,
                                                   pool);

        if (!status)
            serf_logging_add_output(context, output);
    }

    /* ### Connection or Context should have an allocator? */
    app_ctx.bkt_alloc = bkt_alloc;

    connections = apr_pcalloc(pool, conn_count * sizeof(serf_connection_t*));
    for (i = 0; i < conn_count; i++)
    {
        conn_baton_t *conn_ctx = apr_pcalloc(pool, sizeof(*conn_ctx));
        conn_ctx->app = &app_ctx;
        conn_ctx->ssl_ctx = NULL;

        status = serf_connection_create2(&connections[i], context, url,
                                         conn_setup, conn_ctx,
                                         closed_connection, conn_ctx,
                                         pool);
        if (status) {
            printf("Error creating connection: %d\n", status);
            apr_pool_destroy(pool);
            exit(1);
        }

        serf_connection_set_max_outstanding_requests(connections[i], inflight);
    }

    handler_ctx.completed_requests = 0;
    handler_ctx.print_headers = print_headers;

#if APR_VERSION_AT_LEAST(1, 3, 0)
    apr_file_open_flags_stdout(&handler_ctx.output_file, APR_BUFFERED, pool);
#else
    apr_file_open_stdout(&handler_ctx.output_file, pool);
#endif

    handler_ctx.host = url.hostinfo;
    handler_ctx.method = method;
    handler_ctx.path = apr_pstrcat(pool,
                                   url.path,
                                   url.query ? "?" : "",
                                   url.query ? url.query : "",
                                   NULL);
    handler_ctx.username = username;
    handler_ctx.password = password;
    handler_ctx.auth_attempts = 0;

    handler_ctx.req_body_path = req_body_path;

    handler_ctx.acceptor = accept_response;
    handler_ctx.acceptor_baton = &app_ctx;
    handler_ctx.handler = handle_response;
    handler_ctx.req_hdrs = req_hdrs;

    for (i = 0; i < count; i++) {
        /* We don't need the returned request here. */
        serf_connection_request_create(connections[i % conn_count],
                                       setup_request, &handler_ctx);
    }

    while (1) {
        status = serf_context_run(context, SERF_DURATION_FOREVER, pool);
        if (APR_STATUS_IS_TIMEUP(status))
            continue;
        if (status) {
            char buf[200];
            const char *err_string;
            err_string = serf_error_string(status);
            if (!err_string) {
                err_string = apr_strerror(status, buf, sizeof(buf));
            }

            printf("Error running context: (%d) %s\n", status, err_string);
            apr_pool_destroy(pool);
            exit(1);
        }
        if (apr_atomic_read32(&handler_ctx.completed_requests) >= count) {
            break;
        }
        /* Debugging purposes only! */
        serf_debug__closed_conn(app_ctx.bkt_alloc);
    }

    apr_file_close(handler_ctx.output_file);

    for (i = 0; i < conn_count; i++)
    {
        serf_connection_close(connections[i]);
    }

    apr_pool_destroy(pool);
    return 0;
}
示例#15
0
文件: dbd.c 项目: Ga-vin/apache
int main(int argc, char** argv)
{
    const char *name;
    const char *params;
    apr_pool_t *pool = NULL;
    apr_dbd_t *sql = NULL;
    const apr_dbd_driver_t *driver = NULL;
    int rv;

    apr_initialize();
    apr_pool_create(&pool, NULL);

    if (argc >= 2 && argc <= 3) {
        name = argv[1];
        params = ( argc == 3 ) ? argv[2] : "";
        apr_dbd_init(pool);
        setbuf(stdout,NULL);
        rv = apr_dbd_get_driver(pool, name, &driver);
        switch (rv) {
        case APR_SUCCESS:
           printf("Loaded %s driver OK.\n", name);
           break;
        case APR_EDSOOPEN:
           printf("Failed to load driver file apr_dbd_%s.so\n", name);
           goto finish;
        case APR_ESYMNOTFOUND:
           printf("Failed to load driver apr_dbd_%s_driver.\n", name);
           goto finish;
        case APR_ENOTIMPL:
           printf("No driver available for %s.\n", name);
           goto finish;
        default:        /* it's a bug if none of the above happen */
           printf("Internal error loading %s.\n", name);
           goto finish;
        }
        rv = apr_dbd_open(driver, pool, params, &sql);
        switch (rv) {
        case APR_SUCCESS:
           printf("Opened %s[%s] OK\n", name, params);
           break;
        case APR_EGENERAL:
           printf("Failed to open %s[%s]\n", name, params);
           goto finish;
        default:        /* it's a bug if none of the above happen */
           printf("Internal error opening %s[%s]\n", name, params);
           goto finish;
        }
        TEST("create table", create_table);
        TEST("insert rows", insert_rows);
        TEST("invalid op", invalid_op);
        TEST("select random", select_random);
        TEST("select sequential", select_sequential);
        TEST("transactions", test_transactions);
        TEST("prepared select", test_pselect);
        TEST("prepared query", test_pquery);
        TEST("drop table", drop_table);
        apr_dbd_close(driver, sql);
    }
    else {
        fprintf(stderr, "Usage: %s driver-name [params]\n", argv[0]);
    }
finish:
    apr_pool_destroy(pool);
    apr_terminate();
    return 0;
}
示例#16
0
/* Standard svn test program */
int
main(int argc, const char *argv[])
{
  const char *prog_name;
  int i;
  svn_boolean_t got_error = FALSE;
  apr_pool_t *pool, *test_pool;
  svn_boolean_t ran_a_test = FALSE;
  svn_boolean_t list_mode = FALSE;
  int opt_id;
  apr_status_t apr_err;
  apr_getopt_t *os;
  svn_error_t *err;
  char errmsg[200];
  /* How many tests are there? */
  int array_size = get_array_size();

  svn_test_opts_t opts = { NULL };

  opts.fs_type = DEFAULT_FS_TYPE;

  /* Initialize APR (Apache pools) */
  if (apr_initialize() != APR_SUCCESS)
    {
      printf("apr_initialize() failed.\n");
      exit(1);
    }

  /* set up the global pool.  Use a separate allocator to limit memory
   * usage but make it thread-safe to allow for multi-threaded tests.
   */
  pool = apr_allocator_owner_get(svn_pool_create_allocator(TRUE));

  /* Remember the command line */
  test_argc = argc;
  test_argv = argv;

  err = svn_cmdline__getopt_init(&os, argc, argv, pool);

  os->interleave = TRUE; /* Let options and arguments be interleaved */

  /* Strip off any leading path components from the program name.  */
  prog_name = strrchr(argv[0], '/');
  if (prog_name)
    prog_name++;
  else
    {
      /* Just check if this is that weird platform that uses \ instead
         of / for the path separator. */
      prog_name = strrchr(argv[0], '\\');
      if (prog_name)
        prog_name++;
      else
        prog_name = argv[0];
    }

  if (err)
    return svn_cmdline_handle_exit_error(err, pool, prog_name);
  while (1)
    {
      const char *opt_arg;

      /* Parse the next option. */
      apr_err = apr_getopt_long(os, cl_options, &opt_id, &opt_arg);
      if (APR_STATUS_IS_EOF(apr_err))
        break;
      else if (apr_err && (apr_err != APR_BADCH))
        {
          /* Ignore invalid option error to allow passing arbitary options */
          fprintf(stderr, "apr_getopt_long failed : [%d] %s\n",
                  apr_err, apr_strerror(apr_err, errmsg, sizeof(errmsg)));
          exit(1);
        }

      switch (opt_id) {
        case cleanup_opt:
          cleanup_mode = TRUE;
          break;
        case config_opt:
          opts.config_file = apr_pstrdup(pool, opt_arg);
          break;
        case fstype_opt:
          opts.fs_type = apr_pstrdup(pool, opt_arg);
          break;
        case list_opt:
          list_mode = TRUE;
          break;
        case mode_filter_opt:
          if (svn_cstring_casecmp(opt_arg, "PASS") == 0)
            mode_filter = svn_test_pass;
          else if (svn_cstring_casecmp(opt_arg, "XFAIL") == 0)
            mode_filter = svn_test_xfail;
          else if (svn_cstring_casecmp(opt_arg, "SKIP") == 0)
            mode_filter = svn_test_skip;
          else if (svn_cstring_casecmp(opt_arg, "ALL") == 0)
            mode_filter = svn_test_all;
          else
            {
              fprintf(stderr, "FAIL: Invalid --mode-filter option.  Try ");
              fprintf(stderr, " PASS, XFAIL, SKIP or ALL.\n");
              exit(1);
            }
          break;
        case verbose_opt:
          verbose_mode = TRUE;
          break;
        case quiet_opt:
          quiet_mode = TRUE;
          break;
        case allow_segfault_opt:
          allow_segfaults = TRUE;
          break;
        case server_minor_version_opt:
          {
            char *end;
            opts.server_minor_version = (int) strtol(opt_arg, &end, 10);
            if (end == opt_arg || *end != '\0')
              {
                fprintf(stderr, "FAIL: Non-numeric minor version given\n");
                exit(1);
              }
            if ((opts.server_minor_version < 3)
                || (opts.server_minor_version > 6))
              {
                fprintf(stderr, "FAIL: Invalid minor version given\n");
                exit(1);
              }
          }
      }
    }

  /* Disable sleeping for timestamps, to speed up the tests. */
  apr_env_set(
         "SVN_I_LOVE_CORRUPTED_WORKING_COPIES_SO_DISABLE_SLEEP_FOR_TIMESTAMPS",
         "yes", pool);

  /* You can't be both quiet and verbose. */
  if (quiet_mode && verbose_mode)
    {
      fprintf(stderr, "FAIL: --verbose and --quiet are mutually exclusive\n");
      exit(1);
    }

  /* Create an iteration pool for the tests */
  cleanup_pool = svn_pool_create(pool);
  test_pool = svn_pool_create(pool);

  if (!allow_segfaults)
    svn_error_set_malfunction_handler(svn_error_raise_on_malfunction);

  if (argc >= 2)  /* notice command-line arguments */
    {
      if (! strcmp(argv[1], "list") || list_mode)
        {
          const char *header_msg;
          ran_a_test = TRUE;

          /* run all tests with MSG_ONLY set to TRUE */
          header_msg = "Test #  Mode   Test Description\n"
                       "------  -----  ----------------\n";
          for (i = 1; i <= array_size; i++)
            {
              if (do_test_num(prog_name, i, TRUE, &opts, &header_msg,
                              test_pool))
                got_error = TRUE;

              /* Clear the per-function pool */
              svn_pool_clear(test_pool);
              svn_pool_clear(cleanup_pool);
            }
        }
      else
        {
          for (i = 1; i < argc; i++)
            {
              if (svn_ctype_isdigit(argv[i][0]) || argv[i][0] == '-')
                {
                  int test_num = atoi(argv[i]);
                  if (test_num == 0)
                    /* A --option argument, most likely. */
                    continue;

                  ran_a_test = TRUE;
                  if (do_test_num(prog_name, test_num, FALSE, &opts, NULL,
                                  test_pool))
                    got_error = TRUE;

                  /* Clear the per-function pool */
                  svn_pool_clear(test_pool);
                  svn_pool_clear(cleanup_pool);
                }
            }
        }
    }

  if (! ran_a_test)
    {
      /* just run all tests */
      for (i = 1; i <= array_size; i++)
        {
          if (do_test_num(prog_name, i, FALSE, &opts, NULL, test_pool))
            got_error = TRUE;

          /* Clear the per-function pool */
          svn_pool_clear(test_pool);
          svn_pool_clear(cleanup_pool);
        }
    }

  /* Clean up APR */
  svn_pool_destroy(pool);      /* takes test_pool with it */
  apr_terminate();

  return got_error;
}
示例#17
0
int
main(int argc, char **argv)
{
  apr_file_t *source_file_A = NULL;
  apr_file_t *target_file_A = NULL;
  int count_A = 0;
  apr_off_t len_A = 0;

  apr_file_t *source_file_B = NULL;
  apr_file_t *target_file_B = NULL;
  int count_B = 0;
  apr_off_t len_B = 0;

  apr_pool_t *pool;
  int quiet = 0;

  if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'q')
    {
      quiet = 1;
      --argc; ++argv;
    }

  apr_initialize();
  pool = svn_pool_create(NULL);

  if (argc == 2)
    {
      target_file_A = open_binary_read(argv[1], pool);
    }
  else if (argc == 3)
    {
      source_file_A = open_binary_read(argv[1], pool);
      target_file_A = open_binary_read(argv[2], pool);
    }
  else if (argc == 4)
    {
      source_file_A = open_binary_read(argv[1], pool);
      target_file_A = open_binary_read(argv[2], pool);
      source_file_B = open_binary_read(argv[2], pool);
      target_file_B = open_binary_read(argv[3], pool);
    }
  else
    {
      fprintf(stderr,
              "Usage: vdelta-test [-q] <target>\n"
              "   or: vdelta-test [-q] <source> <target>\n"
              "   or: vdelta-test [-q] <source> <intermediate> <target>\n");
      exit(1);
    }

  do_one_diff(source_file_A, target_file_A,
              &count_A, &len_A, quiet, pool, "A ", stdout);

  if (source_file_B)
    {
      apr_pool_t *fpool = svn_pool_create(pool);
      apr_pool_t *wpool = svn_pool_create(pool);
      svn_txdelta_stream_t *stream_A = NULL;
      svn_txdelta_stream_t *stream_B = NULL;
      svn_txdelta_window_t *window_A = NULL;
      svn_txdelta_window_t *window_B = NULL;
      svn_txdelta_window_t *window_AB = NULL;
      int count_AB = 0;
      apr_off_t len_AB = 0;

      putc('\n', stdout);
      do_one_diff(source_file_B, target_file_B,
                  &count_B, &len_B, quiet, pool, "B ", stdout);

      putc('\n', stdout);

      {
        apr_off_t offset = 0;

        apr_file_seek(source_file_A, APR_SET, &offset);
        apr_file_seek(target_file_A, APR_SET, &offset);
        apr_file_seek(source_file_B, APR_SET, &offset);
        apr_file_seek(target_file_B, APR_SET, &offset);
      }

      svn_txdelta(&stream_A,
                  svn_stream_from_aprfile(source_file_A, fpool),
                  svn_stream_from_aprfile(target_file_A, fpool),
                  fpool);
      svn_txdelta(&stream_B,
                  svn_stream_from_aprfile(source_file_B, fpool),
                  svn_stream_from_aprfile(target_file_B, fpool),
                  fpool);

      for (count_AB = 0; count_AB < count_B; ++count_AB)
        {
          svn_error_t *err;

          err = svn_txdelta_next_window(&window_A, stream_A, wpool);
          if (err)
            svn_handle_error2(err, stderr, TRUE, "vdelta-test: ");
          err = svn_txdelta_next_window(&window_B, stream_B, wpool);
          if (err)
            svn_handle_error2(err, stderr, TRUE, "vdelta-test: ");

          /* Note: It's not possible that window_B is null, we already
             counted the number of windows in the second delta. */
          assert(window_A != NULL || window_B->src_ops == 0);
          if (window_B->src_ops == 0)
            {
              window_AB = window_B;
              window_AB->sview_len = 0;
            }
          else
            window_AB = svn_txdelta_compose_windows(window_A, window_B,
                                                    wpool);
          len_AB += print_delta_window(window_AB, "AB", quiet, stdout);
          svn_pool_clear(wpool);
        }

      fprintf(stdout, "AB: (LENGTH %" APR_OFF_T_FMT " +%d)\n",
              len_AB, count_AB);
    }

  if (source_file_A) apr_file_close(source_file_A);
  if (target_file_A) apr_file_close(target_file_A);
  if (source_file_B) apr_file_close(source_file_B);
  if (target_file_B) apr_file_close(source_file_B);

  svn_pool_destroy(pool);
  apr_terminate();
  exit(0);
}
示例#18
0
/* TODO: Comment */
static void *doit(void *a){
  int rc, thread_id = (pthread_t) a;
  FCGX_Request request;
  apr_pool_t* pool;
  struct range_request* rr;
  struct libcrange *lr;
  char *config_file = NULL;
  char * r_query;		/* range query */
  int r_status = 0;

  apr_initialize();
  atexit(apr_terminate);
  apr_pool_create(&pool, NULL);

  config_file = LIBCRANGE_CONF;

  lr = libcrange_new(pool, config_file);

  /* malloc for query */
  r_query = (char *)malloc(QUERY_STR_SIZE);

  FCGX_InitRequest(&request, 0, 0);

  for (;;)
    {
      static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;

      apr_pool_t* sub_pool;

      apr_pool_create(&sub_pool, pool);

      /* zero it out */
      bzero(r_query, QUERY_STR_SIZE);
      r_status = 0;
	

      /* Some platforms require accept() serialization, some don't.. */
      pthread_mutex_lock(&accept_mutex);
      rc = FCGX_Accept_r(&request);
      pthread_mutex_unlock(&accept_mutex);

      if (rc < 0)
	break;

      
      r_status = get_range_query(&request, r_query);
      rr = range_expand(lr, sub_pool, r_query);

      FCGX_FPrintF(request.out, "Content-type: text/plain\r\n");
      
      /* set headers */
      if (range_request_has_warnings(rr)) {
      	const char *warnings = range_request_warnings(rr);
      	FCGX_FPrintF(request.out,
      		     "RangeException: %s\r\nRange_FCGI_Thread_Id: %d\r\n",
      		     warnings, thread_id);
      }

      /* End Delimiter */
      FCGX_FPrintF(request.out, "\r\n");

      /* r_status == 1, then wants list */
      if (r_status == 1) {
      	const char **nodes = range_request_nodes(rr);
      	while(*nodes) {
      	  FCGX_FPrintF(request.out, "%s\n", *nodes++);
      	}
      } else if (r_status == 0) {
      	FCGX_FPrintF(request.out, "%s\n", range_request_compressed(rr));
      }
      
      apr_pool_destroy(sub_pool);

      FCGX_Finish_r(&request);

    } /* for (;;) */

  /* free, what I hogged :-) */
  free(r_query);

  apr_pool_destroy(pool);

  return NULL;
}
示例#19
0
文件: bench_rpc.c 项目: Abioy/mpaxos
int main(int argc, char **argv) {
//    for (int i=1; i<NSIG; i++) {
//        //if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n");
//        if (signal(i, sig_handler) == SIG_ERR) printf("\ncan't catch %s\n", strsignal(i));
//    }
    signal(SIGPIPE, SIG_IGN);

    apr_initialize();

    apr_pool_create(&mp_rpc_, NULL);
    apr_thread_cond_create(&cd_rpc_, mp_rpc_);
    apr_thread_mutex_create(&mx_rpc_, APR_THREAD_MUTEX_UNNESTED, mp_rpc_);
    rpc_init();

    arg_parse(argc, argv);
    ADD = is_fast_ ? FAST_ADD : SLOW_ADD;
    bool exit = false;

    exit |=  !(is_server_ || is_client_);
    exit |= (addr_ == NULL);
    exit |= (port_ == 0);

    if (exit) {
	fprintf(stderr, "wrong arguments.\n");
	usage(argv[0]);
	return 0;
    }

    if (is_server_) {
        server_t *server = NULL;
	poll_mgr_t *mgr_server = NULL;
	poll_mgr_create(&mgr_server, n_server_thread_);
        server_create(&server, mgr_server);    
        strcpy(server->comm->ip, addr_);
        server->comm->port = port_;
        server_reg(server, ADD, add); 
        server_start(server);
        LOG_INFO("server started start on %s, port %d.", addr_, port_);
    } 
    
    if (is_client_) {
	LOG_INFO("client to %s:%d, test for %d rpc in total, outstanding rpc: %d",
		 addr_, port_, max_rpc_, max_outst_);

	mgrs_ = (poll_mgr_t **) malloc(n_client_ * sizeof(poll_mgr_t*));
	clis_ = (client_t **) malloc(n_client_ * sizeof(client_t *));
	n_issues_ = (uint64_t*) malloc(n_client_ * sizeof(uint64_t));	
	n_callbacks_ = (uint64_t*) malloc(n_client_ * sizeof(uint64_t));
	n_active_cli_ = n_client_;
       
        apr_thread_mutex_lock(mx_rpc_);
        for (int i = 0; i < n_client_; i++) {
            apr_thread_t *th;
            apr_thread_create(&th, NULL, client_thread, (intptr_t) i, mp_rpc_);
        }
	
	
	if (max_rpc_ < 0) {
	    LOG_INFO("infinite rpc on %d threads (clients)", n_client_);
	} else {
	    LOG_INFO("%d threads (clients), each client run for %d rpc.", 
		     n_client_, max_rpc_ * n_client_);
	}

        apr_thread_cond_wait(cd_rpc_, mx_rpc_);
        apr_thread_mutex_unlock(mx_rpc_);

        int period = (tm_end_ - tm_begin_); //micro seconds
        LOG_INFO("finish %d rpc in %d ms.", max_rpc_ * n_client_, period/1000);
        float rate = (float) max_rpc_ * n_client_ / period;
        LOG_INFO("rpc rate %f million per sec.", rate);
	
	for (int i = 0; i < n_client_; i++) {
	    client_destroy(clis_[i]);
	    poll_mgr_destroy(mgrs_[i]);
	}
	free (clis_);
	free (n_issues_);
    }

    fflush(stdout);
    fflush(stderr);

    while(is_server_) {
	apr_sleep(1000000);
    }

    rpc_destroy();
    atexit(apr_terminate);
}
示例#20
0
文件: fun_apr.c 项目: Abioy/mpaxos
int main(int argc, char** argv) {
    apr_pool_t *mp;
    apr_hash_t *ht;

    //Initialize
    apr_initialize();
    apr_pool_create(&mp, NULL);

    ht = apr_hash_make(mp);

//  char key[100] = "key1";
//  char val[100] = "val1";
//  char val2[100] = "val2";
//
//  //test a string
//  //apr_hash_set(ht, key, APR_HASH_KEY_STRING, val);
//  void *val_ptr;
//  //val_ptr = apr_hash_get(ht, key, APR_HASH_KEY_STRING);
//  //printf("%s\n", val_ptr);
//
//  //test for different key;
//  char *k1 = (char *)malloc(100);
//  char *k2 = (char *)malloc(100);
//  strcpy(k1, key);
//  strcpy(k2, key);
//  apr_hash_set(ht, k1, APR_HASH_KEY_STRING, val);
////    free(k1);
//  val_ptr = apr_hash_get(ht, k2, APR_HASH_KEY_STRING);
////    printf("%s\t",
//  printf("%s\n", val_ptr);
//
////    free(k1);
//
//  printf("count:%d\n", apr_hash_count(ht));
//
//  apr_hash_set(ht, k2, APR_HASH_KEY_STRING, val);
//  free(k1);
//  free(k2);
//
//  apr_hash_index_t *hi;
//  for (hi = apr_hash_first(mp, ht); hi; hi = apr_hash_next(hi)) {
//      void *k, *v;
//      apr_hash_this(hi, &k, NULL, &v);
//      printf("k:%s\t", k);
//      printf("v:%s\n", v);
//  }

//  // TEST FOR INVALID KEY;
//  // This test has some problem.
//  int COUNT = 10000000;
//  char *key;
//  char *value;
//  int i;
//  for (i = 0; i < COUNT; i++) {
//      key = (char *)malloc(10);
//      memset(key, 0, 10);
//      value   = (char *)malloc(10);
//      sprintf(key, "%d", i);
//      sprintf(value, "%d", i);
//      apr_hash_set(ht, key, 10, value);
//      free(key);
//  }
//
//  printf("Start to iterate.\n");
//  apr_hash_index_t *hi;
//  for (hi = apr_hash_first(mp, ht); hi; hi = apr_hash_next(hi)) {
//      void *k, *v;
//      apr_hash_this(hi, &k, NULL, &v);
//  //  printf("k:%s\t", k);
//      printf("v:%s\n", v);
//  }
//
//  printf("Start to validate.\n");
//  for (i = 0; i < COUNT; i++) {
//      char *k = (char*) malloc(10);
//      memset(k, 0, 10);
//      char *v;
//      sprintf(k, "%d", i);
//      v = apr_hash_get(ht, k, 10);
//      if (v == NULL) {
//          printf("ERROR, value is null");
//          break;
//      }
//      int vint = atoi(v);
//      printf("Test key:%s value:%s\n", k, v);
//      if (vint != i) {
//          printf("ERROR, not equal %d %d", i, vint);
//      }
//      free(k);
//  }

//  char key[100];
//  char val[100];
//  sprintf(value, "hello world!");
//  sprintf(key, "k1");
//  apr_hash_set(ht, key, 2, val);
////    sprintf(key, "k2");
//  void *r = apr_hash_get(ht, "k1", 2);
//  if (r == NULL) {
//      printf("cannot find k1\n");
//  } else {
//      printf("found k1, val: %s\n", r);
//  }
//
//  r = apr_hash_get(ht, "k2", 2);
//  if (r == NULL) {
//      printf("cannot find k2\n");
//  } else {
//      printf("found k2, val: %s\n", r);
//  }


    char k1[100];
    char k2[100];
    char val[100];
    sprintf(val, "hello world!");
    sprintf(k1, "key");
    sprintf(k2, "key");
    apr_hash_set(ht, k1, 3, val);
    apr_hash_set(ht, k2, 3, val);

    sprintf(k1, "key1");
    sprintf(k2, "key2");

    apr_hash_index_t *hi;
    for (hi = apr_hash_first(mp, ht); hi; hi = apr_hash_next(hi)) {
        void *k, *v;
        apr_hash_this(hi, &k, NULL, &v);
        printf("k:%s\t", k);
        printf("v:%s\n", v);
    }

    //Finalize;
    apr_pool_destroy(mp);
    apr_terminate();
    return 0;
}
示例#21
0
int main(int argc, char **argv) {
//    for (int i=1; i<NSIG; i++) {
//        //if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n");
//        if (signal(i, sig_handler) == SIG_ERR) printf("\ncan't catch %s\n", strsignal(i));
//    }
    signal(SIGPIPE, SIG_IGN);

    apr_initialize();
    apr_pool_create(&mp_rpc_, NULL);
    apr_thread_cond_create(&cd_rpc_, mp_rpc_);
    apr_thread_mutex_create(&mx_rpc_, APR_THREAD_MUTEX_UNNESTED, mp_rpc_);
    rpc_init();

    arg_parse(argc, argv);

    bool exit = false;

    exit |=  !(is_server_ || is_client_);
    exit |= (addr_ == NULL);
    exit |= (port_ == 0);

    if (exit) {
	fprintf(stderr, "wrong arguments.\n");
	usage(argv[0]);
	return 0;
    }

    if (is_server_) {
        server_t *server = NULL;
        server_create(&server, NULL);    
        strcpy(server->comm->ip, addr_);
        server->comm->port = port_;
        server_reg(server, ADD, add); 
        server_start(server);
        LOG_INFO("server started start on %s, port %d.", addr_, port_);
    } 
    
    if (is_client_) {
	LOG_INFO("client to %s:%d, test for %d rpc in total, outstanding rpc: %d", addr_, port_, max_rpc_, max_outst_);
       
        apr_thread_mutex_lock(mx_rpc_);
        for (int i = 0; i < n_client_; i++) {
            apr_thread_t *th;
            apr_thread_create(&th, NULL, client_thread, NULL, mp_rpc_);
        }
        LOG_INFO("rpc triggered for %d adds on %d threads.", max_rpc_ * n_client_, n_client_);
        apr_thread_cond_wait(cd_rpc_, mx_rpc_);
        apr_thread_mutex_unlock(mx_rpc_);

        int period = (tm_end_ - tm_begin_); //micro seconds
        LOG_INFO("finish %d rpc in %d ms.", max_rpc_ * n_client_, period/1000);
        float rate = (float) max_rpc_ * n_client_ / period;
        LOG_INFO("rpc rate %f million per sec.", rate);
    }

    fflush(stdout);
    fflush(stderr);

    while(is_server_) {
	apr_sleep(1000000);
    }

    rpc_destroy();
    atexit(apr_terminate);
}
示例#22
0
int
main ( int argc, char *argv[] )
{
   int rc;
   struct stat struct_stat;
   pthread_t pid;
   pthread_attr_t attr;
   int i, num_sources;
   uid_t gmetad_uid;
   mode_t rrd_umask;
   char * gmetad_username;
   struct passwd *pw;
   gmetad_config_t *c = &gmetad_config;
   apr_interval_time_t sleep_time;
   apr_time_t last_metadata;
   double random_sleep_factor;
   unsigned int rand_seed;

   rc = apr_initialize();
   if (rc != APR_SUCCESS) {
      return -1;
   }

   /* create a memory pool. */
   apr_pool_create(&global_context, NULL);

   /* Ignore SIGPIPE */
   signal( SIGPIPE, SIG_IGN );

   initialize_scoreboard();

   /* Mark the time this gmetad started */
   started = apr_time_now();

   if (cmdline_parser(argc, argv, &args_info) != 0)
      err_quit("command-line parser error");

   num_sources = number_of_datasources( args_info.conf_arg );
   if(!num_sources)
      {
         err_quit("%s doesn't have any data sources specified", args_info.conf_arg);
      }

   memset(&root, 0, sizeof(root));
   root.id = ROOT_NODE;

   /* Get the real number of data sources later */
   sources = hash_create( num_sources + 10 );
   if (! sources )
      {
         err_quit("Unable to create sources hash\n");
      }

   root.authority = hash_create( num_sources + 10 );
   if (!root.authority)
      {
         err_quit("Unable to create root authority (our grids and clusters) hash\n");
      }

   root.metric_summary = hash_create (DEFAULT_METRICSIZE);
   if (!root.metric_summary)
      {
         err_quit("Unable to create root summary hash");
      }

   parse_config_file ( args_info.conf_arg );
    /* If given, use command line directives over config file ones. */
   if (args_info.debug_given)
      {
         c->debug_level = args_info.debug_arg;
      }
   debug_level = c->debug_level;
   set_debug_msg_level(debug_level);

   /* Setup our default authority pointer if the conf file hasnt yet.
    * Done in the style of hash node strings. */
   if (!root.stringslen)
      {
         gethostname(hostname, HOSTNAMESZ);
         root.authority_ptr = 0;
         sprintf(root.strings, "http://%s/ganglia/", hostname);
         root.stringslen += strlen(root.strings) + 1;
      }

   rand_seed = apr_time_now() * (int)pthread_self();
   for(i = 0; i < root.stringslen; rand_seed = rand_seed * root.strings[i++]);

   /* Debug level 1 is error output only, and no daemonizing. */
   if (!debug_level)
      {
         rrd_umask = c->umask;
         daemon_init (argv[0], 0, rrd_umask);
      }

   if (args_info.pid_file_given)
     {
       update_pidfile (args_info.pid_file_arg);
     }

   /* The rrd_rootdir must be writable by the gmetad process */
   if( c->should_setuid )
      {
         if(! (pw = getpwnam(c->setuid_username)))
            {
               err_sys("Getpwnam error");
            }
         gmetad_uid = pw->pw_uid;
         gmetad_username = c->setuid_username;
      }
   else
      {
         gmetad_uid = getuid();
         if(! (pw = getpwuid(gmetad_uid)))
            {
               err_sys("Getpwnam error");
            } 
         gmetad_username = strdup(pw->pw_name);
      }

   debug_msg("Going to run as user %s", gmetad_username);
   if( c->should_setuid )
      {
         become_a_nobody(c->setuid_username);
      }

   if( c->write_rrds )
      {
         if( stat( c->rrd_rootdir, &struct_stat ) )
            {
                err_sys("Please make sure that %s exists", c->rrd_rootdir);
            }
         if ( struct_stat.st_uid != gmetad_uid )
            {
                err_quit("Please make sure that %s is owned by %s", c->rrd_rootdir, gmetad_username);
            }
         if (! (struct_stat.st_mode & S_IWUSR) )
            {
                err_quit("Please make sure %s has WRITE permission for %s", gmetad_username, c->rrd_rootdir);
            }
      }

   if(debug_level)
      {
         fprintf(stderr,"Sources are ...\n");
         hash_foreach( sources, print_sources, NULL);
      }

#ifdef WITH_MEMCACHED
   if (c->memcached_parameters != NULL)
      {
         memcached_connection_pool = memcached_pool(c->memcached_parameters, strlen(c->memcached_parameters));
      }
#endif /* WITH_MEMCACHED */

   server_socket = g_tcp_socket_server_new( c->xml_port );
   if (server_socket == NULL)
      {
         err_quit("tcp_listen() on xml_port failed");
      }
   debug_msg("xml listening on port %d", c->xml_port);
   
   interactive_socket = g_tcp_socket_server_new( c->interactive_port );
   if (interactive_socket == NULL)
      {
         err_quit("tcp_listen() on interactive_port failed");
      }
   debug_msg("interactive xml listening on port %d", c->interactive_port);

    /* Forward metrics to Graphite using carbon protocol */
    if (c->carbon_server != NULL)
      {
         if (!strcmp(c->carbon_protocol, "udp"))
            {
               carbon_udp_socket = init_carbon_udp_socket (c->carbon_server, c->carbon_port);

               if (carbon_udp_socket == NULL)
                  err_quit("carbon %s socket failed for %s:%d", c->carbon_protocol, c->carbon_server, c->carbon_port);
            }
         debug_msg("carbon forwarding ready to send via %s to %s:%d", c->carbon_protocol, c->carbon_server, c->carbon_port);
      }

#ifdef WITH_RIEMANN
    if (c->riemann_server !=NULL)
      {
         if (!strcmp(c->riemann_protocol, "udp"))
            {
               riemann_udp_socket = init_riemann_udp_socket (c->riemann_server, c->riemann_port);

               if (riemann_udp_socket == NULL)
                  err_quit("[riemann] %s socket failed for %s:%d", c->riemann_protocol, c->riemann_server, c->riemann_port);
            } else {
               err_quit("[riemann] TCP transport not supported yet.");
            }
         debug_msg("[riemann] ready to forward metrics via %s to %s:%d", c->riemann_protocol, c->riemann_server, c->riemann_port);
      }
#endif /* WITH_RIEMANN */

   /* initialize summary mutex */
   root.sum_finished = (pthread_mutex_t *) 
                          malloc(sizeof(pthread_mutex_t));
   pthread_mutex_init(root.sum_finished, NULL);

   pthread_attr_init( &attr );
   pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED );

   /* Spin off the non-interactive server threads. (Half as many as interactive). */
   for (i=0; i < c->server_threads/2; i++)
      pthread_create(&pid, &attr, server_thread, (void*) 0);

   /* Spin off the interactive server threads. */
   for (i=0; i < c->server_threads; i++)
      pthread_create(&pid, &attr, server_thread, (void*) 1);

   hash_foreach( sources, spin_off_the_data_threads, NULL );

   /* A thread to cleanup old metrics and hosts */
   pthread_create(&pid, &attr, cleanup_thread, (void *) NULL);
   debug_msg("cleanup thread has been started");

    /* Meta data */
   last_metadata = 0;
   for(;;)
      {
         /* Do at a random interval, between 
                 (shortest_step/2) +/- METADATA_SLEEP_RANDOMIZE percent */
         random_sleep_factor = (1 + (METADATA_SLEEP_RANDOMIZE / 50.0) * ((rand_r(&rand_seed) - RAND_MAX/2)/(float)RAND_MAX));
         sleep_time = random_sleep_factor * apr_time_from_sec(c->shortest_step) / 2;
         /* Make sure the sleep time is at least 1 second */
         if(apr_time_sec(apr_time_now() + sleep_time) < (METADATA_MINIMUM_SLEEP + apr_time_sec(apr_time_now())))
            sleep_time += apr_time_from_sec(METADATA_MINIMUM_SLEEP);
         apr_sleep(sleep_time);

         /* Need to be sure root is locked while doing summary */
         pthread_mutex_lock(root.sum_finished);

         /* Flush the old values */
         hash_foreach(root.metric_summary, zero_out_summary, NULL);
         root.hosts_up = 0;
         root.hosts_down = 0;

         /* Sum the new values */
         hash_foreach(root.authority, do_root_summary, NULL );

         /* summary completed */
         pthread_mutex_unlock(root.sum_finished);

         /* Save them to RRD */
         hash_foreach(root.metric_summary, write_root_summary, NULL);

         /* Remember our last run */
         last_metadata = apr_time_now();
      }

   apr_pool_destroy(global_context);

   apr_terminate();
   return 0;
}
示例#23
0
int main(int argc, char *argv[])
{
    apr_pool_t *p;
    apr_socket_t *sock;
    apr_status_t rv;
    apr_sockaddr_t *remote_sa;

    apr_initialize();
    atexit(apr_terminate);
    apr_pool_create(&p, NULL);

    if (argc < 3) {
        exit(-1);
    }

    rv = apr_sockaddr_info_get(&remote_sa, argv[2], APR_UNSPEC, 8021, 0, p);
    if (rv != APR_SUCCESS) {
        exit(-1);
    }

    if (apr_socket_create(&sock, remote_sa->family, SOCK_STREAM, 0,
                p) != APR_SUCCESS) {
        exit(-1);
    }

    rv = apr_socket_timeout_set(sock, apr_time_from_sec(3));
    if (rv) {
        exit(-1);
    }

    apr_socket_connect(sock, remote_sa);
        
    if (!strcmp("read", argv[1])) {
        char datarecv[STRLEN];
        apr_size_t length = STRLEN;
        apr_status_t rv;

        memset(datarecv, 0, STRLEN);
        rv = apr_socket_recv(sock, datarecv, &length);
        apr_socket_close(sock);
        if (APR_STATUS_IS_TIMEUP(rv)) {
            exit(SOCKET_TIMEOUT); 
        }

        if (strcmp(datarecv, DATASTR)) {
            exit(-1);
        }
        
        exit((int)length);
    }
    else if (!strcmp("write", argv[1])
             || !strcmp("write_after_delay", argv[1])) {
        apr_size_t length = strlen(DATASTR);

        if (!strcmp("write_after_delay", argv[1])) {
            apr_sleep(apr_time_from_sec(2));
        }

        apr_socket_send(sock, DATASTR, &length);

        apr_socket_close(sock);
        exit((int)length);
    }
    else if (!strcmp("close", argv[1])) {
        apr_socket_close(sock);
        exit(0);
    }
    exit(-1);
}
示例#24
0
int main(int argc, const char * const *argv)
{
	apr_pool_t *pool;
	apr_status_t rv;
	apr_getopt_t *opt;
	apt_bool_t ret = TRUE;
	uni_service_register_e reg = USR_NONE;
	uni_service_control_e control = USC_NONE;
	const char *root_dir = "..";
	const char *name = NULL;
	apt_bool_t autostart = FALSE;
	unsigned long recover = 0;
	int log_priority = -1;
	const char *disp_name = NULL;
	const char *description = NULL;

	static const apr_getopt_option_t opt_option[] = {
		/* long-option, short-option, has-arg flag, description */
		{ "register",    'r', TRUE,  "register service" },   /* -r or --register arg */
		{ "unregister",  'u', FALSE, "unregister service" }, /* -u or --unregister */
		{ "start",       's', FALSE, "start service" },      /* -s or --start */
		{ "stop",        't', FALSE, "stop service" },       /* -t or --stop */
		{ "name",        'n', TRUE,  "service name" },       /* -n or --name arg */
		{ "autostart",   'a', FALSE, "start automatically" },/* -a or --autostart */
		{ "fail-restart",'f', TRUE,  "restart if fails" },   /* -f or --fail-restart arg */
		{ "log-prio",    'l', TRUE,  "log priority" },       /* -l arg or --log-prio arg */
		{ "disp-name",   'p', TRUE,  "display name" },       /* -p arg or --disp-name arg */
		{ "description", 'c', TRUE,  "description" },        /* -c arg or --description arg */
		{ "help",        'h', FALSE, "show help" },          /* -h or --help */
		{ NULL, 0, 0, NULL },                                /* end */
	};

	/* APR global initialization */
	if(apr_initialize() != APR_SUCCESS) {
		apr_terminate();
		return 1;
	}

	/* create APR pool */
	pool = apt_pool_create();
	if(!pool) {
		apr_terminate();
		return 1;
	}

	rv = apr_getopt_init(&opt, pool , argc, argv);
	if(rv == APR_SUCCESS) {
		int optch;
		const char *optarg;
		while((rv = apr_getopt_long(opt, opt_option, &optch, &optarg)) == APR_SUCCESS) {
			switch(optch) {
				case 'r':
					if ((reg == USR_NONE) || (reg == USR_REGISTER)) {
						reg = USR_REGISTER;
						root_dir = optarg;
					} else {
						puts("Incosistent arguments");
						ret = FALSE;
					}
					break;
				case 'u':
					if ((reg == USR_NONE) || (reg == USR_UNREGISTER))
						reg = USR_UNREGISTER;
					else {
						puts("Incosistent arguments");
						ret = FALSE;
					}
					break;
				case 's':
					if ((control == USC_NONE) || (control == USC_START))
						control = USC_START;
					else {
						puts("Incosistent arguments");
						ret = FALSE;
					}
					break;
				case 't':
					if ((control == USC_NONE) || (control == USC_STOP))
						control = USC_STOP;
					else {
						puts("Incosistent arguments");
						ret = FALSE;
					}
					break;
				case 'n':
					name = optarg;
					break;
				case 'a':
					autostart = TRUE;
					break;
				case 'f':
					if (sscanf(optarg, "%lu", &recover) != 1) {
						puts("Invalid value for param --fail-restart");
						ret = FALSE;
					}
					break;
				case 'l':
					if ((sscanf(optarg, "%d", &log_priority) != 1) ||
						(log_priority < 0) || (log_priority > 7))
					{
						puts("Invalid value for param --log-prio");
						ret = FALSE;
					}
					break;
				case 'p':
					disp_name = optarg;
					break;
				case 'c':
					description = optarg;
					break;
				case 'h':
					usage();
					break;
			}
			if (!ret) break;
		}
		if (ret &&
				(((reg == USR_REGISTER) && (control == USC_STOP)) ||
				((reg == USR_UNREGISTER) && (control == USC_START)))) {
			ret = FALSE;
			puts("Inconsistent arguments");
		}
		if((rv != APR_EOF) || !ret || (!reg && !control)) {
			ret = FALSE;
			usage();
		}
	}

	while (ret) {  /* No problem so far */
		if (reg == USR_REGISTER)
			ret = uni_service_register(root_dir, pool, name, autostart, recover, log_priority, disp_name, description);
		if (!ret) break;

		if (control == USC_START)
			ret = uni_service_start(name);
		if (!ret) break;

		if (control == USC_STOP)
			ret = uni_service_stop(name);
		/* Do not break here, stop failure should not matter before unregistration */

		if (reg == USR_UNREGISTER)
			ret = uni_service_unregister(name);
		break;
	}

	/* destroy APR pool */
	apr_pool_destroy(pool);
	/* APR global termination */
	apr_terminate();
	return ret ? 0 : 1;
}
示例#25
0
文件: server.c 项目: EvaIPDBG/IPDBG
int jtagHostLoop()
{


    apr_status_t rv;
    apr_pool_t *mp;
    apr_pollset_t *pollset;
    apr_int32_t num;
    const apr_pollfd_t *ret_pfd;

    apr_initialize();
    apr_pool_create(&mp, NULL);

    serv_ctx_t *channel_contexts[IPDBG_CHANNELS];


    apr_pollset_create(&pollset, DEF_POLLSET_NUM, mp, 0);
    for(uint8_t ch = 0; ch < IPDBG_CHANNELS; ++ch)
    {
        serv_ctx_t *serv_ctx = apr_palloc(mp, sizeof(serv_ctx_t));
        channel_contexts[ch] = serv_ctx;
        serv_ctx->channel_number = ch;
        serv_ctx->channel_state = listening;
        serv_ctx->up_buf_level = 0;
        serv_ctx->down_buf_level = 0;

        if(ch == 0) serv_ctx->valid_mask = IPDBG_LA_VALID_MASK;
        if(ch == 1) serv_ctx->valid_mask = IPDBG_IOVIEW_VALID_MASK;
        if(ch == 2) serv_ctx->valid_mask = IPDBG_GDB_VALID_MASK;
        if(ch == 3) serv_ctx->valid_mask = IPDBG_WFG_VALID_MASK;

        apr_socket_t *listening_sock = create_listen_sock(mp, ch);
        assert(listening_sock);

        apr_pollfd_t pfd = { mp, APR_POLL_SOCKET, APR_POLLIN, 0, { NULL }, serv_ctx };
        pfd.desc.s = listening_sock;
        apr_pollset_add(pollset, &pfd);
    }

    // reset JtagCDC
    uint16_t val;
    ipdbgJTAGtransfer(&val, 0xf00);

    while (1)
    {
        size_t transfers = 0;
        for(size_t ch = 0 ; ch < IPDBG_CHANNELS ; ++ch)
        {
            for(size_t idx = 0 ; idx < channel_contexts[ch]->down_buf_level; ++idx)
            {
                uint16_t val;
                ipdbgJTAGtransfer(&val, channel_contexts[ch]->down_buf[idx] | channel_contexts[ch]->valid_mask);
                transfers++;

                distribute_to_up_buffer(val, channel_contexts);
            }
            channel_contexts[ch]->down_buf_level = 0;
        }
        for(size_t k = transfers ; k < MIN_TRANSFERS ; ++k)
        {
            uint16_t val;
            ipdbgJTAGtransfer(&val, 0x000);
            distribute_to_up_buffer(val, channel_contexts);
        }

        rv = apr_pollset_poll(pollset, DEF_POLL_TIMEOUT, &num, &ret_pfd);
        if (rv == APR_SUCCESS)
        {
            int i;
            /* scan the active sockets */
            for (i = 0; i < num; i++)
            {
                serv_ctx_t *serv_ctx = ret_pfd[i].client_data;
                if(serv_ctx)
                {
                    if (serv_ctx->channel_state == listening)
                    {
                        apr_socket_t *listening_sock = ret_pfd[i].desc.s;
                         /* the listen socket is readable. that indicates we accepted a new connection */
                        do_accept(serv_ctx, pollset, listening_sock, mp);
                        apr_socket_close(listening_sock);
                        apr_pollset_remove(pollset, &ret_pfd[i]);
                    }
                    else
                    {
                        int ret = TRUE;
                        if(ret_pfd[i].rtnevents & (APR_POLLIN | APR_POLLHUP))
                        {
                            ret = connection_rx_cb(serv_ctx, pollset, ret_pfd[i].desc.s);
                        }
                        else // (ret_pfd[i].rtnevents & APR_POLLOUT)
                        {
                            ret = connection_tx_cb(serv_ctx, pollset, ret_pfd[i].desc.s);
                        }
                        if (ret == FALSE)
                        {
                            //printf("closing connection %d", serv_ctx->channel_number);
                            apr_socket_t *sock = ret_pfd[i].desc.s;

                            apr_socket_close(sock);
                            apr_pollset_remove(pollset, &ret_pfd[i]);

                            apr_socket_t *listening_sock = create_listen_sock(mp, serv_ctx->channel_number);
                            serv_ctx->channel_state = listening;

                            apr_pollfd_t pfd = { mp, APR_POLL_SOCKET, APR_POLLIN, 0, { NULL }, serv_ctx };
                            pfd.desc.s = listening_sock;
                            apr_pollset_add(pollset, &pfd);
                        }
                    }
                }
            }
        }
    }

    return 0;
}
示例#26
0
int main(int argc, const char **argv)
{
    apr_status_t status;
    apr_pool_t *pool;
    apr_sockaddr_t *address;
    serf_context_t *context;
    serf_connection_t *connection;
    app_baton_t app_ctx;
    handler_baton_t *handler_ctx;
    apr_uri_t url;
    const char *raw_url, *method;
    int count;
    apr_getopt_t *opt;
    char opt_c;
    char *authn = NULL;
    const char *opt_arg;

    /* For the parser threads */
    apr_thread_t *thread[3];
    apr_threadattr_t *tattr;
    apr_status_t parser_status;
    parser_baton_t *parser_ctx;

    apr_initialize();
    atexit(apr_terminate);

    apr_pool_create(&pool, NULL);
    apr_atomic_init(pool);
    /* serf_initialize(); */

    /* Default to one round of fetching. */
    count = 1;
    /* Default to GET. */
    method = "GET";

    apr_getopt_init(&opt, pool, argc, argv);

    while ((status = apr_getopt(opt, "a:hv", &opt_c, &opt_arg)) ==
           APR_SUCCESS) {
        int srclen, enclen;

        switch (opt_c) {
        case 'a':
            srclen = strlen(opt_arg);
            enclen = apr_base64_encode_len(srclen);
            authn = apr_palloc(pool, enclen + 6);
            strcpy(authn, "Basic ");
            (void) apr_base64_encode(&authn[6], opt_arg, srclen);
            break;
        case 'h':
            print_usage(pool);
            exit(0);
            break;
        case 'v':
            puts("Serf version: " SERF_VERSION_STRING);
            exit(0);
        default:
            break;
        }
    }

    if (opt->ind != opt->argc - 1) {
        print_usage(pool);
        exit(-1);
    }

    raw_url = argv[opt->ind];

    apr_uri_parse(pool, raw_url, &url);
    if (!url.port) {
        url.port = apr_uri_port_of_scheme(url.scheme);
    }
    if (!url.path) {
        url.path = "/";
    }

    if (strcasecmp(url.scheme, "https") == 0) {
        app_ctx.using_ssl = 1;
    }
    else {
        app_ctx.using_ssl = 0;
    }

    status = apr_sockaddr_info_get(&address,
                                   url.hostname, APR_UNSPEC, url.port, 0,
                                   pool);
    if (status) {
        printf("Error creating address: %d\n", status);
        exit(1);
    }

    context = serf_context_create(pool);

    /* ### Connection or Context should have an allocator? */
    app_ctx.bkt_alloc = serf_bucket_allocator_create(pool, NULL, NULL);
    app_ctx.ssl_ctx = NULL;
    app_ctx.authn = authn;

    connection = serf_connection_create(context, address,
                                        conn_setup, &app_ctx,
                                        closed_connection, &app_ctx,
                                        pool);

    handler_ctx = (handler_baton_t*)serf_bucket_mem_alloc(app_ctx.bkt_alloc,
                                                      sizeof(handler_baton_t));
    handler_ctx->allocator = app_ctx.bkt_alloc;
    handler_ctx->doc_queue = apr_array_make(pool, 1, sizeof(doc_path_t*));
    handler_ctx->doc_queue_alloc = app_ctx.bkt_alloc;

    handler_ctx->requests_outstanding =
        (apr_uint32_t*)serf_bucket_mem_alloc(app_ctx.bkt_alloc,
                                             sizeof(apr_uint32_t));
    apr_atomic_set32(handler_ctx->requests_outstanding, 0);
    handler_ctx->hdr_read = 0;

    parser_ctx = (void*)serf_bucket_mem_alloc(app_ctx.bkt_alloc,
                                       sizeof(parser_baton_t));

    parser_ctx->requests_outstanding = handler_ctx->requests_outstanding;
    parser_ctx->connection = connection;
    parser_ctx->app_ctx = &app_ctx;
    parser_ctx->doc_queue = handler_ctx->doc_queue;
    parser_ctx->doc_queue_alloc = handler_ctx->doc_queue_alloc;
    /* Restrict ourselves to this host. */
    parser_ctx->hostinfo = url.hostinfo;

    status = apr_thread_mutex_create(&parser_ctx->mutex,
                                     APR_THREAD_MUTEX_DEFAULT, pool);
    if (status) {
        printf("Couldn't create mutex %d\n", status);
        return status;
    }

    status = apr_thread_cond_create(&parser_ctx->condvar, pool);
    if (status) {
        printf("Couldn't create condvar: %d\n", status);
        return status;
    }

    /* Let the handler now which condvar to use. */
    handler_ctx->doc_queue_condvar = parser_ctx->condvar;

    apr_threadattr_create(&tattr, pool);

    /* Start the parser thread. */
    apr_thread_create(&thread[0], tattr, parser_thread, parser_ctx, pool);

    /* Deliver the first request. */
    create_request(url.hostinfo, url.path, NULL, NULL, parser_ctx, pool);

    /* Go run our normal thread. */
    while (1) {
        int tries = 0;

        status = serf_context_run(context, SERF_DURATION_FOREVER, pool);
        if (APR_STATUS_IS_TIMEUP(status))
            continue;
        if (status) {
            char buf[200];

            printf("Error running context: (%d) %s\n", status,
                   apr_strerror(status, buf, sizeof(buf)));
            exit(1);
        }

        /* We run this check to allow our parser threads to add more
         * requests to our queue.
         */
        for (tries = 0; tries < 3; tries++) {
            if (!apr_atomic_read32(handler_ctx->requests_outstanding)) {
#ifdef SERF_VERBOSE
                printf("Waiting...");
#endif
                apr_sleep(100000);
#ifdef SERF_VERBOSE
                printf("Done\n");
#endif
            }
            else {
                break;
            }
        }
        if (tries >= 3) {
            break;
        }
        /* Debugging purposes only! */
        serf_debug__closed_conn(app_ctx.bkt_alloc);
    }

    printf("Quitting...\n");
    serf_connection_close(connection);

    /* wake up the parser via condvar signal */
    apr_thread_cond_signal(parser_ctx->condvar);

    status = apr_thread_join(&parser_status, thread[0]);
    if (status) {
        printf("Error joining thread: %d\n", status);
        return status;
    }

    serf_bucket_mem_free(app_ctx.bkt_alloc, handler_ctx->requests_outstanding);
    serf_bucket_mem_free(app_ctx.bkt_alloc, parser_ctx);

    apr_pool_destroy(pool);
    return 0;
}
示例#27
0
文件: main.c 项目: odmanV2/freecenter
int main(int argc, const char * const *argv)
{
	apr_pool_t *pool;
	server_options_t options;
	const char *log_conf_path;
	apt_dir_layout_t *dir_layout = NULL;

	/* APR global initialization */
	if(apr_initialize() != APR_SUCCESS) {
		apr_terminate();
		return 0;
	}

	/* create APR pool */
	pool = apt_pool_create();
	if(!pool) {
		apr_terminate();
		return 0;
	}

	/* load options */
	if(options_load(&options,argc,argv,pool) != TRUE) {
		apr_pool_destroy(pool);
		apr_terminate();
		return 0;
	}

	if(options.dir_layout_conf) {
		/* create and load directories layout from the configuration file */
		dir_layout = apt_dir_layout_create(pool);
		if(dir_layout)
			apt_dir_layout_load(dir_layout,options.dir_layout_conf,pool);
	}
	else {
		/* create default directories layout */
		dir_layout = apt_default_dir_layout_create(options.root_dir_path,pool);
	}

	if(!dir_layout) {
		printf("Failed to Create Directories Layout\n");
		apr_pool_destroy(pool);
		apr_terminate();
		return 0;
	}

	/* get path to logger configuration file */
	log_conf_path = apt_confdir_filepath_get(dir_layout,"logger.xml",pool);
	/* create and load singleton logger */
	apt_log_instance_load(log_conf_path,pool);

	if(options.log_priority) {
		/* override the log priority, if specified in command line */
		apt_log_priority_set(atoi(options.log_priority));
	}
	if(options.log_output) {
		/* override the log output mode, if specified in command line */
		apt_log_output_mode_set(atoi(options.log_output));
	}

	if(apt_log_output_mode_check(APT_LOG_OUTPUT_FILE) == TRUE) {
		/* open the log file */
		const char *log_dir_path = apt_dir_layout_path_get(dir_layout,APT_LAYOUT_LOG_DIR);
		apt_log_file_open(log_dir_path,"unimrcpserver",MAX_LOG_FILE_SIZE,MAX_LOG_FILE_COUNT,TRUE,pool);
	}

	if(options.foreground == TRUE) {
		/* run command line */
		uni_cmdline_run(dir_layout,pool);
	}
#ifdef WIN32
	else {
		/* run as windows service */
		uni_service_run(options.svcname,dir_layout,pool);
	}
#else
	else {
示例#28
0
文件: diff.c 项目: lysine/wasp
int main(int argc, const char *argv[])
{
  apr_pool_t *pool;
  svn_stream_t *ostream;
  svn_error_t *svn_err;
  svn_boolean_t has_changes;
  svn_diff_file_options_t *diff_options;
  apr_array_header_t *options_array;
  int i;
  const char *from = NULL;
  const char *to = NULL;
  svn_boolean_t show_c_function = FALSE;
  svn_boolean_t no_more_options = FALSE;

  apr_initialize();
  atexit(apr_terminate);

  pool = svn_pool_create(NULL);

  svn_err = svn_stream_for_stdout(&ostream, pool);
  if (svn_err)
    {
      svn_handle_error2(svn_err, stdout, FALSE, "diff: ");
      return 2;
    }

  options_array = apr_array_make(pool, 0, sizeof(const char *));

  diff_options = svn_diff_file_options_create(pool);

  for (i = 1 ; i < argc ; i++)
    {
      if (!no_more_options && (argv[i][0] == '-'))
        {
          /* Special case: '--' means "no more options follow" */
          if (argv[i][1] == '-' && !argv[i][2])
            {
              no_more_options = TRUE;
              continue;
            }
          /* Special case: we need to detect '-p' and handle it specially */
          if (argv[i][1] == 'p' && !argv[i][2])
            {
              show_c_function = TRUE;
              continue;
            }
          if (argv[i][1] == 'w' && !argv[i][2])
            {
              diff_options->ignore_space = svn_diff_file_ignore_space_all;
              continue;
            }

          APR_ARRAY_PUSH(options_array, const char *) = argv[i];

          /* Special case: '-U' takes an argument, so capture the
           * next argument in the array. */
          if (argv[i][1] == 'U' && !argv[i][2])
            {
              i++;
              APR_ARRAY_PUSH(options_array, const char *) = argv[i];
            }
        }
      else
        {
          if (from == NULL)
            from = argv[i];
          else if (to == NULL)
            to = argv[i];
          else
            {
              print_usage(ostream, argv[0], pool);
              return 2;
            }
        }
    }

  if (!from || !to)
    {
      print_usage(ostream, argv[0], pool);
      return 2;
    }

  svn_err = svn_diff_file_options_parse(diff_options, options_array, pool);
  if (svn_err)
    {
      svn_handle_error2(svn_err, stdout, FALSE, "diff: ");
      return 2;
    }

  svn_err = do_diff(ostream, from, to, &has_changes,
                    diff_options, show_c_function, pool);
  if (svn_err)
    {
      svn_handle_error2(svn_err, stdout, FALSE, "diff: ");
      return 2;
    }

  return has_changes ? 1 : 0;
}
示例#29
0
int main(int argc, const char const* argv[]) {
        apr_pool_t* p = NULL;
        apr_initialize();
        apr_pool_create(&p, NULL);

        apr_getopt_t* opt;
        apr_status_t rv;

        char ch = '\0';
        const char* optarg = NULL;
        const char* config_opts = NULL;
        const char* install_opts = NULL;
        const char* make_opts = NULL;
        const char* url = NULL;
        Command request = None;

        rv = apr_getopt_init(&opt, p, argc, argv);

        while(apr_getopt(opt, "I:Lc:m:i:d:SF:B:", &ch, &optarg) == APR_SUCCESS) {
                switch(ch) {
                case 'I':
                        request = Install;
                        url = optarg;
                        break;

                case 'L':
                        request = List;
                        break;

                case 'c':
                        config_opts = optarg;
                        break;

                case 'm':
                        make_opts = optarg;
                        break;

                case 'i':
                        install_opts = optarg;
                        break;

                case 'S':
                        request = Init;
                        break;

                case 'F':
                        request = Fetch;
                        url = optarg;
                        break;

                case 'B':
                        request = Build;
                        url = optarg;
                        break;
                }
        }

        switch(request) {
        case Install:
                check(url, "You must give a url.");
                Command_install(p, url, config_opts, make_opts, install_opts);
                break;

        case List:
                DB_list();
                break;

        case Fetch:
                check(url, "You must give a url.");
                Command_fetch(p, url, true);
                log_info("Downloaded to %s and in /tmp", BUILD_DIR);
                break;

        case Build:
                check(url, "You must give a url.");
                Command_build(p, url, config_opts, make_opts, install_opts);
                break;

        case Init:
                rv = DB_init();
                check(rv == 0, "Failed to make the database.");
                break;

        default:
                sentinel("Invalid command given.");
        }

        return EXIT_SUCCESS;

 error:
        return EXIT_FAILURE;
}
示例#30
-1
int main(int argc, const char* const argv[])
{
    apr_thread_t **t;
    apr_queue_t *queue;
    int i;
    apr_status_t rv;
    apr_getopt_t *opt;
    const char *optarg;
    char c;
    int numconsumers=3;
    int numproducers=4;
    int queuesize=100;
    int sleeptime=30;
    char errorbuf[200];

    apr_initialize();
    srand((unsigned int)apr_time_now());
    printf("APR Queue Test\n======================\n\n");
    
    printf("%-60s", "Initializing the context"); 
    if (apr_pool_create(&context, NULL) != APR_SUCCESS) {
        fflush(stdout);
        fprintf(stderr, "Failed.\nCould not initialize\n");
        exit(-1);
    }
    printf("OK\n");

    apr_getopt_init(&opt, context, argc, argv);
    while ((rv = apr_getopt(opt, "p:c:P:C:q:s:v", &c, &optarg))
            == APR_SUCCESS) {
        switch (c)  {
        case 'c':
            numconsumers = atoi( optarg);
            break;
        case 'p':
            numproducers = atoi( optarg);
            break;
        case 'C':
            consumer_activity = atoi( optarg);
            break;
        case 'P':
            producer_activity = atoi( optarg);
            break;
        case 's':
            sleeptime= atoi(optarg);
            break;
        case 'q':
            queuesize = atoi(optarg);
            break;
        case 'v':
            verbose= 1;
            break;
        default:
            usage();
            exit(-1);
        }
    }
    /* bad cmdline option?  then we die */
    if (rv != APR_EOF || opt->ind < opt->argc) {
        usage();
        exit(-1);
    }



    printf("test stats %d consumers (rate %d/sec) %d producers (rate %d/sec) queue size %d sleep %d\n",
            numconsumers,consumer_activity, numproducers, producer_activity, queuesize,sleeptime); 
    printf("%-60s", "Initializing the queue"); 
    rv  = apr_queue_create(&queue, queuesize, context);

    if (rv != APR_SUCCESS) {
        fflush(stdout);
        fprintf(stderr, "Failed\nCould not create queue %d\n",rv);
        apr_strerror(rv, errorbuf,200);
        fprintf(stderr,"%s\n",errorbuf);
        exit(-1);
    }
    printf("OK\n");

    t = apr_palloc( context, sizeof(apr_thread_t*) * (numconsumers+numproducers));
    printf("%-60s", "Starting consumers"); 
    for (i=0;i<numconsumers;i++) {
        rv = apr_thread_create(&t[i], NULL, consumer, queue, context);
        if (rv != APR_SUCCESS) {
            apr_strerror(rv, errorbuf,200);
            fprintf(stderr, "Failed\nError starting consumer thread (%d) rv=%d:%s\n",i, rv,errorbuf);
            exit(-1);

        }
    }
    for (i=numconsumers;i<(numconsumers+numproducers);i++) {
        rv = apr_thread_create(&t[i], NULL, producer, queue, context);
        if (rv != APR_SUCCESS) {
            apr_strerror(rv, errorbuf,200);
            fprintf(stderr, "Failed\nError starting producer thread (%d) rv=%d:%s\n",i, rv,errorbuf);
            exit(-1);

        }
    }

    printf("OK\n");
    printf("%-60s", "Sleeping\n"); 
    apr_sleep( sleeptime * 1000000 ); /* sleep 10 seconds */
    printf("OK\n");

    printf("%-60s", "Terminating queue"); 
    rv = apr_queue_term(queue);
    if (rv != APR_SUCCESS) {
        apr_strerror(rv, errorbuf,200);
        fprintf( stderr, "apr_queue_term failed  %d:%s\n",rv,errorbuf);
    }
    printf("OK\n");


    printf("%-60s", "Waiting for threads to exit\n");
    fflush(stdout);
    for (i=0;i<numconsumers+numproducers;i++) {
        apr_thread_join(&rv, t[i]);
        if (rv != 0 ) {
            apr_strerror(rv, errorbuf,200);
            if (i<numconsumers) 
                fprintf( stderr, "consumer thread %d failed rv %d:%s\n",i,rv,errorbuf);
            else
                fprintf( stderr, "producer thread %d failed rv %d:%s\n",i,rv,errorbuf);
        }
    }

    printf("OK\n");

    apr_terminate();

    return 0;
}