Main.c 15.2 KB
Newer Older
1
2
3
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
iker_martin's avatar
iker_martin committed
4
#include <fcntl.h>
5
#include <unistd.h>
iker_martin's avatar
iker_martin committed
6
#include <sys/stat.h>
7
8
#include "process_stage.h"
#include "Main_datatypes.h"
9
#include "configuration.h"
10
#include "../IOcodes/results.h"
11
#include "../malleability/CommDist.h"
12
13
#include "../malleability/malleabilityManager.h"
#include "../malleability/malleabilityStates.h"
14

iker_martin's avatar
iker_martin committed
15
int work();
16
double iterate(int async_comm);
17
18
double iterate_relaxed(double *time, double *times_stages);
double iterate_rigid(double *time, double *times_stages);
19

20
void init_group_struct(char *argv[], int argc, int myId, int numP);
21
void init_application();
22
void obtain_op_times();
23
24
void free_application_data();

25
void print_general_info(int myId, int grp, int numP);
26
int print_local_results();
27
int print_final_results();
iker_martin's avatar
iker_martin committed
28
int create_out_file(char *nombre, int *ptr, int newstdout);
29

iker_martin's avatar
iker_martin committed
30
31
configuration *config_file;
group_data *group;
32
results_data *results;
33
MPI_Comm comm;
34
int run_id = 0; // Utilizado para diferenciar más fácilmente ejecuciones en el análisis
35

36
int main(int argc, char *argv[]) {
37
    int numP, myId, res;
iker_martin's avatar
iker_martin committed
38
    int req;
39
    int im_child;
40

41
    int num_cpus, num_nodes;
42
    char *nodelist = NULL;
43
    num_cpus = 20; //FIXME NUMERO MAGICO //TODO Usar openMP para obtener el valor con un pragma
44
45
46
    if (argc >= 5) {
      nodelist = argv[3];
      num_nodes = atoi(argv[4]);
47
      num_cpus = num_nodes * num_cpus;
48
49
    }

50
    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &req);
iker_martin's avatar
iker_martin committed
51
    MPI_Comm_rank(MPI_COMM_WORLD, &myId);
52
    MPI_Comm_size(MPI_COMM_WORLD, &numP);
53
    comm = MPI_COMM_WORLD;
iker_martin's avatar
iker_martin committed
54

55
56
57
58
    if(req != MPI_THREAD_MULTIPLE) {
      printf("No se ha obtenido la configuración de hilos necesaria\nSolicitada %d -- Devuelta %d\n", req, MPI_THREAD_MULTIPLE);
    }

59
    init_group_struct(argv, argc, myId, numP);
60
    im_child = init_malleability(myId, numP, ROOT, comm, argv[0], nodelist, num_cpus, num_nodes);
61

62
    if(!im_child) { //TODO REFACTOR Simplificar inicio
63
64
      init_application();

65
      set_benchmark_grp(group->grp);
66
67
68
      set_benchmark_configuration(config_file);
      set_benchmark_results(results);

69
70
71
72
73

      malleability_add_data(&(group->grp), 1, MAL_INT, 1, 1);
      malleability_add_data(&run_id, 1, MAL_INT, 1, 1);
      malleability_add_data(&(group->iter_start), 1, MAL_INT, 1, 1);

74
      MPI_Barrier(comm);
75
      results->exec_start = MPI_Wtime();
76
    } else { //Init hijos
77

78
      get_malleability_user_comm(&comm);
79
80
      get_benchmark_configuration(&config_file);
      get_benchmark_results(&results);
81

82
83
      // TODO Refactor - Que sea una unica funcion
      // Obtiene las variables que van a utilizar los hijos
84
85
86
      void *value = NULL;
      malleability_get_data(&value, 0, 1, 1);
      group->grp = *((int *)value);
87

88
89
      malleability_get_data(&value, 1, 1, 1);
      run_id = *((int *)value);
90
91
92
      
      malleability_get_data(&value, 2, 1, 1);
      group->iter_start = *((int *)value);
93

94
      set_results_post_reconfig(results, group->grp, config_file->sdr, config_file->adr); //TODO Cambio al añadir nueva redistribucion
95
      group->grp = group->grp + 1;
96
97
    }

98
99
100
    //
    // EMPIEZA LA EJECUCION-------------------------------
    //
