Пример #1
0
t_config *config_create(char *path) {
    t_config *config = malloc(sizeof(t_config));

    config->path = strdup(path);
    config->properties = dictionary_create();

    struct stat stat_file;
    stat(path, &stat_file);
    FILE* file = NULL;

    file = fopen(path, "r");

    if (file != NULL) {
        char* buffer = calloc(1, stat_file.st_size + 1);
        fread(buffer, stat_file.st_size, 1, file);

        char** lines = string_split(buffer, "\n");

        void add_cofiguration(char *line) {
            if (!string_starts_with(line, "#")) {
                char** keyAndValue = string_split(line, "=");
                dictionary_put(config->properties, keyAndValue[0], keyAndValue[1]);
                free(keyAndValue[0]);
                free(keyAndValue);
            }
        }
        string_iterate_lines(lines, add_cofiguration);
        string_iterate_lines(lines, (void*) free);

        free(lines);
        free(buffer);
        fclose(file);
    }
// ver de notificar que agregar un job, blah
void job_agregar(int fdJob, header_t header){
	t_job *job = calloc(1, sizeof(t_job));
	job->fd = fdJob;
	job->archivos = dictionary_create();
	pthread_mutex_lock(&mutex_lista_jobs);
	list_add(lista_jobs, job);
	pthread_mutex_unlock(&mutex_lista_jobs);
}
void cargar_dispositivos() {
	char** hioId = config_get_array_value(config, "ID_HIO");
	char** hioRetardo = config_get_array_value(config, "HIO");

	dispositivos = dictionary_create();

	int i;

	for(i = 0; hioId[i] != NULL; i++) {
		io_t *registro_hio = crear_registro(hioRetardo[i]);
		dictionary_put(dispositivos, hioId[i], registro_hio);
	}

	string_iterate_lines(hioId, free);
	string_iterate_lines(hioRetardo, free);
	free(hioId);
	free(hioRetardo);
}
void inicializarMSP(void) {

	int i;

	CantPaginasEnSwapMax = MaxSwap / PAG_SIZE;
	CantPaginasEnSwapDisponibles = CantPaginasEnSwapMax == 0 ? 0 : CantPaginasEnSwapMax - 1; 					/* Dejo un lugar disponible para hacer los intercambios */
	CantPaginasEnMemoriaDisponibles = CantidadMarcosTotal = MaxMem / PAG_SIZE;
	CantPaginasDisponibles = CantPaginasEnMemoriaDisponibles + CantPaginasEnSwapDisponibles;


	if ((MemoriaPrincipal = malloc(CantidadMarcosTotal * sizeof(t_marco))) == NULL)
		perror("MALLOC");

	/* Inicializo el bit ocupado con 0 (todos los marcos disponibles) */
	for (i = 0; i < CantidadMarcosTotal; ++i)
		MemoriaPrincipal[i].ocupado = 0;

	TablaSegmentosGlobal = dictionary_create();

	/* Configuro las rutinas del algoritmo de selección a utilizar. Elige Clock por default */
	if (strcmp(AlgoritmoSustitucion,"LRU")) {
		ArrayClock = malloc(CantidadMarcosTotal * sizeof(t_clock_node));

		RutinaSeleccionPaginaVictima = seleccionVictimaClock;
		ImprimirInfoAlgoritmosSustitucion = imprimirArrayClock;
		QuitarDeEstructuraDeSeleccion = quitarPaginaDeArrayClock;
		ActualizarEnEstructuraDeSustitucion = actualizarEnArrayClock;
		AgregarPaginaAEstructuraSustitucion = agregarPaginaEnArrayClock;
	}
	else {
		ListaLRU = list_create();

		RutinaSeleccionPaginaVictima = seleccionVictimaLRU;
		ImprimirInfoAlgoritmosSustitucion = imprimirListaLRU;
		QuitarDeEstructuraDeSeleccion = quitarPaginaDeListaLRU;
		ActualizarEnEstructuraDeSustitucion = actualizarEnListaLRU;
		AgregarPaginaAEstructuraSustitucion = agregarPaginaAListaLRU;
	}

	pthread_mutex_init(&LogMutex, NULL);
	pthread_mutex_init(&MemMutex, NULL);

}
void cargar_variablesCompartidas()
{
	char** variablesCompartidasArray = config_get_array_value(config, "VARIABLES_COMPARTIDAS");

	variablesCompartidas = dictionary_create();

	int i;

	for(i = 0; variablesCompartidasArray[i] != NULL; i++)
	{
		int32_t *valor = malloc(sizeof(int32_t));
		*valor = 0;

		dictionary_put(variablesCompartidas, variablesCompartidasArray[i], valor);
	}

	string_iterate_lines(variablesCompartidasArray, free);
	free(variablesCompartidasArray);
}
Пример #6
0
REGISTRY_MACHINE *registry_machine_allocate(const char *machine_guid, time_t when) {
    debug(D_REGISTRY, "Registry: registry_machine_allocate('%s'): creating new machine, sizeof(MACHINE)=%zu", machine_guid, sizeof(REGISTRY_MACHINE));

    REGISTRY_MACHINE *m = mallocz(sizeof(REGISTRY_MACHINE));

    strncpyz(m->guid, machine_guid, GUID_LEN);

    debug(D_REGISTRY, "Registry: registry_machine_allocate('%s'): creating dictionary of urls", machine_guid);
    m->machine_urls = dictionary_create(DICTIONARY_FLAGS);

    m->first_t = m->last_t = (uint32_t)when;
    m->usages = 0;

    registry.machines_memory += sizeof(REGISTRY_MACHINE);

    registry.machines_count++;
    dictionary_set(registry.machines, m->guid, m, sizeof(REGISTRY_MACHINE));

    return m;
}
Пример #7
0
//----------------Archivo de Configuracion---------------------------------
void cargarArchivoDeConfiguracion() {

	t_dictionary* diccionario;
	diccionario = dictionary_create();
	char* dato;
	char* clave;

	char textoLeido[200];
	FILE* archivo;
	//archivo = fopen("/home/utnso/workspace/tp-2015-1c-sinergia/Nodo/Debug/configNodo","r");
	char* config = "configNodo";
	archivo = fopen(config,"r");


	while ((feof(archivo)) == 0) {
		fgets(textoLeido, 200, archivo);

		clave = string_split(textoLeido, ",")[0];
		dato = string_split(textoLeido, ",")[1];
		dictionary_put(diccionario, clave, dato);

	}

	// IMPORTANTE hay que hacer esto que viene abajo pq el dato obtenido del diccionario viene con un caracter
	//de mas entonces tenemos que "limpiarlo" (se lo sacamos)




	ipNodo = malloc(15);
	puertoNodo = malloc(10);
	dirTemp = malloc(100);

	puertoFileSystem = obtenerDatoLimpioDelDiccionario(diccionario, "puertoFS");
	ipFileSystem = obtenerDatoLimpioDelDiccionario(diccionario, "ipFS");
	ipNodo = obtenerDatoLimpioDelDiccionario(diccionario, "ipNodo");
	puertoNodo = obtenerDatoLimpioDelDiccionario(diccionario, "puertoNodo");
	tamanioNodo = obtenerDatoLimpioDelDiccionario(diccionario, "tamanioNodo");
	nodoNuevo = obtenerDatoLimpioDelDiccionario(diccionario, "nodoNuevo");
	dirTemp = obtenerDatoLimpioDelDiccionario(diccionario, "dirTemp");
}
int main(void) {


t_dictionary* diccionario;
diccionario = dictionary_create();
char* dato;
char* clave;
char* textoLeido;
FILE* archivo;
archivo = fopen("/home/utnso/workspace/extraer datos de archivo de configuracion/src/texto","r");

while (feof(archivo) == 0){
fgets(textoLeido,50,archivo);



clave = string_split(textoLeido,",")[0];
dato = string_split(textoLeido,",")[1];
dictionary_put(diccionario,clave,dato);



}
fclose(archivo);


conseguiRutaArchivos(diccionario);
/*
char* info;
info= (char*)dictionary_get(diccionario,"ip");
printf("%s",info);

*/
printf(dictionary_get(diccionario,"ip"));	//cada dato tiene que ser cargado en una variable en ves de imprimirse, ej: ipMarta = dictionary_get(diccionario,"ip");
printf(dictionary_get(diccionario,"puerto"));
printf(dictionary_get(diccionario,"mapper"));
printf(dictionary_get(diccionario,"reducer"));
printf(dictionary_get(diccionario,"combiner"));
printf(dictionary_get(diccionario,"resultado"));

}
void cargar_semaforos()
{
	char** semaforosArray = config_get_array_value(config, "SEMAFOROS");
	char** valorSemaforosArray = config_get_array_value(config, "VALOR_SEMAFORO");

	semaforos = dictionary_create();

	int i;
	semaforo_t *semaforo;

	for(i = 0; semaforosArray[i] != NULL && valorSemaforosArray[i] != NULL; i++)
	{
		semaforo = malloc(sizeof(semaforo_t));
		semaforo->valor = atoi(valorSemaforosArray[i]);
		semaforo->cola = queue_create();

		dictionary_put(semaforos, semaforosArray[i], semaforo);
	}

	string_iterate_lines(semaforosArray, free);
	string_iterate_lines(valorSemaforosArray, free);
	free(semaforosArray);
	free(valorSemaforosArray);
}
Пример #10
0
int main(){
	char *proxInstrucc;

	dic_Variables = dictionary_create();

	cpu_file_log = txt_open_for_append("./CPU/logs/cpu.log");
	txt_write_in_file(cpu_file_log,"---------------------Nueva ejecucion------------------------------\n");

	txt_write_in_file(cpu_file_log, "Cargo la configuracion desde el archivo\n");

	t_config *unaConfig = config_create("./CPU/cpu_config");
	char *puertoKernel = config_get_string_value(unaConfig, "Puerto_Kernel");
	char *ipKernel = config_get_string_value(unaConfig, "IP_Kernel");
	char *puertoUmv = config_get_string_value(unaConfig, "Puerto_UMV");
	char *ipUmv = config_get_string_value(unaConfig, "IP_UMV");
	imprimo_config(puertoKernel, ipKernel, puertoUmv, ipUmv);

	printf("El PID de este CPU es %d \n", getpid());

	/*conexion con el kernel*/
	handshake_kernel(puertoKernel, ipKernel);

	/*conexion con la umv*/
	handshake_umv(puertoUmv, ipUmv);

	/*maneja si recibe la señal SIGUSR, hay que revisarlo todavia*/
	signal(SIGUSR1, signal_handler);
	signal(SIGINT, signal_handler);

	while(quit_sistema){
		/*recibe un pcb del kernel*/
		recibirUnPcb();
		if(pcb == NULL)
			goto _fin;
		/* le digo a la UMV q cambie el proceso activo */
		cambio_PA(pcb->id);

		traerIndiceEtiquetas();
		/*se crea un diccionario para guardar las variables del contexto*/
		regenerar_dicc_var();

		for (quantum_actual = 0;(quantum_actual < quantum_max) && (!fueFinEjecucion) && (!entre_io) && (!sem_block); quantum_actual++){//aca cicla hasta q el haya terminado los quantums
			printf("Quantum nº%i\n",quantum_actual+1);
			proxInstrucc = solicitarProxSentenciaAUmv();
			analizadorLinea(proxInstrucc, &functions, &kernel_functions);
			free(proxInstrucc);
		}
		if(!fueFinEjecucion){
			salirPorQuantum();
		}
		free(etiquetas);
		free(pcb);
		pcb = NULL;
		cambio_PA(0);//lo cambio a 0 asi la UMV puede comprobar q hay un error
		fueFinEjecucion = 0;
		huboSegFault = 0;
		entre_io = 0;
		sem_block = 0;
	}
	socket_cerrar(socketKernel);
	socket_cerrar(socketUmv);
	_fin:
	return 0;
}
void core_conexion_kernel(void){
	if((sockKernel=socket_crearYConectarCliente(configuracion_cpu.ip_kernel,configuracion_cpu.puerto_kernel))==-1){
		log_error_socket();
		//abort();
	}
	log_escribir(archLog, "Conexion", INFO, "Se conecto correctamente al Kernel");
	t_tipoEstructura tipoRecibido;
	void* structRecibida;
	socket_recibir(sockKernel,&tipoRecibido,&structRecibida);
	t_struct_numero* k = ((t_struct_numero*)structRecibida);
	quantum = k->numero;
	free(k);
	log_escribir(archLog, "Quantum", INFO, "Se seteo el quantum en %d al ser recibido del kernel", quantum);


	socket_recibir(sockKernel,&tipoRecibido,&structRecibida);
	k = ((t_struct_numero*)structRecibida);
	configuracion_cpu.retardo= k->numero;
	free(k);


	int id;
	dicc_variables =dictionary_create();

	t_struct_pcb* pcb_recibida;
	t_struct_pcb_io* pcb_actualizada;
	t_struct_numero * solicitarPCB;
	sem_wait(&sem_kernel);

	while(1){
		t_tipoEstructura tipoRecibido;
		void* structRecibida;
		sleep(configuracion_cpu.retardo);
		solicitarPCB = malloc(sizeof(t_struct_numero));
		solicitarPCB->numero = 1;
		int j = socket_enviar(sockKernel, D_STRUCT_NUMERO, solicitarPCB);
		if(j==1){
		printf("Se solicita la liberacion de la cpu\n");}else{printf("NO MANDA\n");}
		free(solicitarPCB);
		fin_PCB = 0;
		sig_flag = 0;
		UMV_flag = 0;
		SEG_flag = 0;
		fin_quantum = 0;
		socket_recibir(sockKernel,&tipoRecibido,&structRecibida);
		if(tipoRecibido!=D_STRUCT_PCB){
			printf("NO ES PCB!\nEs tipo %d\n", tipoRecibido);
			return;
		}
		pcb_recibida = ((t_struct_pcb*)structRecibida);
		log_escribir(archLog, "Recibida pcb", INFO, "Se recibio la pcb con pid: %d", pcb_recibida->pid);


		temp_id=pcb_recibida->pid;
		log_escribir(archLog, "PCB", INFO, "Se recibio el pid %d", temp_id);
		temp_cursor_stack= pcb_recibida->c_stack;
		temp_seg_codigo = pcb_recibida->codigo;
		temp_ind_codigo = pcb_recibida->index_codigo;
		var_ind_etiquetas = pcb_recibida->index_etiquetas;
		temp_counter = pcb_recibida->program_counter;
		var_seg_stack = pcb_recibida->stack;
		var_tamanio_contexto = pcb_recibida->tamanio_contexto;
		var_tamanio_etiquetas = pcb_recibida->tamanio_indice;
		temp_estado = pcb_recibida->estado;
		recupero_diccionario(dicc_variables,var_tamanio_contexto);

			while((fin_quantum!=quantum)&&(fin_PCB==0)){
				t_struct_sol_bytes * solicitar_indice = malloc(sizeof(t_struct_sol_bytes));

				solicitar_indice->base = temp_ind_codigo;
				solicitar_indice->offset = temp_counter * 8;
				solicitar_indice->tamanio = 2 * sizeof(uint32_t);
				socket_enviar(sockUMV, D_STRUCT_SOL_BYTES, solicitar_indice); //
				free(solicitar_indice);
				/************************* Solicita indice *************************/
				void * estructuraRecibida2;
				t_tipoEstructura tipoRecibido2;

				socket_recibir(sockUMV, &tipoRecibido2, &estructuraRecibida2);
				/************************* Recibe indice *************************/
				uint32_t temp_tamanio;
				void * temp_buffer;
				temp_buffer = ((t_struct_respuesta_umv*) estructuraRecibida2)->buffer;
				temp_tamanio = ((t_struct_respuesta_umv*) estructuraRecibida2)->tamano_buffer;

				if (temp_tamanio == sizeof(int)) {
					int*respuesta2 = malloc(sizeof(int));
					memcpy(respuesta2, ((t_struct_respuesta_umv*) estructuraRecibida2)->buffer, temp_tamanio);
					int valor = *respuesta2;
					printf("Valor respondido: %d",valor);
					if (valor ==-30) {
							excepcion_UMV(0);
							break;
						}

				}


				uint32_t indice_temp;
				uint32_t tamanio_temp;
				int off_set;

				memcpy(&indice_temp, temp_buffer, off_set = sizeof(uint32_t));
				memcpy(&tamanio_temp, temp_buffer + off_set, sizeof(uint32_t));



				t_struct_sol_bytes * solicitar_instruccion = malloc(sizeof(t_struct_sol_bytes));
				solicitar_instruccion->base = temp_seg_codigo;
				solicitar_instruccion->offset = indice_temp;
				solicitar_instruccion->tamanio = tamanio_temp;
				/************************* Se solicita la proxima instruccion *************************/
				socket_enviar(sockUMV, D_STRUCT_SOL_BYTES, solicitar_instruccion);
				free(solicitar_instruccion);
				/************************* Se recibe la siguiente instruccion *************************/
				void * estructuraRecibida3;
				t_tipoEstructura tipoRecibido3;

				socket_recibir(sockUMV, &tipoRecibido3, &estructuraRecibida3);

				int tamanio_instruccion = ((t_struct_respuesta_umv*) estructuraRecibida3)->tamano_buffer;

				if (tamanio_instruccion == sizeof(int)) {
					int*respuesta = malloc(sizeof(int));
					memcpy(respuesta, ((t_struct_respuesta_umv*) estructuraRecibida3)->buffer, tamanio_instruccion);
					int valor = *respuesta;
					printf("Valor respondido: %d",valor);
					if (valor ==-30) {
							excepcion_UMV(0);
							break;
						}

				}

				char * codigo = malloc(tamanio_instruccion);
				memcpy(codigo, ((t_struct_respuesta_umv*) estructuraRecibida3)->buffer, tamanio_instruccion);
							// codigo=((t_struct_respuesta_umv*)estructuraRecibida3)->buffer;
				char** partes = string_split(codigo, "\n");
				free(codigo);
				codigo = partes[0];
				free(partes);
				printf("\n\n>>>>> %s\n\n", codigo);
				char * codigoContac = strcat(codigo, "\0");

				analizadorLinea(codigoContac, &funciones_parser, &funciones_kernel);
				free(((t_struct_respuesta_umv*) estructuraRecibida3)->buffer);
				free(temp_buffer);
				free(estructuraRecibida3);
				free(estructuraRecibida2);
				free(codigo);
				sleep(configuracion_cpu.retardo);
				temp_counter++;
				fin_quantum++;

				signal(SIGUSR1, llegoSenialParaTerminar);

				if (sig_flag == 1 && (quantum - fin_quantum == 0)) {

					break;
				}




			}


			if(fin_PCB==0 && UMV_flag == 0){
				t_struct_pcb* pcb_fin = malloc(sizeof(t_struct_pcb));
				pcb_fin->c_stack=temp_cursor_stack;
				pcb_fin->codigo=temp_seg_codigo;
				pcb_fin->index_codigo=temp_ind_codigo;
				pcb_fin->index_etiquetas=var_ind_etiquetas;
				pcb_fin->pid=temp_id;
				pcb_fin->program_counter=temp_counter;
				pcb_fin->stack=var_seg_stack;
				pcb_fin->tamanio_contexto=var_tamanio_contexto;
				pcb_fin->tamanio_indice=var_tamanio_etiquetas;
				pcb_fin->estado=temp_estado;

				socket_enviar(sockKernel, D_STRUCT_PCB, pcb_fin);

				log_escribir(archLog,"Se envio la PCB al kernel",INFO,"El estado de finalizacion es normal");
			}

			fin_quantum = 0;
			if (sig_flag == 1) {
				break;
			}

	}


	printf("Gracias al SIGUSR1, se sale del bucle");
	t_struct_numero* valor = malloc(sizeof(t_struct_numero));
	valor->numero=0;
	socket_enviar(sockUMV,D_STRUCT_NUMERO,valor);
	if(socket_cerrarConexion(sockUMV)==0){
				log_escribir(archLog,"Cerrar Conexion",ERROR,"Finalizo la ejecucion de la CPU por SISGUR1");
			}
	if(socket_cerrarConexion(sockKernel)==0){
		log_escribir(archLog,"Cerrar Conexion",ERROR,"Finalizo la ejecucion de la CPU por SISGUR1");
	}
	return;
}
Пример #12
0
int main(int argc, char **argv) {
	if(argc || argv) {;}

//	DICTIONARY *dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED|DICTIONARY_FLAG_WITH_STATISTICS);
	DICTIONARY *dict = dictionary_create(DICTIONARY_FLAG_WITH_STATISTICS);
	if(!dict) fatal("Cannot create dictionary.");

	struct rusage start, end;
	unsigned long long dt;
	char buf[100 + 1];
	struct myvalue value, *v;
	int i, max = 100000, max2;

	// ------------------------------------------------------------------------

	getrusage(RUSAGE_SELF, &start);
	dict->stats->inserts = dict->stats->deletes = dict->stats->searches = 0ULL;
	fprintf(stderr, "Inserting %d entries in the dictionary\n", max);
	for(i = 0; i < max; i++) {
		value.i = i;
		snprintf(buf, 100, "%d", i);

		dictionary_set(dict, buf, &value, sizeof(struct myvalue));
	}
	getrusage(RUSAGE_SELF, &end);
	dt = (end.ru_utime.tv_sec * 1000000ULL + end.ru_utime.tv_usec) - (start.ru_utime.tv_sec * 1000000ULL + start.ru_utime.tv_usec);
	fprintf(stderr, "Added %d entries in %llu nanoseconds: %llu inserts per second\n", max, dt, max * 1000000ULL / dt);
	fprintf(stderr, " > Dictionary: %llu inserts, %llu deletes, %llu searches\n\n", dict->stats->inserts, dict->stats->deletes, dict->stats->searches);

	// ------------------------------------------------------------------------

	getrusage(RUSAGE_SELF, &start);
	dict->stats->inserts = dict->stats->deletes = dict->stats->searches = 0ULL;
	fprintf(stderr, "Retrieving %d entries from the dictionary\n", max);
	for(i = 0; i < max; i++) {
		value.i = i;
		snprintf(buf, 100, "%d", i);

		v = dictionary_get(dict, buf);
		if(!v)
			fprintf(stderr, "ERROR: cannot get value %d from the dictionary\n", i);
		else if(v->i != i)
			fprintf(stderr, "ERROR: expected %d but got %d\n", i, v->i);
	}
	getrusage(RUSAGE_SELF, &end);
	dt = (end.ru_utime.tv_sec * 1000000ULL + end.ru_utime.tv_usec) - (start.ru_utime.tv_sec * 1000000ULL + start.ru_utime.tv_usec);
	fprintf(stderr, "Read %d entries in %llu nanoseconds: %llu searches per second\n", max, dt, max * 1000000ULL / dt);
	fprintf(stderr, " > Dictionary: %llu inserts, %llu deletes, %llu searches\n\n", dict->stats->inserts, dict->stats->deletes, dict->stats->searches);

	// ------------------------------------------------------------------------

	getrusage(RUSAGE_SELF, &start);
	dict->stats->inserts = dict->stats->deletes = dict->stats->searches = 0ULL;
	fprintf(stderr, "Resetting %d entries in the dictionary\n", max);
	for(i = 0; i < max; i++) {
		value.i = i;
		snprintf(buf, 100, "%d", i);

		dictionary_set(dict, buf, &value, sizeof(struct myvalue));
	}
	getrusage(RUSAGE_SELF, &end);
	dt = (end.ru_utime.tv_sec * 1000000ULL + end.ru_utime.tv_usec) - (start.ru_utime.tv_sec * 1000000ULL + start.ru_utime.tv_usec);
	fprintf(stderr, "Reset %d entries in %llu nanoseconds: %llu resets per second\n", max, dt, max * 1000000ULL / dt);
	fprintf(stderr, " > Dictionary: %llu inserts, %llu deletes, %llu searches\n\n", dict->stats->inserts, dict->stats->deletes, dict->stats->searches);

	// ------------------------------------------------------------------------

	getrusage(RUSAGE_SELF, &start);
	dict->stats->inserts = dict->stats->deletes = dict->stats->searches = 0ULL;
	fprintf(stderr, "Searching  %d non-existing entries in the dictionary\n", max);
	max2 = max * 2;
	for(i = max; i < max2; i++) {
		value.i = i;
		snprintf(buf, 100, "%d", i);

		v = dictionary_get(dict, buf);
		if(v)
			fprintf(stderr, "ERROR: cannot got non-existing value %d from the dictionary\n", i);
	}
	getrusage(RUSAGE_SELF, &end);
	dt = (end.ru_utime.tv_sec * 1000000ULL + end.ru_utime.tv_usec) - (start.ru_utime.tv_sec * 1000000ULL + start.ru_utime.tv_usec);
	fprintf(stderr, "Searched %d non-existing entries in %llu nanoseconds: %llu not found searches per second\n", max, dt, max * 1000000ULL / dt);
	fprintf(stderr, " > Dictionary: %llu inserts, %llu deletes, %llu searches\n\n", dict->stats->inserts, dict->stats->deletes, dict->stats->searches);

	// ------------------------------------------------------------------------

	getrusage(RUSAGE_SELF, &start);
	dict->stats->inserts = dict->stats->deletes = dict->stats->searches = 0ULL;
	fprintf(stderr, "Deleting %d entries from the dictionary\n", max);
	for(i = 0; i < max; i++) {
		value.i = i;
		snprintf(buf, 100, "%d", i);

		dictionary_del(dict, buf);
	}
	getrusage(RUSAGE_SELF, &end);
	dt = (end.ru_utime.tv_sec * 1000000ULL + end.ru_utime.tv_usec) - (start.ru_utime.tv_sec * 1000000ULL + start.ru_utime.tv_usec);
	fprintf(stderr, "Deleted %d entries in %llu nanoseconds: %llu deletes per second\n", max, dt, max * 1000000ULL / dt);
	fprintf(stderr, " > Dictionary: %llu inserts, %llu deletes, %llu searches\n\n", dict->stats->inserts, dict->stats->deletes, dict->stats->searches);

	// ------------------------------------------------------------------------

	getrusage(RUSAGE_SELF, &start);
	dict->stats->inserts = dict->stats->deletes = dict->stats->searches = 0ULL;
	fprintf(stderr, "Destroying dictionary\n");
	dictionary_destroy(dict);
	getrusage(RUSAGE_SELF, &end);
	dt = (end.ru_utime.tv_sec * 1000000ULL + end.ru_utime.tv_usec) - (start.ru_utime.tv_sec * 1000000ULL + start.ru_utime.tv_usec);
	fprintf(stderr, "Destroyed in %llu nanoseconds\n", dt);

	return 0;
}
Пример #13
0
pcb_t* recibirPCBdeCPU(int socket,int pidLocal){
	pcb_t* pcb_Recibido = malloc(sizeof(pcb_t));
	pcb_Recibido->PID = recibirCpu(socket,sizeof(int),pidLocal);
	pidLocal = *(pcb_Recibido->PID);
	pcb_Recibido->PC = recibirCpu(socket,sizeof(int),pidLocal);
	pcb_Recibido->PCI = recibirCpu(socket,sizeof(int),pidLocal);
	pcb_Recibido->SP = recibirCpu(socket,sizeof(int),pidLocal);
	pcb_Recibido->paginasDisponible = recibirCpu(socket,sizeof(int),pidLocal);

	pcb_Recibido->indice_codigo = dictionary_create();
	pcb_Recibido->indice_funciones = list_create();
	pcb_Recibido->indice_stack = dictionary_create();

	int* tamanioIC = recibirCpu(socket, sizeof(int),pidLocal);
	int* tamanioStack = recibirCpu(socket, sizeof(int),pidLocal);
	int* tamanioIF = recibirCpu(socket, sizeof(int),pidLocal);

	int i;

	//RECIBO INDICE DE CODIGO
	for(i=0;i<*tamanioIC && *tamanioIC != 0;i++){
		int* nuevaPagina = malloc(sizeof(int));
		*nuevaPagina = i;
		direccionMemoria* nuevaDireccionMemoria = recibirCpu(socket,sizeof(direccionMemoria),pidLocal);
		dictionary_put(pcb_Recibido->indice_codigo,nuevaPagina,nuevaDireccionMemoria);
	}
	free(tamanioIC);


	//RECIBO INDICE FUNCIONES
	for(i=0;i<*tamanioIF && *tamanioIF!=0;i++){
		funcionTemp* funcion = recibirCpu(socket,sizeof(funcionTemp),pidLocal);
		char* funcionNombre = recibirCpu(socket,funcion->tamanioNombreFuncion,pidLocal);
		funcion_sisop* new_funcion = malloc(sizeof(new_funcion));
		new_funcion->funcion = funcionNombre;
		new_funcion->posicion_codigo = malloc(sizeof(int));
		*(new_funcion->posicion_codigo) = funcion->posicionPID;
		list_add_in_index(pcb_Recibido->indice_funciones,i,new_funcion);
	}
	free(tamanioIF);


	//RECIBO STACK
	for(i=0;i<*tamanioStack && *tamanioStack!=0;i++){
		stack* stackNuevo = malloc(sizeof(stack));
		//Argumentos
		int* tamArgs = recibirCpu(socket, sizeof(int),pidLocal);
		if(*tamArgs==-1)
			stackNuevo->args = NULL;
		else
			stackNuevo->args = list_create();
		//Variables
		int* tamVars = recibirCpu(socket, sizeof(int),pidLocal);
		if(*tamVars==-1)
			stackNuevo->vars = NULL;
		else
			stackNuevo->vars = list_create();
		//Retorno PID del renglon stack
		int* RetornoPID = recibirCpu(socket, sizeof(int),pidLocal);
		if(*RetornoPID == -1)
			stackNuevo->pos_ret = NULL;
		else
			stackNuevo->pos_ret = RetornoPID;
		//Retorno
		direccionMemoria* memoriaRetorno = recibirCpu(socket, sizeof(direccionMemoria),pidLocal);
		if(memoriaRetorno->offset == -1)
			memoriaRetorno = NULL;

		stackNuevo->memoriaRetorno = memoriaRetorno;
		int j;
		for(j=0;j<*tamArgs;j++){
			direccionMemoria* new_direc = recibirCpu(socket, sizeof(direccionMemoria),pidLocal);
			list_add_in_index(stackNuevo->args,j,new_direc);
		}
		free(tamArgs);
		for(j=0;j<*tamVars;j++){
			direccionStack* new_direc = recibirCpu(socket, sizeof(direccionStack),pidLocal);
			list_add_in_index(stackNuevo->vars,j,new_direc);
		}
		free(tamVars);
		int* key = malloc(sizeof(int));
		*key = i;
		dictionary_put(pcb_Recibido->indice_stack,key,stackNuevo);
	}
	//recibo quantum y quantumSleep
	 return pcb_Recibido;
}
Пример #14
0
int main(int argc, char * argv[]) {

    Dictionary      dict;
    Sentence        sent;
    char            *dictionary_file=NULL;
    char            *post_process_knowledge_file=NULL;
    char            *constituent_knowledge_file=NULL;
    char            *affix_file=NULL;
    int             pp_on=TRUE;
    int             af_on=TRUE;
    int             cons_on=TRUE;
    int             num_linkages, i;
    char            input_string[MAXINPUT];
    Label           label = NO_LABEL;  
    int             parsing_space_leaked, reported_leak, dictionary_and_option_space;


    i = 1;
    if ((argc > 1) && (argv[1][0] != '-')) {
	/* the dictionary is the first argument if it doesn't begin with "-" */
	dictionary_file = argv[1];	
	i++;
    }

    for (; i<argc; i++) {
	if (argv[i][0] == '-') {
	    if (strcmp("-pp", argv[i])==0) {
		if ((post_process_knowledge_file != NULL) || (i+1 == argc)) 
		  print_usage(argv[0]);
		post_process_knowledge_file = argv[i+1];
		i++;
	    } else 
	    if (strcmp("-c", argv[i])==0) {
		if ((constituent_knowledge_file != NULL) || (i+1 == argc)) 
		  print_usage(argv[0]);
		constituent_knowledge_file = argv[i+1];
		i++;
	    } else 
	    if (strcmp("-a", argv[i])==0) {
		if ((affix_file != NULL) || (i+1 == argc)) print_usage(argv[0]);
		affix_file = argv[i+1];
		i++;
	    } else if (strcmp("-ppoff", argv[i])==0) {
		pp_on = FALSE;
	    } else if (strcmp("-coff", argv[i])==0) {
		cons_on = FALSE;
	    } else if (strcmp("-aoff", argv[i])==0) {
		af_on = FALSE;
	    } else if (strcmp("-batch", argv[i])==0) {
	    } else if (strncmp("-!", argv[i],2)==0) {
	    } else {
		print_usage(argv[0]);		
	    }
	} else {
	    print_usage(argv[0]);
	}
    }

    if (!pp_on && post_process_knowledge_file != NULL) print_usage(argv[0]);

    if (dictionary_file == NULL) {
	dictionary_file = "4.0.dict";
        fprintf(stderr, "No dictionary file specified.  Using %s.\n", 
		dictionary_file);
    }

    if (af_on && affix_file == NULL) {
	affix_file = "4.0.affix";
        fprintf(stderr, "No affix file specified.  Using %s.\n", affix_file);
    }

    if (pp_on && post_process_knowledge_file == NULL) {
	post_process_knowledge_file = "4.0.knowledge";
        fprintf(stderr, "No post process knowledge file specified.  Using %s.\n",
		post_process_knowledge_file);
    }

    if (cons_on && constituent_knowledge_file == NULL) {
        constituent_knowledge_file = "4.0.constituent-knowledge"; 
	fprintf(stderr, "No constituent knowledge file specified.  Using %s.\n", 
		constituent_knowledge_file);
    }

    opts = parse_options_create();
    if (opts == NULL) {
	fprintf(stderr, "%s\n", lperrmsg);
	exit(-1);
    }

    panic_parse_opts = parse_options_create();
    if (panic_parse_opts == NULL) {
	fprintf(stderr, "%s\n", lperrmsg);
	exit(-1);
    }
    setup_panic_parse_options(panic_parse_opts);
    parse_options_set_max_sentence_length(opts, 70);
    parse_options_set_panic_mode(opts, TRUE);
    parse_options_set_max_parse_time(opts, 30);
    parse_options_set_linkage_limit(opts, 1000);
    parse_options_set_short_length(opts, 10);

    dict = dictionary_create(dictionary_file, 
			     post_process_knowledge_file,
			     constituent_knowledge_file,
			     affix_file);
    if (dict == NULL) {
	fprintf(stderr, "%s\n", lperrmsg);
	exit(-1);
    }

    /* process the command line like commands */
    for (i=1; i<argc; i++) {
	if ((strcmp("-pp", argv[i])==0) || 
	    (strcmp("-c", argv[i])==0) || 
	    (strcmp("-a", argv[i])==0)) {
	  i++;
	} else if ((argv[i][0] == '-') && (strcmp("-ppoff", argv[i])!=0) &&
		   (argv[i][0] == '-') && (strcmp("-coff", argv[i])!=0) &&
		   (argv[i][0] == '-') && (strcmp("-aoff", argv[i])!=0)) {
	  issue_special_command(argv[i]+1, opts, dict);
	}
    }

    dictionary_and_option_space = space_in_use;  
    reported_leak = external_space_in_use = 0;
    verbosity = parse_options_get_verbosity(opts);

    while (fget_input_string(input_string, stdin, stdout, opts)) {

	if (space_in_use != dictionary_and_option_space + reported_leak) {
	    fprintf(stderr, "Warning: %d bytes of space leaked.\n",
		    space_in_use-dictionary_and_option_space-reported_leak);
	    reported_leak = space_in_use - dictionary_and_option_space;
	}

	if ((strcmp(input_string, "quit\n")==0) ||
	    (strcmp(input_string, "exit\n")==0)) break;

	if (special_command(input_string, dict)) continue;
	if (parse_options_get_echo_on(opts)) {
	    printf("%s", input_string);
	}

	if (parse_options_get_batch_mode(opts)) {
	    label = strip_off_label(input_string);
	}

	sent = sentence_create(input_string, dict);

	if (sent == NULL) {
	    if (verbosity > 0) fprintf(stderr, "%s\n", lperrmsg);
	    if (lperrno != NOTINDICT) exit(-1);
	    else continue;
	} 
	if (sentence_length(sent) > parse_options_get_max_sentence_length(opts)) {
	    sentence_delete(sent);
	    if (verbosity > 0) {
	      fprintf(stdout, 
		      "Sentence length (%d words) exceeds maximum allowable (%d words)\n",
		    sentence_length(sent), parse_options_get_max_sentence_length(opts));
	    }
	    continue;
	}

	/* First parse with cost 0 or 1 and no null links */
	parse_options_set_disjunct_cost(opts, 2);
	parse_options_set_min_null_count(opts, 0);
	parse_options_set_max_null_count(opts, 0);
	parse_options_reset_resources(opts);

	num_linkages = sentence_parse(sent, opts);

	/* Now parse with null links */
	if ((num_linkages == 0) && (!parse_options_get_batch_mode(opts))) {
	    if (verbosity > 0) fprintf(stdout, "No complete linkages found.\n");
	    if (parse_options_get_allow_null(opts)) {
		parse_options_set_min_null_count(opts, 1);
		parse_options_set_max_null_count(opts, sentence_length(sent));
		num_linkages = sentence_parse(sent, opts);
	    }
	}

	if (parse_options_timer_expired(opts)) {
	    if (verbosity > 0) fprintf(stdout, "Timer is expired!\n");
	}
	if (parse_options_memory_exhausted(opts)) {
	    if (verbosity > 0) fprintf(stdout, "Memory is exhausted!\n");
	}

	if ((num_linkages == 0) && 
	    parse_options_resources_exhausted(opts) &&
	    parse_options_get_panic_mode(opts)) {
	    print_total_time(opts);
	    if (verbosity > 0) fprintf(stdout, "Entering \"panic\" mode...\n");
	    parse_options_reset_resources(panic_parse_opts);
	    parse_options_set_verbosity(panic_parse_opts, verbosity);
	    num_linkages = sentence_parse(sent, panic_parse_opts);
	    if (parse_options_timer_expired(panic_parse_opts)) {
		if (verbosity > 0) fprintf(stdout, "Timer is expired!\n");
	    }
	}

	print_total_time(opts);

	if (parse_options_get_batch_mode(opts)) {
	    batch_process_some_linkages(label, sent, opts);
	}
	else {
	    process_some_linkages(sent, opts);
	}

	sentence_delete(sent);
	if (external_space_in_use != 0) {
	    fprintf(stderr, "Warning: %d bytes of external space leaked.\n", 
		    external_space_in_use);
	}
    }

    if (parse_options_get_batch_mode(opts)) {
	print_time(opts, "Total");
	fprintf(stderr, 
		"%d error%s.\n", batch_errors, (batch_errors==1) ? "" : "s");
    }

    parsing_space_leaked = space_in_use - dictionary_and_option_space;
    if (parsing_space_leaked != 0) {
        fprintf(stderr, "Warning: %d bytes of space leaked during parsing.\n", 
		parsing_space_leaked);
    }

    parse_options_delete(panic_parse_opts);
    parse_options_delete(opts);
    dictionary_delete(dict);

    if (space_in_use != parsing_space_leaked) {
        fprintf(stderr, 
		"Warning: %d bytes of dictionary and option space leaked.\n", 
		space_in_use - parsing_space_leaked);
    } 
    else if (parsing_space_leaked == 0) {
        fprintf(stderr, "Good news: no space leaked.\n");
    }

    if (external_space_in_use != 0) {
        fprintf(stderr, "Warning: %d bytes of external space leaked.\n", 
		external_space_in_use);
    }

    return 0;
}
Пример #15
0
int
main(
	void
)
{
	io_printf("%s\n", "I'm a skip list!");
	io_printf("%s\n\n", "Commands:\nInsert (I <key> <value> | 'I 23 test') " \
			"Delete (D <key> | 'D 64') Update (U <key> <new value> | 'U 99 " \
			"muffin')\nQuery (Q <key> | 'Q 16') Print (P | 'P') Find Node (" \
			"F <key> | 'F 72')\n\nX to stop.");

	int key_size, value_size, maxheight;
	key_type_t key_type;
	dictionary_handler_t skip_handler;
	dictionary_t test_dict;

	key_size 	= 4;
	key_type 	= key_type_numeric_signed;
	value_size 	= 10;
	maxheight 	= 7;

	sldict_init(&skip_handler);

	dictionary_create(&skip_handler, &test_dict, key_type, key_size,
														value_size, maxheight);

	char in;
	while( (in = getchar()) != 'X')
	{
#if DEBUG > 0
		io_printf("You said: %c\n", in);
#endif

		switch(in)
		{
			case 'P': {
#if DEBUG > 0
				io_printf("%s\n", "Printing skiplist");
#endif
				print_skiplist((skiplist_t*) test_dict.instance);
				break;
			}

			case 'I': {
							int		 key;
				unsigned 	char	 value[10];
				scanf("%i %s", &key, value);
#if DEBUG > 0
				io_printf("Inserting (%d|%s)...\n", key, value);
#endif
				dictionary_insert(&test_dict, (ion_key_t) &key, value);
				break;
			}

			case 'D': {
				int key;
				scanf("%i", &key);
#if DEBUG > 0
				io_printf("Deleting (%d)...\n", key);
#endif
				dictionary_delete(&test_dict, (ion_key_t) &key);
				break;
			}

			case 'U': {
							int 	key;
				unsigned 	char 	value[10];
				scanf("%i %s", &key, value);
#if DEBUG > 0
				io_printf("Updating (%d with %s)...\n", key, value);
#endif
				dictionary_update(&test_dict, (ion_key_t) &key, value);
				break;
			}

			case 'Q': {
							int 	key;
				unsigned 	char 	value[10];
				scanf("%i", &key);
#if DEBUG > 0
				io_printf("Querying (%d)...\n", key);
#endif
				dictionary_get(&test_dict, (ion_key_t) &key, value);
				io_printf("Got the value back of '%s' stored in %d.\n", value,
																		key);
				break;
			}
			case 'F': {
				int key;
				scanf("%i", &key);
#if DEBUG > 0
				io_printf("Finding Node (%d)...\n", key);
#endif
				sl_node_t 	*node = sl_find_node(
										(skiplist_t*) test_dict.instance,
										(ion_key_t) &key
									);
				io_printf("Got back node, key '%d'.\n",
							NULL != node->key ? *((int*) node->key) : -1337);
				break;
			}
		}

		io_printf("%s", "\n");
		getchar(); /* Eat newline */
	}

	dictionary_delete_dictionary(&test_dict);
	return 0;
}
static inline void do_disk_space_stats(struct mountinfo *mi, int update_every) {
    const char *family = mi->mount_point;
    const char *disk = mi->persistent_id;

    static SIMPLE_PATTERN *excluded_mountpoints = NULL;
    static SIMPLE_PATTERN *excluded_filesystems = NULL;
    int do_space, do_inodes;

    if(unlikely(!dict_mountpoints)) {
        SIMPLE_PREFIX_MODE mode = SIMPLE_PATTERN_EXACT;

        if(config_move("plugin:proc:/proc/diskstats", "exclude space metrics on paths", CONFIG_SECTION_DISKSPACE, "exclude space metrics on paths") != -1) {
            // old configuration, enable backwards compatibility
            mode = SIMPLE_PATTERN_PREFIX;
        }

        excluded_mountpoints = simple_pattern_create(
                config_get(CONFIG_SECTION_DISKSPACE, "exclude space metrics on paths", DELAULT_EXLUDED_PATHS),
                mode
        );

        excluded_filesystems = simple_pattern_create(
                config_get(CONFIG_SECTION_DISKSPACE, "exclude space metrics on filesystems", DEFAULT_EXCLUDED_FILESYSTEMS),
                SIMPLE_PATTERN_EXACT
        );

        dict_mountpoints = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED);
    }

    struct mount_point_metadata *m = dictionary_get(dict_mountpoints, mi->mount_point);
    if(unlikely(!m)) {
        char var_name[4096 + 1];
        snprintfz(var_name, 4096, "plugin:proc:diskspace:%s", mi->mount_point);

        int def_space = config_get_boolean_ondemand(CONFIG_SECTION_DISKSPACE, "space usage for all disks", CONFIG_BOOLEAN_AUTO);
        int def_inodes = config_get_boolean_ondemand(CONFIG_SECTION_DISKSPACE, "inodes usage for all disks", CONFIG_BOOLEAN_AUTO);

        if(unlikely(simple_pattern_matches(excluded_mountpoints, mi->mount_point))) {
            def_space = CONFIG_BOOLEAN_NO;
            def_inodes = CONFIG_BOOLEAN_NO;
        }

        if(unlikely(simple_pattern_matches(excluded_filesystems, mi->filesystem))) {
            def_space = CONFIG_BOOLEAN_NO;
            def_inodes = CONFIG_BOOLEAN_NO;
        }

        // check if the mount point is a directory #2407
        {
            struct stat bs;
            if(stat(mi->mount_point, &bs) == -1) {
                error("DISKSPACE: Cannot stat() mount point '%s' (disk '%s', filesystem '%s', root '%s')."
                      , mi->mount_point
                      , disk
                      , mi->filesystem?mi->filesystem:""
                      , mi->root?mi->root:""
                );
                def_space = CONFIG_BOOLEAN_NO;
                def_inodes = CONFIG_BOOLEAN_NO;
            }
            else {
                if((bs.st_mode & S_IFMT) != S_IFDIR) {
                    error("DISKSPACE: Mount point '%s' (disk '%s', filesystem '%s', root '%s') is not a directory."
                          , mi->mount_point
                          , disk
                          , mi->filesystem?mi->filesystem:""
                          , mi->root?mi->root:""
                    );
                    def_space = CONFIG_BOOLEAN_NO;
                    def_inodes = CONFIG_BOOLEAN_NO;
                }
            }
        }

        do_space = config_get_boolean_ondemand(var_name, "space usage", def_space);
        do_inodes = config_get_boolean_ondemand(var_name, "inodes usage", def_inodes);

        struct mount_point_metadata mp = {
                .do_space = do_space,
                .do_inodes = do_inodes,
                .shown_error = 0,
                .updated = 0,

                .collected = 0,

                .st_space = NULL,
                .rd_space_avail = NULL,
                .rd_space_used = NULL,
                .rd_space_reserved = NULL,

                .st_inodes = NULL,
                .rd_inodes_avail = NULL,
                .rd_inodes_used = NULL,
                .rd_inodes_reserved = NULL
        };

        m = dictionary_set(dict_mountpoints, mi->mount_point, &mp, sizeof(struct mount_point_metadata));
    }

    m->updated = 1;

    if(unlikely(m->do_space == CONFIG_BOOLEAN_NO && m->do_inodes == CONFIG_BOOLEAN_NO))
        return;

    if(unlikely(mi->flags & MOUNTINFO_READONLY && !m->collected))
        return;

    struct statvfs buff_statvfs;
    if (statvfs(mi->mount_point, &buff_statvfs) < 0) {
        if(!m->shown_error) {
            error("DISKSPACE: failed to statvfs() mount point '%s' (disk '%s', filesystem '%s', root '%s')"
                  , mi->mount_point
                  , disk
                  , mi->filesystem?mi->filesystem:""
                  , mi->root?mi->root:""
            );
            m->shown_error = 1;
        }
        return;
    }
    m->shown_error = 0;

    // logic found at get_fs_usage() in coreutils
    unsigned long bsize = (buff_statvfs.f_frsize) ? buff_statvfs.f_frsize : buff_statvfs.f_bsize;

    fsblkcnt_t bavail         = buff_statvfs.f_bavail;
    fsblkcnt_t btotal         = buff_statvfs.f_blocks;
    fsblkcnt_t bavail_root    = buff_statvfs.f_bfree;
    fsblkcnt_t breserved_root = bavail_root - bavail;
    fsblkcnt_t bused;
    if(likely(btotal >= bavail_root))
        bused = btotal - bavail_root;
    else
        bused = bavail_root - btotal;

#ifdef NETDATA_INTERNAL_CHECKS
    if(unlikely(btotal != bavail + breserved_root + bused))
        error("DISKSPACE: disk block statistics for '%s' (disk '%s') do not sum up: total = %llu, available = %llu, reserved = %llu, used = %llu", mi->mount_point, disk, (unsigned long long)btotal, (unsigned long long)bavail, (unsigned long long)breserved_root, (unsigned long long)bused);
#endif

    // --------------------------------------------------------------------------

    fsfilcnt_t favail         = buff_statvfs.f_favail;
    fsfilcnt_t ftotal         = buff_statvfs.f_files;
    fsfilcnt_t favail_root    = buff_statvfs.f_ffree;
    fsfilcnt_t freserved_root = favail_root - favail;
    fsfilcnt_t fused          = ftotal - favail_root;

#ifdef NETDATA_INTERNAL_CHECKS
    if(unlikely(btotal != bavail + breserved_root + bused))
        error("DISKSPACE: disk inode statistics for '%s' (disk '%s') do not sum up: total = %llu, available = %llu, reserved = %llu, used = %llu", mi->mount_point, disk, (unsigned long long)ftotal, (unsigned long long)favail, (unsigned long long)freserved_root, (unsigned long long)fused);
#endif

    // --------------------------------------------------------------------------

    int rendered = 0;

    if(m->do_space == CONFIG_BOOLEAN_YES || (m->do_space == CONFIG_BOOLEAN_AUTO && (bavail || breserved_root || bused))) {
        if(unlikely(!m->st_space)) {
            m->do_space = CONFIG_BOOLEAN_YES;
            m->st_space = rrdset_find_bytype_localhost("disk_space", disk);
            if(unlikely(!m->st_space)) {
                char title[4096 + 1];
                snprintfz(title, 4096, "Disk Space Usage for %s [%s]", family, mi->mount_source);
                m->st_space = rrdset_create_localhost(
                        "disk_space"
                        , disk
                        , NULL
                        , family
                        , "disk.space"
                        , title
                        , "GB"
                        , 2023
                        , update_every
                        , RRDSET_TYPE_STACKED
                );
            }

            m->rd_space_avail    = rrddim_add(m->st_space, "avail", NULL, (collected_number)bsize, 1024 * 1024 * 1024, RRD_ALGORITHM_ABSOLUTE);
            m->rd_space_used     = rrddim_add(m->st_space, "used", NULL, (collected_number)bsize, 1024 * 1024 * 1024, RRD_ALGORITHM_ABSOLUTE);
            m->rd_space_reserved = rrddim_add(m->st_space, "reserved_for_root", "reserved for root", (collected_number)bsize, 1024 * 1024 * 1024, RRD_ALGORITHM_ABSOLUTE);
        }
        else
            rrdset_next(m->st_space);

        rrddim_set_by_pointer(m->st_space, m->rd_space_avail,    (collected_number)bavail);
        rrddim_set_by_pointer(m->st_space, m->rd_space_used,     (collected_number)bused);
        rrddim_set_by_pointer(m->st_space, m->rd_space_reserved, (collected_number)breserved_root);
        rrdset_done(m->st_space);

        rendered++;
    }

    // --------------------------------------------------------------------------

    if(m->do_inodes == CONFIG_BOOLEAN_YES || (m->do_inodes == CONFIG_BOOLEAN_AUTO && (favail || freserved_root || fused))) {
        if(unlikely(!m->st_inodes)) {
            m->do_inodes = CONFIG_BOOLEAN_YES;
            m->st_inodes = rrdset_find_bytype_localhost("disk_inodes", disk);
            if(unlikely(!m->st_inodes)) {
                char title[4096 + 1];
                snprintfz(title, 4096, "Disk Files (inodes) Usage for %s [%s]", family, mi->mount_source);
                m->st_inodes = rrdset_create_localhost(
                        "disk_inodes"
                        , disk
                        , NULL
                        , family
                        , "disk.inodes"
                        , title
                        , "Inodes"
                        , 2024
                        , update_every
                        , RRDSET_TYPE_STACKED
                );
            }

            m->rd_inodes_avail    = rrddim_add(m->st_inodes, "avail", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
            m->rd_inodes_used     = rrddim_add(m->st_inodes, "used", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
            m->rd_inodes_reserved = rrddim_add(m->st_inodes, "reserved_for_root", "reserved for root", 1, 1, RRD_ALGORITHM_ABSOLUTE);
        }
        else
            rrdset_next(m->st_inodes);

        rrddim_set_by_pointer(m->st_inodes, m->rd_inodes_avail,    (collected_number)favail);
        rrddim_set_by_pointer(m->st_inodes, m->rd_inodes_used,     (collected_number)fused);
        rrddim_set_by_pointer(m->st_inodes, m->rd_inodes_reserved, (collected_number)freserved_root);
        rrdset_done(m->st_inodes);

        rendered++;
    }

    // --------------------------------------------------------------------------

    if(likely(rendered))
        m->collected++;
}
Пример #17
0
// **************************************************************************************************
// ******************************************    MAIN     ***************************************
// **************************************************************************************************
int main(int argc, char **argv) {

	//Threads
	pthread_t thread_UMC;
	pthread_t thread_CPU;

	sem_init(&semaforoProgramasACargar,0,0);
	sem_init(&sem_READY_dispo,0,0);
	sem_init(&sem_EXIT_dispo,0,0);
	sem_init(&sem_BLOCK_dispo,0,0);
	sem_init(&sem_REJECT_dispo,0,0);
//	sem_init(&sem_cpus_dispo,0,0);

	//declaro indice etiquetas
	t_dictionary indiceEtiquetas;

	dict_pid_consola = dictionary_create();
//	dict_variables = dictionary_create();

	// Inicializa el log.
	logger = log_create("../nucleo.log", "NUCLEO", 1, LOG_LEVEL_TRACE);

	//inizializa logs de prueba
	log_procesador_Exit = log_create("../procesador_EXIT.log", "procesador_EXIT", 1, LOG_LEVEL_TRACE);
	log_procesador_Block = log_create("../procesador_BLOCK.log", "procesador_BLOCK", 1, LOG_LEVEL_TRACE);
	log_procesador_Reject = log_create("../procesador_REJECT.log", "procesador_REJECT", 1, LOG_LEVEL_TRACE);
	//crear listas
//	cpus_dispo = list_create();
	proc_New = list_create();
	proc_Ready = list_create();
	proc_Block = list_create();
	proc_Reject = list_create();
	proc_Exit = list_create();
	proc_Exec = list_create();
	programas_para_procesar = list_create();
//	EXIT
	//Leo archivo de configuracion ------------------------------
	reg_config = get_config_params();



//Administrador de UMC----------------------
	if(pthread_create( &thread_UMC, NULL , procesos_UMC, NULL) < 0)
		{
			log_debug(logger, "No fue posible crear thread para UMC");
			exit(EXIT_FAILURE);
		}
	log_debug(logger, "Creacion Thread para procesos con UMC");


// Crear thread para atender los procesos CPU
	if( pthread_create( &thread_CPU, NULL , atender_conexion_CPU, NULL) < 0)
	{
		log_debug(logger, "No fue posible crear thread para CPU");
		exit(EXIT_FAILURE);
	}
	log_debug(logger, "Creacion Thread para Atender Conexiones CPU");


	//Crear thread para atender los procesos consola
	pthread_t thread_consola;
	if( pthread_create( &thread_consola , NULL , atender_conexion_consolas, NULL) < 0)
	{
		log_debug(logger, "No fue posible crear thread p/ consolas");
		exit(EXIT_FAILURE);
	}
	log_debug(logger, "Creacion Thread para Atender Conexiones Consola");

//Crear thread Administrador de cola EXIT
	pthread_t thread_EXIT_admin;
	if( pthread_create( &thread_EXIT_admin, NULL , administrar_cola_Exit, NULL) < 0)
	{
		log_debug(logger, "No fue posible crear thread Admin de EXIT");
		exit(EXIT_FAILURE);
	}
	log_debug(logger, "Creacion Thread para Procesar cola EXIT");

//Crear thread Administrador de cola BLOCK
	pthread_t thread_BLOCK_admin;
	if( pthread_create( &thread_BLOCK_admin, NULL , administrar_cola_Block, NULL) < 0)
	{
		log_debug(logger, "No fue posible crear thread Admin de EXIT");
		exit(EXIT_FAILURE);
	}
	log_debug(logger, "Creacion Thread para Procesar cola BLOCK");

//Crear thread Administrador de cola REJECT
	pthread_t thread_REJECT_admin;
	if( pthread_create( &thread_REJECT_admin, NULL , administrar_cola_Reject, NULL) < 0)
	{
		log_debug(logger, "No fue posible crear thread Admin de REJECT");
		exit(EXIT_FAILURE);
	}
	log_debug(logger, "Creacion Thread para Procesar cola REJECT");


	pthread_join(thread_CPU, NULL);
	log_destroy(logger);
	return 0;

}
Пример #18
0
/*******************************************************************************************
*   This functions parses a list of sentences and outputs the results to seperate files in 
*   the out directory,
*   The files are indexed as out_x_y, where x is the index of the sentence in the array and y
*   is the index of the linkage
*******************************************************************************************/
void normal_parse(char input_string[][200], int unify_features, int all_linkages, int out_to_file){

    Dictionary    dict;
    Parse_Options opts;
	int n;
	Sentence      sent;
    Linkage       linkage;
    char *        diagram;
    int           i, num_linkages;
    char          txfilename[30];
	FILE *		  fp;


	opts  = parse_options_create();
	parse_options_set_display_walls(opts, TRUE);
	parse_options_set_display_postscript(opts, TRUE);
	parse_options_set_unify_features(opts, unify_features);

    dict  = dictionary_create("4.0.dict", "4.0.knowledge", NULL, NULL, "morphology/morphemes.dict");
	if (!dict){
		fprintf(stderr, "%s\n", lperrmsg);
	    parse_options_delete(opts);
		printf("size : %lld", space_in_use);
		exit(0);
	}

	//setting opts->unify_features to TRUE enables unification
	for (n=0; strcmp (input_string[n],"end")!=0; n++ ){
		sent = sentence_create(input_string[n], dict);
		if (!sent){
			fprintf(stderr, "%s\n", lperrmsg);
			dictionary_delete(dict);
			parse_options_delete(opts);
			exit(0);
		}
		printf ("\n************************************\n%d-%s\n************************************\n", n+1, input_string[n]);
		num_linkages = sentence_parse(sent, opts);
		num_linkages = (all_linkages) ? num_linkages : (num_linkages!=0)*1 ;
		//Echos all linkages to screen, ps file and text file in ./out directory
		for (i=0; i<num_linkages; ++i) {
			linkage = linkage_create(i , sent, opts);
			diagram = linkage_print_diagram(linkage);

			printf ("\n Linkage No. %d-%d\n\n", n+1, i+1);
			printf("%s\n", diagram);
			if (out_to_file){
				sprintf(txfilename,"out/src-%d-%d.txt", n+1, i+1);
				fp=fopen(txfilename,"w+");
                if (fp==NULL){
                    fprintf(stderr, "%s%s\n", "Unable to open ", txfilename);
                    printf("size : %lld", space_in_use);
                    exit(0);
                }
				fprintf(fp,"%s",diagram);
				fclose(fp);
			}
			string_delete(diagram);
			linkage_delete(linkage);
 		}
		sentence_delete(sent);
	}

    dictionary_delete(dict);
    parse_options_delete(opts);

}
Пример #19
0
int registry_init(void) {
    char filename[FILENAME_MAX + 1];

    // registry enabled?
    if(web_server_mode != WEB_SERVER_MODE_NONE) {
        registry.enabled = config_get_boolean(CONFIG_SECTION_REGISTRY, "enabled", 0);
    }
    else {
        info("Registry is disabled - use the central netdata");
        config_set_boolean(CONFIG_SECTION_REGISTRY, "enabled", 0);
        registry.enabled = 0;
    }

    // pathnames
    snprintfz(filename, FILENAME_MAX, "%s/registry", netdata_configured_varlib_dir);
    registry.pathname = config_get(CONFIG_SECTION_REGISTRY, "registry db directory", filename);
    if(mkdir(registry.pathname, 0770) == -1 && errno != EEXIST)
        fatal("Cannot create directory '%s'.", registry.pathname);

    // filenames
    snprintfz(filename, FILENAME_MAX, "%s/netdata.public.unique.id", registry.pathname);
    registry.machine_guid_filename = config_get(CONFIG_SECTION_REGISTRY, "netdata unique id file", filename);

    snprintfz(filename, FILENAME_MAX, "%s/registry.db", registry.pathname);
    registry.db_filename = config_get(CONFIG_SECTION_REGISTRY, "registry db file", filename);

    snprintfz(filename, FILENAME_MAX, "%s/registry-log.db", registry.pathname);
    registry.log_filename = config_get(CONFIG_SECTION_REGISTRY, "registry log file", filename);

    // configuration options
    registry.save_registry_every_entries = (unsigned long long)config_get_number(CONFIG_SECTION_REGISTRY, "registry save db every new entries", 1000000);
    registry.persons_expiration = config_get_number(CONFIG_SECTION_REGISTRY, "registry expire idle persons days", 365) * 86400;
    registry.registry_domain = config_get(CONFIG_SECTION_REGISTRY, "registry domain", "");
    registry.registry_to_announce = config_get(CONFIG_SECTION_REGISTRY, "registry to announce", "https://registry.my-netdata.io");
    registry.hostname = config_get(CONFIG_SECTION_REGISTRY, "registry hostname", netdata_configured_hostname);
    registry.verify_cookies_redirects = config_get_boolean(CONFIG_SECTION_REGISTRY, "verify browser cookies support", 1);

    setenv("NETDATA_REGISTRY_HOSTNAME", registry.hostname, 1);
    setenv("NETDATA_REGISTRY_URL", registry.registry_to_announce, 1);

    registry.max_url_length = (size_t)config_get_number(CONFIG_SECTION_REGISTRY, "max URL length", 1024);
    if(registry.max_url_length < 10) {
        registry.max_url_length = 10;
        config_set_number(CONFIG_SECTION_REGISTRY, "max URL length", (long long)registry.max_url_length);
    }

    registry.max_name_length = (size_t)config_get_number(CONFIG_SECTION_REGISTRY, "max URL name length", 50);
    if(registry.max_name_length < 10) {
        registry.max_name_length = 10;
        config_set_number(CONFIG_SECTION_REGISTRY, "max URL name length", (long long)registry.max_name_length);
    }

    // initialize entries counters
    registry.persons_count = 0;
    registry.machines_count = 0;
    registry.usages_count = 0;
    registry.urls_count = 0;
    registry.persons_urls_count = 0;
    registry.machines_urls_count = 0;

    // initialize memory counters
    registry.persons_memory = 0;
    registry.machines_memory = 0;
    registry.urls_memory = 0;
    registry.persons_urls_memory = 0;
    registry.machines_urls_memory = 0;

    // initialize locks
    netdata_mutex_init(&registry.lock);

    // create dictionaries
    registry.persons = dictionary_create(DICTIONARY_FLAGS);
    registry.machines = dictionary_create(DICTIONARY_FLAGS);
    avl_init(&registry.registry_urls_root_index, registry_url_compare);

    // load the registry database
    if(registry.enabled) {
        registry_log_open();
        registry_db_load();
        registry_log_load();

        if(unlikely(registry_db_should_be_saved()))
            registry_db_save();
    }

    return 0;
}
Пример #20
0
/*******************************************************************************************
*   This functions translats a list of sentences in the input_string array,
*   terminates when it finds "end" in the array
*   Inputs: input_string: Array of sentences
*           all_linkages: if true, translate all possible linkages of the sentence
*           out_to_file : if true, outputs the results to seperate files in the out directory,
*                       the out files names would be something like :
                        src-x-y: Contains a linkage for the source sentence, x is the index
                                 of sentence in the array and y is the index of linkage
                        trg-x-y-z: Contains a linklage for the target sentence, x is the index
                                   of sentence in the array, y is the index of linkage and z
                                   is the zth translation of that linkage x-y(a linkage in the
                                   source language may have more than one correspondent target
*                                  linkage)
*******************************************************************************************/
void translate(char  input_string[][200], int all_linkages, int out_to_file){
    Dictionary    dict;
    Parse_Options opts;
    Sentence      sent;
    Linkage       src_linkage, trg_linkage;
	Transfer trans;
    char *        diagram;
	FILE *		  fp;
    int           i,  j, num_src_linkages, num_trg_linkages;
    //char        filename[30], txfilename[30], filenum[4];
    char          txfilename[30];
    char          output_string[200];
	int n;

	opts  = parse_options_create();
	parse_options_set_verbosity (opts, FALSE);
	parse_options_set_display_walls(opts, TRUE);
	parse_options_set_display_postscript(opts, TRUE);

    dict  = dictionary_create("4.0.dict", "4.0.knowledge", NULL, NULL, "morphology/morphemes.dict");
	if (!dict){
		fprintf(stderr, "%s\n", lperrmsg);
	    parse_options_delete(opts);
		printf("size : %lld", space_in_use);
		exit(0);
	}
	trans=transfer_create("translation/mapfile.txt", "translation/links_list.txt","translation/lexicon.txt", "target/trg.dict" );
	if (!trans){
		fprintf(stderr, "%s\n", maperrmsg);
		fprintf(stderr, "%s\n", lperrmsg);
		printf("size : %lld", space_in_use);
		exit(0);
	}

	for (n=0; strcmp (input_string[n],"end")!=0; n++ ){

		sent = sentence_create(input_string[n], dict);
		if (!sent){
			fprintf(stderr, "%s\n", lperrmsg);
			parse_options_delete(opts);
			printf("size : %lld", space_in_use);
			exit(0);
		}
		printf ("\n************************************\n%d-%s\n************************************\n", n+1, input_string[n]);
		num_src_linkages = sentence_parse(sent, opts);

		num_src_linkages = (all_linkages) ? num_src_linkages: (num_src_linkages!=0)*1;

		for (i=0; i<num_src_linkages;i++) {
			src_linkage = linkage_create(i, sent, opts);
			diagram = linkage_print_diagram(src_linkage);

			printf ("\nLinkage No. %d-%d\n\n", n+1, i+1);
			printf("%s\n", diagram);
			if (out_to_file){
				sprintf(txfilename,"out/src-%d-%d.txt", n+1, i+1);
				fp=fopen(txfilename,"w+");
				if (fp==NULL){
                    fprintf(stderr, "%s%s\n", "Unable to open ", txfilename);
                    printf("size : %lld", space_in_use);
                    exit(0);
				}
				fprintf(fp,"%s",diagram);
				fclose(fp);
			}
			string_delete(diagram);

			num_trg_linkages = transfer_linkage_driver(trans, src_linkage);
			if(num_trg_linkages==0){
				fprintf(stderr, "%s\n", maperrmsg);
			}
			else{
				parse_options_set_display_walls (trans->opts, TRUE);
				for (j=0; j<num_trg_linkages; j++){
					//second parameter should always be 0 !?
					trg_linkage=trans_linkage_create(trans, 0, trans->sent[j], trans->opts);
					diagram = linkage_print_diagram(trg_linkage);

					printf ("\nTranslation No. %d_%d_%d\n\n", n+1,i+1,j+1);
                    printf("Translation: %s\n", output_string);
					printf("%s\n", diagram);
					if (out_to_file){
                        sprintf(txfilename,"out/trg-%d-%d-%d.txt", n+1, i+1, j+1);
						fp=fopen(txfilename,"w+");
                        if (fp==NULL){
                            fprintf(stderr, "%s%s\n", "Unable to open ", txfilename);
                            printf("size : %lld", space_in_use);
                            exit(0);
                        }
                        extract_sent (trg_linkage, output_string);
                        fprintf(fp, "Translation:%s\n", output_string);
						fprintf(fp,"%s",diagram);
						fclose(fp);
					}
					string_delete(diagram);
					linkage_delete(trg_linkage);
				}
			}
			linkage_delete(src_linkage);
		}
		fprintf(stderr, "%s\n", lperrmsg);
		sentence_delete(sent);

	}


	transfer_delete(trans);
    dictionary_delete(dict);
    parse_options_delete(opts);

}