Пример #1
0
int _setup_assoc_list(void)
{
	slurmdb_update_object_t update;
	slurmdb_assoc_rec_t *assoc = NULL;
	slurmdb_tres_rec_t *tres = NULL;

	/* make the main list */
	assoc_mgr_assoc_list =
		list_create(slurmdb_destroy_assoc_rec);
	assoc_mgr_user_list =
		list_create(slurmdb_destroy_user_rec);
	assoc_mgr_qos_list =
		list_create(slurmdb_destroy_qos_rec);

	/* we just want make it so we setup_children so just pretend
	 * we are running off cache */
	running_cache = 1;
	assoc_mgr_init(NULL, NULL, SLURM_SUCCESS);

	/* Here we make the tres we want to add to the system.
	 * We do this as an update to avoid having to do setup. */
	memset(&update, 0, sizeof(slurmdb_update_object_t));
	update.type = SLURMDB_ADD_TRES;
	update.objects = list_create(slurmdb_destroy_tres_rec);

	tres = xmalloc(sizeof(slurmdb_tres_rec_t));
	tres->id = 1;
	tres->type = xstrdup("cpu");
	list_append(update.objects, tres);

	if (assoc_mgr_update_tres(&update, false))
		error("assoc_mgr_update_tres: %m");
	FREE_NULL_LIST(update.objects);

	/* Here we make the associations we want to add to the system.
	 * We do this as an update to avoid having to do setup. */
	update.type = SLURMDB_ADD_ASSOC;
	update.objects = list_create(slurmdb_destroy_assoc_rec);

	/* Just so we don't have to worry about lft's and rgt's we
	 * will just append these on in order.
	 * Note: the commented out lfts and rgts as of 10-29-10 are
	 * correct.  By doing an append they go on
	 * sorted in hierarchy order.  The sort that happens inside
	 * the internal slurm code will sort alpha automatically, (You can
	 * test this by putting AccountF before AccountE.
	 */

	/* First only add the accounts */
	/* root association */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 1;
	/* assoc->lft = 1; */
	/* assoc->rgt = 28; */
	assoc->acct = xstrdup("root");
	list_append(update.objects, assoc);

	/* sub of root id 1 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 2;
	assoc->parent_id = 1;
	assoc->shares_raw = 40;
	/* assoc->lft = 2; */
	/* assoc->rgt = 13; */
	assoc->acct = xstrdup("AccountA");
	list_append(update.objects, assoc);

	/* sub of AccountA id 2 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 21;
	/* assoc->lft = 3; */
	/* assoc->rgt = 6; */
	assoc->parent_id = 2;
	assoc->shares_raw = 30;
	assoc->acct = xstrdup("AccountB");
	list_append(update.objects, assoc);

	/* sub of AccountB id 21 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 211;
	/* assoc->lft = 4; */
	/* assoc->rgt = 5; */
	assoc->parent_id = 21;
	assoc->shares_raw = 1;
	assoc->usage->usage_raw = 20;
	assoc->acct = xstrdup("AccountB");
	assoc->user = xstrdup("User1");
	list_append(update.objects, assoc);

	/* sub of AccountA id 2 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 22;
	/* assoc->lft = 7; */
	/* assoc->rgt = 12; */
	assoc->parent_id = 2;
	assoc->shares_raw = 10;
	assoc->acct = xstrdup("AccountC");
	list_append(update.objects, assoc);

	/* sub of AccountC id 22 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 221;
	/* assoc->lft = 8; */
	/* assoc->rgt = 9; */
	assoc->parent_id = 22;
	assoc->shares_raw = 1;
	assoc->usage->usage_raw = 25;
	assoc->acct = xstrdup("AccountC");
	assoc->user = xstrdup("User2");
	list_append(update.objects, assoc);

	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 222;
	/* assoc->lft = 10; */
	/* assoc->rgt = 11; */
	assoc->parent_id = 22;
	assoc->shares_raw = 1;
	assoc->usage->usage_raw = 0;
	assoc->acct = xstrdup("AccountC");
	assoc->user = xstrdup("User3");
	list_append(update.objects, assoc);

	/* sub of root id 1 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 3;
	/* assoc->lft = 14; */
	/* assoc->rgt = 23; */
	assoc->parent_id = 1;
	assoc->shares_raw = 60;
	assoc->acct = xstrdup("AccountD");
	list_append(update.objects, assoc);

	/* sub of AccountD id 3 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 31;
	/* assoc->lft = 19; */
	/* assoc->rgt = 22; */
	assoc->parent_id = 3;
	assoc->shares_raw = 25;
	assoc->acct = xstrdup("AccountE");
	list_append(update.objects, assoc);

	/* sub of AccountE id 31 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 311;
	/* assoc->lft = 20; */
	/* assoc->rgt = 21; */
	assoc->parent_id = 31;
	assoc->shares_raw = 1;
	assoc->usage->usage_raw = 25;
	assoc->acct = xstrdup("AccountE");
	assoc->user = xstrdup("User4");
	list_append(update.objects, assoc);

	/* sub of AccountD id 3 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 32;
	/* assoc->lft = 15; */
	/* assoc->rgt = 18; */
	assoc->parent_id = 3;
	assoc->shares_raw = 35;
	assoc->acct = xstrdup("AccountF");
	list_append(update.objects, assoc);

	/* sub of AccountF id 32 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 321;
	/* assoc->lft = 16; */
	/* assoc->rgt = 17; */
	assoc->parent_id = 32;
	assoc->shares_raw = 1;
	assoc->usage->usage_raw = 0;
	assoc->acct = xstrdup("AccountF");
	assoc->user = xstrdup("User5");
	list_append(update.objects, assoc);

	/* sub of root id 1 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 4;
	/* assoc->lft = 24; */
	/* assoc->rgt = 27; */
	assoc->parent_id = 1;
	assoc->shares_raw = 0;
	assoc->acct = xstrdup("AccountG");
	list_append(update.objects, assoc);

	/* sub of AccountG id 4 */
	assoc = xmalloc(sizeof(slurmdb_assoc_rec_t));
	assoc->usage = slurmdb_create_assoc_usage(g_tres_count);
	assoc->id = 41;
	/* assoc->lft = 25; */
	/* assoc->rgt = 26; */
	assoc->parent_id = 4;
	assoc->shares_raw = 0;
	assoc->usage->usage_raw = 30;
	assoc->acct = xstrdup("AccountG");
	assoc->user = xstrdup("User6");
	list_append(update.objects, assoc);

	if (assoc_mgr_update_assocs(&update, false))
		error("assoc_mgr_update_assocs: %m");
	list_destroy(update.objects);

	return SLURM_SUCCESS;
}
Пример #2
0
inline void kthreadq_append ( kthread_q *q, kthread_t *kthread )
{
	ASSERT ( kthread && q );
	list_append ( &q->q, kthread, &kthread->list );
}
Пример #3
0
static int _copy_allocation(char *com, List allocated_blocks)
{
	ListIterator results_i;
	allocated_block_t *allocated_block = NULL;
	allocated_block_t *temp_block = NULL;
	select_ba_request_t *request = NULL;

	int i = 1, j;
	int len = strlen(com);
	char letter = '\0';
	int count = 1;
	int *geo = NULL, *geo_ptr = NULL;

	/* look for the space after copy */
	while ((com[i-1] != ' ') && (i < len))
		i++;

	if (i <= len) {
		/* Here we are looking for a real number for the count
		 * instead of the params.cluster_base so atoi is ok */
		if ((com[i] >= '0') && (com[i] <= '9'))
			count = atoi(com+i);
		else {
			letter = com[i];
			i++;
			if (com[i] != '\n') {
				while ((com[i-1] != ' ') && (i < len))
					i++;

				if ((com[i] >= '0') && (com[i] <= '9'))
					count = atoi(com+i);
			}
		}
	}

	results_i = list_iterator_create(allocated_blocks);
	while ((allocated_block = list_next(results_i)) != NULL) {
		temp_block = allocated_block;
		if (allocated_block->letter != letter)
			continue;
		break;
	}
	list_iterator_destroy(results_i);

	if (!letter)
		allocated_block = temp_block;

	if (!allocated_block) {
		memset(error_string, 0, 255);
		sprintf(error_string,
			"Could not find requested record to copy");
		return 0;
	}

	for (i = 0; i < count; i++) {
		request = (select_ba_request_t*)
			  xmalloc(sizeof(select_ba_request_t));
		for (j = 0; j < params.cluster_dims; j++) {
			request->geometry[j] = allocated_block->request->
					       geometry[j];
			request->conn_type[j] = allocated_block->request->
						conn_type[j];
		}
		request->size = allocated_block->request->size;
		request->rotate =allocated_block->request->rotate;
		request->elongate = allocated_block->request->elongate;
		request->deny_pass = allocated_block->request->deny_pass;
#ifndef HAVE_BGL
		request->small16 = allocated_block->request->small16;
		request->small64 = allocated_block->request->small64;
		request->small256 = allocated_block->request->small256;
#endif
		request->small32 = allocated_block->request->small32;
		request->small128 = allocated_block->request->small128;

		request->rotate_count= 0;
		request->elongate_count = 0;
	       	request->elongate_geos = list_create(NULL);
		request->avail_mp_bitmap = NULL;

		results_i = list_iterator_create(request->elongate_geos);
		while ((geo_ptr = list_next(results_i)) != NULL) {
			geo = xmalloc(sizeof(int) * params.cluster_dims);
			for (j = 0; j < params.cluster_dims; j++)
				geo[j] = geo_ptr[j];
			list_append(request->elongate_geos, geo);
		}
		list_iterator_destroy(results_i);

		if ((allocated_block = _make_request(request)) == NULL) {
			memset(error_string, 0, 255);
			sprintf(error_string,
				"Problem with the copy\n"
				"Are you sure there is enough room for it?");
			xfree(request);
			return 0;
		}
		list_append(allocated_blocks, allocated_block);
	}
	return 1;

}
Пример #4
0
/** Run in interactive mode.
 *
 * Repeatedly read in statements from the user and execute them.
 */
