Beispiel #1
0
int main(int argc, char *argv[])
{
  SetDefaultLogging("TEST");
  SetNamePgm("test_cmchash");

  hash_table_t *ht = NULL;
  hash_parameter_t hparam;
  hash_buffer_t buffval;
  hash_buffer_t buffkey;
  hash_buffer_t buffval2;
  hash_buffer_t buffkey2;
  hash_stat_t statistiques;
  int i;
  int val;
  int rc;
  int res;
  struct Temps debut, fin;
  char tmpstr[10];
  char tmpstr2[10];
  char tmpstr3[10];
  char strtab[MAXTEST][10];
  int critere_recherche = 0;
  int random_val = 0;

  hparam.index_size = PRIME;
  hparam.alphabet_length = 10;
  hparam.nb_node_prealloc = NB_PREALLOC;
  hparam.hash_func_key = simple_hash_func;
  hparam.hash_func_rbt = rbt_hash_func;
  hparam.compare_key = compare_string_buffer;
  hparam.key_to_str = display_buff;
  hparam.val_to_str = display_buff;

  BuddyInit(NULL);

  /* Init de la table */
  if((ht = HashTable_Init(hparam)) == NULL)
    {
      LogTest("Test FAILED: Bad init");
      exit(1);
    }

  MesureTemps(&debut, NULL);
  LogTest("Created the table");

  for(i = 0; i < MAXTEST; i++)
    {
      sprintf(strtab[i], "%d", i);

      buffkey.len = strlen(strtab[i]);
      buffkey.pdata = strtab[i];

      buffval.len = strlen(strtab[i]);
      buffval.pdata = strtab[i];

      rc = HashTable_Set(ht, &buffkey, &buffval);
      LogFullDebug(COMPONENT_HASHTABLE,"Added %s , %d , return = %d", strtab[i], i, rc);
    }

  MesureTemps(&fin, &debut);
  LogTest("Time to insert %d entries: %s", MAXTEST,
         ConvertiTempsChaine(fin, NULL));

  LogFullDebug(COMPONENT_HASHTABLE, "-----------------------------------------");
  HashTable_Log(COMPONENT_HASHTABLE,ht);

  LogTest("=========================================");

  /* Premier test simple: verif de la coherence des valeurs lues */
  critere_recherche = CRITERE;

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  MesureTemps(&debut, NULL);
  rc = HashTable_Get(ht, &buffkey, &buffval);
  MesureTemps(&fin, &debut);

  LogTest("Recovery of %d th key ->%d", critere_recherche, rc);

  LogTest("Time to recover = %s", ConvertiTempsChaine(fin, NULL));

  if(rc != HASHTABLE_SUCCESS)
    {
      LogTest("Test FAILED: The key is not found");
      exit(1);
    }

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  MesureTemps(&debut, NULL);
  rc = HashTable_Get(ht, &buffkey, &buffval);
  MesureTemps(&fin, &debut);

  LogTest("Recovery of %d th key (test 2) -> %s", critere_recherche, rc);

  LogTest("Time to recover = %s", ConvertiTempsChaine(fin, NULL));

  if(rc != HASHTABLE_SUCCESS)
    {
      LogTest("Test FAILED: The key is not found (test 2)");
      exit(1);
    }

  LogTest("----> retrieved value = len %d ; val = %s", buffval.len, buffval.pdata);
  val = atoi(buffval.pdata);

  if(val != critere_recherche)
    {
      LogTest("Test FAILED: the reading is incorrect");
      exit(1);
    }

  LogTest("Now, I try to retrieve %d entries (taken at random, almost)",
         MAXGET);
  MesureTemps(&debut, NULL);
  for(i = 0; i < MAXGET; i++)
    {
      random_val = random() % MAXTEST;
      sprintf(tmpstr, "%d", random_val);
      buffkey2.len = strlen(tmpstr);
      buffkey2.pdata = tmpstr;

      rc = HashTable_Get(ht, &buffkey2, &buffval2);
      LogFullDebug(COMPONENT_HASHTABLE,"\tPlaying key = %s  --> %s", buffkey2.pdata, buffval2.pdata);
      if(rc != HASHTABLE_SUCCESS)
        {
          LogTest("Error reading %d = %d", i, rc);
          LogTest("Test FAILED: the reading is incorrect");
          exit(1);
        }
    }
  MesureTemps(&fin, &debut);
  LogTest("Time to read %d elements = %s", MAXGET,
         ConvertiTempsChaine(fin, NULL));

  LogTest("-----------------------------------------");

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  rc = HashTable_Del(ht, &buffkey, NULL, NULL);
  LogTest("Deleting the key %d --> %d", critere_recherche, rc);

  if(rc != HASHTABLE_SUCCESS)
    {
      LogTest("Test FAILED: delete incorrect");
      exit(1);
    }

  LogTest("=========================================");

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  rc = HashTable_Del(ht, &buffkey, NULL, NULL);
  LogTest("Deleting the key %d (2nd try) --> %d", critere_recherche, rc);

  if(rc != HASHTABLE_ERROR_NO_SUCH_KEY)
    {
      printf("Test FAILED: delete incorrect");
      exit(1);
    }

  LogTest("=========================================");

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  rc = HashTable_Get(ht, &buffkey, &buffval);
  LogTest
      ("Recovery of the %d key (erased) (must return HASH_ERROR_NO_SUCH_KEY) = %d --> %d",
       critere_recherche, HASHTABLE_ERROR_NO_SUCH_KEY, rc);

  if(rc != HASHTABLE_ERROR_NO_SUCH_KEY)
    {
      LogTest("Test FAILED: the reading is incorrect");
      exit(1);
    }
  LogTest("-----------------------------------------");

  LogTest
      ("Destruction of %d items, taken at random (well if you want ... I use srandom)",
       MAXDESTROY);
  srandom(getpid());
  random_val = random() % MAXTEST;

  MesureTemps(&debut, NULL);
  for(i = 0; i < MAXDESTROY; i++)
    {
      /* 
      it used to be that the random values were chosen with
      repeated calls to random(), but if the same key comes up twice,
      that causes a fail.  This way we start with a random value and
      just linearly delete from it
      */

      random_val = (random_val + 1) % MAXTEST;
      sprintf(tmpstr, "%d", random_val);
      LogTest("\t Delete %d", random_val);
      buffkey.len = strlen(tmpstr);
      buffkey.pdata = tmpstr;

      rc = HashTable_Del(ht, &buffkey, NULL, NULL);
      

      if(rc != HASHTABLE_SUCCESS)
        {
          LogTest("Error on delete %d = %d", i, rc);
          LogTest("Test FAILED: delete incorrect");
          exit(1);
        }
    }
  MesureTemps(&fin, &debut);
  LogTest("Time to delete %d elements = %s", MAXDESTROY,
         ConvertiTempsChaine(fin, NULL));

  LogTest("-----------------------------------------");

  LogTest("Now, I try to retrieve %d entries (if necessary destroyed)",
         MAXGET);
  MesureTemps(&debut, NULL);
  for(i = 0; i < MAXGET; i++)
    {
      random_val = random() % MAXTEST;
      sprintf(tmpstr, "%d", random_val);
      buffkey.len = strlen(tmpstr);
      buffkey.pdata = tmpstr;

      rc = HashTable_Get(ht, &buffkey, &buffval);
    }
  MesureTemps(&fin, &debut);
  LogTest("Tie to read %d elements = %s", MAXGET,
         ConvertiTempsChaine(fin, NULL));

  LogTest("-----------------------------------------");
  LogTest("Writing a duplicate key ");
  sprintf(tmpstr, "%d", CRITERE_2);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;
  rc = HashTable_Test_And_Set(ht, &buffkey, &buffval, HASHTABLE_SET_HOW_SET_NO_OVERWRITE);
  LogTest("The value should be HASHTABLE_ERROR_KEY_ALREADY_EXISTS  = %d --> %d",
         HASHTABLE_ERROR_KEY_ALREADY_EXISTS, rc);
  if(rc != HASHTABLE_ERROR_KEY_ALREADY_EXISTS)
    {
      LogTest("Test FAILED: duplicate key");
      exit(1);
    }
  LogTest("-----------------------------------------");

  HashTable_Log(COMPONENT_HASHTABLE,ht);
  LogFullDebug(COMPONENT_HASHTABLE,"-----------------------------------------");

  LogTest("Displaying table statistics ");
  HashTable_GetStats(ht, &statistiques);
  LogTest(" Number of entries = %d", statistiques.dynamic.nb_entries);

  LogTest("   Successful operations  : Set = %d,  Get = %d,  Del = %d,  Test = %d",
         statistiques.dynamic.ok.nb_set, statistiques.dynamic.ok.nb_get,
         statistiques.dynamic.ok.nb_del, statistiques.dynamic.ok.nb_test);

  LogTest("   Failed operations : Set = %d,  Get = %d,  Del = %d,  Test = %d",
         statistiques.dynamic.err.nb_set, statistiques.dynamic.err.nb_get,
         statistiques.dynamic.err.nb_del, statistiques.dynamic.err.nb_test);

  LogTest("   Operations 'NotFound': Set = %d,  Get = %d,  Del = %d,  Test = %d",
         statistiques.dynamic.notfound.nb_set, statistiques.dynamic.notfound.nb_get,
         statistiques.dynamic.notfound.nb_del, statistiques.dynamic.notfound.nb_test);

  LogTest
      ("  Calculated statistics: min_rbt_node = %d,  max_rbt_node = %d,  average_rbt_node = %d",
       statistiques.computed.min_rbt_num_node, statistiques.computed.max_rbt_num_node,
       statistiques.computed.average_rbt_num_node);

  /* Test sur la pertinence des valeurs de statistiques */
  if(statistiques.dynamic.ok.nb_set != MAXTEST)
    {
      LogTest("Test FAILED: Incorrect statistics: ok.nb_set ");
      exit(1);
    }

  if(statistiques.dynamic.ok.nb_get + statistiques.dynamic.notfound.nb_get !=
     2 * MAXGET + 3)
    {
      LogTest("Test FAILED: Incorrect statistics: *.nb_get ");
      exit(1);
    }

  if(statistiques.dynamic.ok.nb_del != MAXDESTROY + 1
     || statistiques.dynamic.notfound.nb_del != 1)
    {
      LogTest("Test ECHOUE : statistiques incorrectes: *.nb_del ");
      exit(1);
    }

  if(statistiques.dynamic.err.nb_test != 1)
    {
      LogTest("Test ECHOUE : statistiques incorrectes: err.nb_test ");
      exit(1);
    }

  /* Tous les tests sont ok */
  BuddyDumpMem(stdout);

  LogTest("\n-----------------------------------------");
  LogTest("Test succeeded: all tests pass successfully");

  exit(0);
}
Beispiel #2
0
int
asyncmeta_back_bind( Operation *op, SlapReply *rs )
{
	a_metainfo_t	*mi = ( a_metainfo_t * )op->o_bd->be_private;
	a_metaconn_t	*mc = NULL;

	int		rc = LDAP_OTHER,
			i,
			gotit = 0,
			isroot = 0;

	SlapReply	*candidates;

	candidates = op->o_tmpcalloc(mi->mi_ntargets, sizeof(SlapReply),op->o_tmpmemctx);
	rs->sr_err = LDAP_SUCCESS;

	Debug( LDAP_DEBUG_ARGS, "%s asyncmeta_back_bind: dn=\"%s\".\n",
		op->o_log_prefix, op->o_req_dn.bv_val, 0 );

	/* the test on the bind method should be superfluous */
	switch ( be_rootdn_bind( op, rs ) ) {
	case LDAP_SUCCESS:
		if ( META_BACK_DEFER_ROOTDN_BIND( mi ) ) {
			/* frontend will return success */
			return rs->sr_err;
		}

		isroot = 1;
		/* fallthru */

	case SLAP_CB_CONTINUE:
		break;

	default:
		/* be_rootdn_bind() sent result */
		return rs->sr_err;
	}

	/* we need asyncmeta_getconn() not send result even on error,
	 * because we want to intercept the error and make it
	 * invalidCredentials */
	mc = asyncmeta_getconn( op, rs, candidates, NULL, LDAP_BACK_BIND_DONTSEND, 1 );
	if ( !mc ) {
		if ( LogTest( LDAP_DEBUG_ANY ) ) {
			char	buf[ SLAP_TEXT_BUFLEN ];

			snprintf( buf, sizeof( buf ),
				"asyncmeta_back_bind: no target "
				"for dn \"%s\" (%d%s%s).",
				op->o_req_dn.bv_val, rs->sr_err,
				rs->sr_text ? ". " : "",
				rs->sr_text ? rs->sr_text : "" );
			Debug( LDAP_DEBUG_ANY,
				"%s %s\n",
				op->o_log_prefix, buf, 0 );
		}

		/* FIXME: there might be cases where we don't want
		 * to map the error onto invalidCredentials */
		switch ( rs->sr_err ) {
		case LDAP_NO_SUCH_OBJECT:
		case LDAP_UNWILLING_TO_PERFORM:
			rs->sr_err = LDAP_INVALID_CREDENTIALS;
			rs->sr_text = NULL;
			break;
		}
		send_ldap_result( op, rs );
		return rs->sr_err;
	}

	/*
	 * Each target is scanned ...
	 */
	mc->mc_authz_target = META_BOUND_NONE;
	for ( i = 0; i < mi->mi_ntargets; i++ ) {
		a_metatarget_t	*mt = mi->mi_targets[ i ];
		int		lerr;

		/*
		 * Skip non-candidates
		 */
		if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
			continue;
		}

		if ( gotit == 0 ) {
			/* set rc to LDAP_SUCCESS only if at least
			 * one candidate has been tried */
			rc = LDAP_SUCCESS;
			gotit = 1;

		} else if ( !isroot ) {
			/*
			 * A bind operation is expected to have
			 * ONE CANDIDATE ONLY!
			 */
			Debug( LDAP_DEBUG_ANY,
				"### %s asyncmeta_back_bind: more than one"
				" candidate selected...\n",
				op->o_log_prefix, 0, 0 );
		}

		if ( isroot ) {
			if ( mt->mt_idassert_authmethod == LDAP_AUTH_NONE
				|| BER_BVISNULL( &mt->mt_idassert_authcDN ) )
			{
				a_metasingleconn_t	*msc = &mc->mc_conns[ i ];

				if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
					ch_free( msc->msc_bound_ndn.bv_val );
					BER_BVZERO( &msc->msc_bound_ndn );
				}

				if ( !BER_BVISNULL( &msc->msc_cred ) ) {
					/* destroy sensitive data */
					memset( msc->msc_cred.bv_val, 0,
						msc->msc_cred.bv_len );
					ch_free( msc->msc_cred.bv_val );
					BER_BVZERO( &msc->msc_cred );
				}

				continue;
			}


			(void)asyncmeta_proxy_authz_bind( mc, i, op, rs, LDAP_BACK_DONTSEND, 1 );
			lerr = rs->sr_err;

		} else {
			lerr = asyncmeta_single_bind( op, rs, mc, i );
		}

		if ( lerr != LDAP_SUCCESS ) {
			rc = rs->sr_err = lerr;

			/* FIXME: in some cases (e.g. unavailable)
			 * do not assume it's not candidate; rather
			 * mark this as an error to be eventually
			 * reported to client */
			META_CANDIDATE_CLEAR( &candidates[ i ] );
			break;
		}
	}

	if ( mc != NULL ) {
		for ( i = 0; i < mi->mi_ntargets; i++ ) {
			a_metasingleconn_t	*msc = &mc->mc_conns[ i ];
			if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
				ch_free( msc->msc_bound_ndn.bv_val );
			}

			if ( !BER_BVISNULL( &msc->msc_cred ) ) {
				/* destroy sensitive data */
				memset( msc->msc_cred.bv_val, 0,
					msc->msc_cred.bv_len );
				ch_free( msc->msc_cred.bv_val );
			}
		}
		asyncmeta_back_conn_free( mc );
	}

	/*
	 * rc is LDAP_SUCCESS if at least one bind succeeded,
	 * err is the last error that occurred during a bind;
	 * if at least (and at most?) one bind succeeds, fine.
	 */
	if ( rc != LDAP_SUCCESS ) {

		/*
		 * deal with bind failure ...
		 */

		/*
		 * no target was found within the naming context,
		 * so bind must fail with invalid credentials
		 */
		if ( rs->sr_err == LDAP_SUCCESS && gotit == 0 ) {
			rs->sr_err = LDAP_INVALID_CREDENTIALS;
		} else {
			rs->sr_err = slap_map_api2result( rs );
		}
		send_ldap_result( op, rs );
		return rs->sr_err;

	}
	return LDAP_SUCCESS;
}
Beispiel #3
0
/*
 * FIXME: error return must be handled in a cleaner way ...
 */