101
102
    group->grp = group->grp - 1; // TODO REFACTOR???
    do {
103
104
105
106

      get_malleability_user_comm(&comm);
      MPI_Comm_size(comm, &(group->numP));
      MPI_Comm_rank(comm, &(group->myId));
107
108
      group->grp = group->grp + 1;
      set_benchmark_grp(group->grp);
109
      if(group->grp != 0) {
110
        obtain_op_times(0); //Obtener los nuevos valores de tiempo para el computo
111
      }
112

113
      if(config_file->n_resizes != group->grp + 1) { //TODO Llevar a otra funcion
114
115
116
        set_malleability_configuration(config_file->groups[group->grp+1].sm, config_file->groups[group->grp+1].ss, 
			config_file->groups[group->grp+1].phy_dist, config_file->groups[group->grp+1].at, -1);
        set_children_number(config_file->groups[group->grp+1].procs); // TODO TO BE DEPRECATED
117

118
119
        if(group->grp != 0) {
          malleability_modify_data(&(group->grp), 0, 1, MAL_INT, 1, 1);
120
        }
121
      }
122
123

      res = work();
124
      if(res == MALL_ZOMBIE) break;
125

126
127
128
129
      if(res==1) { // Se ha llegado al final de la aplicacion
        MPI_Barrier(comm); // TODO Posible error al utilizar SHRINK
        results->exec_time = MPI_Wtime() - results->exec_start - results->wasted_time;
      }
130
      print_local_results();
131
      reset_results_index(results);
132
    } while(config_file->n_resizes > group->grp + 1 && config_file->groups[group->grp+1].sm == MALL_SPAWN_MERGE);
133

134
135
136
    //
    // TERMINA LA EJECUCION ----------------------------------------------------------
    //
137
    print_final_results(); // Pasado este punto ya no pueden escribir los procesos
138

139
    MPI_Barrier(comm);
140
141
142
143
    if(comm != MPI_COMM_WORLD && comm != MPI_COMM_NULL) {
      MPI_Comm_free(&comm);
    }

144
    if(group->myId == ROOT && config_file->groups[group->grp].sm == MALL_SPAWN_MERGE) {
145
146
      MPI_Abort(MPI_COMM_WORLD, -100);
    }
147
    free_application_data(); //FIXME Error al liberar memoria de SDR/ADR
148

149
150
151
152
153
    MPI_Finalize();
    return 0;
}

/*
154
155
156
157
158
159
160
161
162
 * Función de trabajo principal.
 *
 * Incializa los datos para realizar el computo y a continuacion
 * pasa a realizar "maxiter" iteraciones de computo.
 *
 * Terminadas las iteraciones realiza el redimensionado de procesos.
 * Si el redimensionado se realiza de forma asincrona se 
 * siguen realizando iteraciones de computo hasta que termine la 
 * comunicacion asincrona y realizar entonces la sincrona.
163
164
165
166
 *
 * Si el grupo de procesos es el ultimo que va a ejecutar, se devuelve
 * el valor 1 para indicar que no se va a seguir trabajando con nuevos grupos
 * de procesos. En caso contrario se devuelve 0.
167
 */
iker_martin's avatar
iker_martin committed
168
int work() {
169
  int iter, maxiter, state, res;
170

171
  maxiter = config_file->groups[group->grp].iters;
172
  state = MALL_NOT_STARTED;
173

174
  res = 0;
175
  for(iter=group->iter_start; iter < maxiter; iter++) {
176
    iterate(state);
177
  }
178

179
  if(config_file->n_resizes != group->grp + 1)
180
181
    state = malleability_checkpoint();

182
  iter = 0;
183
  while(state == MALL_DIST_PENDING || state == MALL_SPAWN_PENDING || state == MALL_SPAWN_SINGLE_PENDING || state == MALL_SPAWN_ADAPT_POSTPONE) {
184
    if(iter < config_file->groups[group->grp+1].iters) {
185
      iterate(state);
186
187
188
      iter++;
      group->iter_start = iter;
    }
189
    state = malleability_checkpoint();
190
  }
191

192
  
193
  if(config_file->n_resizes - 1 == group->grp) res=1;
194
  if(state == MALL_ZOMBIE) res=state;
195
  return res;
196
197
}

198
199
200
201
202
203
204
205
206
207

/////////////////////////////////////////
/////////////////////////////////////////
//COMPUTE FUNCTIONS
/////////////////////////////////////////
/////////////////////////////////////////


/*
 * Simula la ejecucción de una iteración de computo en la aplicación
208
209
 * que dura al menos un tiempo determinado por la suma de todas las
 * etapas definidas en la configuracion.
210
 */