void imode_run(void)
{
	input_t *input;
	lex_t lex;
	parse_t parse;
	stree_program_t *program;
	stree_stat_t *stat;
	stree_proc_t *proc;
	stree_fun_t *fun;
	stree_symbol_t *fun_sym;
	stype_t stype;
	stype_block_vr_t *block_vr;
	list_node_t *bvr_n;
	rdata_item_t *rexpr;
	rdata_item_t *rexpr_vi;

	run_t run;
	run_proc_ar_t *proc_ar;

	bool_t quit_im;

	/* Create an empty program. */
	program = stree_program_new();
	program->module = stree_module_new();

	/* Declare builtin symbols. */
	builtin_declare(program);

	/* Process the library. */
	if (program_lib_process(program) != EOK)
		exit(1);

	/* Resolve ancestry. */
	ancr_module_process(program, program->module);

	/* Bind internal interpreter references to symbols. */
	builtin_bind(program->builtin);

	/* Resolve ancestry. */
	ancr_module_process(program, program->module);

	/* Construct typing context. */
	stype.program = program;
	stype.proc_vr = stype_proc_vr_new();
	list_init(&stype.proc_vr->block_vr);
	stype.current_csi = NULL;
	proc = stree_proc_new();

	fun = stree_fun_new();
	fun_sym = stree_symbol_new(sc_fun);
	fun_sym->u.fun = fun;
	fun->name = stree_ident_new();
	fun->name->sid = strtab_get_sid("$imode");
	fun->sig = stree_fun_sig_new();

	stype.proc_vr->proc = proc;
	fun->symbol = fun_sym;
	proc->outer_symbol = fun_sym;

	/* Create block visit record. */
	block_vr = stype_block_vr_new();
	intmap_init(&block_vr->vdecls);

	/* Add block visit record to the stack. */
	list_append(&stype.proc_vr->block_vr, block_vr);

	/* Construct run context. */
	run_gdata_init(&run);

	run.thread_ar = run_thread_ar_new();
	list_init(&run.thread_ar->proc_ar);
	run_proc_ar_create(&run, run.gdata, proc, &proc_ar);
	list_append(&run.thread_ar->proc_ar, proc_ar);

	printf("SBI interactive mode. ");
	os_input_disp_help();

	quit_im = b_false;
	while (quit_im != b_true) {
		parse.error = b_false;
		stype.error = b_false;
		run.thread_ar->exc_payload = NULL;
		run.thread_ar->bo_mode = bm_none;

		input_new_interactive(&input);

		/* Parse input. */
		lex_init(&lex, input);
		parse_init(&parse, program, &lex);

		if (lcur_lc(&parse) == lc_eof)
			break;

		stat = parse_stat(&parse);

		if (parse.error != b_false)
			continue;

		/* Type statement. */
		stype_stat(&stype, stat, b_true);

		if (stype.error != b_false)
			continue;

		/* Run statement. */
		run_init(&run);
		run.program = program;
		run_stat(&run, stat, &rexpr);

		/* Check for unhandled exceptions. */
		run_exc_check_unhandled(&run);

		if (rexpr != NULL) {
			/* Convert expression result to value item. */
			run_cvt_value_item(&run, rexpr, &rexpr_vi);
			rdata_item_destroy(rexpr);

			/* Check for unhandled exceptions. */
			run_exc_check_unhandled(&run);
		} else {
			rexpr_vi = NULL;
		}

		/*
		 * rexpr_vi can be NULL if either repxr was null or
		 * if the conversion to value item raised an exception.
		 */
		if (rexpr_vi != NULL) {
			assert(rexpr_vi->ic == ic_value);

			/* Print result. */
			printf("Result: ");
			rdata_value_print(rexpr_vi->u.value);
			printf("\n");

			rdata_item_destroy(rexpr_vi);
		}
	}

	run_proc_ar_destroy(&run, proc_ar);

	/* Remove block visit record from the stack, */
	bvr_n = list_last(&stype.proc_vr->block_vr);
	assert(list_node_data(bvr_n, stype_block_vr_t *) == block_vr);
	list_remove(&stype.proc_vr->block_vr, bvr_n);

	printf("\nBye!\n");
}
Пример #5
0
LIST *
evaluate_rule(
    char    *rulename,
    FRAME *frame )
{
    LIST      *result = L0;
    RULE          *rule;
    profile_frame prof[1];
    module_t    *prev_module = frame->module;
    
    LIST      *l;
    {
        LOL arg_context_, *arg_context = &arg_context_;
        if ( !frame->prev )
            lol_init(arg_context);
        else
            arg_context = frame->prev->args;
        
        l = var_expand( L0, rulename, rulename+strlen(rulename), arg_context, 0 );
    }

    if ( !l )
    {
        backtrace_line( frame->prev );
        printf( "warning: rulename %s expands to empty string\n", rulename );
        backtrace( frame->prev );
        return result;
    }

    rulename = l->string;
    rule = bindrule( l->string, frame->module );

#ifdef HAVE_PYTHON
    if (rule->python_function)
    {
        return call_python_function(rule, frame);
    }
#endif

    /* drop the rule name */
    l = list_pop_front( l );

    /* tack the rest of the expansion onto the front of the first argument */
    frame->args->list[0] = list_append( l, lol_get( frame->args, 0 ) );

    if ( DEBUG_COMPILE )
    {
        /* Try hard to indicate in which module the rule is going to execute */
        if ( rule->module != frame->module
             && rule->procedure != 0 && strcmp(rulename, rule->procedure->rulename) )
        {
            char buf[256] = "";
            strncat( buf, rule->module->name, sizeof(buf) - 1 );
            strncat( buf, rule->name, sizeof(buf) - 1 );
            debug_compile( 1, buf, frame);
        }
        else
        {
            debug_compile( 1, rulename, frame);
        }

        lol_print( frame->args );
        printf( "\n" );
    }
    
    if ( rule->procedure && rule->module != prev_module )
    {
        /* propagate current module to nested rule invocations */
        frame->module = rule->module;
        
        /* swap variables */
        exit_module( prev_module );
        enter_module( rule->module );
    }
        
    /* record current rule name in frame */
    if ( rule->procedure )
    {
        frame->rulename = rulename;
        /* and enter record profile info */
        if ( DEBUG_PROFILE )
            profile_enter( rule->procedure->rulename, prof );
    }

    /* Check traditional targets $(<) and sources $(>) */

    if( !rule->actions && !rule->procedure )
    {
        backtrace_line( frame->prev );
        printf( "rule %s unknown in module %s\n", rule->name, frame->module->name );
        backtrace( frame->prev );
        exit(1);
    }

    /* If this rule will be executed for updating the targets */
    /* then construct the action for make(). */

    if( rule->actions )
    {
        TARGETS *t;
        ACTION  *action;

        /* The action is associated with this instance of this rule */

        action = (ACTION *)malloc( sizeof( ACTION ) );
        memset( (char *)action, '\0', sizeof( *action ) );

        action->rule = rule;
        action->targets = targetlist( (TARGETS *)0, lol_get( frame->args, 0 ) );
        action->sources = targetlist( (TARGETS *)0, lol_get( frame->args, 1 ) );

        /* Append this action to the actions of each target */

        for( t = action->targets; t; t = t->next )
            t->target->actions = actionlist( t->target->actions, action );
    }

    /* Now recursively compile any parse tree associated with this rule */
    /* refer/free to ensure rule not freed during use */

    if( rule->procedure )
    {
        SETTINGS *local_args = collect_arguments( rule, frame );
        PARSE *parse = rule->procedure;
        parse_refer( parse );
        
        pushsettings( local_args );
        result = parse_evaluate( parse, frame );
        popsettings( local_args );
        freesettings( local_args );
        
        parse_free( parse );
    }

    if ( frame->module != prev_module )
    {
        exit_module( frame->module );
        enter_module( prev_module );
    }

    if ( DEBUG_PROFILE && rule->procedure )
        profile_exit( prof );

    if( DEBUG_COMPILE )
        debug_compile( -1, 0, frame);

    return result;
}
Пример #6
0
Файл: s2ir.c Проект: Rayerd/dmd
void ForeachStatement::toIR(IRState *irs)
{
    printf("ForeachStatement::toIR() %s\n", toChars());
    assert(0);  // done by "lowering" in the front end
#if 0
    Type *tab;
    elem *eaggr;
    elem *e;
    elem *elength;
    tym_t keytym;

    //printf("ForeachStatement::toIR()\n");
    block *bpre;
    block *bcond;
    block *bbody;
    block *bbodyx;
    Blockx *blx = irs->blx;

    IRState mystate(irs,this);
    mystate.breakBlock = block_calloc(blx);
    mystate.contBlock = block_calloc(blx);

    tab = aggr->type->toBasetype();
    assert(tab->ty == Tarray || tab->ty == Tsarray);

    incUsage(irs, aggr->loc);
    eaggr = aggr->toElem(irs);

    /* Create sp: pointer to start of array data
     */

    Symbol *sp = symbol_genauto(TYnptr);

    if (tab->ty == Tarray)
    {
        // stmp is copy of eaggr (the array), so eaggr is evaluated only once
        Symbol *stmp;

        // Initialize stmp
        stmp = symbol_genauto(eaggr);
        e = el_bin(OPeq, eaggr->Ety, el_var(stmp), eaggr);
        block_appendexp(blx->curblock, e);

        // Initialize sp
        e = el_una(OPmsw, TYnptr, el_var(stmp));
        e = el_bin(OPeq, TYnptr, el_var(sp), e);
        block_appendexp(blx->curblock, e);

        // Get array.length
        elength = el_var(stmp);
        elength->Ety = TYsize_t;
    }
    else // Tsarray
    {
        // Initialize sp
        e = el_una(OPaddr, TYnptr, eaggr);
        e = el_bin(OPeq, TYnptr, el_var(sp), e);
        block_appendexp(blx->curblock, e);

        // Get array.length
        elength = el_long(TYsize_t, ((TypeSArray *)tab)->dim->toInteger());
    }

    Symbol *spmax;
    Symbol *skey;

    if (key)
    {
        /* Create skey, the index to the array.
         * Initialize skey to 0 (foreach) or .length (foreach_reverse).
         */
        skey = key->toSymbol();
        symbol_add(skey);
        keytym = key->type->totym();
        elem *einit = (op == TOKforeach_reverse) ? elength : el_long(keytym, 0);
        e = el_bin(OPeq, keytym, el_var(skey), einit);
    }
    else
    {
        /* Create spmax, pointer past end of data.
         * Initialize spmax = sp + array.length * size
         */
        spmax = symbol_genauto(TYnptr);
        e = el_bin(OPmul, TYsize_t, elength, el_long(TYsize_t, tab->nextOf()->size()));
        e = el_bin(OPadd, TYnptr, el_var(sp), e);
        e = el_bin(OPeq, TYnptr, el_var(spmax), e);

        /* For foreach_reverse, swap sp and spmax
         */
        if (op == TOKforeach_reverse)
        {   Symbol *s = sp;
            sp = spmax;
            spmax = s;
        }
    }
    block_appendexp(blx->curblock, e);

    bpre = blx->curblock;
    block_next(blx,BCgoto,NULL);
    bcond = blx->curblock;

    if (key)
    {
        if (op == TOKforeach_reverse)
        {
            // Construct (key != 0)
            e = el_bin(OPne, TYint, el_var(skey), el_long(keytym, 0));
        }
        else
        {
            // Construct (key < elength)
            e = el_bin(OPlt, TYint, el_var(skey), elength);
        }
    }
    else
    {
        if (op == TOKforeach_reverse)
        {
            // Construct (sp > spmax)
            e = el_bin(OPgt, TYint, el_var(sp), el_var(spmax));
        }
        else
        {
            // Construct (sp < spmax)
            e = el_bin(OPlt, TYint, el_var(sp), el_var(spmax));
        }
    }
    bcond->Belem = e;
    block_next(blx, BCiftrue, NULL);

    if (op == TOKforeach_reverse)
    {
        if (key)
        {   // Construct (skey -= 1)
            e = el_bin(OPminass, keytym, el_var(skey), el_long(keytym, 1));
        }
        else
        {   // Construct (sp--)
            e = el_bin(OPminass, TYnptr, el_var(sp), el_long(TYsize_t, tab->nextOf()->size()));
        }
        block_appendexp(blx->curblock, e);
    }

    Symbol *s;
    FuncDeclaration *fd = NULL;
    if (value->toParent2())
        fd = value->toParent2()->isFuncDeclaration();
    int nrvo = 0;
    if (fd && fd->nrvo_can && fd->nrvo_var == value)
    {
        s = fd->shidden;
        nrvo = 1;
    }
    else
    {   s = value->toSymbol();
        symbol_add(s);
    }

    // Construct (value = *sp) or (value = sp[skey * elemsize])
    tym_t tym = value->type->totym();
    if (key)
    {   // sp + skey * elemsize
        e = el_bin(OPmul, keytym, el_var(skey), el_long(keytym, tab->nextOf()->size()));
        e = el_bin(OPadd, TYnptr, el_var(sp), e);
    }
    else
        e = el_var(sp);

    elem *evalue;
#if DMDV2
    if (value->offset)  // if value is a member of a closure
    {
        assert(irs->sclosure);
        evalue = el_var(irs->sclosure);
        evalue = el_bin(OPadd, TYnptr, evalue, el_long(TYint, value->offset));
        evalue = el_una(OPind, value->type->totym(), evalue);
    }
    else
#endif
        evalue = el_var(s);

    if (value->isOut() || value->isRef())
    {
        assert(value->storage_class & (STCout | STCref));
        e = el_bin(OPeq, TYnptr, evalue, e);
    }
    else
    {
        if (nrvo)
            evalue = el_una(OPind, tym, evalue);
        StructDeclaration *sd = needsPostblit(value->type);
        if (tybasic(tym) == TYstruct)
        {
            e = el_bin(OPeq, tym, evalue, el_una(OPind, tym, e));
            e->Eoper = OPstreq;
            e->ET = value->type->toCtype();
#if DMDV2
            // Call postblit on e
            if (sd)
            {   FuncDeclaration *fd = sd->postblit;
                elem *ec = el_copytree(evalue);
                ec = el_una(OPaddr, TYnptr, ec);
                ec = callfunc(loc, irs, 1, Type::tvoid, ec, sd->type->pointerTo(), fd, fd->type, NULL, NULL);
                e = el_combine(e, ec);
            }
#endif
        }
        else if (tybasic(tym) == TYarray)
        {
            if (sd)
            {
                /* Generate:
                 *      _d_arrayctor(ti, efrom, eto)
                 */
                Expression *ti = value->type->toBasetype()->nextOf()->toBasetype()->getTypeInfo(NULL);
                elem *esize = el_long(TYsize_t, ((TypeSArray *)value->type->toBasetype())->dim->toInteger());
                elem *eto = el_pair(TYdarray, esize, el_una(OPaddr, TYnptr, evalue));
                elem *efrom = el_pair(TYdarray, el_copytree(esize), e);
                elem *ep = el_params(eto, efrom, ti->toElem(irs), NULL);
                int rtl = RTLSYM_ARRAYCTOR;
                e = el_bin(OPcall, TYvoid, el_var(rtlsym[rtl]), ep);
            }
            else
            {
                e = el_bin(OPeq, tym, evalue, el_una(OPind, tym, e));
                e->Eoper = OPstreq;
                e->Ejty = e->Ety = TYstruct;
                e->ET = value->type->toCtype();
            }
        }
        else
            e = el_bin(OPeq, tym, evalue, el_una(OPind, tym, e));
    }
    incUsage(irs, loc);
    block_appendexp(blx->curblock, e);

    bbody = blx->curblock;
    if (body)
        body->toIR(&mystate);
    bbodyx = blx->curblock;
    block_next(blx,BCgoto,mystate.contBlock);

    if (op == TOKforeach)
    {
        if (key)
        {   // Construct (skey += 1)
            e = el_bin(OPaddass, keytym, el_var(skey), el_long(keytym, 1));
        }
        else
        {   // Construct (sp++)
            e = el_bin(OPaddass, TYnptr, el_var(sp), el_long(TYsize_t, tab->nextOf()->size()));
        }
        mystate.contBlock->Belem = e;
    }
    block_next(blx,BCgoto,mystate.breakBlock);

    list_append(&bpre->Bsucc,bcond);
    list_append(&bcond->Bsucc,bbody);
    list_append(&bcond->Bsucc,mystate.breakBlock);
    list_append(&bbodyx->Bsucc,mystate.contBlock);
    list_append(&mystate.contBlock->Bsucc,bcond);
#endif
}
Пример #7
0
Файл: s2ir.c Проект: Rayerd/dmd
void SwitchStatement::toIR(IRState *irs)
{
    int string;
    Blockx *blx = irs->blx;

    //printf("SwitchStatement::toIR()\n");
    IRState mystate(irs,this);

    mystate.switchBlock = blx->curblock;

    /* Block for where "break" goes to
     */
    mystate.breakBlock = block_calloc(blx);

    /* Block for where "default" goes to.
     * If there is a default statement, then that is where default goes.
     * If not, then do:
     *   default: break;
     * by making the default block the same as the break block.
     */
    mystate.defaultBlock = sdefault ? block_calloc(blx) : mystate.breakBlock;

    int numcases = 0;
    if (cases)
        numcases = cases->dim;

    incUsage(irs, loc);
    elem *econd = condition->toElemDtor(&mystate);
#if DMDV2
    if (hasVars)
    {   /* Generate a sequence of if-then-else blocks for the cases.
         */
        if (econd->Eoper != OPvar)
        {
            elem *e = exp2_copytotemp(econd);
            block_appendexp(mystate.switchBlock, e);
            econd = e->E2;
        }

        for (int i = 0; i < numcases; i++)
        {   CaseStatement *cs = cases->tdata()[i];

            elem *ecase = cs->exp->toElemDtor(&mystate);
            elem *e = el_bin(OPeqeq, TYbool, el_copytree(econd), ecase);
            block *b = blx->curblock;
            block_appendexp(b, e);
            block *bcase = block_calloc(blx);
            cs->cblock = bcase;
            block_next(blx, BCiftrue, NULL);
            list_append(&b->Bsucc, bcase);
            list_append(&b->Bsucc, blx->curblock);
        }

        /* The final 'else' clause goes to the default
         */
        block *b = blx->curblock;
        block_next(blx, BCgoto, NULL);
        list_append(&b->Bsucc, mystate.defaultBlock);

        body->toIR(&mystate);

        /* Have the end of the switch body fall through to the block
         * following the switch statement.
         */
        block_goto(blx, BCgoto, mystate.breakBlock);
        return;
    }
#endif

    if (condition->type->isString())
    {
        // Number the cases so we can unscramble things after the sort()
        for (int i = 0; i < numcases; i++)
        {   CaseStatement *cs = cases->tdata()[i];
            cs->index = i;
        }

        cases->sort();

        /* Create a sorted array of the case strings, and si
         * will be the symbol for it.
         */
        dt_t *dt = NULL;
        Symbol *si = symbol_generate(SCstatic,type_fake(TYdarray));
#if MACHOBJ
        si->Sseg = DATA;
#endif
        dtsize_t(&dt, numcases);
        dtxoff(&dt, si, PTRSIZE * 2, TYnptr);

        for (int i = 0; i < numcases; i++)
        {   CaseStatement *cs = cases->tdata()[i];

            if (cs->exp->op != TOKstring)
            {   error("case '%s' is not a string", cs->exp->toChars()); // BUG: this should be an assert
            }
            else
            {
                StringExp *se = (StringExp *)(cs->exp);
                unsigned len = se->len;
                dtsize_t(&dt, len);
                dtabytes(&dt, TYnptr, 0, se->len * se->sz, (char *)se->string);
            }
        }

        si->Sdt = dt;
        si->Sfl = FLdata;
        outdata(si);

        /* Call:
         *      _d_switch_string(string[] si, string econd)
         */
        elem *eparam = el_param(econd, el_var(si));
        switch (condition->type->nextOf()->ty)
        {
        case Tchar:
            econd = el_bin(OPcall, TYint, el_var(rtlsym[RTLSYM_SWITCH_STRING]), eparam);
            break;
        case Twchar:
            econd = el_bin(OPcall, TYint, el_var(rtlsym[RTLSYM_SWITCH_USTRING]), eparam);
            break;
        case Tdchar:        // BUG: implement
            econd = el_bin(OPcall, TYint, el_var(rtlsym[RTLSYM_SWITCH_DSTRING]), eparam);
            break;
        default:
            assert(0);
        }
        elem_setLoc(econd, loc);
        string = 1;
    }
    else
        string = 0;
    block_appendexp(mystate.switchBlock, econd);
    block_next(blx,BCswitch,NULL);

    // Corresponding free is in block_free
    targ_llong *pu = (targ_llong *) ::malloc(sizeof(*pu) * (numcases + 1));
    mystate.switchBlock->BS.Bswitch = pu;
    /* First pair is the number of cases, and the default block
     */
    *pu++ = numcases;
    list_append(&mystate.switchBlock->Bsucc, mystate.defaultBlock);

    /* Fill in the first entry in each pair, which is the case value.
     * CaseStatement::toIR() will fill in
     * the second entry for each pair with the block.
     */
    for (int i = 0; i < numcases; i++)
    {
        CaseStatement *cs = cases->tdata()[i];
        if (string)
        {
            pu[cs->index] = i;
        }
        else
        {
            pu[i] = cs->exp->toInteger();
        }
    }

    body->toIR(&mystate);

    /* Have the end of the switch body fall through to the block
     * following the switch statement.
     */
    block_goto(blx, BCgoto, mystate.breakBlock);
}
Пример #8
0
static list *
sequential_block (mvc *sql, sql_subtype *restype, list *restypelist, dlist *blk, char *opt_label, int is_func) 
{
	list *l=0;
	dnode *n;

	assert(!restype || !restypelist);

 	if (THRhighwater())
		return sql_error(sql, 10, SQLSTATE(42000) "SELECT: too many nested operators");

	if (blk->h)
 		l = sa_list(sql->sa);
	if(!stack_push_frame(sql, opt_label))
		return sql_error(sql, 02, SQLSTATE(HY001) MAL_MALLOC_FAIL);
	for (n = blk->h; n; n = n->next ) {
		sql_exp *res = NULL;
		list *reslist = NULL;
		symbol *s = n->data.sym;

		switch (s->token) {
		case SQL_SET:
			res = psm_set_exp(sql, s->data.lval->h);
			break;
		case SQL_DECLARE:
			reslist = rel_psm_declare(sql, s->data.lval->h);
			break;
		case SQL_DECLARE_TABLE:
		case SQL_CREATE_TABLE: 
			res = rel_psm_declare_table(sql, s->data.lval->h);
			break;
		case SQL_WHILE:
			res = rel_psm_while_do(sql, restype, restypelist, s->data.lval->h, is_func);
			break;
		case SQL_IF:
			res = rel_psm_if_then_else(sql, restype, restypelist, s->data.lval->h, is_func);
			break;
		case SQL_CASE:
			reslist = rel_psm_case(sql, restype, restypelist, s->data.lval->h, is_func);
			break;
		case SQL_CALL:
			res = rel_psm_call(sql, s->data.sym);
			break;
		case SQL_RETURN:
			/*If it is not a function it cannot have a return statement*/
			if (!is_func)
				res = sql_error(sql, 01, SQLSTATE(42000) "Return statement in the procedure body");
			else {
				/* should be last statement of a sequential_block */
				if (n->next) { 
					res = sql_error(sql, 01, SQLSTATE(42000) "Statement after return");
				} else {
					res = NULL;
					reslist = rel_psm_return(sql, restype, restypelist, s->data.sym);
				}
			}
			break;
		case SQL_SELECT: { /* row selections (into variables) */
			exp_kind ek = {type_value, card_row, TRUE};
			reslist = rel_select_into(sql, s, ek);
		}	break;
		case SQL_COPYFROM:
		case SQL_BINCOPYFROM:
		case SQL_INSERT:
		case SQL_UPDATE:
		case SQL_DELETE:
		case SQL_TRUNCATE:
		case SQL_MERGE: {
			sql_rel *r = rel_updates(sql, s);
			if (!r)
				return NULL;
			res = exp_rel(sql, r);
		}	break;
		default:
			res = sql_error(sql, 01, SQLSTATE(42000) "Statement '%s' is not a valid flow control statement",
			 token2string(s->token));
		}
		if (!res && !reslist) {
			l = NULL;
			break;
		}
		if (res)
			list_append(l, res);
		else
			list_merge(l, reslist, NULL);
	}
	stack_pop_frame(sql);
	return l;
}
Пример #9
0
/* assoc_mgr locks need to be unlocked before coming here */
static int _get_object_usage(mysql_conn_t *mysql_conn,
			     slurmdbd_msg_type_t type, char *my_usage_table,
			     char *cluster_name, char *id_str,
			     time_t start, time_t end, List *usage_list)
{
	char *tmp = NULL;
	int i = 0;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;
	char *query = NULL;
	assoc_mgr_lock_t locks = { NO_LOCK, NO_LOCK, NO_LOCK, NO_LOCK,
				   READ_LOCK, NO_LOCK, NO_LOCK };

	char *usage_req_inx[] = {
		"t3.id_assoc",
		"t1.id_tres",
		"t1.time_start",
		"t1.alloc_secs",
	};
	enum {
		USAGE_ID,
		USAGE_TRES,
		USAGE_START,
		USAGE_ALLOC,
		USAGE_COUNT
	};

	if (type == DBD_GET_WCKEY_USAGE)
		usage_req_inx[0] = "t1.id";

	xstrfmtcat(tmp, "%s", usage_req_inx[i]);
	for (i=1; i<USAGE_COUNT; i++) {
		xstrfmtcat(tmp, ", %s", usage_req_inx[i]);
	}

	switch (type) {
	case DBD_GET_ASSOC_USAGE:
		query = xstrdup_printf(
			"select %s from \"%s_%s\" as t1, "
			"\"%s_%s\" as t2, \"%s_%s\" as t3 "
			"where (t1.time_start < %ld && t1.time_start >= %ld) "
			"&& t1.id=t2.id_assoc && (%s) && "
			"t2.lft between t3.lft and t3.rgt "
			"order by t3.id_assoc, time_start;",
			tmp, cluster_name, my_usage_table,
			cluster_name, assoc_table, cluster_name, assoc_table,
			end, start, id_str);
		break;
	case DBD_GET_WCKEY_USAGE:
		query = xstrdup_printf(
			"select %s from \"%s_%s\" as t1 "
			"where (time_start < %ld && time_start >= %ld) "
			"&& (%s) order by id, time_start;",
			tmp, cluster_name, my_usage_table, end, start, id_str);
		break;
	default:
		error("Unknown usage type %d", type);
		xfree(tmp);
		return SLURM_ERROR;
		break;
	}
	xfree(tmp);

	if (debug_flags & DEBUG_FLAG_DB_USAGE)
		DB_DEBUG(mysql_conn->conn, "query\n%s", query);
	result = mysql_db_query_ret(mysql_conn, query, 0);
	xfree(query);

	if (!result)
		return SLURM_ERROR;

	if (!(*usage_list))
		(*usage_list) = list_create(slurmdb_destroy_accounting_rec);

	assoc_mgr_lock(&locks);
	while ((row = mysql_fetch_row(result))) {
		slurmdb_tres_rec_t *tres_rec;
		slurmdb_accounting_rec_t *accounting_rec =
			xmalloc(sizeof(slurmdb_accounting_rec_t));

		accounting_rec->tres_rec.id = slurm_atoul(row[USAGE_TRES]);
		if ((tres_rec = list_find_first(
			     assoc_mgr_tres_list, slurmdb_find_tres_in_list,
			     &accounting_rec->tres_rec.id))) {
			accounting_rec->tres_rec.name =
				xstrdup(tres_rec->name);
			accounting_rec->tres_rec.type =
				xstrdup(tres_rec->type);
		}

		accounting_rec->id = slurm_atoul(row[USAGE_ID]);
		accounting_rec->period_start = slurm_atoul(row[USAGE_START]);
		accounting_rec->alloc_secs = slurm_atoull(row[USAGE_ALLOC]);

		list_append(*usage_list, accounting_rec);
	}
	assoc_mgr_unlock(&locks);

	mysql_free_result(result);

	return SLURM_SUCCESS;
}
Пример #10
0
int
config_parse_file( const char *filename, config_t *c ){
	int fd;
	char *line;
  char *arg,*val;
  int in_profile = 0;
  int rc = 0;
  profile_config_t *p = NULL;
	fd = open( filename, O_RDONLY );
	if( fd == -1 ){
    LOGERROR( "Could not open file %s: (%d) %s", filename, errno, strerror( errno ) );
		return 1;
	}
  val = NULL;
	while ( ( line = f_readline( fd ) ) ){
    arg = skip_whitespaces( line );
    if( arg[0] == '#' || arg[0] == ';' ){
      free(line);
      continue;
    }
    if( !strncmp( arg, "<profile>", strlen( "<profile>" ) ) ){
      in_profile = 1;
      p = profile_config_new( );
      free(line);
      if( p == NULL ){
        LOGERROR( "Could not allocate memory for new profile" );
        rc = 1;
        break;
      }
      list_append( c->profiles, p );
      continue;
    }
    if( !strncmp( arg, "</profile>", strlen( "</profile>" ) ) ){
      in_profile = 0;
      STRDUP_IFNOTSET(p->search_filter, OSEARCH_FILTER);
      p = NULL;
      free(line);
      continue;
    }
    arg = strtok( arg, "=" );
    if(arg && *arg != '\n'){
      val = strtok( NULL, "\n");
      /* global conf -> ldap */
      if( !strcmp( arg, "uri" ) ){
        STRDUP_IFNOTSET(c->ldap->uri, val );
      } else if ( !strcmp( arg, "binddn" ) ) {
        STRDUP_IFNOTSET(c->ldap->binddn, val );
      }else if ( !strcmp( arg, "bindpw" ) ) {
        STRDUP_IFNOTSET(c->ldap->bindpw, val );
      }else if ( !strcmp( arg, "version" ) ){
        if(!c->ldap->version) c->ldap->version = atoi(val);
      }else if ( !strcmp( arg, "ssl" ) ){
        STRDUP_IFNOTSET(c->ldap->ssl, val );
      }else if ( !strcmp( arg, "tls_cacertfile" ) ){
        STRDUP_IFNOTSET(c->ldap->tls_cacertfile, val );
      }else if ( !strcmp( arg, "tls_cacertdir" ) ){
        STRDUP_IFNOTSET(c->ldap->tls_cacertdir, val );
      }else if ( !strcmp( arg, "tls_certfile" ) ){
        STRDUP_IFNOTSET(c->ldap->tls_certfile, val );
      }else if ( !strcmp( arg, "tls_certkey" ) ){
        STRDUP_IFNOTSET(c->ldap->tls_certkey, val );
      }else if ( !strcmp( arg, "tls_ciphersuite" ) ){
        STRDUP_IFNOTSET(c->ldap->tls_ciphersuite, val );
      }else if ( !strcmp( arg, "tls_reqcert" ) ){
        STRDUP_IFNOTSET(c->ldap->tls_reqcert, val );
      }else if( !strcmp( arg, "timeout" ) ){
        if( !c->ldap->timeout ) c->ldap->timeout = atoi(val);
      /* profile conf */
      }else if ( !strcmp( arg, "basedn" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->basedn, val );
      }else if ( !strcmp( arg, "search_filter" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->search_filter, val );
      }else if ( !strcmp( arg, "search_scope" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        if( !strcasecmp( val, "LDAP_SCOPE_BASE" ) ){
          p->search_scope = LA_SCOPE_BASE;
        }else if( !strcasecmp( val, "LDAP_SCOPE_ONELEVEL" ) ){
          p->search_scope = LA_SCOPE_ONELEVEL;
        }else if( !strcasecmp( val, "LDAP_SCOPE_SUBTREE" ) ){
          p->search_scope = LA_SCOPE_SUBTREE;
        }
      /* Group */
      }else if( !strcmp( arg, "groupdn" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->groupdn, val );
      }else if( !strcmp( arg, "group_search_filter" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->group_search_filter, val );
      }else if( !strcmp( arg, "member_attribute" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->member_attribute, val );
      /* Default GW */
      }else if( !strcmp( arg, "redirect_gateway_prefix" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->redirect_gateway_prefix, val );
      }else if( !strcmp( arg, "redirect_gateway_flags" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->redirect_gateway_flags, val );
      /* PF */
      }else if( !strcmp( arg, "enable_pf" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        p->enable_pf = string_to_ternary( val );
      }else if( !strcmp( arg, "default_pf_rules" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->default_pf_rules, val );
#ifdef ENABLE_LDAPUSERCONF
      }else if( !strcmp( arg, "default_profiledn" ) ){
        CHECK_IF_IN_PROFILE( arg, in_profile );
        STRDUP_IFNOTSET(p->default_profiledn, val );
#endif
      }else{
        LOGWARNING("Unrecognized option *%s=%s*", arg, val);
      }

    }
		free( line );
	}
	close( fd );
	return rc;
}
Пример #11
0
/* 	1
	CASE
	WHEN search_condition THEN statements
	[ WHEN search_condition THEN statements ]
	[ ELSE statements ]
	END CASE

	2
	CASE case_value
	WHEN when_value THEN statements
	[ WHEN when_value THEN statements ]
	[ ELSE statements ]
	END CASE
 */
static list * 
rel_psm_case( mvc *sql, sql_subtype *res, list *restypelist, dnode *case_when, int is_func )
{
	list *case_stmts = sa_list(sql->sa);

	if (!case_when)
		return NULL;

	/* case 1 */
	if (case_when->type == type_symbol) {
		dnode *n = case_when;
		symbol *case_value = n->data.sym;
		dlist *when_statements = n->next->data.lval;
		dlist *else_statements = n->next->next->data.lval;
		list *else_stmt = NULL;
		sql_rel *rel = NULL;
		exp_kind ek = {type_value, card_value, FALSE};
		sql_exp *v = rel_value_exp(sql, &rel, case_value, sql_sel, ek);

		if (!v)
			return NULL;
		if (rel)
			return sql_error(sql, 02, SQLSTATE(42000) "CASE: No SELECT statements allowed within the CASE condition");
		if (else_statements) {
			else_stmt = sequential_block( sql, res, restypelist, else_statements, NULL, is_func);
			if (!else_stmt) 
				return NULL;
		}
		n = when_statements->h;
		while(n) {
			dnode *m = n->data.sym->data.lval->h;
			sql_exp *cond=0, *when_value = rel_value_exp(sql, &rel, m->data.sym, sql_sel, ek);
			list *if_stmts = NULL;
			sql_exp *case_stmt = NULL;

			if (!when_value || rel ||
			   (cond = rel_binop_(sql, v, when_value, NULL, "=", card_value)) == NULL || 
			   (if_stmts = sequential_block( sql, res, restypelist, m->next->data.lval, NULL, is_func)) == NULL ) {
				if (rel)
					return sql_error(sql, 02, SQLSTATE(42000) "CASE: No SELECT statements allowed within the CASE condition");
				return NULL;
			}
			case_stmt = exp_if(sql->sa, cond, if_stmts, NULL);
			list_append(case_stmts, case_stmt);
			n = n->next;
		}
		if (else_stmt)
			list_merge(case_stmts, else_stmt, NULL);
		return case_stmts;
	} else { 
		/* case 2 */
		dnode *n = case_when;
		dlist *whenlist = n->data.lval;
		dlist *else_statements = n->next->data.lval;
		list *else_stmt = NULL;

		if (else_statements) {
			else_stmt = sequential_block( sql, res, restypelist, else_statements, NULL, is_func);
			if (!else_stmt) 
				return NULL;
		}
		n = whenlist->h;
		while(n) {
			dnode *m = n->data.sym->data.lval->h;
			sql_rel *rel = NULL;
			sql_exp *cond = rel_logical_value_exp(sql, &rel, m->data.sym, sql_sel);
			list *if_stmts = NULL;
			sql_exp *case_stmt = NULL;

			if (!cond || rel ||
			   (if_stmts = sequential_block( sql, res, restypelist, m->next->data.lval, NULL, is_func)) == NULL ) {
				if (rel)
					return sql_error(sql, 02, SQLSTATE(42000) "CASE: No SELECT statements allowed within the CASE condition");
				return NULL;
			}
			case_stmt = exp_if(sql->sa, cond, if_stmts, NULL);
			list_append(case_stmts, case_stmt);
			n = n->next;
		}
		if (else_stmt)
			list_merge(case_stmts, else_stmt, NULL);
		return case_stmts;
	}
}
Пример #12
0
/*
 * information about relative ranks as assigned by the RM
 */
static void _set_procdatas(List lresp)
{
	pmixp_namespace_t *nsptr = pmixp_nspaces_local();
	pmix_info_t *kvp, *tkvp;
	char *p = NULL;
	int i;

	/* (char*) jobid assigned by scheduler */
	xstrfmtcat(p, "%d.%d", pmixp_info_jobid(), pmixp_info_stepid());
	PMIXP_ALLOC_KEY(kvp, PMIX_JOBID);
	PMIX_VAL_SET(&kvp->value, string, p);
	xfree(p);
	list_append(lresp, kvp);

	PMIXP_ALLOC_KEY(kvp, PMIX_NODEID);
	PMIX_VAL_SET(&kvp->value, uint32_t, nsptr->node_id);
	list_append(lresp, kvp);

	/* store information about local processes */
	for (i = 0; i < pmixp_info_tasks(); i++) {
		List rankinfo;
		ListIterator it;
		int count, j, localid, nodeid;
		char *nodename;
		pmix_info_t *info;

		rankinfo = list_create(pmixp_xfree_xmalloced);

		PMIXP_ALLOC_KEY(kvp, PMIX_RANK);
		PMIX_VAL_SET(&kvp->value, int, i);
		list_append(rankinfo, kvp);

		/* TODO: always use 0 so far. this is not the general case though
		 * (see SLURM MIMD: man srun, section MULTIPLE PROGRAM CONFIGURATION)
		 */
		PMIXP_ALLOC_KEY(kvp, PMIX_APPNUM);
		PMIX_VAL_SET(&kvp->value, int, 0);
		list_append(rankinfo, kvp);

		/* TODO: the same as for previous here */
		PMIXP_ALLOC_KEY(kvp, PMIX_APPLDR);
		PMIX_VAL_SET(&kvp->value, int, 0);
		list_append(rankinfo, kvp);

		/* TODO: fix when several apps will appear */
		PMIXP_ALLOC_KEY(kvp, PMIX_GLOBAL_RANK);
		PMIX_VAL_SET(&kvp->value, uint32_t, i);
		list_append(rankinfo, kvp);

		/* TODO: fix when several apps will appear */
		PMIXP_ALLOC_KEY(kvp, PMIX_APP_RANK);
		PMIX_VAL_SET(&kvp->value, uint32_t, i);
		list_append(rankinfo, kvp);

		localid = pmixp_info_taskid2localid(i);
		/* this rank is local, store local info ab't it! */
		if (0 <= localid) {
			PMIXP_ALLOC_KEY(kvp, PMIX_LOCAL_RANK);
			PMIX_VAL_SET(&kvp->value, uint16_t, localid);
			list_append(rankinfo, kvp);

			/* TODO: fix when several apps will appear */
			PMIXP_ALLOC_KEY(kvp, PMIX_NODE_RANK);
			PMIX_VAL_SET(&kvp->value, uint16_t, localid);
			list_append(rankinfo, kvp);
		}

		nodeid = nsptr->task_map[i];
		nodename = hostlist_nth(nsptr->hl, nodeid);
		PMIXP_ALLOC_KEY(kvp, PMIX_HOSTNAME);
		PMIX_VAL_SET(&kvp->value, string, nodename);
		list_append(rankinfo, kvp);
		free(nodename);

		/* merge rankinfo into one PMIX_PROC_DATA key */
		count = list_count(rankinfo);
		PMIXP_ALLOC_KEY(kvp, PMIX_PROC_DATA);
		kvp->value.type = PMIX_INFO_ARRAY;
		kvp->value.data.array.size = count;
		PMIX_INFO_CREATE(info, count);
		it = list_iterator_create(rankinfo);
		j = 0;
		while (NULL != (tkvp = list_next(it))) {
			/* Just copy all the fields here. We will free original kvp's
			 * using list_destroy without free'ing their fields so it is
			 * safe to do so.
			 */
			info[j] = *tkvp;
			j++;
		}
		list_destroy(rankinfo);

		kvp->value.data.array.array = (pmix_info_t *)info;
		info = NULL;

		/* put the complex key to the list */
		list_append(lresp, kvp);
	}
}
Пример #13
0
/** Perform a path lookup.
 *
 * @param path    Path to be resolved; it must be a NULL-terminated
 *                string.
 * @param lflag   Flags to be used during lookup.
 * @param result  Empty structure where the lookup result will be stored.
 *                Can be NULL.
 * @param altroot If non-empty, will be used instead of rootfs as the root
 *                of the whole VFS tree.
 *
 * @return EOK on success or an error code from errno.h.
 *
 */
int vfs_lookup_internal(char *path, int lflag, vfs_lookup_res_t *result,
    vfs_pair_t *altroot, ...)
{
	vfs_pair_t *root;

	if (altroot)
		root = altroot;
	else
		root = &rootfs;

	if (!root->fs_handle)
		return ENOENT;
	
	size_t len;
	path = canonify(path, &len);
	if (!path)
		return EINVAL;
	
	fs_index_t index = 0;
	if (lflag & L_LINK) {
		va_list ap;

		va_start(ap, altroot);
		index = va_arg(ap, fs_index_t);
		va_end(ap);
	}
	
	fibril_mutex_lock(&plb_mutex);

	plb_entry_t entry;
	link_initialize(&entry.plb_link);
	entry.len = len;

	size_t first;	/* the first free index */
	size_t last;	/* the last free index */

	if (list_empty(&plb_entries)) {
		first = 0;
		last = PLB_SIZE - 1;
	} else {
		plb_entry_t *oldest = list_get_instance(
		    list_first(&plb_entries), plb_entry_t, plb_link);
		plb_entry_t *newest = list_get_instance(
		    list_last(&plb_entries), plb_entry_t, plb_link);

		first = (newest->index + newest->len) % PLB_SIZE;
		last = (oldest->index - 1) % PLB_SIZE;
	}

	if (first <= last) {
		if ((last - first) + 1 < len) {
			/*
			 * The buffer cannot absorb the path.
			 */
			fibril_mutex_unlock(&plb_mutex);
			return ELIMIT;
		}
	} else {
		if (PLB_SIZE - ((first - last) + 1) < len) {
			/*
			 * The buffer cannot absorb the path.
			 */
			fibril_mutex_unlock(&plb_mutex);
			return ELIMIT;
		}
	}

	/*
	 * We know the first free index in PLB and we also know that there is
	 * enough space in the buffer to hold our path.
	 */

	entry.index = first;
	entry.len = len;

	/*
	 * Claim PLB space by inserting the entry into the PLB entry ring
	 * buffer.
	 */
	list_append(&entry.plb_link, &plb_entries);
	
	fibril_mutex_unlock(&plb_mutex);

	/*
	 * Copy the path into PLB.
	 */
	size_t cnt1 = min(len, (PLB_SIZE - first) + 1);
	size_t cnt2 = len - cnt1;
	
	memcpy(&plb[first], path, cnt1);
	memcpy(plb, &path[cnt1], cnt2);

	ipc_call_t answer;
	async_exch_t *exch = vfs_exchange_grab(root->fs_handle);
	aid_t req = async_send_5(exch, VFS_OUT_LOOKUP, (sysarg_t) first,
	    (sysarg_t) (first + len - 1) % PLB_SIZE,
	    (sysarg_t) root->service_id, (sysarg_t) lflag, (sysarg_t) index,
	    &answer);
	
	sysarg_t rc;
	async_wait_for(req, &rc);
	vfs_exchange_release(exch);
	
	fibril_mutex_lock(&plb_mutex);
	list_remove(&entry.plb_link);
	/*
	 * Erasing the path from PLB will come handy for debugging purposes.
	 */
	memset(&plb[first], 0, cnt1);
	memset(plb, 0, cnt2);
	fibril_mutex_unlock(&plb_mutex);
	
	if ((int) rc < EOK)
		return (int) rc;

	if (!result)
		return EOK;
	
	result->triplet.fs_handle = (fs_handle_t) rc;
	result->triplet.service_id = (service_id_t) IPC_GET_ARG1(answer);
	result->triplet.index = (fs_index_t) IPC_GET_ARG2(answer);
	result->size =
	    (aoff64_t) MERGE_LOUP32(IPC_GET_ARG3(answer), IPC_GET_ARG4(answer));
	result->lnkcnt = (unsigned int) IPC_GET_ARG5(answer);
	
	if (lflag & L_FILE)
		result->type = VFS_NODE_FILE;
	else if (lflag & L_DIRECTORY)
		result->type = VFS_NODE_DIRECTORY;
	else
		result->type = VFS_NODE_UNKNOWN;
	
	return EOK;
}
Пример #14
0
//============================================================================
//                                 add_to_set
//============================================================================
int set_add(set_t *set, uint64_t val)
{
    int index = list_in(set, val);
    if (index >= 0) return index;
    return list_append(set, val);
}
Пример #15
0
Файл: s2ir.c Проект: Rayerd/dmd
void TryCatchStatement::toIR(IRState *irs)
{
    Blockx *blx = irs->blx;

#if SEH
    nteh_declarvars(blx);
#endif

    IRState mystate(irs, this);

    block *tryblock = block_goto(blx,BCgoto,NULL);

    int previndex = blx->scope_index;
    tryblock->Blast_index = previndex;
    blx->scope_index = tryblock->Bscope_index = blx->next_index++;

    // Set the current scope index
    setScopeIndex(blx,tryblock,tryblock->Bscope_index);

    // This is the catch variable
    tryblock->jcatchvar = symbol_genauto(type_fake(mTYvolatile | TYnptr));

    blx->tryblock = tryblock;
    block *breakblock = block_calloc(blx);
    block_goto(blx,BC_try,NULL);
    if (body)
    {
        body->toIR(&mystate);
    }
    blx->tryblock = tryblock->Btry;

    // break block goes here
    block_goto(blx, BCgoto, breakblock);

    setScopeIndex(blx,blx->curblock, previndex);
    blx->scope_index = previndex;

    // create new break block that follows all the catches
    breakblock = block_calloc(blx);

    list_append(&blx->curblock->Bsucc, breakblock);
    block_next(blx,BCgoto,NULL);

    assert(catches);
    for (size_t i = 0 ; i < catches->dim; i++)
    {
        Catch *cs = catches->tdata()[i];
        if (cs->var)
            cs->var->csym = tryblock->jcatchvar;
        block *bcatch = blx->curblock;
        if (cs->type)
            bcatch->Bcatchtype = cs->type->toBasetype()->toSymbol();
        list_append(&tryblock->Bsucc,bcatch);
        block_goto(blx,BCjcatch,NULL);
        if (cs->handler != NULL)
        {
            IRState catchState(irs, this);
            cs->handler->toIR(&catchState);
        }
        list_append(&blx->curblock->Bsucc, breakblock);
        block_next(blx, BCgoto, NULL);
    }

    block_next(blx,(enum BC)blx->curblock->BC, breakblock);
}
Пример #16
0
/* assoc_mgr locks need to unlocked before you get here */
static int _get_cluster_usage(mysql_conn_t *mysql_conn, uid_t uid,
			      slurmdb_cluster_rec_t *cluster_rec,
			      slurmdbd_msg_type_t type,
			      time_t start, time_t end)
{
	int rc = SLURM_SUCCESS;
	int i=0;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;
	char *tmp = NULL;
	char *my_usage_table = cluster_day_table;
	char *query = NULL;
	assoc_mgr_lock_t locks = { NO_LOCK, NO_LOCK, NO_LOCK, NO_LOCK,
				   READ_LOCK, NO_LOCK, NO_LOCK };
	char *cluster_req_inx[] = {
		"id_tres",
		"alloc_secs",
		"down_secs",
		"pdown_secs",
		"idle_secs",
		"resv_secs",
		"over_secs",
		"count",
		"time_start",
	};

	enum {
		CLUSTER_TRES,
		CLUSTER_ACPU,
		CLUSTER_DCPU,
		CLUSTER_PDCPU,
		CLUSTER_ICPU,
		CLUSTER_RCPU,
		CLUSTER_OCPU,
		CLUSTER_CNT,
		CLUSTER_START,
		CLUSTER_COUNT
	};

	if (!cluster_rec->name || !cluster_rec->name[0]) {
		error("We need a cluster name to set data for");
		return SLURM_ERROR;
	}

	if (set_usage_information(&my_usage_table, type, &start, &end)
	    != SLURM_SUCCESS) {
		return SLURM_ERROR;
	}

	xfree(tmp);
	i=0;
	xstrfmtcat(tmp, "%s", cluster_req_inx[i]);
	for(i=1; i<CLUSTER_COUNT; i++) {
		xstrfmtcat(tmp, ", %s", cluster_req_inx[i]);
	}

	query = xstrdup_printf(
		"select %s from \"%s_%s\" where (time_start < %ld "
		"&& time_start >= %ld)",
		tmp, cluster_rec->name, my_usage_table, end, start);

	xfree(tmp);
	if (debug_flags & DEBUG_FLAG_DB_USAGE)
		DB_DEBUG(mysql_conn->conn, "query\n%s", query);

	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		return SLURM_ERROR;
	}
	xfree(query);

	if (!cluster_rec->accounting_list)
		cluster_rec->accounting_list =
			list_create(slurmdb_destroy_cluster_accounting_rec);

	assoc_mgr_lock(&locks);
	while ((row = mysql_fetch_row(result))) {
		slurmdb_tres_rec_t *tres_rec;
		slurmdb_cluster_accounting_rec_t *accounting_rec =
			xmalloc(sizeof(slurmdb_cluster_accounting_rec_t));

		accounting_rec->tres_rec.id = slurm_atoul(row[CLUSTER_TRES]);
		accounting_rec->tres_rec.count = slurm_atoul(row[CLUSTER_CNT]);
		if ((tres_rec = list_find_first(
			     assoc_mgr_tres_list, slurmdb_find_tres_in_list,
			     &accounting_rec->tres_rec.id))) {
			accounting_rec->tres_rec.name =
				xstrdup(tres_rec->name);
			accounting_rec->tres_rec.type =
				xstrdup(tres_rec->type);
		}

		accounting_rec->alloc_secs = slurm_atoull(row[CLUSTER_ACPU]);
		accounting_rec->down_secs = slurm_atoull(row[CLUSTER_DCPU]);
		accounting_rec->pdown_secs = slurm_atoull(row[CLUSTER_PDCPU]);
		accounting_rec->idle_secs = slurm_atoull(row[CLUSTER_ICPU]);
		accounting_rec->over_secs = slurm_atoull(row[CLUSTER_OCPU]);
		accounting_rec->resv_secs = slurm_atoull(row[CLUSTER_RCPU]);
		accounting_rec->period_start = slurm_atoul(row[CLUSTER_START]);
		list_append(cluster_rec->accounting_list, accounting_rec);
	}
	assoc_mgr_unlock(&locks);

	mysql_free_result(result);
	return rc;
}
Пример #17
0
Файл: s2ir.c Проект: Rayerd/dmd
void AsmStatement::toIR(IRState *irs)
{
    block *bpre;
    block *basm;
    Declaration *d;
    Symbol *s;
    Blockx *blx = irs->blx;

    //printf("AsmStatement::toIR(asmcode = %x)\n", asmcode);
    bpre = blx->curblock;
    block_next(blx,BCgoto,NULL);
    basm = blx->curblock;
    list_append(&bpre->Bsucc, basm);
    basm->Bcode = asmcode;
    basm->Balign = asmalign;
#if 0
    if (label)
    {   block *b;

        b = labelToBlock(loc, blx, label);
        printf("AsmStatement::toIR() %p\n", b);
        if (b)
            list_append(&basm->Bsucc, b);
    }
#endif
    // Loop through each instruction, fixing Dsymbols into Symbol's
    for (code *c = asmcode; c; c = c->next)
    {   LabelDsymbol *label;
        block *b;

        switch (c->IFL1)
        {
        case FLblockoff:
        case FLblock:
            // FLblock and FLblockoff have LabelDsymbol's - convert to blocks
            label = c->IEVlsym1;
            b = labelToBlock(loc, blx, label);
            list_append(&basm->Bsucc, b);
            c->IEV1.Vblock = b;
            break;

        case FLdsymbol:
        case FLfunc:
            s = c->IEVdsym1->toSymbol();
            if (s->Sclass == SCauto && s->Ssymnum == -1)
                symbol_add(s);
            c->IEVsym1 = s;
            c->IFL1 = s->Sfl ? s->Sfl : FLauto;
            break;
        }

        // Repeat for second operand
        switch (c->IFL2)
        {
        case FLblockoff:
        case FLblock:
            label = c->IEVlsym2;
            b = labelToBlock(loc, blx, label);
            list_append(&basm->Bsucc, b);
            c->IEV2.Vblock = b;
            break;

        case FLdsymbol:
        case FLfunc:
            d = c->IEVdsym2;
            s = d->toSymbol();
            if (s->Sclass == SCauto && s->Ssymnum == -1)
                symbol_add(s);
            c->IEVsym2 = s;
            c->IFL2 = s->Sfl ? s->Sfl : FLauto;
            if (d->isDataseg())
                s->Sflags |= SFLlivexit;
            break;
        }
        //c->print();
    }

    basm->bIasmrefparam = refparam;             // are parameters reference?
    basm->usIasmregs = regs;                    // registers modified

    block_next(blx,BCasm, NULL);
    list_prepend(&basm->Bsucc, blx->curblock);

    if (naked)
    {
        blx->funcsym->Stype->Tty |= mTYnaked;
    }
}
Пример #18
0
/* checks should already be done before this to see if this is a valid
   user or not.  The assoc_mgr locks should be unlocked before coming here.
*/
extern int get_usage_for_list(mysql_conn_t *mysql_conn,
			      slurmdbd_msg_type_t type, List object_list,
			      char *cluster_name, time_t start, time_t end)
{
	int rc = SLURM_SUCCESS;
	char *my_usage_table = NULL;
	List usage_list = NULL;
	char *id_str = NULL;
	ListIterator itr = NULL, u_itr = NULL;
	void *object = NULL;
	slurmdb_assoc_rec_t *assoc = NULL;
	slurmdb_wckey_rec_t *wckey = NULL;
	slurmdb_accounting_rec_t *accounting_rec = NULL;

	if (!object_list) {
		error("We need an object to set data for getting usage");
		return SLURM_ERROR;
	}

	if (check_connection(mysql_conn) != SLURM_SUCCESS)
		return ESLURM_DB_CONNECTION;

	switch (type) {
	case DBD_GET_ASSOC_USAGE:
		itr = list_iterator_create(object_list);
		while ((assoc = list_next(itr))) {
			if (id_str)
				xstrfmtcat(id_str, " || t3.id_assoc=%d",
					   assoc->id);
			else
				xstrfmtcat(id_str, "t3.id_assoc=%d", assoc->id);
		}
		list_iterator_destroy(itr);

		my_usage_table = assoc_day_table;
		break;
	case DBD_GET_WCKEY_USAGE:
		itr = list_iterator_create(object_list);
		while ((wckey = list_next(itr))) {
			if (id_str)
				xstrfmtcat(id_str, " || id=%d",
					   wckey->id);
			else
				xstrfmtcat(id_str, "id=%d", wckey->id);
		}
		list_iterator_destroy(itr);

		my_usage_table = wckey_day_table;
		break;
	default:
		error("Unknown usage type %d", type);
		return SLURM_ERROR;
		break;
	}

	if (set_usage_information(&my_usage_table, type, &start, &end)
	    != SLURM_SUCCESS) {
		xfree(id_str);
		return SLURM_ERROR;
	}

	if (_get_object_usage(mysql_conn, type, my_usage_table, cluster_name,
			      id_str, start, end, &usage_list)
	    != SLURM_SUCCESS) {
		xfree(id_str);
		return SLURM_ERROR;
	}

	xfree(id_str);

	if (!usage_list) {
		error("No usage given back?  This should never happen");
		return SLURM_ERROR;
	}

	u_itr = list_iterator_create(usage_list);
	itr = list_iterator_create(object_list);
	while ((object = list_next(itr))) {
		int found = 0;
		int id = 0;
		List acct_list = NULL;

		switch (type) {
		case DBD_GET_ASSOC_USAGE:
			assoc = (slurmdb_assoc_rec_t *)object;
			if (!assoc->accounting_list)
				assoc->accounting_list = list_create(
					slurmdb_destroy_accounting_rec);
			acct_list = assoc->accounting_list;
			id = assoc->id;
			break;
		case DBD_GET_WCKEY_USAGE:
			wckey = (slurmdb_wckey_rec_t *)object;
			if (!wckey->accounting_list)
				wckey->accounting_list = list_create(
					slurmdb_destroy_accounting_rec);
			acct_list = wckey->accounting_list;
			id = wckey->id;
			break;
		default:
			continue;
			break;
		}

		while ((accounting_rec = list_next(u_itr))) {
			if (id == accounting_rec->id) {
				list_append(acct_list, accounting_rec);
				list_remove(u_itr);
				found = 1;
			} else if (found) {
				/* here we know the
				   list is in id order so
				   if the next record
				   isn't the correct id
				   just continue since
				   there is no reason to
				   go through the rest of
				   the list when we know
				   it isn't going to be
				   the correct id */
				break;
			}
		}
		list_iterator_reset(u_itr);
	}
	list_iterator_destroy(itr);
	list_iterator_destroy(u_itr);

	if (list_count(usage_list))
		error("we have %d records not added "
		      "to the association list",
		      list_count(usage_list));
	list_destroy(usage_list);

	return rc;
}
Пример #19
0
Файл: s2ir.c Проект: Rayerd/dmd
void ForeachRangeStatement::toIR(IRState *irs)
{
    assert(0);
#if 0
    Type *tab;
    elem *eaggr;
    elem *elwr;
    elem *eupr;
    elem *e;
    elem *elength;
    tym_t keytym;

    //printf("ForeachStatement::toIR()\n");
    block *bpre;
    block *bcond;
    block *bbody;
    block *bbodyx;
    Blockx *blx = irs->blx;

    IRState mystate(irs,this);
    mystate.breakBlock = block_calloc(blx);
    mystate.contBlock = block_calloc(blx);

    incUsage(irs, lwr->loc);
    elwr = lwr->toElem(irs);

    incUsage(irs, upr->loc);
    eupr = upr->toElem(irs);

    /* Create skey, the index to the array.
     * Initialize skey to elwr (foreach) or eupr (foreach_reverse).
     */
    Symbol *skey = key->toSymbol();
    symbol_add(skey);
    keytym = key->type->totym();

    elem *ekey;
    if (key->offset)            // if key is member of a closure
    {
        assert(irs->sclosure);
        ekey = el_var(irs->sclosure);
        ekey = el_bin(OPadd, TYnptr, ekey, el_long(TYint, key->offset));
        ekey = el_una(OPind, keytym, ekey);
    }
    else
        ekey = el_var(skey);

    elem *einit = (op == TOKforeach_reverse) ? eupr : elwr;
    e = el_bin(OPeq, keytym, ekey, einit);   // skey = einit;
    block_appendexp(blx->curblock, e);

    /* Make a copy of the end condition, so it only
     * gets evaluated once.
     */
    elem *eend = (op == TOKforeach_reverse) ? elwr : eupr;
    Symbol *send = symbol_genauto(eend);
    e = el_bin(OPeq, eend->Ety, el_var(send), eend);
    assert(tybasic(e->Ety) != TYstruct);
    block_appendexp(blx->curblock, e);

    bpre = blx->curblock;
    block_next(blx,BCgoto,NULL);
    bcond = blx->curblock;

    if (op == TOKforeach_reverse)
    {
        // Construct (key > elwr)
        e = el_bin(OPgt, TYint, el_copytree(ekey), el_var(send));
    }
    else
    {
        // Construct (key < eupr)
        e = el_bin(OPlt, TYint, el_copytree(ekey), el_var(send));
    }

    // The size of the increment
    size_t sz = 1;
    Type *tkeyb = key->type->toBasetype();
    if (tkeyb->ty == Tpointer)
        sz = tkeyb->nextOf()->size();

    bcond->Belem = e;
    block_next(blx, BCiftrue, NULL);

    if (op == TOKforeach_reverse)
    {
        // Construct (skey -= 1)
        e = el_bin(OPminass, keytym, el_copytree(ekey), el_long(keytym, sz));
        block_appendexp(blx->curblock, e);
    }

    bbody = blx->curblock;
    if (body)
        body->toIR(&mystate);
    bbodyx = blx->curblock;
    block_next(blx,BCgoto,mystate.contBlock);

    if (op == TOKforeach)
    {
        // Construct (skey += 1)
        e = el_bin(OPaddass, keytym, el_copytree(ekey), el_long(keytym, sz));
        mystate.contBlock->Belem = e;
    }
    block_next(blx,BCgoto,mystate.breakBlock);

    list_append(&bpre->Bsucc,bcond);
    list_append(&bcond->Bsucc,bbody);
    list_append(&bcond->Bsucc,mystate.breakBlock);
    list_append(&bbodyx->Bsucc,mystate.contBlock);
    list_append(&mystate.contBlock->Bsucc,bcond);
#endif
}
Пример #20
0
void process_data(FILE *input_file)
{
	char filestream[2000000]; 
	struct node *new_node = NULL; 
	if (input_file == stdin)
	{
	   printf("Type input: "); 
	   int number;
	   fflush(stdout);
	   while(fgets(filestream, 2000000,stdin)!= NULL)
	   { 	
	        int slen = strlen(filestream);
		filestream[slen-1] = '\0';  
 
	        if(strlen(filestream) >= 1)
	        {
		    char *token = strtok(filestream, " \t\n");
		    while(token != NULL)
		    {
		        int counter= 0; 
		        for(int i=0; i<strlen(token); i++)
    		        {
    			    if(i == 0 && (isdigit(token[i]) || token[i]=='-'))
    			    {
    			    	counter++; 
    			    }	 
    			    else if(isdigit(token[i]))
    			    {
    				counter++; 
	    		    }
       		        }
	    		if (counter == strlen(token))
	    		{
	    			number = atoi(token); 
	    			list_append(&number, &new_node); 
	    		}
                        if(token[0]=='#')
                        {
                            token=strtok(NULL,"\n");
                        }
                        else
                        {
                            token = strtok(NULL, " \t\n");
                        }
		    }
		    printf("add next item, or ctrl+d to exit: ");
		    fflush(stdout);
	        }
   	   }
	}
	else
	{
		int number; 
		while(fgets(filestream, 2000000,input_file) != NULL)
		{
			int slen = strlen(filestream);
			filestream[slen-1] = '\0';   
	
			char *token = strtok(filestream, " \t\n"); 

			while(token != NULL)
			{
			    int counter= 0; 
	        	    for(int i=0; i<strlen(token); i++)
			    {
			        if(i == 0 && (isdigit(token[i]) || token[i]=='-'))
				{
				    counter++; 
				}	 
				else if(isdigit(token[i]))
				{
				    counter++; 
				}
			    }
			    if (counter == strlen(token))
			    {
			        number = atoi(token); 
				list_append(&number, &new_node); 
			    }
                            if(token[0]=='#')
                            {
                                token=strtok(NULL,"\n");
                            }
                            else
                            {
                                token=strtok(NULL, " \t\n");
                            }
			}
		}
	}
        if(ferror input_file!=0)
        {
            printf("\nError reading file\n");
            return;
        }
	list_print(new_node);
        list_clear(new_node);
        struct rusage use;
        getrusage(RUSAGE_SELF,&use);
        printf("\nUser time: %ld.%06lds\n",use.ru_utime.tv_sec,use.ru_utime.tv_usec);
        printf("System time: %ld.%06lds\n",use.ru_stime.tv_sec,use.ru_stime.tv_usec);
}
Пример #21
0
static inline void Command_extra(Command *cmd, int next, struct params *p)
{
    bstring extra = match_release(p, next, 0);
    list_append(cmd->extra, lnode_create(extra));
}
extern List as_mysql_get_federations(mysql_conn_t *mysql_conn, uid_t uid,
				     slurmdb_federation_cond_t *federation_cond)
{
	char *query = NULL;
	char *extra = NULL;
	char *tmp = NULL;
	List federation_list = NULL;
	int i=0;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;
	slurmdb_federation_rec_t *fed = NULL;

	if (check_connection(mysql_conn) != SLURM_SUCCESS)
		return NULL;

	if (!federation_cond) {
		xstrcat(extra, " where t1.deleted=0");
		goto empty;
	}

	_setup_federation_cond_limits(federation_cond, &extra);

empty:

	xfree(tmp);
	i=0;
	xstrfmtcat(tmp, "%s", fed_req_inx[i]);
	for(i = 1; i < FED_REQ_COUNT; i++) {
		xstrfmtcat(tmp, ", %s", fed_req_inx[i]);
	}

	query = xstrdup_printf(
		"select distinct %s from %s as t1 "
		"left join %s as t2 on t1.name=t2.federation and t2.deleted=0"
		"%s order by t1.name",
		tmp, federation_table, cluster_table, extra);
	xfree(tmp);
	xfree(extra);

	if (debug_flags & DEBUG_FLAG_FEDR)
		DB_DEBUG(mysql_conn->conn, "query\n%s", query);
	if (!(result = mysql_db_query_ret(
		      mysql_conn, query, 0))) {
		xfree(query);
		return NULL;
	}
	xfree(query);

	federation_list = list_create(slurmdb_destroy_federation_rec);

	while ((row = mysql_fetch_row(result))) {
 		slurmdb_cluster_cond_t clus_cond;
 		List tmp_list = NULL;
 		fed = xmalloc(sizeof(slurmdb_federation_rec_t));
 		list_append(federation_list, fed);

 		fed->name  = xstrdup(row[FED_REQ_NAME]);
 		fed->flags = slurm_atoul(row[FED_REQ_FLAGS]);

 		/* clusters in federation */
 		slurmdb_init_cluster_cond(&clus_cond, 0);
 		clus_cond.federation_list = list_create(slurm_destroy_char);
 		list_append(clus_cond.federation_list, xstrdup(fed->name));

 		tmp_list = as_mysql_get_clusters(mysql_conn, uid, &clus_cond);
 		FREE_NULL_LIST(clus_cond.federation_list);
 		if (!tmp_list) {
 			error("Unable to get federation clusters");
 			continue;
 		}
 		fed->cluster_list = tmp_list;
	}
	mysql_free_result(result);

	return federation_list;
}
Пример #23
0
/**
 * Put one frame into the jitter buffer
 *
 * @param jb   Jitter buffer
 * @param hdr  RTP Header
 * @param mem  Memory pointer - will be referenced
 *
 * @return 0 if success, otherwise errorcode
 */
int jbuf_put(struct jbuf *jb, const struct rtp_header *hdr, void *mem)
{
	struct frame *f;
	struct le *le, *tail;
	uint16_t seq;
	int err = 0;

	if (!jb || !hdr)
		return EINVAL;

	seq = hdr->seq;

	STAT_INC(n_put);

	if (jb->running) {

		/* Packet arrived too late to be put into buffer */
		if (seq_less((seq + jb->n), jb->seq_put)) {
			STAT_INC(n_late);
			DEBUG_INFO("packet too late: seq=%u (seq_put=%u)\n",
				   seq, jb->seq_put);
			return ETIMEDOUT;
		}
	}

	frame_alloc(jb, &f);

	tail = jb->framel.tail;

	/* If buffer is empty -> append to tail
	   Frame is later than tail -> append to tail
	*/
	if (!tail || seq_less(((struct frame *)tail->data)->hdr.seq, seq)) {
		list_append(&jb->framel, &f->le, f);
		goto out;
	}

	/* Out-of-sequence, find right position */
	for (le = tail; le; le = le->prev) {
		const uint16_t seq_le = ((struct frame *)le->data)->hdr.seq;

		if (seq_less(seq_le, seq)) { /* most likely */
			DEBUG_INFO("put: out-of-sequence"
				   " - inserting after seq=%u (seq=%u)\n",
				   seq_le, seq);
			list_insert_after(&jb->framel, le, &f->le, f);
			break;
		}
		else if (seq == seq_le) { /* less likely */
			/* Detect duplicates */
			DEBUG_INFO("duplicate: seq=%u\n", seq);
			STAT_INC(n_dups);
			list_insert_after(&jb->framel, le, &f->le, f);
			frame_deref(jb, f);
			return EALREADY;
		}

		/* sequence number less than current seq, continue */
	}

	/* no earlier timestamps found, put in head */
	if (!le) {
		DEBUG_INFO("put: out-of-sequence"
			   " - put in head (seq=%u)\n", seq);
		list_prepend(&jb->framel, &f->le, f);
	}

	STAT_INC(n_oos);

 out:
	/* Update last timestamp */
	jb->running = true;
	jb->seq_put = seq;

	/* Success */
	f->hdr = *hdr;
	f->mem = mem_ref(mem);

	return err;
}
extern List as_mysql_modify_federations(
				mysql_conn_t *mysql_conn, uint32_t uid,
				slurmdb_federation_cond_t *fed_cond,
				slurmdb_federation_rec_t *fed)
{
	List ret_list = NULL;
	int rc = SLURM_SUCCESS;
	int req_inx = 0;
	char *object = NULL;
	char *vals = NULL, *extra = NULL, *query = NULL,
	     *name_char = NULL, *fed_items = NULL;
	char *tmp_char1 = NULL, *tmp_char2 = NULL;
	time_t now = time(NULL);
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;

	if (!fed_cond || !fed) {
		error("we need something to change");
		return NULL;
	}

	if (check_connection(mysql_conn) != SLURM_SUCCESS)
		return NULL;

	if (!is_user_min_admin_level(mysql_conn, uid,
				     SLURMDB_ADMIN_SUPER_USER)) {
		errno = ESLURM_ACCESS_DENIED;
		return NULL;
	}

	/* force to only do non-deleted federations */
	fed_cond->with_deleted = 0;
	_setup_federation_cond_limits(fed_cond, &extra);
	_setup_federation_rec_limits(fed, &tmp_char1, &tmp_char2, &vals);
	xfree(tmp_char1);
	xfree(tmp_char2);

	if (!extra ||
	    (!vals && (!fed->cluster_list || !list_count(fed->cluster_list)))) {
		xfree(extra);
		xfree(vals);
		errno = SLURM_NO_CHANGE_IN_DATA;
		error("Nothing to change");
		return NULL;
	}

	if (fed->cluster_list &&
	    fed_cond->federation_list &&
	    (list_count(fed_cond->federation_list) > 1)) {
		xfree(extra);
		xfree(vals);
		error("Clusters can only be assigned to one federation");
		errno = ESLURM_FED_CLUSTER_MULTIPLE_ASSIGNMENT;
		return NULL;
	}

	/* Select records that are going to get updated.
	 * 1 - to be able to report what is getting updated
	 * 2 - to create an update object to let the controller know.  */
	xstrfmtcat(fed_items, "%s", fed_req_inx[req_inx]);
	for(req_inx = 1; req_inx < FED_REQ_COUNT; req_inx++) {
		xstrfmtcat(fed_items, ", %s", fed_req_inx[req_inx]);
	}

	xstrfmtcat(query, "select %s from %s as t1 %s;",
		   fed_items, federation_table, extra);
	xfree(fed_items);

	if (debug_flags & DEBUG_FLAG_FEDR)
		DB_DEBUG(mysql_conn->conn, "query\n%s", query);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		xfree(vals);
		xfree(extra);
		error("no result given for %s", extra);
		return NULL;
	}
	xfree(extra);

	ret_list = list_create(slurm_destroy_char);
	while ((row = mysql_fetch_row(result))) {
		object = xstrdup(row[0]);

		list_append(ret_list, object);
		if (!name_char) {
			xstrfmtcat(name_char, "(name='%s'", object);
		} else  {
			xstrfmtcat(name_char, " || name='%s'", object);
		}
	}
	mysql_free_result(result);

	if (fed->cluster_list &&
	    (_assign_clusters_to_federation(mysql_conn, object,
					    fed->cluster_list))) {
		xfree(vals);
		xfree(name_char);
		xfree(query);
		return NULL;
	}

	if (!list_count(ret_list)) {
		errno = SLURM_NO_CHANGE_IN_DATA;
		if (debug_flags & DEBUG_FLAG_FEDR)
			DB_DEBUG(mysql_conn->conn,
				 "didn't effect anything\n%s", query);
		xfree(vals);
		xfree(name_char);
		xfree(query);
		return ret_list;
	}
	xfree(query);
	xstrcat(name_char, ")");

	if (vals) {
		char *user_name = uid_to_string((uid_t) uid);
		rc = modify_common(mysql_conn, DBD_MODIFY_FEDERATIONS, now,
				   user_name, federation_table,
				   name_char, vals, NULL);
		xfree(user_name);
	}
	xfree(name_char);
	xfree(vals);

	if (rc == SLURM_ERROR) {
		error("Couldn't modify federation");
		FREE_NULL_LIST(ret_list);
		ret_list = NULL;
	} else
		as_mysql_add_feds_to_update_list(mysql_conn);

	return ret_list;
}
Пример #25
0
extern List priority_p_get_priority_factors_list(
	priority_factors_request_msg_t *req_msg)
{
	List req_job_list;
	List req_user_list;
	List ret_list = NULL;
	ListIterator itr;
	priority_factors_object_t *obj = NULL;
	struct job_record *job_ptr = NULL;
	time_t start_time = time(NULL);

	xassert(req_msg);
	req_job_list = req_msg->job_id_list;
	req_user_list = req_msg->uid_list;

	/* Read lock on jobs, nodes, and partitions */
	slurmctld_lock_t job_read_lock =
		{ NO_LOCK, READ_LOCK, READ_LOCK, READ_LOCK };

	if (job_list && list_count(job_list)) {
		ret_list = list_create(slurm_destroy_priority_factors_object);
		lock_slurmctld(job_read_lock);
		itr = list_iterator_create(job_list);
		if (itr == NULL)
			fatal("list_iterator_create: malloc failure");
		while ((job_ptr = list_next(itr))) {
			/*
			 * We are only looking for pending jobs
			 */
			if (!IS_JOB_PENDING(job_ptr))
				continue;
			/*
			 * This means the job is not eligible yet
			 */
			if (!job_ptr->details->begin_time
			    || (job_ptr->details->begin_time > start_time))
				continue;

			/*
			 * 0 means the job is held; 1 means system hold
			 */
			if (job_ptr->priority <= 1)
				continue;

			/*
			 * Priority has been set elsewhere (e.g. by SlurmUser)
			 */
			if (job_ptr->direct_set_prio)
				continue;

			if (_filter_job(job_ptr, req_job_list, req_user_list))
				continue;

			obj = xmalloc(sizeof(priority_factors_object_t));
			memcpy(obj, job_ptr->prio_factors,
			       sizeof(priority_factors_object_t));
			obj->job_id = job_ptr->job_id;
			obj->user_id = job_ptr->user_id;
			list_append(ret_list, obj);
		}
		list_iterator_destroy(itr);
		unlock_slurmctld(job_read_lock);
		if (!list_count(ret_list)) {
			list_destroy(ret_list);
			ret_list = NULL;
		}
	}

	return ret_list;
}
extern List as_mysql_remove_federations(mysql_conn_t *mysql_conn, uint32_t uid,
					slurmdb_federation_cond_t *fed_cond)
{
	List ret_list = NULL;
	int rc = SLURM_SUCCESS;
	char *extra = NULL, *query = NULL, *name_char = NULL;
	time_t now = time(NULL);
	char *user_name = NULL;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;

	if (!fed_cond) {
		error("we need something to change");
		return NULL;
	}

	if (check_connection(mysql_conn) != SLURM_SUCCESS)
		return NULL;

	if (!is_user_min_admin_level(
		    mysql_conn, uid, SLURMDB_ADMIN_SUPER_USER)) {
		errno = ESLURM_ACCESS_DENIED;
		return NULL;
	}

	/* force to only do non-deleted federations */
	fed_cond->with_deleted = 0;
	_setup_federation_cond_limits(fed_cond, &extra);

	if (!extra) {
		error("Nothing to remove");
		return NULL;
	}

	query = xstrdup_printf("select name from %s as t1 %s;",
			       federation_table, extra);
	xfree(extra);
	if (!(result = mysql_db_query_ret( mysql_conn, query, 0))) {
		xfree(query);
		return NULL;
	}
	rc = 0;
	ret_list = list_create(slurm_destroy_char);

	if (!mysql_num_rows(result)) {
		mysql_free_result(result);
		errno = SLURM_NO_CHANGE_IN_DATA;
		if (debug_flags & DEBUG_FLAG_FEDR)
			DB_DEBUG(mysql_conn->conn,
				 "didn't effect anything\n%s", query);
		xfree(query);
		return ret_list;
	}
	xfree(query);

	user_name = uid_to_string((uid_t) uid);
	while ((row = mysql_fetch_row(result))) {
		char *object = xstrdup(row[0]);
		list_append(ret_list, object);

		if ((rc = _remove_all_clusters_from_fed(mysql_conn, object,
							NULL)))
			break;

		xfree(name_char);
		xstrfmtcat(name_char, "name='%s'", object);

		if ((rc = remove_common(mysql_conn, DBD_REMOVE_FEDERATIONS, now,
					user_name, federation_table, name_char,
					NULL, NULL, ret_list, NULL)))
			break;
	}
	mysql_free_result(result);
	xfree(user_name);
	xfree(name_char);

	if (rc != SLURM_SUCCESS) {
		FREE_NULL_LIST(ret_list);
		return NULL;
	} else
		as_mysql_add_feds_to_update_list(mysql_conn);

	return ret_list;
}
Пример #27
0
static int _full_request(select_ba_request_t *request,
			 bitstr_t *usable_mp_bitmap,
			 List allocated_blocks)
{
	char *tmp_char = NULL, *tmp_char2 = NULL;
	allocated_block_t *allocated_block;
	int rc = 1;

	if (!strcasecmp(layout_mode,"OVERLAP"))
		bg_configure_reset_ba_system(true);

	if (usable_mp_bitmap)
		bg_configure_ba_set_removable_mps(usable_mp_bitmap, 1);

	/*
	 * Here is where we do the allocating of the partition.
	 * It will send a request back which we will throw into
	 * a list just incase we change something later.
	 */
	if (!bg_configure_new_ba_request(request)) {
		memset(error_string, 0, 255);
		if (request->size != -1) {
			sprintf(error_string,
				"Problems with request for %d\n"
				"Either you put in something "
				"that doesn't work,\n"
				"or we are unable to process "
				"your request.",
				request->size);
			rc = 0;
		} else {
			tmp_char = bg_configure_give_geo(request->geometry,
							 params.cluster_dims,
							 1);
			sprintf(error_string,
				"Problems with request of size %s\n"
				"Either you put in something "
				"that doesn't work,\n"
				"or we are unable to process "
				"your request.",
				tmp_char);
			xfree(tmp_char);
			rc = 0;
		}
	} else {
		if ((allocated_block = _make_request(request)) != NULL)
			list_append(allocated_blocks, allocated_block);
		else {
			if (request->geometry[0] != (uint16_t)NO_VAL)
				tmp_char = bg_configure_give_geo(
					request->geometry,
					params.cluster_dims, 1);
			tmp_char2 = bg_configure_give_geo(request->start,
							  params.cluster_dims,
							  1);

			memset(error_string, 0, 255);
			sprintf(error_string,
				"allocate failure\nSize requested "
				"was %d MidPlanes\n",
				request->size);
			if (tmp_char) {
				sprintf(error_string + strlen(error_string),
					"Geo requested was %s\n", tmp_char);
				xfree(tmp_char);
			} else {
				sprintf(error_string + strlen(error_string),
					"No geometry could be laid out "
					"for that size\n");
			}
			sprintf(error_string + strlen(error_string),
				"Start position was %s", tmp_char2);
			xfree(tmp_char2);
			rc = 0;
		}
	}

	if (usable_mp_bitmap)
		bg_configure_ba_reset_all_removed_mps();

	return rc;
}
Пример #28
0
static List _create_block_list(partition_info_msg_t *part_info_ptr,
			       block_info_msg_t *block_info_ptr)
{
	int i;
	static List block_list = NULL;
	static partition_info_msg_t *last_part_info_ptr = NULL;
	static block_info_msg_t *last_block_info_ptr = NULL;
	List last_list = NULL;
	ListIterator last_list_itr = NULL;
	sview_block_info_t *block_ptr = NULL;
	char tmp_mp_str[50];

	if (block_list && (part_info_ptr == last_part_info_ptr)
	    && (block_info_ptr == last_block_info_ptr))
		return block_list;

	last_part_info_ptr = part_info_ptr;
	if (block_list) {
		/* Only the partition info changed so lets update just
		   that part.
		*/
		if (block_info_ptr == last_block_info_ptr) {
			ListIterator itr = list_iterator_create(block_list);

			while ((block_ptr = list_next(itr)))
				_set_block_partition(part_info_ptr, block_ptr);

			return block_list;
		}
		last_list = block_list;
	}

	block_list = list_create(_block_list_del);
	if (!block_list) {
		g_print("malloc error\n");
		return NULL;
	}

	last_block_info_ptr = block_info_ptr;

	if (last_list)
		last_list_itr = list_iterator_create(last_list);
	for (i=0; i<block_info_ptr->record_count; i++) {
		/* If we don't have a block name just continue since
		   ths block hasn't been made in the system yet. */
		if (!block_info_ptr->block_array[i].bg_block_id)
			continue;

		block_ptr = NULL;

		if (last_list_itr) {
			while ((block_ptr = list_next(last_list_itr))) {
				if (!xstrcmp(block_ptr->bg_block_name,
					     block_info_ptr->
					     block_array[i].bg_block_id)) {
					list_remove(last_list_itr);
					_block_info_free(block_ptr);
					break;
				}
			}
			list_iterator_reset(last_list_itr);
		}

		if (!block_ptr)
			block_ptr = xmalloc(sizeof(sview_block_info_t));
		block_ptr->pos = i;
		block_ptr->bg_block_name
			= xstrdup(block_info_ptr->
				  block_array[i].bg_block_id);


		block_ptr->color_inx =
			atoi(block_ptr->bg_block_name+7);

		/* on some systems they make there own blocks named
		   whatever they want, so doing this fixes what could
		   be a negative number.
		*/
		if (block_ptr->color_inx < 0)
			block_ptr->color_inx = i;

		block_ptr->color_inx %= sview_colors_cnt;

		block_ptr->mp_str
			= xstrdup(block_info_ptr->block_array[i].mp_str);
		if (block_info_ptr->block_array[i].ionode_str) {
			block_ptr->small_block = 1;
			snprintf(tmp_mp_str, sizeof(tmp_mp_str),
				 "%s[%s]",
				 block_ptr->mp_str,
				 block_info_ptr->block_array[i].ionode_str);
			xfree(block_ptr->mp_str);
			block_ptr->mp_str = xstrdup(tmp_mp_str);
		}
		block_ptr->reason
			= xstrdup(block_info_ptr->block_array[i].reason);

		if (cluster_flags & CLUSTER_FLAG_BGP) {
			block_ptr->imagelinux = xstrdup(
				block_info_ptr->block_array[i].linuximage);
			block_ptr->imageramdisk = xstrdup(
				block_info_ptr->block_array[i].ramdiskimage);
		} else if (cluster_flags & CLUSTER_FLAG_BGL) {
			block_ptr->imageblrts = xstrdup(
				block_info_ptr->block_array[i].blrtsimage);
			block_ptr->imagelinux = xstrdup(
				block_info_ptr->block_array[i].linuximage);
			block_ptr->imageramdisk = xstrdup(
				block_info_ptr->block_array[i].ramdiskimage);
		}

		block_ptr->imagemloader = xstrdup(
			block_info_ptr->block_array[i].mloaderimage);

		block_ptr->state
			= block_info_ptr->block_array[i].state;
		memcpy(block_ptr->bg_conn_type,
		       block_info_ptr->block_array[i].conn_type,
		       sizeof(block_ptr->bg_conn_type));

		if (cluster_flags & CLUSTER_FLAG_BGL)
			block_ptr->bg_node_use
				= block_info_ptr->block_array[i].node_use;

		block_ptr->cnode_cnt
			= block_info_ptr->block_array[i].cnode_cnt;
		block_ptr->cnode_err_cnt
			= block_info_ptr->block_array[i].cnode_err_cnt;
		block_ptr->mp_inx
			= block_info_ptr->block_array[i].mp_inx;
		_set_block_partition(part_info_ptr, block_ptr);

		block_ptr->job_list = list_create(slurm_free_block_job_info);
		if (block_info_ptr->block_array[i].job_list)
			list_transfer(block_ptr->job_list,
				      block_info_ptr->block_array[i].job_list);

		if (block_ptr->bg_conn_type[0] >= SELECT_SMALL)
			block_ptr->size = 0;

		list_append(block_list, block_ptr);
	}

	list_sort(block_list,
		  (ListCmpF)_sview_block_sort_aval_dec);

	if (last_list) {
		list_iterator_destroy(last_list_itr);
		FREE_NULL_LIST(last_list);
	}

	return block_list;
}
Пример #29
0
extern List as_mysql_modify_accts(mysql_conn_t *mysql_conn, uint32_t uid,
				  slurmdb_account_cond_t *acct_cond,
				  slurmdb_account_rec_t *acct)
{
	ListIterator itr = NULL;
	List ret_list = NULL;
	int rc = SLURM_SUCCESS;
	char *object = NULL;
	char *vals = NULL, *extra = NULL, *query = NULL, *name_char = NULL;
	time_t now = time(NULL);
	char *user_name = NULL;
	int set = 0;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;

	if (!acct_cond || !acct) {
		error("we need something to change");
		return NULL;
	}

	if (check_connection(mysql_conn) != SLURM_SUCCESS)
		return NULL;

	if (!is_user_min_admin_level(mysql_conn, uid, SLURMDB_ADMIN_OPERATOR)) {
		errno = ESLURM_ACCESS_DENIED;
		return NULL;
	}

	xstrcat(extra, "where deleted=0");
	if (acct_cond->assoc_cond
	    && acct_cond->assoc_cond->acct_list
	    && list_count(acct_cond->assoc_cond->acct_list)) {
		set = 0;
		xstrcat(extra, " && (");
		itr = list_iterator_create(acct_cond->assoc_cond->acct_list);
		while ((object = list_next(itr))) {
			if (set)
				xstrcat(extra, " || ");
			xstrfmtcat(extra, "name='%s'", object);
			set = 1;
		}
		list_iterator_destroy(itr);
		xstrcat(extra, ")");
	}

	if (acct_cond->description_list
	    && list_count(acct_cond->description_list)) {
		set = 0;
		xstrcat(extra, " && (");
		itr = list_iterator_create(acct_cond->description_list);
		while ((object = list_next(itr))) {
			if (set)
				xstrcat(extra, " || ");
			xstrfmtcat(extra, "description='%s'", object);
			set = 1;
		}
		list_iterator_destroy(itr);
		xstrcat(extra, ")");
	}

	if (acct_cond->organization_list
	    && list_count(acct_cond->organization_list)) {
		set = 0;
		xstrcat(extra, " && (");
		itr = list_iterator_create(acct_cond->organization_list);
		while ((object = list_next(itr))) {
			if (set)
				xstrcat(extra, " || ");
			xstrfmtcat(extra, "organization='%s'", object);
			set = 1;
		}
		list_iterator_destroy(itr);
		xstrcat(extra, ")");
	}

	if (acct->description)
		xstrfmtcat(vals, ", description='%s'", acct->description);
	if (acct->organization)
		xstrfmtcat(vals, ", organization='%s'", acct->organization);

	if (!extra || !vals) {
		errno = SLURM_NO_CHANGE_IN_DATA;
		error("Nothing to change");
		return NULL;
	}

	query = xstrdup_printf("select name from %s %s;", acct_table, extra);
	xfree(extra);
	if (debug_flags & DEBUG_FLAG_DB_ASSOC)
		DB_DEBUG(mysql_conn->conn, "query\n%s", query);
	if (!(result = mysql_db_query_ret(
		      mysql_conn, query, 0))) {
		xfree(query);
		xfree(vals);
		return NULL;
	}

	rc = 0;
	ret_list = list_create(slurm_destroy_char);
	while ((row = mysql_fetch_row(result))) {
		object = xstrdup(row[0]);
		list_append(ret_list, object);
		if (!rc) {
			xstrfmtcat(name_char, "(name='%s'", object);
			rc = 1;
		} else  {
			xstrfmtcat(name_char, " || name='%s'", object);
		}

	}
	mysql_free_result(result);

	if (!list_count(ret_list)) {
		errno = SLURM_NO_CHANGE_IN_DATA;
		if (debug_flags & DEBUG_FLAG_DB_ASSOC)
			DB_DEBUG(mysql_conn->conn,
				 "didn't effect anything\n%s", query);
		xfree(query);
		xfree(vals);
		return ret_list;
	}
	xfree(query);
	xstrcat(name_char, ")");

	user_name = uid_to_string((uid_t) uid);
	rc = modify_common(mysql_conn, DBD_MODIFY_ACCOUNTS, now,
			   user_name, acct_table, name_char, vals, NULL);
	xfree(user_name);
	if (rc == SLURM_ERROR) {
		error("Couldn't modify accounts");
		FREE_NULL_LIST(ret_list);
		errno = SLURM_ERROR;
		ret_list = NULL;
	}

	xfree(name_char);
	xfree(vals);

	return ret_list;
}
Пример #30
0
/*
 * _event_server_service_connection
 *
 * Service a connection from a client to receive event packets.  Use
 * wrapper functions minimally, b/c we want to return errors to the
 * user instead of exitting with errors.
 *
 */