int
asyncmeta_back_op_result(
	a_metaconn_t		*mc,
	Operation		*op,
	SlapReply		*rs,
	int			candidate,
	ber_int_t		msgid,
	time_t			timeout,
	ldap_back_send_t	sendok )
{
	a_metainfo_t	*mi = mc->mc_info;

	const char	*save_text = rs->sr_text,
			*save_matched = rs->sr_matched;
	BerVarray	save_ref = rs->sr_ref;
	LDAPControl	**save_ctrls = rs->sr_ctrls;
	void		*matched_ctx = NULL;

	char		*matched = NULL;
	char		*text = NULL;
	char		**refs = NULL;
	LDAPControl	**ctrls = NULL;

	assert( mc != NULL );

	rs->sr_text = NULL;
	rs->sr_matched = NULL;
	rs->sr_ref = NULL;
	rs->sr_ctrls = NULL;

	if ( candidate != META_TARGET_NONE ) {
		a_metatarget_t		*mt = mi->mi_targets[ candidate ];
		a_metasingleconn_t	*msc = &mc->mc_conns[ candidate ];

		if ( LDAP_ERR_OK( rs->sr_err ) ) {
			int		rc;
			struct timeval	tv;
			LDAPMessage	*res = NULL;
			time_t		stoptime = (time_t)(-1);
			int		timeout_err = op->o_protocol >= LDAP_VERSION3 ?
						LDAP_ADMINLIMIT_EXCEEDED : LDAP_OTHER;
			const char	*timeout_text = "Operation timed out";

			/* if timeout is not specified, compute and use
			 * the one specific to the ongoing operation */
			if ( timeout == (time_t)(-1) ) {
				slap_op_t	opidx = slap_req2op( op->o_tag );

				if ( opidx == SLAP_OP_SEARCH ) {
					if ( op->ors_tlimit <= 0 ) {
						timeout = 0;

					} else {
						timeout = op->ors_tlimit;
						timeout_err = LDAP_TIMELIMIT_EXCEEDED;
						timeout_text = NULL;
					}

				} else {
					timeout = mt->mt_timeout[ opidx ];
				}
			}

			/* better than nothing :) */
			if ( timeout == 0 ) {
				if ( mi->mi_idle_timeout ) {
					timeout = mi->mi_idle_timeout;

				}
			}

			if ( timeout ) {
				stoptime = op->o_time + timeout;
			}

			LDAP_BACK_TV_SET( &tv );

retry:;
			rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
			switch ( rc ) {
			case 0:
				if ( timeout && slap_get_time() > stoptime ) {
					(void)asyncmeta_back_cancel( mc, op, msgid, candidate );
					rs->sr_err = timeout_err;
					rs->sr_text = timeout_text;
					break;
				}

				LDAP_BACK_TV_SET( &tv );
				ldap_pvt_thread_yield();
				goto retry;

			case -1:
				ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE,
						&rs->sr_err );
				break;


			/* otherwise get the result; if it is not
			 * LDAP_SUCCESS, record it in the reply
			 * structure (this includes
			 * LDAP_COMPARE_{TRUE|FALSE}) */
			default:
				/* only touch when activity actually took place... */
				if ( mi->mi_idle_timeout != 0 && msc->msc_time < op->o_time ) {
					msc->msc_time = op->o_time;
				}

				rc = ldap_parse_result( msc->msc_ld, res, &rs->sr_err,
						&matched, &text, &refs, &ctrls, 1 );
				res = NULL;
				if ( rc == LDAP_SUCCESS ) {
					rs->sr_text = text;
				} else {
					rs->sr_err = rc;
				}
				rs->sr_err = slap_map_api2result( rs );

				/* RFC 4511: referrals can only appear
				 * if result code is LDAP_REFERRAL */
				if ( refs != NULL
					&& refs[ 0 ] != NULL
					&& refs[ 0 ][ 0 ] != '\0' )
				{
					if ( rs->sr_err != LDAP_REFERRAL ) {
						Debug( LDAP_DEBUG_ANY,
							"%s asyncmeta_back_op_result[%d]: "
							"got referrals with err=%d\n",
							op->o_log_prefix,
							candidate, rs->sr_err );

					} else {
						int	i;

						for ( i = 0; refs[ i ] != NULL; i++ )
							/* count */ ;
						rs->sr_ref = op->o_tmpalloc( sizeof( struct berval ) * ( i + 1 ),
							op->o_tmpmemctx );
						for ( i = 0; refs[ i ] != NULL; i++ ) {
							ber_str2bv( refs[ i ], 0, 0, &rs->sr_ref[ i ] );
						}
						BER_BVZERO( &rs->sr_ref[ i ] );
					}

				} else if ( rs->sr_err == LDAP_REFERRAL ) {
					Debug( LDAP_DEBUG_ANY,
						"%s asyncmeta_back_op_result[%d]: "
						"got err=%d with null "
						"or empty referrals\n",
						op->o_log_prefix,
						candidate, rs->sr_err );

					rs->sr_err = LDAP_NO_SUCH_OBJECT;
				}

				if ( ctrls != NULL ) {
					rs->sr_ctrls = ctrls;
				}
			}

			assert( res == NULL );
		}

		/* if the error in the reply structure is not
		 * LDAP_SUCCESS, try to map it from client
		 * to server error */
		if ( !LDAP_ERR_OK( rs->sr_err ) ) {
			rs->sr_err = slap_map_api2result( rs );

			/* internal ops ( op->o_conn == NULL )
			 * must not reply to client */
			if ( op->o_conn && !op->o_do_not_cache && matched ) {

				/* record the (massaged) matched
				 * DN into the reply structure */
				rs->sr_matched = matched;
			}
		}

		if ( META_BACK_TGT_QUARANTINE( mt ) ) {
			asyncmeta_quarantine( op, mi, rs, candidate );
		}

	} else {
		int	i,
			err = rs->sr_err;

		for ( i = 0; i < mi->mi_ntargets; i++ ) {
			a_metasingleconn_t	*msc = &mc->mc_conns[ i ];
			char			*xtext = NULL;
			char			*xmatched = NULL;

			if ( msc->msc_ld == NULL ) {
				continue;
			}

			rs->sr_err = LDAP_SUCCESS;

			ldap_get_option( msc->msc_ld, LDAP_OPT_RESULT_CODE, &rs->sr_err );
			if ( rs->sr_err != LDAP_SUCCESS ) {
				/*
				 * better check the type of error. In some cases
				 * (search ?) it might be better to return a
				 * success if at least one of the targets gave
				 * positive result ...
				 */
				ldap_get_option( msc->msc_ld,
						LDAP_OPT_DIAGNOSTIC_MESSAGE, &xtext );
				if ( xtext != NULL && xtext [ 0 ] == '\0' ) {
					ldap_memfree( xtext );
					xtext = NULL;
				}

				ldap_get_option( msc->msc_ld,
						LDAP_OPT_MATCHED_DN, &xmatched );
				if ( xmatched != NULL && xmatched[ 0 ] == '\0' ) {
					ldap_memfree( xmatched );
					xmatched = NULL;
				}

				rs->sr_err = slap_map_api2result( rs );

				if ( LogTest( LDAP_DEBUG_ANY ) ) {
					char	buf[ SLAP_TEXT_BUFLEN ];

					snprintf( buf, sizeof( buf ),
						"asyncmeta_back_op_result[%d] "
						"err=%d text=\"%s\" matched=\"%s\"",
						i, rs->sr_err,
						( xtext ? xtext : "" ),
						( xmatched ? xmatched : "" ) );
					Debug( LDAP_DEBUG_ANY, "%s %s.\n",
						op->o_log_prefix, buf, 0 );
				}

				/*
				 * FIXME: need to rewrite "match" (need rwinfo)
				 */
				switch ( rs->sr_err ) {
				default:
					err = rs->sr_err;
					if ( xtext != NULL ) {
						if ( text ) {
							ldap_memfree( text );
						}
						text = xtext;
						xtext = NULL;
					}
					if ( xmatched != NULL ) {
						if ( matched ) {
							ldap_memfree( matched );
						}
						matched = xmatched;
						xmatched = NULL;
					}
					break;
				}

				if ( xtext ) {
					ldap_memfree( xtext );
				}

				if ( xmatched ) {
					ldap_memfree( xmatched );
				}
			}

			if ( META_BACK_TGT_QUARANTINE( mi->mi_targets[ i ] ) ) {
				asyncmeta_quarantine( op, mi, rs, i );
			}
		}

		if ( err != LDAP_SUCCESS ) {
			rs->sr_err = err;
		}
	}

	if ( matched != NULL ) {
		struct berval	dn, pdn;

		ber_str2bv( matched, 0, 0, &dn );
		if ( dnPretty( NULL, &dn, &pdn, op->o_tmpmemctx ) == LDAP_SUCCESS ) {
			ldap_memfree( matched );
			matched_ctx = op->o_tmpmemctx;
			matched = pdn.bv_val;
		}
		rs->sr_matched = matched;
	}

	if ( rs->sr_err == LDAP_UNAVAILABLE ) {
		if ( !( sendok & LDAP_BACK_RETRYING ) ) {
			if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
				if ( rs->sr_text == NULL ) rs->sr_text = "Proxy operation retry failed";
				send_ldap_result( op, rs );
			}
		}

	} else if ( op->o_conn &&
		( ( ( sendok & LDAP_BACK_SENDOK ) && LDAP_ERR_OK( rs->sr_err ) )
			|| ( ( sendok & LDAP_BACK_SENDERR ) && !LDAP_ERR_OK( rs->sr_err ) ) ) )
	{
		send_ldap_result( op, rs );
	}
	if ( matched ) {
		op->o_tmpfree( (char *)rs->sr_matched, matched_ctx );
	}
	if ( text ) {
		ldap_memfree( text );
	}
	if ( rs->sr_ref ) {
		op->o_tmpfree( rs->sr_ref, op->o_tmpmemctx );
		rs->sr_ref = NULL;
	}
	if ( refs ) {
		ber_memvfree( (void **)refs );
	}
	if ( ctrls ) {
		assert( rs->sr_ctrls != NULL );
		ldap_controls_free( ctrls );
	}

	rs->sr_text = save_text;
	rs->sr_matched = save_matched;
	rs->sr_ref = save_ref;
	rs->sr_ctrls = save_ctrls;

	return( LDAP_ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
}
Beispiel #4
0
int main(int argc, char **argv)
{
  int rc, i;
  ns_testset_t *p_test;
  char path[FSAL_MAX_PATH_LEN];
  unsigned int gen = 0;
  unsigned int dev = DEV;

  /* Init logging */

  SetNamePgm("test_ns");
  SetDefaultLogging("TEST");
  SetNameFunction("main");
  InitLogging();

  /* namespace init */
  rc = NamespaceInit(ROOT_INODE, DEV, &gen);
  if(rc)
    {
      LogTest("NamespaceInit rc=%d\n", rc);
      exit(1);
    }

  for(i = 0; i < 2; i++)
    {

      /* creation des entrees */
      for(p_test = testset; p_test->name != NULL; p_test++)
        {
          rc = NamespaceAdd(p_test->parent_inode, DEV, gen, p_test->name,
                            p_test->entry_inode, DEV, &gen);
          LogTest("NamespaceAdd(%lu,%s->%lu) = %d\n", p_test->parent_inode, p_test->name,
                 p_test->entry_inode, rc);
          if(rc)
            exit(1);            /* This is an error */
        }

      /* tentative de recreation */
      for(p_test = testset; p_test->name != NULL; p_test++)
        {
          rc = NamespaceAdd(p_test->parent_inode, DEV, gen, p_test->name,
                            p_test->entry_inode, DEV, &gen);
          LogTest("Redundant NamespaceAdd(%lu,%s->%lu) = %d\n", p_test->parent_inode,
                 p_test->name, p_test->entry_inode, rc);
          if(rc)
            exit(1);            /* This is an error */
        }

      /* recolte du chemin complet de root */

      rc = NamespacePath(ROOT_INODE, DEV, gen, path);
      if(rc)
        {
          LogTest("NamespacePath(%lu) rc=%d\n", ROOT_INODE, rc);
          exit(1);
        }
      else
        LogTest("NamespacePath(%lu) => \"%s\"\n", ROOT_INODE, path);

      /* recolte du chemin complet des entrees */

      for(p_test = testset; p_test->name != NULL; p_test++)
        {
          rc = NamespacePath(p_test->entry_inode, DEV, gen, path);
          if(rc)
            {
              LogTest("NamespacePath(%lu) rc=%d\n", p_test->entry_inode, rc);
              exit(1);
            }
          else
            LogTest("NamespacePath(%lu) => \"%s\"\n", p_test->entry_inode, path);
        }

      /* on efface les entrees en ordre inverse */
      for(p_test--; p_test >= testset; p_test--)
        {
          rc = NamespaceRemove(p_test->parent_inode, DEV, gen, p_test->name);
          LogTest("NamespaceRemove(%lu,%s) = %d\n", p_test->parent_inode,
                 p_test->name, rc);
        }

      /* on essaye d'obtenir leur nom */
      for(p_test = testset; p_test->name != NULL; p_test++)
        {
          rc = NamespacePath(p_test->entry_inode, DEV, gen, path);
          if(rc == 0)
            {
              LogTest("NamespacePath(%lu) => \"%s\"\n", p_test->entry_inode, path);
              exit(1);
            }
          else if(rc != ENOENT)
            {
              LogTest("NamespacePath(%lu) rc=%d\n", p_test->entry_inode, rc);
              exit(1);
            }
          else
            LogTest("NamespacePath(%lu) rc=%d (ENOENT)\n", p_test->entry_inode, rc);
        }
    }

  /* now create/remove a hardlink to a file N times */

  rc = NamespaceAdd(ROOT_INODE, DEV, gen, "dir", ROOT_INODE + 1, DEV, &gen);
  if(rc)
    {
      LogTest("NamespaceAdd error %d line %d\n", rc, __LINE__ - 1);
      exit(1);
    }

  rc = NamespaceAdd(ROOT_INODE + 1, DEV, gen, "subdir", ROOT_INODE + 2, DEV, &gen);
  if(rc)
    {
      LogTest("NamespaceAdd error %d line %d\n", rc, __LINE__ - 1);
      exit(1);
    }

  rc = NamespaceAdd(ROOT_INODE + 2, DEV, gen, "entry", ROOT_INODE + 3, DEV, &gen);
  if(rc)
    {
      LogTest("NamespaceAdd error %d line %d\n", rc, __LINE__ - 1);
      exit(1);
    }

  /* create hardlinks and lookup */
  for(i = 0; i < 3; i++)
    {
      char name[FSAL_MAX_NAME_LEN];

      sprintf(name, "entry.hl%d", i);

      rc = NamespaceAdd(ROOT_INODE + 2, DEV, gen, name, ROOT_INODE + 3, DEV, &gen);
      LogTest("NamespaceAdd(%lu,%s->%lu) = %d\n", ROOT_INODE + 2, name, ROOT_INODE + 3,
             rc);
      if(rc)
        exit(1);

      rc = NamespacePath(ROOT_INODE + 3, DEV, gen, path);
      if(rc)
        {
          LogTest("NamespacePath(%lu) rc=%d\n", ROOT_INODE + 3, rc);
          exit(1);
        }
      else
        LogTest("NamespacePath(%lu) => \"%s\"\n", ROOT_INODE + 3, path);

    }

  /* delete hardlinks and lookup */
  for(i = 0; i < 3; i++)
    {
      char name[FSAL_MAX_NAME_LEN];

      sprintf(name, "entry.hl%d", i);

      rc = NamespaceRemove(ROOT_INODE + 2, DEV, gen, name);
      LogTest("NamespaceRemove(%lu,%s) = %d\n", ROOT_INODE + 2, name, rc);
      if(rc)
        exit(1);

      rc = NamespacePath(ROOT_INODE + 3, DEV, gen, path);
      if(rc)
        {
          LogTest("NamespacePath(%lu) rc=%d\n", ROOT_INODE + 3, rc);
          exit(1);
        }
      else
        LogTest("NamespacePath(%lu) => \"%s\"\n", ROOT_INODE + 3, path);

    }

  return 0;

}
Beispiel #5
0
meta_search_candidate_t
asyncmeta_dobind_init_with_retry(Operation *op, SlapReply *rs, bm_context_t *bc, a_metaconn_t *mc, int candidate)
{

	int rc, retries = 1;
	a_metasingleconn_t *msc = &mc->mc_conns[candidate];
	a_metainfo_t		*mi = mc->mc_info;
	a_metatarget_t		*mt = mi->mi_targets[ candidate ];
	SlapReply		*candidates = bc->candidates;

retry_dobind:
	rc = asyncmeta_dobind_init(op, rs, bc, mc, candidate);
	if (rs->sr_err != LDAP_UNAVAILABLE) {
		return rc;
	} else if (retries <= 0) {
		ldap_pvt_thread_mutex_lock( &mc->mc_om_mutex );
		if (mc->mc_active < 1) {
			asyncmeta_clear_one_msc(NULL, mc, candidate);
		}
		ldap_pvt_thread_mutex_unlock( &mc->mc_om_mutex );
		return rc;
	}
	/* need to retry */
	retries--;
	if ( LogTest( LDAP_DEBUG_ANY ) ) {
		char	buf[ SLAP_TEXT_BUFLEN ];

		/* this lock is required; however,
		 * it's invoked only when logging is on */
		ldap_pvt_thread_mutex_lock( &mt->mt_uri_mutex );
		snprintf( buf, sizeof( buf ),
			  "retrying URI=\"%s\" DN=\"%s\"",
			  mt->mt_uri,
			  BER_BVISNULL( &msc->msc_bound_ndn ) ?
			  "" : msc->msc_bound_ndn.bv_val );
		ldap_pvt_thread_mutex_unlock( &mt->mt_uri_mutex );

		Debug( LDAP_DEBUG_ANY,
		       "%s asyncmeta_search_dobind_init_with_retry[%d]: %s.\n",
		       op->o_log_prefix, candidate, buf );
	}

	ldap_pvt_thread_mutex_lock( &mc->mc_om_mutex );
	if (mc->mc_active < 1) {
		asyncmeta_clear_one_msc(NULL, mc, candidate);
	}
	ldap_pvt_thread_mutex_unlock( &mc->mc_om_mutex );

	( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );

	rc = asyncmeta_init_one_conn( op, rs, mc, candidate,
				      LDAP_BACK_CONN_ISPRIV( mc ), LDAP_BACK_DONTSEND, 0 );

	if (rs->sr_err != LDAP_SUCCESS) {
		ldap_pvt_thread_mutex_lock( &mc->mc_om_mutex );
		if (mc->mc_active < 1) {
			asyncmeta_clear_one_msc(NULL, mc, candidate);
		}
		ldap_pvt_thread_mutex_unlock( &mc->mc_om_mutex );
		return META_SEARCH_ERR;
	}

	goto retry_dobind;
	return rc;
}
Beispiel #6
0
void printmask(fsal_attrib_mask_t mask)
{

  if(FSAL_TEST_MASK(mask, FSAL_ATTR_SUPPATTR))
    LogTest("FSAL_ATTR_SUPPATTR");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_TYPE))
    LogTest("FSAL_ATTR_TYPE");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_SIZE))
    LogTest("FSAL_ATTR_SIZE");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_FSID))
    LogTest("FSAL_ATTR_FSID");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_ACL))
    LogTest("FSAL_ATTR_ACL ");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_FILEID))
    LogTest("FSAL_ATTR_FILEID");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_MODE))
    LogTest("FSAL_ATTR_MODE");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_NUMLINKS))
    LogTest("FSAL_ATTR_NUMLINKS");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_OWNER))
    LogTest("FSAL_ATTR_OWNER");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_GROUP))
    LogTest("FSAL_ATTR_GROUP");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_RAWDEV))
    LogTest("FSAL_ATTR_RAWDEV");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_ATIME))
    LogTest("FSAL_ATTR_ATIME");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_CREATION))
    LogTest("FSAL_ATTR_CREATION");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_CTIME))
    LogTest("FSAL_ATTR_CTIME");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_CHGTIME))
    LogTest("FSAL_ATTR_CHGTIME");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_MTIME))
    LogTest("FSAL_ATTR_MTIME");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_SPACEUSED))
    LogTest("FSAL_ATTR_SPACEUSED");
  if(FSAL_TEST_MASK(mask, FSAL_ATTR_MOUNTFILEID))
    LogTest("FSAL_ATTR_MOUNTFILEID");

}
Beispiel #7
0
int main(int argc, char *argv[])
{
  SetDefaultLogging("TEST");
  SetNamePgm("test_configurable_lru");

  char buf[LENBUF];
  int ok = 1;
  int hrc = 0;
  int rc = 0;
  int expected_rc;
  char c;
  char *p;
  int key;

  LRU_status_t status = 0;
  LRU_list_t *plru;
  LRU_parameter_t param;

  param.nb_entry_prealloc = PREALLOC;
  param.entry_to_str = print_entry;
  param.clean_entry = clean_entry;
  param.name = "Test";

  BuddyInit(NULL);

  if((plru = LRU_Init(param, &status)) == NULL)
    {
      LogTest("Test ECHOUE : Mauvaise init");
      exit(1);
    }

  /*
   *
   * La syntaxe d'un test est 
   * 'i key rc' : invalide l'entree avec la clef key
   * 'n key rc' : cree une nouvelle entree avec la clef key
   * 'g key rc' : passage du garbage collector (key ne sert a rien)
   * 'p key rc' : imprime le LRU (key et rc ne servent a rien).
   * 
   * Une ligne qui debute par '#' est un commentaire
   * Une ligne qui debute par un espace ou un tab est une ligne vide [meme si il y a des trucs derriere.. :-( ]
   * Une ligne vide (juste un CR) est une ligne vide (cette citation a recu le Premier Prix lors du Festival International 
   * de la Tautologie de Langue Francaise (FITLF), a Poully le Marais, en Aout 2004)
   *
   */

  LogTest("============ Debut de l'interactif =================");

  while(ok)
    {
      /* Code interactif, pompe sur le test rbt de Jacques */
      fputs("> ", stdout);
      if((p = fgets(buf, LENBUF, stdin)) == NULL)
        {
          LogTest("fin des commandes");
          ok = 0;
          continue;
        }
      if((p = strchr(buf, '\n')) != NULL)
        *p = '\0';

      rc = sscanf(buf, "%c %d %d", &c, &key, &expected_rc);
      if(c == '#')
        {
          /* # indique un commentaire */
          continue;
        }
      else if(c == ' ' || c == '\t' || rc == -1)
        {
          /* Cas d'une ligne vide */
          if(rc > 1)
            LogTest("Erreur de syntaxe : mettre un diese au debut d'un commentaire");

          continue;
        }
      else
        {
          if(rc != 3)
            {
              LogTest("Erreur de syntaxe : sscanf retourne %d au lieu de 3", rc);
              continue;
            }
          LogTest("---> %c %d %d", c, key, expected_rc);
        }

      switch (c)
        {
        case 'i':
          /* set overwrite */
          LogTest("invalidate  %d  --> %d ?", key, expected_rc);

          hrc = do_invalidate(plru, key);

          if(hrc != expected_rc)
            LogTest(">>>> ERREUR: invalidate  %d : %d != %d (expected)",
                    key, hrc, expected_rc);
          else
            LogTest(">>>> OK invalidate %d", key);
          break;

        case 'n':
          /* test */
          LogTest("new %d --> %d ?", key, expected_rc);

          hrc = do_new(plru, key);

          if(hrc != expected_rc)
            LogTest(">>>> ERREUR: new %d : %d != %d (expected)", key, hrc, expected_rc);
          else
            LogTest(">>>> OK new %d", key);
          break;

        case 'g':
          /* set no overwrite */
          LogTest("gc  %d --> %d ?", key, expected_rc);

          hrc = do_gc(plru);

          if(hrc != expected_rc)
            LogTest(">>>> ERREUR: gc %d: %d != %d (expected)", key, hrc, expected_rc);
          else
            LogTest(">>>> OK new  %d", key);
          break;

        case 'p':
          /* Print */
          LRU_Print(plru);
          break;

        default:
          /* syntaxe error */
          LogTest("ordre '%c' non-reconnu", c);
          break;
        }
    }

  LogTest("====================================================");
  LogTest("Test reussi : tous les tests sont passes avec succes");
  exit(0);
  return;
}                               /* main */
void Test2()
{
  char tempstr[2048];
  int  n1, n2;

  /*
   * Set up for tests that will verify what was actually produced by log messages.
   * This is used to test log levels and to test the log_vnsprintf function.
   */
  SetComponentLogBuffer(COMPONENT_MAIN, tempstr);
  SetComponentLogBuffer(COMPONENT_INIT, tempstr);
  SetComponentLogLevel(COMPONENT_MAIN, NIV_EVENT);

  LogTest("------------------------------------------------------");
  LogTest("Test string/char formats");
  TestFormat("none");
  TestFormat("String: %s", "str");
  TestFormat("String: %12s", "str");
  TestFormat("String: %-12s", "str");
  TestFormat("String: %12s", "too long string");
  TestFormat("String: %-12s", "too long string");
  TestFormat("%c", (char) 65);
  // Not tested lc, ls, C, S

  LogTest("------------------------------------------------------");
  LogTest("Test integer formats");
  TestFormat("Integer: %d %d %i %i %u %s", 1, -1, 2, -2, 3, "extra");
  TestFormat("Octal and Hex: 0%o 0x%x 0x%X %s", 0123, 0xabcdef, 0xABCDEF, "extra");
  TestFormat("Field Length: %3d %s", 1, "extra");
  TestFormat("Variable Field Length: %*d %s", 5, 123, "extra");
  TestFormat("Alignment flags: %+d %+d %-5d %-5d %05d %05d % d % d %s", 2, -2, 333, -333, 444, -444, 5, -5, "extra");
  // TestFormat("Two Flags: %-05d %-05d %0-5d %0-5d %s", 333, -333, 444, -444, "extra");
  // TestFormat("Two Flags: %+ d %+ d % +d % +d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %-+5d %-+5d %+-5d %+-5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %- 5d %- 5d % -5d % -5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %+05d %+05d %0+5d %0+5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: % 05d % 05d %0 5d %0 5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Use of # Flag: %#x %#3x %#05x %#-5x %-#5x %0#5x", 1, 2, 3, 4, 5, 6);
  // TestFormat("Many Flags: %#-0 +#-0 +#-0 +5d", 4);
  TestFormat("Special Flags (may not be supported) %'d %Id %s", 12345, 67, "extra");

  LogTest("------------------------------------------------------");
  LogTest("Test floating point formats");
  TestFormat("%e %E %e %E %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%f %F %f %F %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%g %G %g %G %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%a %A %a %A %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%Le %LE %Le %LE %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%Lf %LF %Lf %LF %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%Lg %LG %Lg %LG %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%La %LA %La %LA %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%lle %llE %lle %llE %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%llf %llF %llf %llf %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%llg %llG %llg %llG %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%lla %llA %lla %llA %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("Field Length: %8f %8.2f %8f %8.2f %s", 1.1, 1.1, 1.1E10, 1.1E3, "extra");
  TestFormat("Field Length: %08f %08.2f %08f %08.2f %s", 1.1, 1.1, 1.1E10, 1.1E3, "extra");
  TestFormat("Field Length: %-8f %-8.2f %-8f %-8.2f %s", 1.1, 1.1, 1.1E10, 1.1E3, "extra");
  TestFormat("Variable Field Length: %*.*f %*.2f %6.*f %s", 6, 2, 1.1, 6, 2.2, 2, 3.3, "extra");
  TestFormat("Negative:      %e %E %e %E %s    ", -1.1, -1.1, -1.1E10, -1.1E10, "extra");
  TestFormat("With '+' flag: %+e %+E %+e %+E %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("With ' ' flag: % e % E % e % E %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("With '#' flag: %#8.0e %8.0e %s", 1.0, 1.0, "extra");
  TestFormat("With '#' flag: %#g %g %#5g %#5g %5g %s", 1.0, 1.0, 2.0, 10.0, 2.0, "extra");

  LogTest("------------------------------------------------------");
  LogTest("Test some special formats");
  TestFormat("pointer: %p %s", &n1, "extra");
#if 0
// we can't support %n due to security considerations
  TestFormat("count: 12345678%n %s", &n1, "extra");
  snprintf(tempstr, 2048, "count: 12345678%n %s", &n1, "extra");
  log_snprintf(tempstr, 2048, "count: 12345678%n %s", &n2, "extra");
  if (n1 != n2)
    {
      LogTest("FAILURE: 12345678%%n produced %d expected %d", n2, n1);
      exit(1);
    }
  LogTest("SUCCESS: 12345678%%n produced %d", n2);
#endif
  errno = EIO;
  TestFormat("strerror: %m %64m %s", "extra");
  TestFormat("percent char: %% %s", "extra");

  LogTest("------------------------------------------------------");
  LogTest("Test integer size qualifier tags");
  TestFormat("%hhd %s", (char) 1, "extra");
  TestFormat("%hd %s", (short) 500, "extra");
  TestFormat("%lld %s", (long long) 12345678, "extra");
  TestFormat("%Ld %s", (long long) 12345678, "extra");
  TestFormat("%ld %s", (long) 12345, "extra");
  TestFormat("%qd %s", (long long) 12345678, "extra");
  TestFormat("%jd %s", (long long) 1, "extra");
  TestFormat("%td %s", (char *) &n1 - (char *) &n2, "extra");
  TestFormat("%zd %s", sizeof(int), "extra");

  /*
   * Ganesha can't properly support the $ parameter index tag, so don't bother testing, even if it does work
   * when the indices are in ascending order.
  TestFormat("%1$08x", 6);
  TestFormat("%3$llx %2$d %1d", 1, 2, (long long)0x12345678);
   */

}
int main(int argc, char *argv[])
{

  if(argc >= 2)
    {

      /* TEST 1 Standard */

      if(!strcmp(argv[1], "STD"))
        {
          char *str = "No extra string provided";
          char *file = NULL;

          if (argc >= 3)
            str = argv[2];

          if (argc >= 4)
            file = argv[3];

          SetNamePgm("test_liblog");
          SetNameHost("localhost");
          SetDefaultLogging("TEST");
          InitLogging();
          AddFamilyError(ERR_POSIX, "POSIX Errors", tab_systeme_status);
          LogTest("AddFamilyError = %d",
                  AddFamilyError(ERR_DUMMY, "Family Dummy", tab_test_err));
          LogTest("The family which was added is %s",
                  ReturnNameFamilyError(ERR_DUMMY));

          run_Tests(TRUE,  "monothread", str, file);
        }

      /* TEST 1 multithread */

      else if(!strcmp(argv[1], "MT"))
        {

          /* multithread test */
          pthread_attr_t th_attr[NB_THREADS];
          pthread_t threads[NB_THREADS];
          int th_index, i;
          void *result;

          SetNamePgm("test_liblog");
          SetNameHost("localhost");
          SetDefaultLogging("STDOUT");
          InitLogging();
          AddFamilyError(ERR_POSIX, "POSIX Errors", tab_systeme_status);
          LogTest("AddFamilyError = %d",
                  AddFamilyError(ERR_DUMMY, "Family Dummy", tab_test_err));
          LogTest("The family which was added is %s",
                  ReturnNameFamilyError(ERR_DUMMY));

          /* creation of attributes */
          for(th_index = 0; th_index < NB_THREADS; th_index++)
            {
              pthread_attr_init(&th_attr[th_index]);
              pthread_attr_setdetachstate(&th_attr[th_index], PTHREAD_CREATE_JOINABLE);
            }

          /* creation of threads with their names */
          for(i = 0; i < NB_THREADS; i++)
            {
              int rc;
              char *thread_name = malloc(256);
              snprintf(thread_name, 256, "thread %3d", i);
              rc = pthread_create(&(threads[i]), &th_attr[i], run_MT_Tests,
                                  (void *)thread_name);
            }

          /* waiting for threads termination */
          for(i = 0; i < NB_THREADS; i++)
            {
              pthread_join(threads[i], &result);
              if(result)
                return 1;
            }

          return 0;

        }

      /* unknown test */
      else
        {
          fprintf(stderr, "%s", usage);
          exit(1);
        }

    }
  else
    {
      fprintf(stderr, "%s", usage);
      exit(1);
    }
  return 0;
}
Beispiel #10
0
main(int argc, char *argv[])
{
  char localmachine[256];

  cache_inode_client_t client;
  LRU_parameter_t lru_param;
  LRU_status_t lru_status;
  cache_inode_fsal_data_t fsdata;

  fsal_status_t status;
  fsal_parameter_t init_param;
  fsal_name_t name;
  fsal_path_t path;
  fsal_attrib_mask_t mask;
  fsal_path_t pathroot;
  fsal_attrib_list_t attribs;
  fsal_handle_t root_handle;

  cache_inode_endofdir_t eod_met;
  cache_inode_dir_entry_t dirent_array[100];
  cache_inode_dir_entry_t dirent_array_loop[5];
  unsigned int nbfound;

  unsigned int begin_cookie = 0;
  hash_buffer_t key, value;

  uid_t uid;
  fsal_cred_t cred;

  cache_inode_status_t cache_status;
  cache_inode_parameter_t cache_param;
  cache_inode_client_parameter_t cache_client_param;

  hash_table_t *ht = NULL;
  fsal_attrib_list_t attrlookup;
  cache_entry_t *cache_entry_root = NULL;
  cache_entry_t *cache_entry_lookup = NULL;
  cache_entry_t *cache_entry_lookup2 = NULL;
  cache_entry_t *cache_entry_lookup3 = NULL;
  cache_entry_t *cache_entry_lookup4 = NULL;
  cache_entry_t *cache_entry_dircont = NULL;

  cache_inode_gc_policy_t gcpol;

  char *configfile = argv[1];
  int i = 0;
  int rc = 0;

  /* Init the Buddy System allocation */
  if((rc = BuddyInit(NULL)) != BUDDY_SUCCESS)
    {
      LogTest("Error initializing memory allocator");
      exit(1);
    }


  /* init debug */
  SetDefaultLogging("TEST");
  SetNamePgm("test_cache_inode");
  SetNameFunction("main");
  InitLogging();

#if defined( _USE_GHOSTFS )
  if(argc != 2)
    {
      LogTest("Please set the configuration file as parameter");
      exit(1);
    }
#endif

  /* Obtention du nom de la machine */
  if(gethostname(localmachine, sizeof(localmachine)) != 0)
    {
      LogError(COMPONENT_STDOUT,ERR_SYS, ERR_GETHOSTNAME, errno);
      exit(1);
    }
  else
    SetNameHost(localmachine);

  AddFamilyError(ERR_FSAL, "FSAL related Errors", tab_errstatus_FSAL);
  AddFamilyError(ERR_CACHE_INODE, "FSAL related Errors", tab_errstatus_cache_inode);

  /* creating log */
  LogTest( "Starting the test");
  LogTest( "-----------------");

#if defined( _USE_GHOSTFS )
  if(FSAL_IS_ERROR(status = FSAL_str2path(configfile,
                                          strlen(configfile) + 1,
                                          &(init_param.fs_specific_info.
                                            definition_file))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
    }
#elif defined( _USE_HPSS )

  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, Flags);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DebugValue);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, TransferType);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, NumRetries);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, BusyDelay);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, BusyRetries);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, TotalDelay);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, GKTotalDelay);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, LimitedRetries);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, MaxConnections);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, ReuseDataConnections);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, UsePortRange);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, RetryStageInp);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DMAPWriteUpdates);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, ServerName);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DescName);

  init_param.fs_specific_info.behaviors.PrincipalName = FSAL_INIT_FORCE_VALUE;
  strncpy(init_param.fs_specific_info.hpss_config.PrincipalName,
          HPSS_SSM, HPSS_MAX_PRINCIPAL_NAME);

  init_param.fs_specific_info.behaviors.KeytabPath = FSAL_INIT_FORCE_VALUE;
  strncpy(init_param.fs_specific_info.hpss_config.KeytabPath,
          HPSS_KEYTAB, HPSS_MAX_PATH_NAME);

  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DebugPath);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, HostName);
  FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, RegistrySiteName);