211
double iterate(int async_comm) {
212
  double time, *times_stages_aux;
213
  size_t i;
214
215
  double aux = 0;

216
  times_stages_aux = malloc(config_file->n_stages * sizeof(double));
217

218
  if(config_file->rigid_times) {
219
    aux = iterate_rigid(&time, times_stages_aux);
220
  } else {
221
    aux = iterate_relaxed(&time, times_stages_aux);
222
223
  }

224
225
  // Se esta realizando una redistribucion de datos asincrona
  if(async_comm == MALL_DIST_PENDING || async_comm == MALL_SPAWN_PENDING || async_comm == MALL_SPAWN_SINGLE_PENDING) { 
226
  // TODO Que diferencie entre ambas en el IO
227
    results->iters_async += 1;
228
229
230
  }

  if(results->iter_index == results->iters_size) { // Aumentar tamaño de ambos vectores de resultados
231
    realloc_results_iters(results, config_file->n_stages, results->iters_size + 100);
232
  }
233
  results->iters_time[results->iter_index] = time;
234
  for(i=0; i < config_file->n_stages; i++) {
235
    results->stage_times[i][results->iter_index] = times_stages_aux[i];
236
  }
237
  results->iter_index = results->iter_index + 1;
238

239
  free(times_stages_aux);
240

241
  return aux;
242
243
}

244
245
246

/*
 * Performs an iteration. The gathered times for iterations
247
 * and stages could be IMPRECISE in order to ensure the 
248
249
250
251
252
 * global execution time is precise.
 */
double iterate_relaxed(double *time, double *times_stages) {
  size_t i;
  double start_time, start_time_stage, aux=0;
253
  start_time = MPI_Wtime(); // Imprecise timings
254
255

  for(i=0; i < config_file->n_stages; i++) {
256
    start_time_stage = MPI_Wtime(); 
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    aux+= process_stage(*config_file, config_file->stages[i], *group, comm);
    times_stages[i] = MPI_Wtime() - start_time_stage;
  }

  *time = MPI_Wtime() - start_time; // Guardar tiempos
  return aux;
}

/*
 * Performs an iteration. The gathered times for iterations
 * and stages are ensured to be precise but the global 
 * execution time could be imprecise.
 */
double iterate_rigid(double *time, double *times_stages) {
  size_t i;
  double start_time, start_time_stage, aux=0;

  MPI_Barrier(comm);
  start_time = MPI_Wtime();

  for(i=0; i < config_file->n_stages; i++) {
278
    MPI_Barrier(comm);
279
280
281
282
283
    start_time_stage = MPI_Wtime();
    aux+= process_stage(*config_file, config_file->stages[i], *group, comm);
    times_stages[i] = MPI_Wtime() - start_time_stage;
  }

284
  MPI_Barrier(comm);
285
286
287
288
  *time = MPI_Wtime() - start_time; // Guardar tiempos
  return aux;
}

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//======================================================||
//======================================================||
//=============INIT/FREE/PRINT FUNCTIONS================||
//======================================================||
//======================================================||

/*
 * Muestra datos generales sobre los procesos, su grupo,
 * en que nodo residen y la version de MPI utilizada.
 */
void print_general_info(int myId, int grp, int numP) {
  int len;
  char *name = malloc(MPI_MAX_PROCESSOR_NAME * sizeof(char));
  char *version = malloc(MPI_MAX_LIBRARY_VERSION_STRING * sizeof(char));
  MPI_Get_processor_name(name, &len);
  MPI_Get_library_version(version, &len);
  printf("P%d Nuevo GRUPO %d de %d procs en nodo %s con %s\n", myId, grp, numP, name, version);

  free(name);
  free(version);
}

311

312
313
314
/*
 * Pide al proceso raiz imprimir los datos sobre las iteraciones realizadas por el grupo de procesos.
 */
315
316
int print_local_results() {
  int ptr_local, ptr_out, err;
317
318
  char *file_name;

319
  compute_results_iter(results, group->myId, group->numP, ROOT, comm);
320
  compute_results_stages(results, group->myId, group->numP, config_file->n_stages, ROOT, comm);
321
  if(group->myId == ROOT) {
322
323
    ptr_out = dup(1);

324
325
326
327
328
329
330
331
    file_name = NULL;
    file_name = malloc(40 * sizeof(char));
    if(file_name == NULL) return -1; // No ha sido posible alojar la memoria
    err = snprintf(file_name, 40, "R%d_G%dNP%dID%d.out", run_id, group->grp, group->numP, group->myId);
    if(err < 0) return -2; // No ha sido posible obtener el nombre de fichero
    create_out_file(file_name, &ptr_local, 1);
  
    print_config_group(config_file, group->grp);
332
    print_iter_results(*results);
333
    print_stage_results(*results, config_file->n_stages);
334
335
    free(file_name);

336
    fflush(stdout);
337
338
    close(1);
    dup(ptr_out);
339
    close(ptr_out);
340
341
342
343
344
345
346
347
348
  }
  return 0;
}

/*
 * Si es el ultimo grupo de procesos, pide al proceso raiz mostrar los datos obtenidos de tiempo de ejecucion, creacion de procesos
 * y las comunicaciones.
 */
