Main.c 13.4 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
#include "computing_func.h"
8
9
10
11
12
13
//#include "../IOcodes/read_ini.h"
//#include "../IOcodes/results.h"
//#include "../malleability/ProcessDist.h"
#include "../malleability/CommDist.h" //TODO Refactor para que no haga falta
#include "../malleability/malleabilityManager.h"
#include "../malleability/malleabilityStates.h"
14
15
16

#define ROOT 0

iker_martin's avatar
iker_martin committed
17
int work();
18
/*void Sons_init();
iker_martin's avatar
iker_martin committed
19

20
int checkpoint(int iter, int state, MPI_Request **comm_req);
21
int TC(int numS, int comm_type);
22
int start_redistribution(int iter, int numS, MPI_Request **comm_req);
23
int check_redistribution(int iter, MPI_Request **comm_req);
24
25
26
int end_redistribution(int iter);

int thread_creation();
27
int thread_check(int iter);
28
void* thread_async_work(void* void_arg);
29
*/
30
void iterate(double *matrix, int n, int async_comm);
31

32
void init_group_struct(char *argv[], int argc, int myId, int numP);
33
void init_application();
34
void obtain_op_times();
35
36
void free_application_data();

37
void print_general_info(int myId, int grp, int numP);
38
int print_local_results();
39
int print_final_results();
iker_martin's avatar
iker_martin committed
40
int create_out_file(char *nombre, int *ptr, int newstdout);
41

iker_martin's avatar
iker_martin committed
42
43
44
45
typedef struct {
  int myId;
  int numP;
  int grp;
46
  int iter_start;
47
  int argc;
iker_martin's avatar
iker_martin committed
48

49
  int numS; // Cantidad de procesos hijos
iker_martin's avatar
iker_martin committed
50
  MPI_Comm children, parents;
51
52

  char *compute_comm_array;
iker_martin's avatar
iker_martin committed
53
  char **argv;
54
  char *sync_array, *async_array;
iker_martin's avatar
iker_martin committed
55
56
57
58
} group_data;

configuration *config_file;
group_data *group;
59
results_data *results;
60
MPI_Comm comm;
61
int run_id = 0; // Utilizado para diferenciar más fácilmente ejecuciones en el análisis
62

63
int main(int argc, char *argv[]) {
64
    int numP, myId, res;
iker_martin's avatar
iker_martin committed
65
    int req;
66
    int im_child;
67

68
    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &req);
69
    MPI_Comm_size(MPI_COMM_WORLD, &numP);
iker_martin's avatar
iker_martin committed
70
    MPI_Comm_rank(MPI_COMM_WORLD, &myId);
71
    comm = MPI_COMM_WORLD;
iker_martin's avatar
iker_martin committed
72

73
74
75
76
    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);
    }

77
    init_group_struct(argv, argc, myId, numP);
78
    im_child = init_malleability(myId, numP, ROOT, comm, argv[0]);
79

80
    if(!im_child) {
81
82
      init_application();

83
      set_benchmark_grp(group->grp);
84
85
86
      set_benchmark_configuration(config_file);
      set_benchmark_results(results);

87
      MPI_Barrier(comm);
88
      results->exec_start = MPI_Wtime();
89
90
    } else { //Init hijos
      get_malleability_user_comm(&comm);
91
92
93
      get_benchmark_configuration(&config_file); //No se obtiene bien el archivo
      get_benchmark_results(&results); //No se obtiene bien el archivo
      set_results_post_reconfig(results, group->grp, config_file->sdr, config_file->adr);
94
      printf("HIJOS 2\n"); fflush(stdout); MPI_Barrier(comm);
95

96
97
98
      if(config_file->comm_tam) {
        group->compute_comm_array = malloc(config_file->comm_tam * sizeof(char));
      }
99
100
101
102
103
104
105
106
107
108
109
110
111
112

      int entries;
      void *value = NULL;

      malleability_get_entries(&entries, 1, 1);

      malleability_get_data(&value, 0, 1, 1);
      group->grp = *((int *)value);
      free(value);
      malleability_get_data(&value, 1, 1, 1);
      run_id = *((int *)value);
      free(value);

      group->grp = group->grp + 1;
113
114
    }