static void
_event_server_service_connection(int fd)
{
  int recv_len;
  struct cerebro_event_server_request req;
  struct cerebrod_event_connection_data *ecd = NULL;
  char buf[CEREBRO_MAX_PACKET_LEN];
  char event_name_buf[CEREBRO_MAX_EVENT_NAME_LEN+1];
  char *event_name_ptr = NULL;
  int32_t version;
  int *fdptr = NULL;
  List connections = NULL;

  assert(fd >= 0);

  memset(&req, '\0', sizeof(struct cerebro_event_server_request));
  if ((recv_len = receive_data(fd,
                               CEREBRO_EVENT_SERVER_REQUEST_PACKET_LEN,
                               buf,
                               CEREBRO_MAX_PACKET_LEN,
                               CEREBRO_EVENT_SERVER_PROTOCOL_CLIENT_TIMEOUT_LEN,
                               NULL)) < 0)
    goto cleanup;

  if (recv_len < sizeof(version))
    goto cleanup;

  if (_event_server_request_check_version(buf, recv_len, &version) < 0)
    {
      _event_server_err_only_response(fd,
                                      version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_VERSION_INVALID);
      goto cleanup;
    }

  if (recv_len != CEREBRO_EVENT_SERVER_REQUEST_PACKET_LEN)
    {
      _event_server_err_only_response(fd,
                                      version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_PACKET_INVALID);
      goto cleanup;
    }

  if (_event_server_request_unmarshall(&req, buf, recv_len) < 0)
    {
      _event_server_err_only_response(fd,
                                      version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_PACKET_INVALID);
      goto cleanup;
    }

  _event_server_request_dump(&req);

  /* Guarantee ending '\0' character */
  memset(event_name_buf, '\0', CEREBRO_MAX_EVENT_NAME_LEN+1);
  memcpy(event_name_buf, req.event_name, CEREBRO_MAX_EVENT_NAME_LEN);

  if (!strlen(event_name_buf))
    {
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_EVENT_INVALID);
      goto cleanup;
    }

  /* Is it the special event-names request */
  if (!strcmp(event_name_buf, CEREBRO_EVENT_NAMES))
    {
      pthread_t thread;
      pthread_attr_t attr;
      int *arg;

      Pthread_attr_init(&attr);
      Pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
      Pthread_attr_setstacksize(&attr, CEREBROD_THREAD_STACKSIZE);
      arg = Malloc(sizeof(int));
      *arg = fd;
      Pthread_create(&thread,
                     &attr,
                     _respond_with_event_names,
                     (void *)arg);
      Pthread_attr_destroy(&attr);
      return;
    }

  if (!event_names)
    {
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_EVENT_INVALID);
      goto cleanup;
    }

  /* Event names is not changeable - so no need for a lock */
  if (!(event_name_ptr = list_find_first(event_names, 
                                         _event_names_compare,
                                         event_name_buf)))
    {
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_EVENT_INVALID);
      goto cleanup;
    }
  
  if (!(ecd = (struct cerebrod_event_connection_data *)malloc(sizeof(struct cerebrod_event_connection_data))))
    {
      CEREBROD_ERR(("malloc: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }
  
  ecd->event_name = event_name_ptr;
  ecd->fd = fd;
  
  if (!(fdptr = (int *)malloc(sizeof(int))))
    {
      CEREBROD_ERR(("malloc: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }
  *fdptr = fd;

  Pthread_mutex_lock(&event_connections_lock);
  if (!list_append(event_connections, ecd))
    {
      CEREBROD_ERR(("list_append: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }

  if (!(connections = Hash_find(event_connections_index, 
                                ecd->event_name)))
    {
      if (!(connections = list_create((ListDelF)free)))
        {
          CEREBROD_ERR(("list_create: %s", strerror(errno)));
          _event_server_err_only_response(fd,
                                          req.version,
                                          CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
          goto cleanup;
        }

      if (!Hash_insert(event_connections_index, ecd->event_name, connections))
        {
          CEREBROD_ERR(("Hash_insert: %s", strerror(errno)));
          _event_server_err_only_response(fd,
                                          req.version,
                                          CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
          list_destroy(connections);
          goto cleanup;
        }
    }

  if (!list_append(connections, fdptr))
    {
      CEREBROD_ERR(("list_append: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }

  Pthread_mutex_unlock(&event_connections_lock);
  /* Clear this pointer so we know it's stored away in a list */
  fdptr = NULL;

  _event_server_err_only_response(fd,
                                  req.version,
                                  CEREBRO_EVENT_SERVER_PROTOCOL_ERR_SUCCESS);

  return;
  
 cleanup:
  if (ecd)
    free(ecd);
  if (fdptr)
    free(fdptr);
  /* ignore potential error, we're in the error path already */
  close(fd);
  return;
}