int print_final_results() {
349
  int ptr_global, err, ptr_out;
350
351
352
353
  char *file_name;

  if(group->myId == ROOT) {

354
    if(group->grp == config_file->n_resizes -1) {
355
356
357
358
359
360
      file_name = NULL;
      file_name = malloc(20 * sizeof(char));
      if(file_name == NULL) return -1; // No ha sido posible alojar la memoria
      err = snprintf(file_name, 20, "R%d_Global.out", run_id);
      if(err < 0) return -2; // No ha sido posible obtener el nombre de fichero

361
      ptr_out = dup(1);
362
      create_out_file(file_name, &ptr_global, 1);
363
364
      print_config(config_file);
      print_global_results(*results, config_file->n_resizes);
365
      fflush(stdout);
366
      free(file_name);
367
368
369

      close(1);
      dup(ptr_out);
370
371
372
373
374
375
376
377
378
    }
  }
  return 0;
}

/*
 * Inicializa la estructura group
 */
void init_group_struct(char *argv[], int argc, int myId, int numP) {
379
  group = malloc(sizeof(group_data));
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
  group->myId        = myId;
  group->numP        = numP;
  group->grp         = 0;
  group->iter_start  = 0;
  group->argc        = argc;
  group->argv        = argv;
}

/*
 * Inicializa los datos para este grupo de procesos.
 *
 * En caso de ser el primer grupo de procesos, lee el fichero de configuracion
 * e inicializa los vectores de comunicacion.
 *
 * En caso de ser otro grupo de procesos entra a la funcion "Sons_init()" donde
 * se comunican con los padres para inicializar sus datos.
 */
void init_application() {
  if(group->argc < 2) {
    printf("Falta el fichero de configuracion. Uso:\n./programa config.ini id\nEl argumento numerico id es opcional\n");
    MPI_Abort(MPI_COMM_WORLD, -1);
  }
  if(group->argc > 2) {
    run_id = atoi(group->argv[2]);
  }

406
  init_config(group->argv[1], &config_file);
407
  results = malloc(sizeof(results_data));
408
  init_results_data(results, config_file->n_resizes, config_file->n_stages, config_file->groups[group->grp].iters);
409
410
411
412
413
414
  if(config_file->sdr) {
    malloc_comm_array(&(group->sync_array), config_file->sdr , group->myId, group->numP);
  }
  if(config_file->adr) {
    malloc_comm_array(&(group->async_array), config_file->adr , group->myId, group->numP);
  }
415
416

  obtain_op_times(1);
417
418
419
420
}

/*
 * Obtiene cuanto tiempo es necesario para realizar una operacion de PI
421
422
423
424
425
426
427
428
 *
 * Si compute esta a 1 se considera que se esta inicializando el entorno
 * y realizará trabajo extra.
 *
 * Si compute esta a 0 se considera un entorno inicializado y solo hay que
 * realizar algunos cambios de reserva de memoria. Si es necesario recalcular
 * algo se obtiene el total de tiempo utilizado en dichas tareas y se resta
 * al tiempo total de ejecucion.
429
 */
430
void obtain_op_times(int compute) {
431
  size_t i;
432
  double time = 0;
433
  for(i=0; i<config_file->n_stages; i++) {
434
    time+=init_stage(config_file, i, *group, comm, compute);
435
  }
436
  if(!compute) {results->wasted_time += time;}
437
438
439
440
441
442
443
444
445
446
447
448
449
}

/*
 * Libera toda la memoria asociada con la aplicacion
 */
void free_application_data() {
  if(config_file->sdr) {
    free(group->sync_array);
  }
  if(config_file->adr) {
    free(group->async_array);
  }
  
450
451
  free_malleability();

452
  if(group->grp == 0) { //FIXME Revisar porque cuando es diferente a 0 no funciona
453
    free_results_data(results, config_file->n_stages);
454
    free(results);
455
  }
456
  free_config(config_file);
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
  free(group);
}


/* 
 * Función para crear un fichero con el nombre pasado como argumento.
 * Si el nombre ya existe, se escribe la informacion a continuacion.
 *
 * El proceso que llama a la función pasa a tener como salida estandar
 * dicho fichero si el valor "newstdout" es verdadero.
 *
 */
int create_out_file(char *nombre, int *ptr, int newstdout) {
  int err;

  *ptr = open(nombre, O_WRONLY | O_CREAT | O_APPEND, 0644);
  if(*ptr < 0) return -1; // No ha sido posible crear el fichero

  if(newstdout) {
    err = close(1);
    if(err < 0) return -2; // No es posible modificar la salida estandar
    err = dup(*ptr);
    if(err < 0) return -3; // No es posible modificar la salida estandar
  }

  return 0;
}