115
116
117
118
    int spawn_type = COMM_SPAWN_MERGE; // TODO Pasar a CONFIG
    int spawn_is_single = COMM_SPAWN_MULTIPLE; // TODO Pasar a CONFIG
    group->grp = group->grp - 1; // TODO REFACTOR???
    do {
119

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
      group->grp = group->grp + 1;
      set_benchmark_grp(group->grp);
      get_malleability_user_comm(&comm);
      MPI_Comm_size(comm, &(group->numP));
      MPI_Comm_rank(comm, &(group->myId));
      printf("MAIN 2\n"); fflush(stdout); MPI_Barrier(comm);

      if(config_file->resizes != group->grp + 1) { 
        set_malleability_configuration(spawn_type, spawn_is_single, config_file->phy_dist[group->grp+1], -1, config_file->aib, -1);
        set_children_number(config_file->procs[group->grp+1]); // TODO TO BE DEPRECATED

        if(group->grp == 0) {
          malleability_add_data(&(group->grp), 1, MAL_INT, 1, 1);
          malleability_add_data(&run_id, 1, MAL_INT, 1, 1);
        }
135
      }
136
137
138
139
140
141
      printf("MAIN 3\n"); fflush(stdout); MPI_Barrier(comm);

      res = work();

      print_local_results();
    } while((config_file->resizes > group->grp + 1) && (spawn_type == COMM_SPAWN_MERGE || spawn_type == COMM_SPAWN_MERGE_PTHREAD));
142

143

144
    if(res) { // Se he llegado al final de la aplicacion
145
//      MPI_Barrier(comm); FIXME?
146
      results->exec_time = MPI_Wtime() - results->exec_start;
147
    }
148

149
    print_final_results(); // Pasado este punto ya no pueden escribir los procesos
150
    MPI_Finalize();
151
    free_application_data();
152

153
154
155
156
    return 0;
}

/*
157
158
159
160
161
162
163
164
165
 * 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.
166
167
168
169
 *
 * 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.
170
 */
iker_martin's avatar
iker_martin committed
171
int work() {
172
  int iter, maxiter, state, res;
173
  double *matrix = NULL;
174

iker_martin's avatar
iker_martin committed
175
  maxiter = config_file->iters[group->grp];
176
  //initMatrix(&matrix, config_file->matrix_tam);
177
  state = MAL_NOT_STARTED;
iker_martin's avatar
iker_martin committed
178

179
180
181
182
183
184
185
186
187
  if(group->grp == 0) {
    malleability_add_data(&iter, 1, MAL_INT, 1, 1);
  } else {
    void *value = NULL;
    malleability_get_data(&value, 2, 1, 1);
    group->iter_start = *((int *)value);
    free(value);
  }

188
  res = 0;
189
  for(iter=group->iter_start; iter < maxiter; iter++) {
190
    iterate(matrix, config_file->matrix_tam, state);
191
  }
192
193
194
  if(config_file->iters[group->grp] == iter && config_file->resizes != group->grp + 1)
    state = malleability_checkpoint();

195
  iter = 0;
196
  while(state == MAL_DIST_PENDING || state == MAL_SPAWN_PENDING) {
197
    iterate(matrix, config_file->matrix_tam, state);
198
    iter++;
199
    state = malleability_checkpoint();
200
  }
201
  
202
203
  if(config_file->resizes - 1 == group->grp) res=1;
  return res;
204
205
}

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

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


/*
 * Simula la ejecucción de una iteración de computo en la aplicación
 * que dura al menos un tiempo de "time" segundos.
 */
