aboutsummaryrefslogtreecommitdiff
path: root/Carpet/CarpetIOStreamedHDF5/src/CarpetIOStreamedHDF5.cc
blob: 9bdcbd2525f6d4f31cc48cdf2e46a0240b39bdfe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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
233
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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
440
441
442
443
444
445
446
447
448
449
#include <assert.h>

#include "cctk.h"
#include "cctk_Arguments.h"
#include "cctk_Parameters.h"
#include "util_Network.h"

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include "CactusBase/IOUtil/src/ioGH.h"

#include "CarpetIOStreamedHDF5.hh"


namespace CarpetIOStreamedHDF5
{

using namespace std;
using namespace Carpet;
using namespace CarpetIOHDF5;


// Variable definitions
static vector<vector<vector<int> > > last_output; // [ml][rl][var]

// registered GH extension setup routine
static void* SetupGH (tFleshConfig* const fleshconfig,
                      const int convLevel, cGH* const cctkGH);

// callbacks for CarpetIOStreamedHDF5's I/O method
static int OutputGH (const cGH* const cctkGH);
static int TimeToOutput (const cGH* const cctkGH, const int vindex);
static int OutputVar (const cGH* const cctkGH, const ioRequest* const request,
                      hid_t file);

static void CheckSteerableParameters (const cGH *const cctkGH,
                                      CarpetIOStreamedHDF5GH *myGH);

//////////////////////////////////////////////////////////////////////////////
// public routines
//////////////////////////////////////////////////////////////////////////////

void CarpetIOStreamedHDF5_Startup (void)
{
  CCTK_RegisterBanner ("AMR streamed HDF5 output "
                       "provided by CarpetIOStreamedHDF5");

  const int GHExtension = CCTK_RegisterGHExtension (CCTK_THORNSTRING);
  CCTK_RegisterGHExtensionSetupGH (GHExtension, SetupGH);
}


void CarpetIOStreamedHDF5_Init (const cGH* const cctkGH)
{
  DECLARE_CCTK_ARGUMENTS;

  *this_iteration = -1;
  *next_output_iteration = 0;
  *next_output_time = cctk_time;
}


// close the socket used for HDF5 streaming
void CarpetIOStreamedHDF5_Terminate (const cGH* const cctkGH)
{
  CarpetIOStreamedHDF5GH* myGH =
    (CarpetIOStreamedHDF5GH*) CCTK_GHExtension (cctkGH, CCTK_THORNSTRING);

  Socket_CloseSocket (myGH->socket);
}


//////////////////////////////////////////////////////////////////////////////
// private routines
//////////////////////////////////////////////////////////////////////////////
static void* SetupGH (tFleshConfig* const fleshconfig,
                      const int convLevel, cGH* const cctkGH)
{
  DECLARE_CCTK_PARAMETERS;

  // processor 0 opens a socket on the given port to listen for clients
  unsigned int real_port;
  SOCKET real_socket = INVALID_SOCKET;
  if (dist::rank() == 0) {

    real_socket = Socket_TCPOpenServerSocket (port, &real_port, 1);

    if (real_socket == INVALID_SOCKET) {

      CCTK_VWarn (1, __LINE__, __FILE__, CCTK_THORNSTRING,
                  "Couldn't open TCP server socket on output port %d. "
                  "No HDF5 streaming output will be available !", port);

    } else if (Socket_SetNonBlocking (real_socket) < 0) {

      CCTK_WARN (1, "Couldn't set output socket into non-blocking mode. "
                    "No HDF5 streaming output will be available !");
      Socket_CloseSocket (real_socket);
      real_socket = INVALID_SOCKET;

    }
  }

  // broadcast success of socket operation to all processors
  int have_socket = real_socket != INVALID_SOCKET;
  MPI_Bcast (&have_socket, 1, MPI_INT, 0, dist::comm());

  // do not continue here if no socket is available
  if (not have_socket) {
    return (NULL);
  }

  if (dist::rank() == 0) {
    char hostname[256];
    Util_GetHostName (hostname, sizeof (hostname));
    CCTK_VInfo (CCTK_THORNSTRING,
                "data streaming service started on '%s:%u'", hostname, port);
  }

  // register CarpetIOStreamedHDF5's routines as a new I/O method
  const int IOMethod = CCTK_RegisterIOMethod ("IOStreamedHDF5");
  CCTK_RegisterIOMethodOutputGH (IOMethod, OutputGH);
#if 0
  // for now only register the OutputGH() callback
  CCTK_RegisterIOMethodOutputVarAs (IOMethod, OutputVarAs);
  CCTK_RegisterIOMethodTimeToOutput (IOMethod, TimeToOutput);
  CCTK_RegisterIOMethodTriggerOutput (IOMethod, TriggerOutput);
#endif

  if (not CCTK_Equals (verbose, "none")) {
    CCTK_INFO ("I/O Method 'IOStreamedHDF5' registered: AMR streamed HDF5 "
               "output of grid variables");
  }

  const int numvars = CCTK_NumVars ();

  // allocate a new GH extension structure
  CarpetIOStreamedHDF5GH* myGH = new CarpetIOStreamedHDF5GH;

  myGH->out_last.resize(numvars);
  for (int i = 0; i < numvars; i++) {
    myGH->out_last[i] = -1;
  }
  myGH->requests.resize(numvars);
  myGH->out_vars = strdup ("");
  myGH->out_every_default = out_every - 1;

  // initial I/O parameter check
  myGH->stop_on_parse_errors = strict_io_parameter_check;
  CheckSteerableParameters (cctkGH, myGH);
  myGH->stop_on_parse_errors = 0;

  // no iterations have yet been output
  last_output.resize(mglevels);
  for (int i = 0; i < mglevels; i++) {
    last_output[i].resize (maxreflevels);
    for (int j = 0; j < maxreflevels; j++) {
      last_output[i][j].resize (numvars, INT_MIN);
    }
  }

  myGH->socket = real_socket;
  myGH->port = real_port;

  return (myGH);
}


static void CheckSteerableParameters (const cGH *const cctkGH,
                                      CarpetIOStreamedHDF5GH *myGH)
{
  DECLARE_CCTK_PARAMETERS;

  // re-parse the 'IOHDF5::out_vars' parameter if it has changed
  if (strcmp (out_vars, myGH->out_vars)) {
#ifdef IOUTIL_PARSER_HAS_OUT_DT
    IOUtil_ParseVarsForOutput (cctkGH, CCTK_THORNSTRING,
                               "IOStreamedHDF5::out_vars",
                               myGH->stop_on_parse_errors, out_vars,
                               -1, -1.0, &myGH->requests[0]);
#else
    IOUtil_ParseVarsForOutput (cctkGH, CCTK_THORNSTRING,
                               "IOStreamedHDF5::out_vars",
                               myGH->stop_on_parse_errors, out_vars,
                               -1, &myGH->requests[0]);
#endif

    // notify the user about the new setting
    if (not CCTK_Equals (verbose, "none")) {
      int count = 0;
      string msg ("Periodic streamed HDF5 output requested for '");
      for (int i = CCTK_NumVars () - 1; i >= 0; i--) {
        if (myGH->requests[i]) {
          if (count++) {
            msg += "', '";
          }
          char *fullname = CCTK_FullName (i);
          msg += fullname;
          free (fullname);
        }
      }
      if (count) {
        msg += "'";
        CCTK_INFO (msg.c_str());
      }
    }

    // save the last setting of 'IOHDF5::out_vars' parameter
    free (myGH->out_vars);
    myGH->out_vars = strdup (out_vars);
  }
}


static int OutputGH (const cGH* const cctkGH)
{
  int error_count = 0;
  DECLARE_CCTK_PARAMETERS;

  CarpetIOStreamedHDF5GH *myGH =
    (CarpetIOStreamedHDF5GH *) CCTK_GHExtension (cctkGH, CCTK_THORNSTRING);

  static hid_t file = -1;
  static int client_is_ready = 0;

  // loop over all variables
  for (int vindex = CCTK_NumVars () - 1; vindex >= 0; vindex--) {
    if (TimeToOutput (cctkGH, vindex)) {

      // check if any client is ready to receive streamed data
      //
      // Even though this requires a broadcast operation, it should be
      // by far less expensive than gathering all the data on processor 0
      // and find out afterwards that no client wants to have it.
      if (not client_is_ready) {
        if (file < 0 and dist::rank() == 0) {
          fd_set read_set;
          FD_ZERO (&read_set);
          FD_SET (myGH->socket, &read_set);

          struct timeval timeout = {0, 0};
          client_is_ready =
            select (FD_SETSIZE, &read_set, NULL, NULL, &timeout) == 1;
        }
        MPI_Bcast (&client_is_ready, 1, MPI_INT, 0, dist::comm());
      }

      // short cut if there is nothing to do
      if (not client_is_ready) {
        continue;
      }

      // when called the first time during the current iteration,
      // open the file on processor 0
      if (file < 0 and dist::rank() == 0) {

        if (CCTK_Equals (verbose, "full")) {
          CCTK_VInfo (CCTK_THORNSTRING, "Opening HDF5 output file on output "
                                        "port %u", myGH->port);
        }

        // set file access property list to use the Stream VFD and open the file
        H5FD_stream_fapl_t fapl;
        fapl.increment = 0;
        fapl.socket = myGH->socket;
        fapl.do_socket_io = 1;
        fapl.backlog = max_num_clients;
        fapl.broadcast_fn = NULL;
        fapl.broadcast_arg = NULL;

        hid_t plist;
        HDF5_ERROR (plist = H5Pcreate (H5P_FILE_ACCESS));
        HDF5_ERROR (H5Pset_fapl_stream (plist, &fapl));

        // a filename is not used by Stream VFD
        assert (file < 0);
        HDF5_ERROR (file = H5Fcreate ("unused", H5F_ACC_TRUNC, H5P_DEFAULT,
                                      plist));
        HDF5_ERROR (H5Pclose (plist));
      }
      assert (dist::rank() or file >= 0);

      OutputVar (cctkGH, myGH->requests[vindex], file);
    }
  }

  // close an open file if the finest level has been output
  if (reflevel == reflevels - 1) {
    if (dist::rank() == 0 and file >= 0) {
      if (CCTK_Equals (verbose, "full")) {
        CCTK_VInfo (CCTK_THORNSTRING, "Closing HDF5 output file on port %u",
                    myGH->port);
      }
      HDF5_ERROR (H5Fclose (file));
      file = -1;
    }
    client_is_ready = 0;
  }

  // return negative number of errors occured during this output
  return (-error_count);
}


static int TimeToOutput (const cGH* const cctkGH, const int vindex)
{
  DECLARE_CCTK_ARGUMENTS;
  DECLARE_CCTK_PARAMETERS;

  const int numvars = CCTK_NumVars();
  assert (vindex>=0 and vindex<numvars);

  if (CCTK_GroupTypeFromVarI (vindex) != CCTK_GF and not do_global_mode) {
    return 0;
  }

  CarpetIOStreamedHDF5GH *myGH =
    (CarpetIOStreamedHDF5GH *) CCTK_GHExtension (cctkGH, CCTK_THORNSTRING);
  CheckSteerableParameters (cctkGH, myGH);

  // check if output for this variable was requested
  if (not myGH->requests[vindex]) {
    return (0);
  }

  // check whether this refinement level should be output
  if (not (myGH->requests[vindex]->refinement_levels & (1 << reflevel))) {
    return (0);
  }

  // check if output for this variable was requested individually
  // by a "<varname>{ out_every = <number> }" option string
  // this will overwrite the output criterion setting
  const char *myoutcriterion = CCTK_EQUALS (out_criterion, "default") ?
                               io_out_criterion : out_criterion;
  if (myGH->requests[vindex]->out_every >= 0) {
    myoutcriterion = "divisor";
  }

  if (CCTK_EQUALS (myoutcriterion, "never")) {
    return (0);
  }

  // check whether to output at this iteration
  bool output_this_iteration = false;

  if (CCTK_EQUALS (myoutcriterion, "iteration")) {
    int myoutevery = out_every == -2 ? io_out_every : out_every;
    if (myoutevery > 0) {
      if (*this_iteration == cctk_iteration) {
        // we already decided to output this iteration
        output_this_iteration = true;
      } else if (cctk_iteration >= *next_output_iteration) {
        // it is time for the next output
        output_this_iteration = true;
        *this_iteration = cctk_iteration;
        *next_output_iteration = cctk_iteration + myoutevery;
      }
    }
  } else if (CCTK_EQUALS (myoutcriterion, "divisor")) {
    int myoutevery = out_every == -2 ? io_out_every : out_every;
    if (myGH->requests[vindex]->out_every >= 0) {
      myoutevery = myGH->requests[vindex]->out_every;
    }
    if (myoutevery > 0 and (cctk_iteration % myoutevery) == 0) {
      // we already decided to output this iteration
      output_this_iteration = true;
    }
  } else if (CCTK_EQUALS (myoutcriterion, "time")) {
    CCTK_REAL myoutdt = out_dt == -2 ? io_out_dt : out_dt;
    if (myoutdt == 0 or *this_iteration == cctk_iteration) {
      output_this_iteration = true;
    } else if (myoutdt > 0 and (cctk_time / cctk_delta_time
                             >= *next_output_time / cctk_delta_time - 1.0e-12)) {
      // it is time for the next output
      output_this_iteration = true;
      *this_iteration = cctk_iteration;
      *next_output_time = cctk_time + myoutdt;
    }
  }

  if (not output_this_iteration) {
    return 0;
  }

  if (last_output.at(mglevel).at(reflevel).at(vindex) == cctk_iteration) {
    // Has already been output during this iteration
    char* varname = CCTK_FullName(vindex);
    CCTK_VWarn (5, __LINE__, __FILE__, CCTK_THORNSTRING,
                "Skipping output for variable \"%s\", because this variable "
                "has already been output during the current iteration -- "
                "probably via a trigger during the analysis stage",
                varname);
    free (varname);
    return 0;
  }

  assert (last_output.at(mglevel).at(reflevel).at(vindex) < cctk_iteration);

  // Should be output during this iteration
  return 1;
}


static int OutputVar (const cGH* const cctkGH, const ioRequest* const request,
                      hid_t file)
{
  DECLARE_CCTK_PARAMETERS;

  const int group = CCTK_GroupIndexFromVarI (request->vindex);
  assert (group >= 0);
  cGroup groupdata;
  CCTK_GroupData (group, &groupdata);
  if (groupdata.grouptype == CCTK_SCALAR or groupdata.grouptype == CCTK_ARRAY) {
    assert (do_global_mode);
  }

  // check for storage
  if (not CCTK_QueryGroupStorageI (cctkGH, group)) {
    char* fullname = CCTK_FullName (request->vindex);
    CCTK_VWarn (1, __LINE__, __FILE__, CCTK_THORNSTRING,
                "Cannot output variable '%s' because it has no storage",
                fullname);
    free (fullname);
    return (0);
  }

  if (out_unchunked) {
    WriteVarUnchunked (cctkGH, file, request, false);
  } else {
    WriteVarChunkedSequential (cctkGH, file, request, false);
  }

  last_output.at(mglevel).at(reflevel).at(request->vindex) =
    cctkGH->cctk_iteration;

  return (0);
}


} // namespace CarpetIOStreamedHDF5