#endif

  /* 2-common info (default) */
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxfilesize);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxlink);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxnamelen);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxpathlen);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, no_trunc);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, chown_restricted);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, case_insensitive);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, case_preserving);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, fh_expire_type);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, link_support);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, symlink_support);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, named_attr);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, unique_handles);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, lease_time);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, acl_support);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, cansettime);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, homogenous);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxread);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxwrite);

  /* Init */
  if(FSAL_IS_ERROR(status = FSAL_Init(&init_param)))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
    }

  /* getting creds */
  uid = getuid();

  if(FSAL_IS_ERROR(status = FSAL_GetUserCred(uid, NULL, &cred)))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
    }

  /* Init of the cache inode module */
  cache_param.hparam.index_size = 31;
  cache_param.hparam.alphabet_length = 10;      /* Buffer seen as a decimal polynom */
  cache_param.hparam.nb_node_prealloc = 100;
  cache_param.hparam.hash_func_key = cache_inode_fsal_hash_func;
  cache_param.hparam.hash_func_rbt = cache_inode_fsal_rbt_func;
  cache_param.hparam.hash_func_both = NULL ; /* BUGAZOMEU */
  cache_param.hparam.compare_key = cache_inode_compare_key_fsal;
  cache_param.hparam.key_to_str = display_key;
  cache_param.hparam.val_to_str = display_value;

  if((ht = cache_inode_init(cache_param, &cache_status)) == NULL)
    {
      LogTest( "Error %d while init hash ", cache_status);
    }
  else
    LogTest( "Hash Table address = %p", ht);

  /* We need a cache_client to acces the cache */
  cache_client_param.attrmask =
      FSAL_ATTRS_MANDATORY | FSAL_ATTR_MTIME | FSAL_ATTR_CTIME | FSAL_ATTR_ATIME;
  cache_client_param.nb_prealloc_entry = 1000;
  cache_client_param.nb_pre_dir_data = 200;
  cache_client_param.nb_pre_parent = 1200;
  cache_client_param.nb_pre_state_v4 = 100;

  cache_client_param.lru_param.nb_entry_prealloc = 1000;
  cache_client_param.lru_param.entry_to_str = lru_entry_to_str;
  cache_client_param.lru_param.clean_entry = lru_clean_entry;

  cache_client_param.grace_period_attr   = 0;
  cache_client_param.grace_period_link   = 0;
  cache_client_param.grace_period_dirent = 0;
  cache_client_param.expire_type_attr    = CACHE_INODE_EXPIRE_NEVER;
  cache_client_param.expire_type_link    = CACHE_INODE_EXPIRE_NEVER;
  cache_client_param.expire_type_dirent  = CACHE_INODE_EXPIRE_NEVER;

  /* Init the cache_inode client */
  if(cache_inode_client_init(&client, &cache_client_param, 0, NULL) != 0)
    exit(1);

  /* Init the gc */
  gcpol.file_expiration_delay = 3;
  gcpol.directory_expiration_delay = 4;
  gcpol.hwmark_nb_entries = 6;
  gcpol.lwmark_nb_entries = 3;
  gcpol.run_interval = 4;

  cache_inode_set_gc_policy(gcpol);

  /* Getting the root of the FS */
  if((FSAL_IS_ERROR(status = FSAL_str2path("/", 2, &pathroot))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }

  if((FSAL_IS_ERROR(status = FSAL_lookupPath(&pathroot, &cred, &root_handle, &attribs))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }
  fsdata.cookie = 0;
  fsdata.handle = root_handle;

  /* Cache the root of the FS */
  if((cache_entry_root =
      cache_inode_make_root(&fsdata, 1, ht, &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't init fs's root");
      exit(1);
    }

  /* A lookup in the root fsal */
  if((FSAL_IS_ERROR(status = FSAL_str2name("cea", 10, &name))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }

  if((cache_entry_lookup = cache_inode_lookup(cache_entry_root,
                                              &name,
                                              &attrlookup,
                                              ht, &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't lookup");
      exit(1);
    }

  /* Lookup a second time (entry should now be cached) */
  if((cache_entry_lookup2 = cache_inode_lookup(cache_entry_root,
                                               &name,
                                               &attrlookup,
                                               ht,
                                               &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't lookup");
      exit(1);
    }

  if(cache_entry_lookup2 != cache_entry_lookup)
    {
      LogTest("Error: lookup results should be the same");
      exit(1);
    }

  /* A lookup in the root fsal */
  if((FSAL_IS_ERROR(status = FSAL_str2name("log", 10, &name))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }

  if((cache_entry_lookup3 = cache_inode_lookup(cache_entry_root,
                                               &name,
                                               &attrlookup,
                                               ht,
                                               &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't lookup");
      exit(1);
    }

  if((cache_entry_lookup4 = cache_inode_lookup(cache_entry_root,
                                               &name,
                                               &attrlookup,
                                               ht,
                                               &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't lookup");
      exit(1);
    }

  if(cache_entry_lookup3 != cache_entry_lookup4)
    {
      LogTest("Error: lookup results should be the same");
      exit(1);
    }

  /* A lookup in the root fsal */
  if((FSAL_IS_ERROR(status = FSAL_str2name("SunOS_5", 10, &name))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }

  cache_inode_print_dir(cache_entry_root);

  /* Test readdir */
  if(cache_inode_readdir(cache_entry_root,
                         0,
                         100,
                         &nbfound,
                         &eod_met,
                         dirent_array,
                         ht, &client, &cred, &cache_status) != CACHE_INODE_SUCCESS)
    {
      LogTest( "Error: cache_inode_readdir failed");
      exit(1);
    }

  LogTest( "Readdir nbfound=%d, eod_met=%d", nbfound, eod_met);
  for(i = 0; i < nbfound; i++)
    LogTest( "dirent_array[%d] ==> %s | %p", i,
                 dirent_array[i].name.name, dirent_array[i].pentry);

  cache_inode_print_dir(cache_entry_root);

  /* looping on readir */
  LogTest( "Loop directory in several pass");

  eod_met = TO_BE_CONTINUED;
  begin_cookie = 0;

  do
    {

      if(cache_inode_readdir(cache_entry_root,
                             begin_cookie,
                             2,
                             &nbfound,
                             &eod_met,
                             dirent_array_loop,
                             ht, &client, &cred, &cache_status) != CACHE_INODE_SUCCESS)
        {
          LogTest("Error: cache_inode_readdir failed: %d", cache_status);
          exit(1);
        }

      for(i = 0; i < nbfound; i++)
        LogTest( " ==> %s | %p", dirent_array_loop[i].name.name,
                     dirent_array_loop[i].pentry);

      begin_cookie += nbfound;

    }
  while(eod_met == TO_BE_CONTINUED);

  LogTest( "---------------------------------");

  /* A lookup in the root fsal */
  if((FSAL_IS_ERROR(status = FSAL_str2name("cea", 10, &name))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }

  if((cache_entry_lookup = cache_inode_lookup(cache_entry_root,
                                              &name,
                                              &attrlookup,
                                              ht, &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't lookup");
      exit(1);
    }

  /* A lookup in the root fsal */
  if((FSAL_IS_ERROR(status = FSAL_str2name("log", 10, &name))))
    {
      LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor);
      exit(1);
    }

  if((cache_entry_lookup = cache_inode_lookup(cache_entry_root,
                                              &name,
                                              &attrlookup,
                                              ht, &client, &cred, &cache_status)) == NULL)
    {
      LogTest( "Error: can't lookup");
      exit(1);
    }
  /* Print the Hash Table */
  HashTable_Log(COMPONENT_STDOUT, ht);

  LogTest( "Readdir nbfound=%d, eod_met=%d", nbfound, eod_met);
  for(i = 0; i < nbfound; i++)
    LogTest( "dirent_array[%d] ==> %s | %p ", i,
                 dirent_array[i].name.name, dirent_array[i].pentry);

  /* Call the GC */
  LogTest( "Sleeping %d second before gc (for gc invalidation)",
               gcpol.file_expiration_delay + 2);
  sleep(gcpol.file_expiration_delay + 2);

  if(cache_inode_gc(ht, &client, &cache_status) != CACHE_INODE_SUCCESS)
    {
      LogTest( "Error: cache_inode_gc failed");
      exit(1);
    }
  LogTest( "GC performed successfully");

  /* Print the Hash Table */
  HashTable_Log(COMPONENT_STDOUT, ht);

  /* Another readdir, after gc is made */
  eod_met = TO_BE_CONTINUED;
  begin_cookie = 0;

  LogTest( "ANOTHER READDIR AFTER GC");

  do
    {

      if(cache_inode_readdir(cache_entry_root,
                             begin_cookie,
                             2,
                             &nbfound,
                             &eod_met,
                             dirent_array_loop,
                             ht, &client, &cred, &cache_status) != CACHE_INODE_SUCCESS)
        {
          LogTest("Error: cache_inode_readdir failed: %d", cache_status);
          exit(1);
        }

      for(i = 0; i < nbfound; i++)
        LogTest( " ==> %s | %p", dirent_array_loop[i].name.name,
                     dirent_array_loop[i].pentry);

      begin_cookie += nbfound;

    }
  while(eod_met == TO_BE_CONTINUED);

  LogTest( "---------------------------------");

  /* Print the Hash Table */
  HashTable_Log(COMPONENT_STDOUT, ht);

  LogTest( "---------------------------------");

  /* The end of all the tests */
  LogTest( "All tests exited successfully");

  exit(0);
}                               /* main */
/**
 *  Tests about Log streams and special printf functions.
 */
void Test1(char *str, char *file)
{
  char tempstr[2048];
  int  i;

  SetComponentLogFile(COMPONENT_INIT, "STDOUT");
  LogAlways(COMPONENT_INIT, "%s", "Starting Log Tests");
  LogTest("My PID = %d", getpid());

  LogTest("------------------------------------------------------");
  LogTest("Test conversion of log levels between string and integer");
  for (i = NIV_NULL; i < NB_LOG_LEVEL; i++)
    {
      int j;
      if (strcmp(tabLogLevel[i].str, ReturnLevelInt(i)) != 0)
        {
          LogTest("FAILURE: Log level %d did not convert to %s, it converted to %s",
                  i, tabLogLevel[i].str, ReturnLevelInt(i));
          exit(1);
        }
      j = ReturnLevelAscii(tabLogLevel[i].str);
      if (j != i)
        {
          LogTest("FAILURE: Log level %s did not convert to %d, it converted to %d",
                  tabLogLevel[i].str, i, j);
          exit(1);
        }
    }

  LogTest("------------------------------------------------------");

  log_snprintf(tempstr, sizeof(tempstr), "Test log_snprintf");
  LogTest("%s", tempstr);
  LogTest("\nTesting possible environment variable");
  LogTest("COMPONENT_MEMCORRUPT debug level is %s",
          ReturnLevelInt(LogComponents[COMPONENT_MEMCORRUPT].comp_log_level));
  LogFullDebug(COMPONENT_MEMCORRUPT,
               "This should appear if environment is set properly");

  LogTest("------------------------------------------------------");
  LogTest("Send some messages to various files");
  SetComponentLogFile(COMPONENT_DISPATCH, "STDERR");
  LogEvent(COMPONENT_DISPATCH, "This should go to stderr");
  SetComponentLogFile(COMPONENT_DISPATCH, "STDOUT");
  LogEvent(COMPONENT_DISPATCH, "This should go to stdout");
  SetComponentLogFile(COMPONENT_DISPATCH, "SYSLOG");
  LogEvent(COMPONENT_DISPATCH, "This should go to syslog (verf = %s)", str);
  LogTest("About to set %s", file);
  SetComponentLogFile(COMPONENT_DISPATCH, file);
  LogTest("Got it set");
  LogEvent(COMPONENT_DISPATCH, "This should go to %s", file);

  /*
   * Set up for tests that will verify what was actually produced by log messages.
   * This is used to test log levels and to test the log_vnsprintf function.
   */
  SetComponentLogBuffer(COMPONENT_MAIN, tempstr);
  SetComponentLogBuffer(COMPONENT_INIT, tempstr);

#ifdef _SNMP_ADM_ACTIVE
  {
    snmp_adm_type_union param;
    int rc;
    strcpy(param.string, "FAILED");

    LogTest("------------------------------------------------------");
    LogTest("Test SNMP functions");
    SetLevelDebug(NIV_DEBUG);

    rc = getComponentLogLevel(&param, (void *)COMPONENT_ALL);
    LogTest("getComponentLogLevel(&param, (void *)COMPONENT_ALL) rc=%d result=%s",
            rc, param.string);
    if (rc != 0)
    {
      LogTest("FAILURE");
      exit(1);
    }
    strcpy(param.string, "NIV_EVENT");
    rc = setComponentLogLevel(&param, (void *)COMPONENT_MAIN);
    LogTest("setComponentLogLevel(&param, (void *)COMPONENT_MAIN) rc=%d", rc);
    if (rc != 0)
    {
      LogTest("FAILURE");
      exit(1);
    }
    TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
    TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
    TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
    TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
    TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
    TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
    TestAlways    (TRUE,  tempstr, COMPONENT_INIT, "LogAlways (should print)");
    TestMajor     (TRUE,  tempstr, COMPONENT_INIT, "LogMajor (should print)");
    TestCrit      (TRUE,  tempstr, COMPONENT_INIT, "LogCrit (should print)");
    TestEvent     (TRUE,  tempstr, COMPONENT_INIT, "LogEvent (should print)");
    TestDebug     (TRUE,  tempstr, COMPONENT_INIT, "LogDebug (should print)");
    TestFullDebug (FALSE, tempstr, COMPONENT_INIT, "LogFullDebug (shouldn't print)");
  }
#endif /* _SNMP_ADM_ACTIVE */

  LogTest("------------------------------------------------------");
  LogTest("Test all levels of log filtering");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_NULL);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (FALSE, tempstr, COMPONENT_MAIN, "LogMajor (shouldn't print)");
  TestCrit      (FALSE, tempstr, COMPONENT_MAIN, "LogCrit (shouldn't print)");
  TestEvent     (FALSE, tempstr, COMPONENT_MAIN, "LogEvent (shouldn't print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_MAJOR);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (FALSE, tempstr, COMPONENT_MAIN, "LogCrit (shouldn't print)");
  TestEvent     (FALSE, tempstr, COMPONENT_MAIN, "LogEvent (shouldn't print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_CRIT);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (FALSE, tempstr, COMPONENT_MAIN, "LogEvent (shouldn't print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_EVENT);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_DEBUG);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
  TestDebug     (TRUE,  tempstr, COMPONENT_MAIN, "LogDebug (should print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_FULL_DEBUG);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
  TestDebug     (TRUE,  tempstr, COMPONENT_MAIN, "LogDebug (should print)");
  TestFullDebug (TRUE,  tempstr, COMPONENT_MAIN, "LogFullDebug (should print)");
}
Beispiel #12
0
int
asyncmeta_back_search( Operation *op, SlapReply *rs )
{
	a_metainfo_t	*mi = ( a_metainfo_t * )op->o_bd->be_private;
	struct timeval	save_tv = { 0, 0 },
			tv;
	time_t		stoptime = (time_t)(-1),
			lastres_time = slap_get_time(),
			timeout = 0;
	int		rc = 0, sres = LDAP_SUCCESS;
	char		*matched = NULL;
	int		last = 0, ncandidates = 0,
			initial_candidates = 0, candidate_match = 0,
			needbind = 0;
	ldap_back_send_t	sendok = LDAP_BACK_SENDERR;
	long		i,j;
	int		is_ok = 0;
	void		*savepriv;
	SlapReply	*candidates = NULL;
	int		do_taint = 0;
	bm_context_t *bc;
	a_metaconn_t *mc;
	slap_callback *cb = op->o_callback;

	rs_assert_ready( rs );
	rs->sr_flags &= ~REP_ENTRY_MASK; /* paranoia, we can set rs = non-entry */

	/*
	 * controls are set in ldap_back_dobind()
	 *
	 * FIXME: in case of values return filter, we might want
	 * to map attrs and maybe rewrite value
	 */

	asyncmeta_new_bm_context(op, rs, &bc, mi->mi_ntargets );
	if (bc == NULL) {
		rs->sr_err = LDAP_OTHER;
		send_ldap_result(op, rs);
		return rs->sr_err;
	}

	candidates = bc->candidates;
	mc = asyncmeta_getconn( op, rs, candidates, NULL, LDAP_BACK_DONTSEND, 0);
	if ( !mc || rs->sr_err != LDAP_SUCCESS) {
		op->o_callback = cb;
		send_ldap_result(op, rs);
		asyncmeta_clear_bm_context(bc);
		return rs->sr_err;
	}

	/*
	 * Inits searches
	 */

	for ( i = 0; i < mi->mi_ntargets; i++ ) {
		/* reset sr_msgid; it is used in most loops
		 * to check if that target is still to be considered */
		candidates[i].sr_msgid = META_MSGID_UNDEFINED;
		/* a target is marked as candidate by asyncmeta_getconn();
		 * if for any reason (an error, it's over or so) it is
		 * no longer active, sr_msgid is set to META_MSGID_IGNORE
		 * but it remains candidate, which means it has been active
		 * at some point during the operation.  This allows to
		 * use its response code and more to compute the final
		 * response */
		if ( !META_IS_CANDIDATE( &candidates[ i ] ) ) {
			continue;
		}

		candidates[ i ].sr_matched = NULL;
		candidates[ i ].sr_text = NULL;
		candidates[ i ].sr_ref = NULL;
		candidates[ i ].sr_ctrls = NULL;
		candidates[ i ].sr_nentries = 0;
		candidates[ i ].sr_type = -1;

		/* get largest timeout among candidates */
		if ( mi->mi_targets[ i ]->mt_timeout[ SLAP_OP_SEARCH ]
			&& mi->mi_targets[ i ]->mt_timeout[ SLAP_OP_SEARCH ] > timeout )
		{
			timeout = mi->mi_targets[ i ]->mt_timeout[ SLAP_OP_SEARCH ];
		}
	}

	bc->timeout = timeout;
	bc->stoptime = op->o_time + bc->timeout;

	if ( op->ors_tlimit != SLAP_NO_LIMIT ) {
		stoptime = op->o_time + op->ors_tlimit;
		if (stoptime < bc->stoptime) {
			bc->stoptime = stoptime;
			bc->searchtime = 1;
			bc->timeout = op->ors_tlimit;
		}
	}

	ldap_pvt_thread_mutex_lock( &mc->mc_om_mutex);
	rc = asyncmeta_add_message_queue(mc, bc);
	ldap_pvt_thread_mutex_unlock( &mc->mc_om_mutex);

	if (rc != LDAP_SUCCESS) {
		rs->sr_err = LDAP_BUSY;
		rs->sr_text = "Maximum pending ops limit exceeded";
		asyncmeta_clear_bm_context(bc);
		op->o_callback = cb;
		send_ldap_result(op, rs);
		goto finish;
	}

	for ( i = 0; i < mi->mi_ntargets; i++ ) {
		if ( !META_IS_CANDIDATE( &candidates[ i ] )
			|| candidates[ i ].sr_err != LDAP_SUCCESS )
		{
			continue;
		}

		rc = asyncmeta_dobind_init_with_retry(op, rs, bc, mc, i);
		switch (rc)
		{
		case META_SEARCH_CANDIDATE:
			/* target is already bound, just send the search request */
			ncandidates++;
			Debug( LDAP_DEBUG_TRACE, "%s asyncmeta_back_search: IS_CANDIDATE "
			       "cnd=\"%ld\"\n", op->o_log_prefix, i , 0);

			rc = asyncmeta_back_search_start( op, rs, mc, bc, i,  NULL, 0 );
			if (rc == META_SEARCH_ERR) {
				META_CANDIDATE_CLEAR(&candidates[i]);
				candidates[ i ].sr_msgid = META_MSGID_IGNORE;
				if ( META_BACK_ONERR_STOP( mi ) ) {
					asyncmeta_handle_onerr_stop(op,rs,mc,bc,i,cb);
					goto finish;
				}
				else {
					continue;
				}
			}
			break;
		case META_SEARCH_NOT_CANDIDATE:
			Debug( LDAP_DEBUG_TRACE, "%s asyncmeta_back_search: NOT_CANDIDATE "
			       "cnd=\"%ld\"\n", op->o_log_prefix, i , 0);
			candidates[ i ].sr_msgid = META_MSGID_IGNORE;
			break;

		case META_SEARCH_NEED_BIND:
		case META_SEARCH_CONNECTING:
			Debug( LDAP_DEBUG_TRACE, "%s asyncmeta_back_search: NEED_BIND "
			       "cnd=\"%ld\" %p\n", op->o_log_prefix, i , &mc->mc_conns[i]);
			ncandidates++;
			rc = asyncmeta_dobind_init(op, rs, bc, mc, i);
			if (rc == META_SEARCH_ERR) {
				candidates[ i ].sr_msgid = META_MSGID_IGNORE;
				if ( META_BACK_ONERR_STOP( mi ) ) {
					asyncmeta_handle_onerr_stop(op,rs,mc,bc,i,cb);
					goto finish;
				}
				else {
					continue;
				}
			}
			break;
		case META_SEARCH_BINDING:
			Debug( LDAP_DEBUG_TRACE, "%s asyncmeta_back_search: BINDING "
			       "cnd=\"%ld\" %p\n", op->o_log_prefix, i , &mc->mc_conns[i]);
			ncandidates++;
			/* Todo add the context to the message queue but do not send the request
			 the receiver must send this when we are done binding */
			/* question - how would do receiver know to which targets??? */
			break;

		case META_SEARCH_ERR:
			Debug( LDAP_DEBUG_TRACE, "%s asyncmeta_back_search: SEARCH_ERR "
			       "cnd=\"%ldd\"\n", op->o_log_prefix, i , 0);
			candidates[ i ].sr_msgid = META_MSGID_IGNORE;
			candidates[ i ].sr_type = REP_RESULT;

			if ( META_BACK_ONERR_STOP( mi ) ) {
				asyncmeta_handle_onerr_stop(op,rs,mc,bc,i,cb);
				goto finish;
			}
			else {
				continue;
			}
			break;

		default:
			assert( 0 );
			break;
		}
	}

	initial_candidates = ncandidates;

	if ( LogTest( LDAP_DEBUG_TRACE ) ) {
		char	cnd[ SLAP_TEXT_BUFLEN ];
		int	c;

		for ( c = 0; c < mi->mi_ntargets; c++ ) {
			if ( META_IS_CANDIDATE( &candidates[ c ] ) ) {
				cnd[ c ] = '*';
			} else {
				cnd[ c ] = ' ';
			}
		}
		cnd[ c ] = '\0';

		Debug( LDAP_DEBUG_TRACE, "%s asyncmeta_back_search: ncandidates=%d "
			"cnd=\"%s\"\n", op->o_log_prefix, ncandidates, cnd );
	}

	if ( initial_candidates == 0 ) {
		/* NOTE: here we are not sending any matchedDN;
		 * this is intended, because if the back-meta
		 * is serving this search request, but no valid
		 * candidate could be looked up, it means that
		 * there is a hole in the mapping of the targets
		 * and thus no knowledge of any remote superior
		 * is available */
		Debug( LDAP_DEBUG_ANY, "%s asyncmeta_back_search: "
			"base=\"%s\" scope=%d: "
			"no candidate could be selected\n",
			op->o_log_prefix, op->o_req_dn.bv_val,
			op->ors_scope );

		/* FIXME: we're sending the first error we encounter;
		 * maybe we should pick the worst... */
		rc = LDAP_NO_SUCH_OBJECT;
		for ( i = 0; i < mi->mi_ntargets; i++ ) {
			if ( META_IS_CANDIDATE( &candidates[ i ] )
				&& candidates[ i ].sr_err != LDAP_SUCCESS )
			{
				rc = candidates[ i ].sr_err;
				break;
			}
		}
		rs->sr_err = rc;
		ldap_pvt_thread_mutex_lock( &mc->mc_om_mutex);
		asyncmeta_drop_bc(mc, bc);
		ldap_pvt_thread_mutex_unlock( &mc->mc_om_mutex);
		op->o_callback = cb;
		send_ldap_result(op, rs);
		asyncmeta_clear_bm_context(bc);
		goto finish;
	}
	ldap_pvt_thread_mutex_lock( &mc->mc_om_mutex);
	asyncmeta_start_listeners(mc, candidates, bc);
	ldap_pvt_thread_mutex_unlock( &mc->mc_om_mutex);
finish:
	return rs->sr_err;
}
Beispiel #13
0
int main(int argc, char **argv)
{
	unsigned int i;
	struct timeval tv1, tv2, tv3, tvdiff;
	int count, rc;
	char *dir;
	handle_map_param_t param;
	time_t now;

	/* Init logging */
	SetNamePgm("test_handle_mapping");
	SetDefaultLogging("TEST");
	SetNameFunction("main");
	SetNameHost("localhost");
	InitLogging();

	if (argc != 3 || (count = atoi(argv[2])) == 0) {
		LogTest("usage: test_handle_mapping <db_dir> <db_count>");
		exit(1);
	}

	dir = argv[1];

	strcpy(param.databases_directory, dir);
	strcpy(param.temp_directory, "/tmp");
	param.database_count = count;
	param.hashtable_size = 27;
	param.nb_handles_prealloc = 1024;
	param.nb_db_op_prealloc = 1024;
	param.synchronous_insert = false;

	rc = HandleMap_Init(&param);

	LogTest("HandleMap_Init() = %d", rc);
	if (rc)
		exit(rc);

	gettimeofday(&tv1, NULL);

	/* Now insert a set of handles */

	now = time(NULL);

	for (i = 0; i < 10000; i++) {
		nfs23_map_handle_t nfs23_digest;
		fsal_handle_t handle;

		memset(&handle, i, sizeof(fsal_handle_t));
		nfs23_digest.object_id = 12345 + i;
		nfs23_digest.handle_hash = (1999 * i + now) % 479001599;

		rc = HandleMap_SetFH(&nfs23_digest, &handle);
		if (rc && (rc != HANDLEMAP_EXISTS))
			exit(rc);
	}

	gettimeofday(&tv2, NULL);

	timersub(&tv2, &tv1, &tvdiff);

	LogTest("%u threads inserted 10000 handles in %d.%06ds", count,
		(int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	/* Now get them ! */

	for (i = 0; i < 10000; i++) {
		nfs23_map_handle_t nfs23_digest;
		fsal_handle_t handle;

		nfs23_digest.object_id = 12345 + i;
		nfs23_digest.handle_hash = (1999 * i + now) % 479001599;

		rc = HandleMap_GetFH(&nfs23_digest, &handle);
		if (rc) {
			LogTest("Error %d retrieving handle !", rc);
			exit(rc);
		}

		rc = HandleMap_DelFH(&nfs23_digest);
		if (rc) {
			LogTest("Error %d deleting handle !", rc);
			exit(rc);
		}

	}

	gettimeofday(&tv3, NULL);

	timersub(&tv3, &tv2, &tvdiff);

	LogTest("Retrieved and deleted 10000 handles in %d.%06ds",
		(int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	rc = HandleMap_Flush();

	gettimeofday(&tv3, NULL);

	timersub(&tv3, &tv1, &tvdiff);
	LogTest("Total time with %u threads (including flush): %d.%06ds", count,
		(int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	exit(0);

}
void Test2()
{
  char tempstr[2048];
  int  n1, n2;

  /*
   * Set up for tests that will verify what was actually produced by log messages.
   * This is used to test log levels and to test the log_vnsprintf function.
   */
  SetComponentLogBuffer(COMPONENT_MAIN, tempstr);
  SetComponentLogBuffer(COMPONENT_INIT, tempstr);
  SetComponentLogLevel(COMPONENT_MAIN, NIV_EVENT);

  LogTest("------------------------------------------------------");
  LogTest("Test string/char formats");
  TestFormat("none");
  TestFormat("String: %s", "str");
  TestFormat("String: %12s", "str");
  TestFormat("String: %-12s", "str");
  TestFormat("String: %12s", "too long string");
  TestFormat("String: %-12s", "too long string");
  TestFormat("%c", (char) 65);
  // Not tested lc, ls, C, S

  LogTest("------------------------------------------------------");
  LogTest("Test integer formats");
  TestFormat("Integer: %d %d %i %i %u %s", 1, -1, 2, -2, 3, "extra");
  TestFormat("Octal and Hex: 0%o 0x%x 0x%X %s", 0123, 0xabcdef, 0xABCDEF, "extra");
  TestFormat("Field Length: %3d %s", 1, "extra");
  TestFormat("Variable Field Length: %*d %s", 5, 123, "extra");
  TestFormat("Alignment flags: %+d %+d %-5d %-5d %05d %05d % d % d %s", 2, -2, 333, -333, 444, -444, 5, -5, "extra");
  TestFormat("Two Flags: %-05d %-05d %0-5d %0-5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %+ d %+ d % +d % +d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %-+5d %-+5d %+-5d %+-5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %- 5d %- 5d % -5d % -5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: %+05d %+05d %0+5d %0+5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Two Flags: % 05d % 05d %0 5d %0 5d %s", 333, -333, 444, -444, "extra");
  TestFormat("Use of # Flag: %#x %#3x %#05x %#-5x %-#5x %0#5x", 1, 2, 3, 4, 5, 6);
  TestFormat("Many Flags: %#-0 +#-0 +#-0 +5d", 4);
  TestFormat("Special Flags (may not be supported) %'d %Id %s", 12345, 67, "extra");

  LogTest("------------------------------------------------------");
  LogTest("Test floating point formats");
  TestFormat("%e %E %e %E %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%f %F %f %F %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%g %G %g %G %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%a %A %a %A %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("%Le %LE %Le %LE %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%Lf %LF %Lf %LF %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%Lg %LG %Lg %LG %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%La %LA %La %LA %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%lle %llE %lle %llE %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%llf %llF %llf %llF %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%llg %llG %llg %llG %s", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("%lla %llA %lla %llA", (long double) 1.1, (long double) 1.1, (long double) 1.1E10, (long double) 1.1E10, "extra");
  TestFormat("Field Length: %8f %8.2f %8f %8.2f %s", 1.1, 1.1, 1.1E10, 1.1E3, "extra");
  TestFormat("Field Length: %08f %08.2f %08f %08.2f %s", 1.1, 1.1, 1.1E10, 1.1E3, "extra");
  TestFormat("Field Length: %-8f %-8.2f %-8f %-8.2f %s", 1.1, 1.1, 1.1E10, 1.1E3, "extra");
  TestFormat("Variable Field Length: %*.*f %*.2f %6.*f %s", 6, 2, 1.1, 6, 2.2, 2, 3.3, "extra");
  TestFormat("Negative:      %e %E %e %E %s    ", -1.1, -1.1, -1.1E10, -1.1E10, "extra");
  TestFormat("With '+' flag: %+e %+E %+e %+E %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("With ' ' flag: % e % E % e % E %s", 1.1, 1.1, 1.1E10, 1.1E10, "extra");
  TestFormat("With '#' flag: %#8.0e %8.0e %s", 1.0, 1.0, "extra");
  TestFormat("With '#' flag: %#g %g %#5g %#5g %5g %s", 1.0, 1.0, 2.0, 10.0, 2.0, "extra");

  LogTest("------------------------------------------------------");
  LogTest("Test some special formats");
  TestFormat("pointer: %p %s", &n1, "extra");
#if 0
// we can't support %n due to security considerations
  TestFormat("count: 12345678%n %s", &n1, "extra");
  snprintf(tempstr, 2048, "count: 12345678%n %s", &n1, "extra");
  log_snprintf(tempstr, 2048, "count: 12345678%n %s", &n2, "extra");
  if (n1 != n2)
    {
      LogTest("FAILURE: 12345678%%n produced %d expected %d", n2, n1);
      exit(1);
    }
  LogTest("SUCCESS: 12345678%%n produced %d", n2);
#endif
  errno = EIO;
  TestFormat("strerror: %m %64m %s", "extra");
  TestFormat("percent char: %% %s", "extra");

  LogTest("------------------------------------------------------");
  LogTest("Test integer size qualifier tags");
  TestFormat("%hhd %s", (char) 1, "extra");
  TestFormat("%hd %s", (short) 500, "extra");
  TestFormat("%lld %s", (long long) 12345678, "extra");
  TestFormat("%Ld %s", (long long) 12345678, "extra");
  TestFormat("%ld %s", (long) 12345, "extra");
  TestFormat("%qd %s", (long long) 12345678, "extra");
  TestFormat("%jd %s", (long long) 1, "extra");
  TestFormat("%td %s", (char *) &n1 - (char *) &n2, "extra");
  TestFormat("%zd %s", sizeof(int), "extra");

  /* 
   * Ganesha can't properly support the $ parameter index tag, so don't bother testing, even if it does work
   * when the indices are in ascending order.
  TestFormat("%1$08x", 6);
  TestFormat("%3$llx %2$d %1d", 1, 2, (long long)0x12345678);
   */

  LogTest("------------------------------------------------------");
  LogTest("Ganesha specific tags");
  LogTest("\nTest %%b, %%B, %%h, %%H, %%y, and %%Y. These are odd tags:");
  LogTest("   %%b, %%B, %%h, and %%H each consume int1, str2, str3 even if not all are printed");
  LogTest("   %%y and %%Y each consume int1, str2, str3, int4, str5, str6 even if not all are printed");
  LogTest("   An extra string parameter is printed to demonstrate how the parameters are consumed");
  TestGaneshaFormat(TRUE,  "str2(1) (not part of %b)", "%b %s", 1, "str2", "str3", "(not part of %b)");
  TestGaneshaFormat(TRUE,  "str2(1) : 'str3' (not part of %B)", "%B %s", 1, "str2", "str3", "(not part of %B)");
  TestGaneshaFormat(TRUE,  "str2(1) (not part of %h)", "%h %s", 1, "str2", "str3", "(not part of %h)");
  TestGaneshaFormat(TRUE,  "str2(1) : 'str3' (not part of %H)", "%H %s", 1, "str2", "str3", "(not part of %H)");
  TestGaneshaFormat(TRUE,  "str2 str5(4) (not part of %y)", "%y %s", 1, "str2", "str3", 4, "str5", "str6", "(not part of %y)");
  TestGaneshaFormat(TRUE,  "str2(1) : 'str3' -> str5(4) : 'str6' (not part of %Y)", "%Y %s", 1, "str2", "str3", 4, "str5", "str6", "(not part of %Y)");
  LogTest("\nTest new tags for reporting errno values");
  TestGaneshaFormat(TRUE,  "EINVAL(22)", "%w", EINVAL);
  TestGaneshaFormat(TRUE,  "EINVAL(22) : 'Invalid argument'", "%W", EINVAL);
  LogTest("\nTest context sensitive tags");
  LogTest("%%K, %%V, and %%v go together, defaulting to ERR_SYS");
  LogTest("%%J, %%R, and %%r go together, defaulting to ERR_POSIX");
  TestGaneshaFormat(TRUE,  "ERR_SIGACTION(5) : 'sigaction impossible' EINVAL(22) : 'Invalid argument'", "%K%V %K%V", ERR_SYS, ERR_SIGACTION, ERR_POSIX, EINVAL);
  TestGaneshaFormat(TRUE,  "ERR_SIGACTION(5) EINVAL(22)", "%K%v %K%v", ERR_SYS, ERR_SIGACTION, ERR_POSIX, EINVAL);
  TestGaneshaFormat(TRUE,  "ERR_SIGACTION(5) : 'sigaction impossible' EINVAL(22) : 'Invalid argument'", "%J%R %J%R", ERR_SYS, ERR_SIGACTION, ERR_POSIX, EINVAL);
  TestGaneshaFormat(TRUE,  "ERR_SIGACTION(5) EINVAL(22)", "%J%r %J%r", ERR_SYS, ERR_SIGACTION, ERR_POSIX, EINVAL);
  TestGaneshaFormat(TRUE,  "ERR_SIGACTION(5) : 'sigaction impossible' EINVAL(22) : 'Invalid argument'", "%V %R", ERR_SIGACTION, EINVAL);
  TestGaneshaFormat(TRUE,  "ERR_SIGACTION(5) EINVAL(22)", "%v %r", ERR_SIGACTION, EINVAL);
  LogTest("Ganesha expects it's tags to just be two characters, for example %%b");
  TestGaneshaFormat(FALSE, "str2(1) (not part of %b)", "%5b %s", 1, "str2", "str3", "(not part of %b)");
}
Beispiel #15
0
void usage()
{
  LogTest( "Usage :\n\ttest_fsal <no_test>");
  LogTest( "\ttests :");
  LogTest( "\t\t1 - getattrs");
  LogTest( "\t\t2 - lookup");
  LogTest( "\t\t3 - lookupPath");
  LogTest( "\t\t4 - readdir (acces par tableau)");
  LogTest( "\t\t5 - readdir (acces liste chainee)");
  LogTest( "\t\t6 - access/test_access");
  LogTest( "\t\t7 - snprintmem/sscanmem");
  LogTest( "\t\t8 - mkdir/rmdir");
  LogTest( "\t\t9 - setattr");
  LogTest( "\t\tA - digest/expend handle");
  LogTest( "\t\tB - dynamic fs info");
  return;
}
Beispiel #16
0
int main(int argc, char *argv[])
{
  SetDefaultLogging("TEST");
  SetNamePgm("test_lru");

  LRU_list_t *plru;
  LRU_parameter_t param;
  LRU_entry_t *entry = NULL;
  LRU_entry_t *kept_entry = NULL;
  LRU_status_t status = 0;
  int i = 0;
  char strtab[MAXTEST][10];

  param.nb_entry_prealloc = PREALLOC;
  param.entry_to_str = print_entry;
  param.clean_entry = clean_entry;
  param.lp_name = "Test";

  BuddyInit(NULL);

  if((plru = LRU_Init(param, &status)) == NULL)
    {
      LogTest("Test FAILED: Bad Init");
      exit(1);
    }

  for(i = 0; i < MAXTEST; i++)
    {
      LogTest("Added entry %d", i);
      sprintf(strtab[i], "%d", i);
      if((entry = LRU_new_entry(plru, &status)) == NULL)
        {

          LogTest("Test FAILED: bad entry add, status = %d", status);
          exit(1);
        }

      entry->buffdata.pdata = strtab[i];
      entry->buffdata.len = strlen(strtab[i]);

      if(i == KEPT_ENTRY)
        kept_entry = entry;
    }

  /* printing the table */
  LRU_Print(plru);

  LRU_invalidate(plru, kept_entry);

  if(isFullDebug(COMPONENT_LRU))
    LRU_Print(plru);

  if(LRU_gc_invalid(plru, NULL) != LRU_LIST_SUCCESS)
    {
      LogTest("Test FAILED: bad gc");
      exit(1);
    }
  LRU_Print(plru);

  /* Tous les tests sont ok */
  LogTest("\n-----------------------------------------");
  LogTest("Test succeeded: all tests pass successfully");

  exit(0);
}                               /* main */
Beispiel #17
0
int main(int argc, char **argv)
{

  char localmachine[256];
  char *test;
  fsal_parameter_t init_param;
  fsal_status_t st;
  uid_t uid;
  hpssfsal_export_context_t export_ctx;
  hpssfsal_op_context_t op_ctx;
  hpssfsal_handle_t root_handle, handle;
  fsal_name_t name;
  fsal_path_t path;
  fsal_attrib_list_t attribs;
  fsal_attrib_mask_t mask;

  char tracebuff[256];

  if(argc < 2)
    {
      usage();
      exit(-1);
    }
  test = argv[1];
  /* retrieving params */

  /* init debug */
  SetDefaultLogging("TEST");
  SetNamePgm("test_fsal");
  SetNameFunction("main");
  InitLogging();

  /* Obtention du nom de la machine */
  if(gethostname(localmachine, sizeof(localmachine)) != 0)
    {
      LogError(COMPONENT_STDOUT,ERR_SYS, ERR_GETHOSTNAME, errno);
      exit(1);
    }
  else
    SetNameHost(localmachine);

  AddFamilyError(ERR_FSAL, "FSAL related Errors", tab_errstatus_FSAL);

  /* prepare fsal_init */

  /* 1 - fs specific info */

#if HPSS_MAJOR_VERSION == 5

  init_param.fs_specific_info.behaviors.PrincipalName = FSAL_INIT_FORCE_VALUE;
  strcpy(init_param.fs_specific_info.hpss_config.PrincipalName, "hpss_nfs");

  init_param.fs_specific_info.behaviors.KeytabPath = FSAL_INIT_FORCE_VALUE;
  strcpy(init_param.fs_specific_info.hpss_config.KeytabPath, "/krb5/hpssserver.keytab");

#else
  init_param.fs_specific_info.behaviors.AuthnMech = FSAL_INIT_FORCE_VALUE;
  init_param.fs_specific_info.hpss_config.AuthnMech = hpss_authn_mech_krb5;

  init_param.fs_specific_info.behaviors.Principal = FSAL_INIT_FORCE_VALUE;
  strcpy(init_param.fs_specific_info.Principal, "hpssfs");

  init_param.fs_specific_info.behaviors.KeytabPath = FSAL_INIT_FORCE_VALUE;
  strcpy(init_param.fs_specific_info.KeytabPath, "/var/hpss/etc/hpss.keytab");

#endif

  /* 2-common info (default) */
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxfilesize);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxlink);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxnamelen);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxpathlen);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, no_trunc);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, chown_restricted);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, case_insensitive);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, case_preserving);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, fh_expire_type);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, link_support);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, symlink_support);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, named_attr);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, unique_handles);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, lease_time);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, acl_support);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, cansettime);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, homogenous);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, supported_attrs);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxread);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxwrite);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, umask);
  FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, auth_exportpath_xdev);

  /* 3- fsal info */
  init_param.fsal_info.max_fs_calls = 0;

  /* Init */
  if(FSAL_IS_ERROR(st = FSAL_Init(&init_param)))
    {
      LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
    }

  /* getting creds */
  uid = getuid();
  LogTest("uid = %d", uid);

  st = FSAL_BuildExportContext(&export_ctx, NULL, NULL);
  if(FSAL_IS_ERROR(st))
    LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);

  st = FSAL_InitClientContext(&op_ctx);

  if(FSAL_IS_ERROR(st))
    LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);

  st = FSAL_GetClientContext(&op_ctx, &export_ctx, uid, -1, NULL, 0);

  if(FSAL_IS_ERROR(st))
    LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);

  /* getting root handle */

  if(FSAL_IS_ERROR(st = FSAL_lookup(NULL, NULL, &op_ctx, &root_handle, NULL)))
    {
      LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
    }

  snprintHandle(tracebuff, 256, &root_handle);
  LogTest("Root handle = %s", tracebuff);

  /* getting what are the supported attributes */

  attribs.asked_attributes = 0;
  FSAL_SET_MASK(attribs.asked_attributes, FSAL_ATTR_SUPPATTR);
  LogTest("asked attributes :");
  printmask(attribs.asked_attributes);

  if(FSAL_IS_ERROR(st = FSAL_getattrs(&root_handle, &op_ctx, &attribs)))
    {
      LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
    }

  LogTest("supported attributes :");
  printmask(attribs.supported_attributes);

  mask = attribs.supported_attributes;

/* TEST 1 */

  if(test[0] == '1')
    {

      attribs.asked_attributes = 0;
      FSAL_SET_MASK(attribs.asked_attributes, FSAL_ATTR_SUPPATTR);
      LogTest("asked attributes :");
      printmask(attribs.asked_attributes);

      if(FSAL_IS_ERROR(st = FSAL_getattrs(&root_handle, &op_ctx, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      LogTest("supported attributes :");

      /* getting all spported attributes of root */
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_getattrs(&root_handle, &op_ctx, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      printattributes(attribs);

    }
  else
/* TEST 2 */
  if(test[0] == '2')
    {

      /* getting handle and attributes for subdirectory "OSF1_V5" */
      if(FSAL_IS_ERROR(st = FSAL_str2name("cea", 4, &name)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookup(&root_handle, &name, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea handle = %s", tracebuff);

      /* displaying attributes */
      printattributes(attribs);

      /* getting handle and attributes for subdirectory "bin" */
      if(FSAL_IS_ERROR(st = FSAL_str2name("prot", 5, &name)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      root_handle = handle;
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookup(&root_handle, &name, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea/prot handle = %s", tracebuff);

      /* displaying attributes */
      printattributes(attribs);

      /* getting handle and attributes for symlink "AglaePwrSW" */
      if(FSAL_IS_ERROR(st = FSAL_str2name("lama", 5, &name)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      root_handle = handle;
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookup(&root_handle, &name, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea/prot/lama handle = %s", tracebuff);

      /* displaying attributes */
      printattributes(attribs);

    }
  else
/* TEST 3 */
  if(test[0] == '3')
    {

      /* lookup root */
      if(FSAL_IS_ERROR(st = FSAL_str2path("/", 30, &path)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookupPath(&path, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/ handle = %s", tracebuff);

      /* displaying attributes */
      printattributes(attribs);

      /* lookup path */
      if(FSAL_IS_ERROR(st = FSAL_str2path("/cea/prot/lama", 15, &path)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookupPath(&path, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea/prot/lama handle = %s", tracebuff);

      /* displaying attributes */
      printattributes(attribs);

    }
  else
/* TEST 4 */
  if(test[0] == '4')
    {

      /* readdir on root */
      hpssfsal_dir_t dir;
      hpssfsal_cookie_t from, to;
      fsal_dirent_t entries[READDIR_SIZE];
      fsal_count_t number;
      fsal_boolean_t eod = FALSE;
      int error = FALSE;

      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_opendir(&root_handle, &op_ctx, &dir, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      LogTest("'/' attributes :");

      /* displaying attributes */
      printattributes(attribs);

      from = FSAL_READDIR_FROM_BEGINNING;

      while(!error && !eod)
        {
          unsigned int i;
          char cookiebuff[256];

          snprintCookie(cookiebuff, 256, &from);
          LogTest("\nReaddir cookie = %s", cookiebuff);
          if(FSAL_IS_ERROR(st = FSAL_readdir(&dir, from,
                                             mask, READDIR_SIZE * sizeof(fsal_dirent_t),
                                             entries, &to, &number, &eod)))
            {
              LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
              error = TRUE;
            }

          for(i = 0; (!error) && (i < number); i++)
            {

              snprintHandle(tracebuff, 256, &entries[i].handle);

              snprintCookie(cookiebuff, 256, &entries[i].cookie);

              LogTest("\t%s : %s (cookie %s)", tracebuff,
                     entries[i].name.name, cookiebuff);
            }
          /* preparing next call */
          from = to;

        }
      LogTest("Fin de boucle : error=%d ; eod=%d", error, eod);

    }
  else
/* TEST 5 */
  if(test[0] == '5')
    {

      /* readdir on root */
      hpssfsal_dir_t dir;
      hpssfsal_cookie_t from, to;
      fsal_dirent_t entries[READDIR_SIZE];
      fsal_count_t number;
      fsal_boolean_t eod = FALSE;
      int error = FALSE;

      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_opendir(&root_handle, &op_ctx, &dir, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      LogTest("'/' attributes :");

      /* displaying attributes */
      printattributes(attribs);

      from = FSAL_READDIR_FROM_BEGINNING;

      while(!error && !eod)
        {
          fsal_dirent_t *curr;

          char cookiebuff[256];

          snprintCookie(cookiebuff, 256, &from);

          LogTest("\nReaddir cookie = %s", cookiebuff);

          if(FSAL_IS_ERROR(st = FSAL_readdir(&dir, from,
                                             mask, READDIR_SIZE * sizeof(fsal_dirent_t),
                                             entries, &to, &number, &eod)))
            {
              LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
              error = TRUE;
            }

          if(number > 0)
            {
              curr = entries;
              do
                {

                  snprintHandle(tracebuff, 256, &curr->handle);
                  snprintCookie(cookiebuff, 256, &curr->cookie);

                  LogTest("\t%s : %s (cookie %s)", tracebuff,
                         curr->name.name, cookiebuff);
                }
              while(curr = curr->nextentry);
            }
          /* preparing next call */
          from = to;

        }
      LogTest("Fin de boucle : error=%d ; eod=%d", error, eod);

    }
  else
/* TEST 6 */
  if(test[0] == '6')
    {

      /* readdir on root */
      hpssfsal_dir_t dir;
      hpssfsal_cookie_t from, to;
      fsal_dirent_t entries[READDIR_SIZE];
      fsal_count_t number;
      fsal_boolean_t eod = FALSE;
      int error = FALSE;

      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_opendir(&root_handle, &op_ctx, &dir, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      LogTest("'/' attributes :");

      /* displaying attributes */
      printattributes(attribs);

      from = FSAL_READDIR_FROM_BEGINNING;

      while(!error && !eod)
        {
          unsigned int i;

          snprintCookie(tracebuff, 256, &from);
          LogTest("\nReaddir cookie = %s", tracebuff);

          st = FSAL_readdir(&dir, from, mask,
                            READDIR_SIZE * sizeof(fsal_dirent_t),
                            entries, &to, &number, &eod);

          if(FSAL_IS_ERROR(st))
            {
              LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
              error = TRUE;
            }

          /* for each entry, we compare the result of FSAL_access
           * to FSAL_test_access. */
          for(i = 0; (!error) && (i < number); i++)
            {

              fsal_status_t st1, st2;
              char cookiebuff[256];

              snprintHandle(tracebuff, 256, &entries[i].handle);
              snprintCookie(cookiebuff, 256, &entries[i].cookie);

              LogTest("\t%s : %s (cookie %s)", tracebuff,
                     entries[i].name.name, cookiebuff);

              if(FSAL_IS_ERROR(st = FSAL_getattrs(&entries[i].handle, &op_ctx, &attribs)))
                {
                  LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
                }

              /* 1 - test R access */

              st1 = FSAL_access(&entries[i].handle, &op_ctx, FSAL_R_OK, NULL);

              st2 = FSAL_test_access(&op_ctx, FSAL_R_OK, &attribs);

              LogError(COMPONENT_STDOUT, ERR_FSAL, st1.major, st1.minor);
              LogError(COMPONENT_STDOUT, ERR_FSAL, st2.major, st2.minor);

              if(st1.major != st2.major)
                {
                  LogTest(
                      "Error : different access permissions given by FSAL_access and FSAL_test_access : %d <>%d",
                       st1.major, st2.major);
                }

              /* 2 - test W access */

              st1 = FSAL_access(&entries[i].handle, &op_ctx, FSAL_W_OK, NULL);

              st2 = FSAL_test_access(&op_ctx, FSAL_W_OK, &attribs);

              LogError(COMPONENT_STDOUT, ERR_FSAL, st1.major, st1.minor);
              LogError(COMPONENT_STDOUT, ERR_FSAL, st2.major, st2.minor);

              if(st1.major != st2.major)
                {
                  LogTest(
                      "Error : different access permissions given by FSAL_access and FSAL_test_access : %d <>%d",
                       st1.major, st2.major);
                }

              /* 3 - test X access */

              st1 = FSAL_access(&entries[i].handle, &op_ctx, FSAL_X_OK, NULL);

              st2 = FSAL_test_access(&op_ctx, FSAL_X_OK, &attribs);

              LogError(COMPONENT_STDOUT, ERR_FSAL, st1.major, st1.minor);
              LogError(COMPONENT_STDOUT, ERR_FSAL, st2.major, st2.minor);

              if(st1.major != st2.major)
                {
                  LogTest(
                      "Error : different access permissions given by FSAL_access and FSAL_test_access : %d <>%d",
                       st1.major, st2.major);
                }

            }

          /* preparing next call */
          from = to;

        }
      LogTest("Fin de boucle : error=%d ; eod=%d", error, eod);

    }
  else
/* TEST 7 */
  if(test[0] == '7')
    {

      /* test snprintmem and sscanmem */
      char test_string[] =
          "Ceci est une chaine d'essai.\nLes chiffres : 0123456789\nLes lettres : ABCDEFGHIJKLMNOPQRSTUVWXYZ";

      char buffer[256];
      char string[200];         /* 200 suffit car test_string fait <100 */

      int size1, size2, size3, i;

      /* we put bad values in string, to see if it is correctly set. */
      for(i = 0; i < 200; i++)
        string[i] = (char)i;

      LogTest("Initial data (%d Bytes) = <<%s>>", strlen(test_string), test_string);

      /* Write test_string to a buffer. */
      /* We don't give the final '\0'.  */
      snprintmem(buffer, 256, test_string, strlen(test_string));

      LogTest("Dest_Buffer (%d Bytes) = <<%s>>", strlen(buffer), buffer);

      /* read the value from the buffer */
      sscanmem(string, strlen(test_string), buffer);

      /* sets the final 0 to print the content of the buffer */
      LogTest("Retrieved string : following byte = %d",
             (int)string[strlen(test_string)]);
      string[strlen(test_string)] = '\0';

      LogTest("Retrieved string (%d Bytes) = <<%s>>", strlen(string), string);

      /* Automatic tests : */
      size1 = strlen(test_string);
      size2 = strlen(buffer);
      size3 = strlen(string);

      LogTest("-------------------------------------");

      if(size1 <= 0)
        LogTest("***** ERROR: source size=0 !!!");

      if(size1 != size3)
        LogTest("***** ERROR: source size <> target size");
      else
        LogTest("OK: source size = target size");

      if((size1 * 2) != size2)
        LogTest("***** ERROR: hexa size <> 2 * source size");
      else
        LogTest("OK: hexa size = 2 * source size");

      if(strcmp(test_string, string))
        LogTest("***** ERROR: source string <> target string");
      else
        LogTest("OK: source string = target string");

    }
  else
/* TEST 8 */
  if(test[0] == '8')
    {

      hpssfsal_handle_t dir_hdl, subdir_hdl;
      fsal_name_t subdir_name;

      /* lookup on /cea/prot/S/lama/s8/leibovic */

      if(FSAL_IS_ERROR(st = FSAL_str2path("/cea/prot/S/lama/s8/leibovic", 40, &path)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookupPath(&path, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea/prot/S/lama/s8/leibovic: handle = %s", tracebuff);

      sleep(1);

      /* creates a directory */
      LogTest("------- Create a directory -------");

      if(FSAL_IS_ERROR(st = FSAL_str2name("tests_GANESHA", 30, &name)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      attribs.asked_attributes = mask;

      if(FSAL_IS_ERROR(st = FSAL_mkdir(&handle, &name, &op_ctx,
                                       FSAL_MODE_RUSR | FSAL_MODE_WUSR
                                       | FSAL_MODE_XUSR | FSAL_MODE_RGRP
                                       | FSAL_MODE_WGRP, &dir_hdl, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          snprintHandle(tracebuff, 256, &dir_hdl);
          LogTest("newly created dir handle = %s", tracebuff);

          printattributes(attribs);

        }

      sleep(1);

      /* Try to create it again */
      LogTest("------- Try to create it again -------");

      if(FSAL_IS_ERROR(st = FSAL_mkdir(&handle, &name, &op_ctx,
                                       FSAL_MODE_RUSR | FSAL_MODE_WUSR
                                       | FSAL_MODE_XUSR | FSAL_MODE_RGRP
                                       | FSAL_MODE_WGRP, &dir_hdl, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          LogTest("**** Error: FSAL should have returned ERR_FSAL_EXIST");

        }

      sleep(1);

      /* creates a subdirectory */
      LogTest("------- Create a subdirectory -------");

      if(FSAL_IS_ERROR(st = FSAL_str2name("subdir_GANESHA", 30, &subdir_name)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      if(FSAL_IS_ERROR(st = FSAL_mkdir(&dir_hdl, &subdir_name, &op_ctx,
                                       FSAL_MODE_RUSR | FSAL_MODE_WUSR
                                       | FSAL_MODE_XUSR | FSAL_MODE_RGRP
                                       | FSAL_MODE_WGRP, &subdir_hdl, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          snprintHandle(tracebuff, 256, &subdir_hdl);
          LogTest("newly created subdir handle = %s", tracebuff);

          printattributes(attribs);

        }

      /* try to removes the parent directory */
      LogTest("------- Try to removes the parent directory -------");

      if(FSAL_IS_ERROR(st = FSAL_unlink(&handle, &name, &op_ctx, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          LogTest("FSAL should not have unlinked %s because it is not empty", name.name);

        }

      sleep(1);

      /* removes the subdirectory */
      LogTest("------- Removes the subdirectory -------");

      if(FSAL_IS_ERROR(st = FSAL_unlink(&dir_hdl, &subdir_name, &op_ctx, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          LogTest("New attributes for parent directory:");
          printattributes(attribs);

        }

      /* removes the parent directory */
      LogTest("------- Removes the parent directory -------");

      if(FSAL_IS_ERROR(st = FSAL_unlink(&handle, &name, &op_ctx, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          LogTest("Unlink %s OK", name.name);

        }

    }
/* TEST 9 */
  else if(test[0] == '9')
    {

      hpssfsal_handle_t dir_hdl, subdir_hdl;
      fsal_name_t subdir_name;
      fsal_attrib_list_t attr_set;

      fsal_fsid_t set_fsid = { 1LL, 2LL };

#ifdef _LINUX
      struct tm jour_heure = { 56, 34, 12, 31, 12, 110, 0, 0, 0, 0, 0 };
#else
      struct tm jour_heure = { 56, 34, 12, 31, 12, 110, 0, 0, 0 };
#endif

      /* lookup on /cea/prot/S/lama/s8/leibovic */

      if(FSAL_IS_ERROR(st = FSAL_str2path("/cea/prot/S/lama/s8/leibovic", 40, &path)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookupPath(&path, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea/prot/S/lama/s8/leibovic: handle = %s", tracebuff);

      sleep(1);

      /* creates a file */
      LogTest("------- Create a file -------");

      if(FSAL_IS_ERROR(st = FSAL_str2name("tests_GANESHA_setattrs", 30, &name)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      attribs.asked_attributes = mask;

      if(FSAL_IS_ERROR(st = FSAL_create(&handle, &name, &op_ctx,
                                        FSAL_MODE_RUSR | FSAL_MODE_WUSR
                                        | FSAL_MODE_XUSR | FSAL_MODE_RGRP
                                        | FSAL_MODE_WGRP, &dir_hdl, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          snprintHandle(tracebuff, 256, &dir_hdl);
          LogTest("newly created file handle = %s", tracebuff);

          printattributes(attribs);

        }

      sleep(1);

      LogTest("------- Try to change its attributes -------");

      /* Macro that try to change the value for an attribute */

#define CHANGE_ATTRS( str_nom, nom, flag, new_val ) do {\
  memset(&attr_set, 0, sizeof(fsal_attrib_list_t) );    \
  LogTest("\nTry to change '%s' :",str_nom);           \
  FSAL_SET_MASK( attr_set.asked_attributes , flag );    \
  attr_set.nom = new_val;                               \
  attribs.asked_attributes = attr_set.asked_attributes; \
/*  attribs.asked_attributes = mask;                      */\
  st = FSAL_setattrs( &dir_hdl, &op_ctx, &attr_set, &attribs );\
  if ( FSAL_IS_ERROR(st) )                              \
    LogError(COMPONENT_STDOUT,ERR_FSAL,st.major,st.minor);\
  else                                                  \
    printattributes( attribs );                         \
  } while(0)

      CHANGE_ATTRS("supported_attributes", supported_attributes,
                   FSAL_ATTR_SUPPATTR, FSAL_ATTRS_MANDATORY);

      CHANGE_ATTRS("type", type, FSAL_ATTR_TYPE, FSAL_TYPE_LNK);

      sleep(1);                 /* to see mtime modification by truncate */

      CHANGE_ATTRS("filesize", filesize, FSAL_ATTR_SIZE, (fsal_size_t) 12);

      sleep(1);                 /* to see mtime modification by truncate */

      CHANGE_ATTRS("fsid", fsid, FSAL_ATTR_FSID, set_fsid);

      /* @todo : ACLs */

      CHANGE_ATTRS("fileid", fileid, FSAL_ATTR_FILEID, (fsal_u64_t) 1234);

      CHANGE_ATTRS("mode", mode, FSAL_ATTR_MODE,
                   (FSAL_MODE_RUSR | FSAL_MODE_WUSR | FSAL_MODE_RGRP));

      CHANGE_ATTRS("numlinks", numlinks, FSAL_ATTR_NUMLINKS, 7);

      /* FSAL_ATTR_RAWDEV */

      CHANGE_ATTRS("atime", atime.seconds, FSAL_ATTR_ATIME, mktime(&jour_heure));

      jour_heure.tm_min++;

      CHANGE_ATTRS("creation", creation.seconds, FSAL_ATTR_CREATION, mktime(&jour_heure));

      jour_heure.tm_min++;

      CHANGE_ATTRS("mtime", mtime.seconds, FSAL_ATTR_MTIME, mktime(&jour_heure));

      jour_heure.tm_min++;

      CHANGE_ATTRS("ctime", ctime.seconds, FSAL_ATTR_CTIME, mktime(&jour_heure));

      CHANGE_ATTRS("spaceused", spaceused, FSAL_ATTR_SPACEUSED, (fsal_size_t) 12345);

      CHANGE_ATTRS("mounted_on_fileid", mounted_on_fileid,
                   FSAL_ATTR_MOUNTFILEID, (fsal_u64_t) 3210);

      CHANGE_ATTRS("owner", owner, FSAL_ATTR_OWNER, 3051);      /* deniel */

      CHANGE_ATTRS("group", group, FSAL_ATTR_GROUP, 5953);      /* sr */

      sleep(1);

      /* removes the parent directory */
      LogTest("------- Removes the directory -------");

      if(FSAL_IS_ERROR(st = FSAL_unlink(&handle, &name, &op_ctx, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {

          LogTest("Unlink %s OK", name.name);

        }

    }
  else if(test[0] == 'A')
    {

      char digest_buff[FSAL_DIGEST_SIZE_HDLV3];

      /* lookup on /cea/prot/S/lama/s8/leibovic */

      if(FSAL_IS_ERROR(st = FSAL_str2path("/cea/prot/S/lama/s8/leibovic", 40, &path)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      attribs.asked_attributes = mask;
      if(FSAL_IS_ERROR(st = FSAL_lookupPath(&path, &op_ctx, &handle, &attribs)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }

      snprintHandle(tracebuff, 256, &handle);
      LogTest("/cea/prot/S/lama/s8/leibovic: handle = %s", tracebuff);

      /* building digest */

      st = FSAL_DigestHandle(&export_ctx, FSAL_DIGEST_NFSV3, &handle, digest_buff);

      if(FSAL_IS_ERROR(st))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {
          /* print digest */
          snprintmem(tracebuff, 256, digest_buff, FSAL_DIGEST_SIZE_HDLV3);
          LogTest("/cea/prot/S/lama/s8/leibovic: handle_digest = %s", tracebuff);
        }

      memset(&handle, 0, sizeof(hpssfsal_handle_t));

      /* expend digest */

      st = FSAL_ExpandHandle(&export_ctx, FSAL_DIGEST_NFSV3, digest_buff, &handle);

      if(FSAL_IS_ERROR(st))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
        }
      else
        {
          /* print expended handle */
          snprintHandle(tracebuff, 256, &handle);
          LogTest("/cea/prot/S/lama/s8/leibovic: handle expended = %s", tracebuff);
        }

    }
  else if(test[0] == 'B')
    {

      fsal_dynamicfsinfo_t dyninfo;

      if(FSAL_IS_ERROR(st = FSAL_dynamic_fsinfo(&root_handle, &op_ctx, &dyninfo)))
        {
          LogError(COMPONENT_STDOUT, ERR_FSAL, st.major, st.minor);
          exit(st.major);
        }

      LogTest("total_bytes = %llu", dyninfo.total_bytes);
      LogTest("free_bytes = %llu", dyninfo.free_bytes);
      LogTest("avail_bytes = %llu", dyninfo.avail_bytes);
      LogTest("total_files = %llu", dyninfo.total_files);
      LogTest("free_files = %llu", dyninfo.free_files);
      LogTest("avail_files = %llu", dyninfo.avail_files);
      LogTest("time_delta = %u.%u", dyninfo.time_delta.seconds,
             dyninfo.time_delta.nseconds);

    }
  else
    LogTest("%s : test inconnu", test);

  return 0;

}
int main(int argc, char **argv)
{
	unsigned int i;
	struct timeval tv1, tv2, tv3, tvdiff;
	int count, rc;
	char *dir;
	time_t now;

	if (argc != 3) {
		LogTest("usage: test_handle_mapping_db <db_dir> <db_count>");
		exit(1);
	}

	count = atoi(argv[2])
	if (count == 0) {
		LogTest("usage: test_handle_mapping_db <db_dir> <db_count>");
		exit(1);
	}

	dir = argv[1];

	/* Init logging */
	SetNamePgm("test_handle_mapping");
	SetNameFileLog("/dev/tty");
	SetNameFunction("main");
	SetNameHost("localhost");

	/* count databases */

	rc = handlemap_db_count(dir);

	LogTest("handlemap_db_count(%s)=%d", dir, rc);

	if (rc != 0 && count != rc) {
		LogTest(
			"Warning: incompatible thread count %d <> database count %d",
			count, rc);
	}

	rc = handlemap_db_init(dir, "/tmp", count, 1024, false);

	LogTest("handlemap_db_init() = %d", rc);
	if (rc)
		exit(rc);

	rc = handlemap_db_reaload_all(NULL);

	LogTest("handlemap_db_reaload_all() = %d", rc);
	if (rc)
		exit(rc);

	gettimeofday(&tv1, NULL);

	/* Now insert a set of handles */

	now = time(NULL);

	for (i = 0; i < 10000; i++) {
		nfs23_map_handle_t nfs23_digest;
		fsal_handle_t handle;

		memset(&handle, i, sizeof(fsal_handle_t));
		nfs23_digest.object_id = 12345 + i;
		nfs23_digest.handle_hash = (1999 * i + now) % 479001599;

		rc = handlemap_db_insert(&nfs23_digest, &handle);
		if (rc)
			exit(rc);
	}

	gettimeofday(&tv2, NULL);

	timersub(&tv2, &tv1, &tvdiff);

	LogTest("%u threads inserted 10000 handles in %d.%06ds", count,
		(int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	rc = handlemap_db_flush();

	gettimeofday(&tv3, NULL);

	timersub(&tv3, &tv1, &tvdiff);
	LogTest("Total time with %u threads (including flush): %d.%06ds", count,
		(int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	LogTest("Now, delete operations");

	for (i = 0; i < 10000; i++) {
		nfs23_map_handle_t nfs23_digest;

		nfs23_digest.object_id = 12345 + i;
		nfs23_digest.handle_hash = (1999 * i + now) % 479001599;

		rc = handlemap_db_delete(&nfs23_digest);
		if (rc)
			exit(rc);
	}

	gettimeofday(&tv2, NULL);
	timersub(&tv2, &tv3, &tvdiff);

	LogTest("%u threads deleted 10000 handles in %d.%06ds", count,
		(int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	rc = handlemap_db_flush();

	gettimeofday(&tv1, NULL);
	timersub(&tv1, &tv3, &tvdiff);
	LogTest("Delete time with %u threads (including flush): %d.%06ds",
		count, (int)tvdiff.tv_sec, (int)tvdiff.tv_usec);

	exit(0);

}
Beispiel #19
0
void printattributes(fsal_attrib_list_t attrs)
{

  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_RDATTR_ERR))
    LogTest("FSAL_ATTR_RDATTR_ERR");

  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_TYPE))
    LogTest("Type : %s", strtype(attrs.type));
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_SIZE))
    LogTest("Size : %llu", attrs.filesize);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_FSID))
    LogTest("fsId : %llu.%llu", attrs.fsid.major, attrs.fsid.minor);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_ACL))
    LogTest("ACL List ...");
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_FILEID))
    LogTest("FileId : %llu", attrs.fileid);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_MODE))
    LogTest("Mode : %#o", attrs.mode);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_NUMLINKS))
    LogTest("Numlinks : %u", (unsigned int)attrs.numlinks);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_OWNER))
    LogTest("uid : %d", attrs.owner);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_GROUP))
    LogTest("gid : %d", attrs.group);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_RAWDEV))
    LogTest("Rawdev ...");
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_ATIME))
    LogTest("atime : %s", ctime((time_t *) & attrs.atime.seconds));
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_CREATION))
    LogTest("creation time : %s", ctime((time_t *) & attrs.creation.seconds));
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_CTIME))
    LogTest("ctime : %s", ctime((time_t *) & attrs.ctime.seconds));
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_MTIME))
    LogTest("mtime : %s", ctime((time_t *) & attrs.mtime.seconds));
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_CHGTIME))
    LogTest("chgtime : %s", ctime((time_t *) & attrs.chgtime.seconds));
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_SPACEUSED))
    LogTest("spaceused : %llu", attrs.spaceused);
  if(FSAL_TEST_MASK(attrs.asked_attributes, FSAL_ATTR_MOUNTFILEID))
    LogTest("mounted_on_fileid : %llu", attrs.mounted_on_fileid);

}
int main(int argc, char *argv[])
{
  SetDefaultLogging("TEST");
  SetNamePgm("test_libcmc_bugdelete");
  LogTest("Initialized test program");
  
  hash_table_t *ht = NULL;
  hash_parameter_t hparam;
  hash_buffer_t buffval;
  hash_buffer_t buffkey;
  hash_buffer_t buffval2;
  hash_buffer_t buffkey2;
  hash_stat_t statistiques;
  int i;
  int rc;
  struct Temps debut, fin;
  char tmpstr[10];
  char strtab[MAXTEST][10];
  int critere_recherche = 0;
  int random_val = 0;

  hparam.index_size = PRIME;
  hparam.alphabet_length = 10;
  hparam.nb_node_prealloc = NB_PREALLOC;
  hparam.hash_func_key = simple_hash_func;
  hparam.hash_func_rbt = rbt_hash_func;
  hparam.hash_func_both = NULL ; /* BUGAZOMEU */
  hparam.compare_key = compare_string_buffer;
  hparam.key_to_str = display_buff;
  hparam.val_to_str = display_buff;

  BuddyInit(NULL);

  /* Init de la table */
  if((ht = HashTable_Init(hparam)) == NULL)
    {
      LogTest("Test FAILED: Bad init");
      exit(1);
    }

  MesureTemps(&debut, NULL);
  LogTest("Created hash table");

  for(i = 0; i < MAXTEST; i++)
    {
      sprintf(strtab[i], "%d", i);

      buffkey.len = strlen(strtab[i]);
      buffkey.pdata = strtab[i];

      buffval.len = strlen(strtab[i]);
      buffval.pdata = strtab[i];

      rc = HashTable_Set(ht, &buffkey, &buffval);
      LogFullDebug(COMPONENT_HASHTABLE,
                   "Added %s , %d , return code = %d", strtab[i], i, rc);
    }

  MesureTemps(&fin, &debut);
  LogTest("Time to insert %d entries: %s", MAXTEST,
         ConvertiTempsChaine(fin, NULL));

  LogFullDebug(COMPONENT_HASHTABLE,
               "-----------------------------------------");
  HashTable_Log(COMPONENT_HASHTABLE, ht);
  LogFullDebug(COMPONENT_HASHTABLE,
               "=========================================");

  /* Premier test simple: verif de la coherence des valeurs lues */
  critere_recherche = CRITERE;

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  MesureTemps(&debut, NULL);
  rc = HashTable_Get(ht, &buffkey, &buffval);
  MesureTemps(&fin, &debut);

  LogTest("Now, I try to retrieve %d entries (taken at random, almost)",
          MAXGET);

  MesureTemps(&debut, NULL);
  for(i = 0; i < MAXGET; i++)
    {
      random_val = random() % MAXTEST;
      sprintf(tmpstr, "%d", random_val);
      buffkey2.len = strlen(tmpstr);
      buffkey2.pdata = tmpstr;

      rc = HashTable_Get(ht, &buffkey2, &buffval2);
      LogTest("\tPlaying key = %s  --> %s", buffkey2.pdata, buffval2.pdata);
      if(rc != HASHTABLE_SUCCESS)
        {
          LogTest("Error reading %d = %d", i, rc);
          LogTest("Test FAILED: the reading is incorrect");
          exit(1);
        }
    }
  MesureTemps(&fin, &debut);
  LogTest("Time to read elements %d = %s", MAXGET,
         ConvertiTempsChaine(fin, NULL));

  LogTest("-----------------------------------------");

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  sprintf(tmpstr, "%d", critere_recherche);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;

  srandom(getpid());

  MesureTemps(&debut, NULL);
  for(i = 0; i < MAXDESTROY; i++)
    {
      random_val = bugdelete_key_array[i];
      sprintf(tmpstr, "%d", random_val);

      buffkey.len = strlen(tmpstr);
      buffkey.pdata = tmpstr;
      LogFullDebug(COMPONENT_HASHTABLE, "\t Erase %u -> %lu | %lu",
                   random_val,
                   simple_hash_func(&hparam, &buffkey),
                   rbt_hash_func(&hparam, &buffkey));

      rc = HashTable_Del(ht, &buffkey, NULL, NULL);
      if(rc != HASHTABLE_SUCCESS)
        {
          LogTest("Erreur lors de la destruction de %d = %d", random_val, rc);
          LogTest("Test FAILED: delete incorrect");
          exit(1);
        }
    }
  MesureTemps(&fin, &debut);
  LogTest("Time to delete %d elements = %s", MAXDESTROY,
          ConvertiTempsChaine(fin, NULL));

  LogTest("-----------------------------------------");

  LogTest("Now, I try to retrieve %d entries (possibly destroyed)",
          MAXGET);

  MesureTemps(&debut, NULL);
  for(i = 0; i < MAXGET; i++)
    {
      random_val = random() % MAXTEST;
      sprintf(tmpstr, "%d", random_val);
      buffkey.len = strlen(tmpstr);
      buffkey.pdata = tmpstr;

      rc = HashTable_Get(ht, &buffkey, &buffval);
    }
  MesureTemps(&fin, &debut);
  LogTest("Time to read %d elements = %s", MAXGET,
          ConvertiTempsChaine(fin, NULL));

  LogTest("-----------------------------------------");
  LogTest("Writing a duplicated key");
  sprintf(tmpstr, "%d", CRITERE_2);
  buffkey.len = strlen(tmpstr);
  buffkey.pdata = tmpstr;
  rc = HashTable_Test_And_Set(ht, &buffkey, &buffval, HASHTABLE_SET_HOW_SET_NO_OVERWRITE);
  LogTest("The value must be HASHTABLE_ERROR_KEY_ALREADY_EXISTS  = %d --> %d",
         HASHTABLE_ERROR_KEY_ALREADY_EXISTS, rc);
  if(rc != HASHTABLE_ERROR_KEY_ALREADY_EXISTS)
    {
      LogTest("Test ECHOUE : Clef redondante");
      exit(1);
    }
  LogTest("-----------------------------------------");

  HashTable_Log(COMPONENT_HASHTABLE,ht);
  LogFullDebug(COMPONENT_HASHTABLE,"-----------------------------------------");

  LogTest("Displaying table statistics");
  HashTable_GetStats(ht, &statistiques);
  LogTest(" Number of Entrees = %d", statistiques.dynamic.nb_entries);

  LogTest(" Successful operations : Set = %d,  Get = %d,  Del = %d,  Test = %d",
          statistiques.dynamic.ok.nb_set, statistiques.dynamic.ok.nb_get,
          statistiques.dynamic.ok.nb_del, statistiques.dynamic.ok.nb_test);

  LogTest("   Failed operations : Set = %d,  Get = %d,  Del = %d,  Test = %d",
          statistiques.dynamic.err.nb_set, statistiques.dynamic.err.nb_get,
          statistiques.dynamic.err.nb_del, statistiques.dynamic.err.nb_test);

  LogTest("   Operations 'NotFound': Set = %d,  Get = %d,  Del = %d,  Test = %d",
          statistiques.dynamic.notfound.nb_set, statistiques.dynamic.notfound.nb_get,
          statistiques.dynamic.notfound.nb_del, statistiques.dynamic.notfound.nb_test);

  LogTest("  Statistics computed: min_rbt_node = %d,  max_rbt_node = %d,  average_rbt_node = %d",
          statistiques.computed.min_rbt_num_node, statistiques.computed.max_rbt_num_node,
          statistiques.computed.average_rbt_num_node);

  /* Test sur la pertinence des valeurs de statistiques */
  if(statistiques.dynamic.ok.nb_set != MAXTEST)
    {
      LogTest("Test FAILED: Incorrect statistics: ok.nb_set ");
      exit(1);
    }

  if(statistiques.dynamic.ok.nb_get + statistiques.dynamic.notfound.nb_get !=
     2 * MAXGET + 1)
    {
      LogTest("Test FAILED: Incorrect statistics: *.nb_get.  Expected %d, got %d",
              2 * MAXGET + 1,
              statistiques.dynamic.ok.nb_get + statistiques.dynamic.notfound.nb_get);
      exit(1);
    }

  if(statistiques.dynamic.ok.nb_del != MAXDESTROY)
    {
      LogTest("Test FAILED: Incorrect statistics: *.nb_del. Expected %d, got %d",
              MAXDESTROY, statistiques.dynamic.ok.nb_del);
      exit(1);
    }

  if(statistiques.dynamic.notfound.nb_del != 0)
    {
      LogTest("Test FAILED: Incorrect statistics: *.nb_del. Expected %d, got %d",
              0, statistiques.dynamic.notfound.nb_del);
      exit(1);
    }



  if(statistiques.dynamic.err.nb_test != 1)
    {
      LogTest("Test FAILED: Incorrect statistics: err.nb_test ");
      exit(1);
    }

  /* Tous les tests sont ok */
  BuddyDumpMem(stdout);

  LogTest("\n-----------------------------------------");
  LogTest("Test succeeded: all tests pass successfully");

  exit(0);
}
Beispiel #21
0
/* Join two sets according to operator op and flags op_flags.
 * op can be:
 *	'|' (or):	the union between the two sets is returned,
 *		 	eliminating duplicates
 *	'&' (and):	the intersection between the two sets
 *			is returned
 *	'+' (add):	the inner product of the two sets is returned,
 *			namely a set containing the concatenation of
 *			all combinations of the two sets members,
 *			except for duplicates.
 * The two sets are disposed of according to the flags as described
 * for slap_set_dispose().
 */
BerVarray
slap_set_join(
	SetCookie	*cp,
	BerVarray	lset,
	unsigned	op_flags,
	BerVarray	rset )
{
	BerVarray	set;
	long		i, j, last, rlast;
	unsigned	op = ( op_flags & SLAP_SET_OPMASK );

	set = NULL;
	switch ( op ) {
	case '|':	/* union */
		if ( lset == NULL || BER_BVISNULL( &lset[ 0 ] ) ) {
			if ( rset == NULL ) {
				if ( lset == NULL ) {
					set = cp->set_op->o_tmpcalloc( 1,
							sizeof( struct berval ),
							cp->set_op->o_tmpmemctx );
					BER_BVZERO( &set[ 0 ] );
					goto done2;
				}
				set = set_dup( cp, lset, SLAP_SET_LREF2REF( op_flags ) );
				goto done2;
			}
			slap_set_dispose( cp, lset, SLAP_SET_LREF2REF( op_flags ) );
			set = set_dup( cp, rset, SLAP_SET_RREF2REF( op_flags ) );
			goto done2;
		}
		if ( rset == NULL || BER_BVISNULL( &rset[ 0 ] ) ) {
			slap_set_dispose( cp, rset, SLAP_SET_RREF2REF( op_flags ) );
			set = set_dup( cp, lset, SLAP_SET_LREF2REF( op_flags ) );
			goto done2;
		}

		/* worst scenario: no duplicates */
		rlast = slap_set_size( rset );
		i = slap_set_size( lset ) + rlast + 1;
		set = cp->set_op->o_tmpcalloc( i, sizeof( struct berval ), cp->set_op->o_tmpmemctx );
		if ( set != NULL ) {
			/* set_chase() depends on this routine to
			 * keep the first elements of the result
			 * set the same (and in the same order)
			 * as the left-set.
			 */
			for ( i = 0; !BER_BVISNULL( &lset[ i ] ); i++ ) {
				if ( op_flags & SLAP_SET_LREFVAL ) {
					ber_dupbv_x( &set[ i ], &lset[ i ], cp->set_op->o_tmpmemctx );

				} else {
					set[ i ] = lset[ i ];
				}
			}

			/* pointers to values have been used in set - don't free twice */
			op_flags |= SLAP_SET_LREFVAL;

			last = i;

			for ( i = 0; !BER_BVISNULL( &rset[ i ] ); i++ ) {
				int	exists = 0;

				for ( j = 0; !BER_BVISNULL( &set[ j ] ); j++ ) {
					if ( bvmatch( &rset[ i ], &set[ j ] ) )
					{
						if ( !( op_flags & SLAP_SET_RREFVAL ) ) {
							cp->set_op->o_tmpfree( rset[ i ].bv_val, cp->set_op->o_tmpmemctx );
							rset[ i ] = rset[ --rlast ];
							BER_BVZERO( &rset[ rlast ] );
							i--;
						}
						exists = 1;
						break;
					}
				}

				if ( !exists ) {
					if ( op_flags & SLAP_SET_RREFVAL ) {
						ber_dupbv_x( &set[ last ], &rset[ i ], cp->set_op->o_tmpmemctx );

					} else {
						set[ last ] = rset[ i ];
					}
					last++;
				}
			}

			/* pointers to values have been used in set - don't free twice */
			op_flags |= SLAP_SET_RREFVAL;

			BER_BVZERO( &set[ last ] );
		}
		break;

	case '&':	/* intersection */
		if ( lset == NULL || BER_BVISNULL( &lset[ 0 ] )
			|| rset == NULL || BER_BVISNULL( &rset[ 0 ] ) )
		{
			set = cp->set_op->o_tmpcalloc( 1, sizeof( struct berval ),
					cp->set_op->o_tmpmemctx );
			BER_BVZERO( &set[ 0 ] );
			break;

		} else {
			long llen, rlen;
			BerVarray sset;

			llen = slap_set_size( lset );
			rlen = slap_set_size( rset );

			/* dup the shortest */
			if ( llen < rlen ) {
				last = llen;
				set = set_dup( cp, lset, SLAP_SET_LREF2REF( op_flags ) );
				lset = NULL;
				sset = rset;

			} else {
				last = rlen;
				set = set_dup( cp, rset, SLAP_SET_RREF2REF( op_flags ) );
				rset = NULL;
				sset = lset;
			}

			if ( set == NULL ) {
				break;
			}

			for ( i = 0; !BER_BVISNULL( &set[ i ] ); i++ ) {
				for ( j = 0; !BER_BVISNULL( &sset[ j ] ); j++ ) {
					if ( bvmatch( &set[ i ], &sset[ j ] ) ) {
						break;
					}
				}

				if ( BER_BVISNULL( &sset[ j ] ) ) {
					cp->set_op->o_tmpfree( set[ i ].bv_val, cp->set_op->o_tmpmemctx );
					set[ i ] = set[ --last ];
					BER_BVZERO( &set[ last ] );
					i--;
				}
			}
		}
		break;

	case '+':	/* string concatenation */
		i = slap_set_size( rset );
		j = slap_set_size( lset );

		/* handle empty set cases */
		if ( i == 0 || j == 0 ) {
			set = cp->set_op->o_tmpcalloc( 1, sizeof( struct berval ),
					cp->set_op->o_tmpmemctx );
			if ( set == NULL ) {
				break;
			}
			BER_BVZERO( &set[ 0 ] );
			break;
		}

		set = cp->set_op->o_tmpcalloc( i * j + 1, sizeof( struct berval ),
				cp->set_op->o_tmpmemctx );
		if ( set == NULL ) {
			break;
		}

		for ( last = 0, i = 0; !BER_BVISNULL( &lset[ i ] ); i++ ) {
			for ( j = 0; !BER_BVISNULL( &rset[ j ] ); j++ ) {
				struct berval	bv;
				long		k;

				/* don't concatenate with the empty string */
				if ( BER_BVISEMPTY( &lset[ i ] ) ) {
					ber_dupbv_x( &bv, &rset[ j ], cp->set_op->o_tmpmemctx );
					if ( bv.bv_val == NULL ) {
						ber_bvarray_free_x( set, cp->set_op->o_tmpmemctx );
						set = NULL;
						goto done;
					}

				} else if ( BER_BVISEMPTY( &rset[ j ] ) ) {
					ber_dupbv_x( &bv, &lset[ i ], cp->set_op->o_tmpmemctx );
					if ( bv.bv_val == NULL ) {
						ber_bvarray_free_x( set, cp->set_op->o_tmpmemctx );
						set = NULL;
						goto done;
					}

				} else {
					bv.bv_len = lset[ i ].bv_len + rset[ j ].bv_len;
					bv.bv_val = cp->set_op->o_tmpalloc( bv.bv_len + 1,
							cp->set_op->o_tmpmemctx );
					if ( bv.bv_val == NULL ) {
						ber_bvarray_free_x( set, cp->set_op->o_tmpmemctx );
						set = NULL;
						goto done;
					}
					AC_MEMCPY( bv.bv_val, lset[ i ].bv_val, lset[ i ].bv_len );
					AC_MEMCPY( &bv.bv_val[ lset[ i ].bv_len ], rset[ j ].bv_val, rset[ j ].bv_len );
					bv.bv_val[ bv.bv_len ] = '\0';
				}

				for ( k = 0; k < last; k++ ) {
					if ( bvmatch( &set[ k ], &bv ) ) {
						cp->set_op->o_tmpfree( bv.bv_val, cp->set_op->o_tmpmemctx );
						break;
					}
				}

				if ( k == last ) {
					set[ last++ ] = bv;
				}
			}
		}
		BER_BVZERO( &set[ last ] );
		break;

	default:
		break;
	}

done:;
	if ( lset ) slap_set_dispose( cp, lset, SLAP_SET_LREF2REF( op_flags ) );
	if ( rset ) slap_set_dispose( cp, rset, SLAP_SET_RREF2REF( op_flags ) );

done2:;
	if ( LogTest( LDAP_DEBUG_ACL ) ) {
		if ( BER_BVISNULL( set ) ) {
			Debug( LDAP_DEBUG_ACL, "  ACL set: empty\n", 0, 0, 0 );

		} else {
			for ( i = 0; !BER_BVISNULL( &set[ i ] ); i++ ) {
				Debug( LDAP_DEBUG_ACL, "  ACL set[%ld]=%s\n", i, set[i].bv_val, 0 );
			}
		}
	}

	return set;
}
Beispiel #22
0
int idmap_computer_hash_value(char *name, uint32_t * phashval)
{
  char padded_name[PWENT_MAX_LEN];
  uint32_t computed_value = 0;
  unsigned int i = 0;
  unsigned int offset = 0;
  uint64_t extract = 0;
  uint64_t sum = 0;
  uint64_t i1;
  uint64_t i2;
  uint64_t i3;
  uint64_t i4;
  uint64_t i5;
  uint64_t i6;
  uint64_t i7;
  uint64_t i8;
  uint64_t l;

  if(name == NULL || phashval == NULL)
    return CLIENT_ID_INVALID_ARGUMENT;

  memset(padded_name, 0, PWENT_MAX_LEN);

  /* Copy the string to the padded one */
  for(i = 0; i < strnlen(name, PWENT_MAX_LEN); padded_name[i] = name[i], i++) ;

  LogTest("%s \n", padded_name);

  /* For each 9 character pack:
   *   - keep the 7 first bit (the 8th is often 0: ascii string)
   *   - pack 7x9 bit to 63 bits using xor
   *   - xor the last 8th bit to a single 0 , or-ed with the rest
   * Proceeding with the next 9 bytes pack will produce a new value that is xored with the
   * one of the previous iteration */

  for(offset = 0; offset < PWENT_MAX_LEN; offset += 8)
    {
      /* input name is ascii string, remove 8th bit on each byte, not significant */
      i1 = padded_name[offset + 0];
      i2 = (padded_name[offset + 1]) << 8;
      i3 = (padded_name[offset + 2]) << 16;
      i4 = (padded_name[offset + 3]) << 24;
      i5 = (padded_name[offset + 4]) << 32;
      i6 = (padded_name[offset + 5]) << 40;
      i7 = (padded_name[offset + 6]) << 48;
      i8 = (padded_name[offset + 7]) << 56;

      sum = (uint64_t) padded_name[offset + 0] +
          (uint64_t) padded_name[offset + 1] +
          (uint64_t) padded_name[offset + 2] +
          (uint64_t) padded_name[offset + 3] +
          (uint64_t) padded_name[offset + 4] +
          (uint64_t) padded_name[offset + 5] +
          (uint64_t) padded_name[offset + 6] + (uint64_t) padded_name[offset + 7];


      LogTest("|%llx |%llx |%llx |%llx |%llx |%llx |%llx |%llx |%llx | = ",
             i1, i2, i3, i4, i5, i6, i7, i8);

      /* Get xor combibation of all the 8h bit */
      l = (padded_name[offset + 0]) ^
          (padded_name[offset + 1]) ^
          (padded_name[offset + 2]) ^
          (padded_name[offset + 3]) ^
          (padded_name[offset + 4]) ^
          (padded_name[offset + 5]) ^
          (padded_name[offset + 6]) ^ (padded_name[offset + 7]);

      extract = i1 ^ i2 ^ i3 ^ i4 ^ i5 ^ i6 ^ i7 ^ i8 | l;

      LogTest("%llx ", extract);

      computed_value ^= extract;
      computed_value ^= sum;

      LogTest(",%x\n  ", computed_value);
    }

  if(computed_value > 0x00000000FFFFFFFFLL)
    computed_value = (computed_value >> 32) ^ (computed_value & 0x00000000FFFFFFFFLL);

  LogTest("===>%x\n", computed_value);

  *phashval = computed_value;

  return CLIENT_ID_SUCCESS;
}                               /* idmap_computer_hash_value */