void iterate(double *matrix, int n, int async_comm) {
  double start_time, actual_time;
  double time = config_file->general_time * config_file->factors[group->grp];
  double Top = config_file->Top;
  int i, operations = 0;
  double aux = 0;

  start_time = actual_time = MPI_Wtime();

  operations = time / Top; //FIXME Calcular una sola vez
  for(i=0; i < operations; i++) {
    aux += computePiSerial(n);
  }

  if(config_file->comm_tam) {
233
    MPI_Bcast(group->compute_comm_array, config_file->comm_tam, MPI_CHAR, ROOT, comm);
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
  }

  actual_time = MPI_Wtime(); // Guardar tiempos
  // TODO Que diferencie entre ambas en el IO
  if(async_comm == MAL_DIST_PENDING || async_comm == MAL_SPAWN_PENDING) { // Se esta realizando una redistribucion de datos asincrona
    operations=0;
  }

  if(results->iter_index == results->iters_size) { // Aumentar tamaño de ambos vectores de resultados
    realloc_results_iters(results, results->iters_size + 100);
  }
  results->iters_time[results->iter_index] = actual_time - start_time;
  results->iters_type[results->iter_index] = operations;
  results->iter_index = results->iter_index + 1;
}

//======================================================||
//======================================================||
//=============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);
}

272

273
274
275
/*
 * Pide al proceso raiz imprimir los datos sobre las iteraciones realizadas por el grupo de procesos.
 */
276
277
int print_local_results() {
  int ptr_local, ptr_out, err;
278
279
280
  char *file_name;

  if(group->myId == ROOT) {
281
282
    ptr_out = dup(1);

283
284
285
286
287
288
289
290
291
292
293
    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);
    print_iter_results(*results, config_file->iters[group->grp] -1);
    free(file_name);

294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
    close(1);
    dup(ptr_out);
  }
  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() {
  int ptr_global, err;
  char *file_name;

  if(group->myId == ROOT) {

310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    if(group->grp == config_file->resizes -1) {
      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

      create_out_file(file_name, &ptr_global, 1);
      print_config(config_file, group->grp);
      print_global_results(*results, config_file->resizes);
      free(file_name);
      
    }
  }
  return 0;
}

/*
 * Inicializa la estructura group
 */
void init_group_struct(char *argv[], int argc, int myId, int numP) {
  group = malloc(1 * sizeof(group_data));
  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]);
  }

  config_file = read_ini_file(group->argv[1]);
  results = malloc(sizeof(results_data));
  init_results_data(results, config_file->resizes, config_file->iters[group->grp]);
  if(config_file->comm_tam) {
    group->compute_comm_array = malloc(config_file->comm_tam * sizeof(char));
  }
  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);
  }
   
  obtain_op_times();
}

/*
 * Obtiene cuanto tiempo es necesario para realizar una operacion de PI
 */
void obtain_op_times() {
  double result, start_time = MPI_Wtime();
  int i, qty = 20000;
  result = 0;
  for(i=0; i<qty; i++) {
    result += computePiSerial(config_file->matrix_tam);
  }
  //printf("Creado Top con valor %lf\n", result);
  //fflush(stdout);

  config_file->Top = (MPI_Wtime() - start_time) / qty; //Tiempo de una operacion
388
  MPI_Bcast(&(config_file->Top), 1, MPI_DOUBLE, ROOT, comm);
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
}

/*
 * Libera toda la memoria asociada con la aplicacion
 */
void free_application_data() {
  if(config_file->comm_tam) {
    free(group->compute_comm_array);
  }
  if(config_file->sdr) {
    free(group->sync_array);
  }
  if(config_file->adr) {
    free(group->async_array);
  }
  
405
406
407
  free_malleability();
  free_config(config_file);

408
  if(group->grp == 0) { //FIXME Revisar porque cuando es diferente a 0 no funciona
409
    free_results_data(results);
410
    free(results);
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
  }
  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;
}