File: direct-multi.c

package info (click to toggle)
openmpi 5.0.8-4
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 201,684 kB
  • sloc: ansic: 613,078; makefile: 42,353; sh: 11,194; javascript: 9,244; f90: 7,052; java: 6,404; perl: 5,179; python: 1,859; lex: 740; fortran: 61; cpp: 20; tcl: 12
file content (785 lines) | stat: -rw-r--r-- 30,878 bytes parent folder | download | duplicates (4)
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
450
451
452
453
454
455
456
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
/*
 * Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana
 *                         University Research and Technology
 *                         Corporation.  All rights reserved.
 * Copyright (c) 2004-2011 The University of Tennessee and The University
 *                         of Tennessee Research Foundation.  All rights
 *                         reserved.
 * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
 *                         University of Stuttgart.  All rights reserved.
 * Copyright (c) 2004-2005 The Regents of the University of California.
 *                         All rights reserved.
 * Copyright (c) 2006-2013 Los Alamos National Security, LLC.
 *                         All rights reserved.
 * Copyright (c) 2009-2012 Cisco Systems, Inc.  All rights reserved.
 * Copyright (c) 2011      Oak Ridge National Labs.  All rights reserved.
 * Copyright (c) 2013-2020 Intel, Inc.  All rights reserved.
 * Copyright (c) 2015      Mellanox Technologies, Inc.  All rights reserved.
 * Copyright (c) 2021-2025 Nanook Consulting  All rights reserved.
 * Copyright (c) 2021      IBM Corporation.  All rights reserved.
 * $COPYRIGHT$
 *
 * Additional copyrights may follow
 *
 * $HEADER$
 *
 */

#define _GNU_SOURCE
#include <ctype.h>
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include "debugger.h"
#include <pmix_tool.h>

static pmix_proc_t myproc;
static char client_nspace[PMIX_MAX_NSLEN + 1];
static char daemon_nspace[PMIX_MAX_NSLEN + 1];

static bool stop_in_init = true;
static bool stop_on_exec = false;
static bool stop_in_init_supported = false;
static bool stop_on_exec_supported = false;
static int app_npernode = 2; // > 0. Default 2 ppn
static int app_np = 2; // <= 0 means use default from prte. Default to single node. Must be multiple of npernode
static int daemon_colocate_per_proc = 0; // 0 = disable
static int daemon_colocate_per_node = 0; // 0 = disable

/* this is a callback function for the PMIx_Query
 * API. The query will callback with a status indicating
 * if the request could be fully satisfied, partially
 * satisfied, or completely failed. The info parameter
 * contains an array of the returned data, with the
 * info->key field being the key that was provided in
 * the query call. Thus, you can correlate the returned
 * data in the info->value field to the requested key.
 *
 * Once we have dealt with the returned data, we must
 * call the release_fn so that the PMIx library can
 * cleanup */
static void cbfunc(pmix_status_t status, pmix_info_t *info, size_t ninfo, void *cbdata,
                   pmix_release_cbfunc_t release_fn, void *release_cbdata)
{
    myquery_data_t *mq = (myquery_data_t *) cbdata;
    size_t n;

    printf("Called %s as callback for PMIx_Query\n", __FUNCTION__);
    mq->status = status;
    /* save the returned info - the PMIx library "owns" it
     * and will release it and perform other cleanup actions
     * when release_fn is called */
    if (0 < ninfo) {
        PMIX_INFO_CREATE(mq->info, ninfo);
        mq->ninfo = ninfo;
        for (n = 0; n < ninfo; n++) {
            printf("Key %s Type %s(%d)\n", info[n].key, PMIx_Data_type_string(info[n].value.type),
                   info[n].value.type);
            PMIX_INFO_XFER(&mq->info[n], &info[n]);
        }
    }

    /* let the library release the data and cleanup from
     * the operation */
    if (NULL != release_fn) {
        release_fn(release_cbdata);
    }

    /* release the block */
    DEBUG_WAKEUP_THREAD(&mq->lock);
}

/* this is the event notification function we pass down below
 * when registering for general events - i.e.,, the default
 * handler. We don't technically need to register one, but it
 * is usually good practice to catch any events that occur */
static void notification_fn(size_t evhdlr_registration_id, pmix_status_t status,
                            const pmix_proc_t *source, pmix_info_t info[], size_t ninfo,
                            pmix_info_t results[], size_t nresults,
                            pmix_event_notification_cbfunc_fn_t cbfunc, void *cbdata)
{
    myrel_t *lock;
    size_t n;

    printf("%s called as callback for event=%s\n", __FUNCTION__, PMIx_Error_string(status));
    lock = NULL;
    if (PMIX_ERR_UNREACH == status || PMIX_ERR_LOST_CONNECTION == status) {
        /* we should always have info returned to us - if not, there is
         * nothing we can do */
        if (NULL != info) {
            for (n = 0; n < ninfo; n++) {
                if (PMIX_CHECK_KEY(&info[n], PMIX_EVENT_RETURN_OBJECT)) {
                    lock = (myrel_t *) info[n].value.data.ptr;
                }
            }
        }

        /* If a pointer to a lock was passed then save status and
         * release the lock */
        if (NULL != lock) {
            lock->exit_code = status;
            lock->exit_code_given = true;
            DEBUG_WAKEUP_THREAD(&lock->lock);
        }
    }

    /* this example doesn't do anything with default events */
    if (NULL != cbfunc) {
        cbfunc(PMIX_SUCCESS, NULL, 0, NULL, NULL, cbdata);
    }
}

/* this is an event notification function that we explicitly request
 * be called when the PMIX_EVENT_JOB_END notification is issued.
 * We could catch it in the general event notification function and test
 * the status to see if it was "job terminated", but it often is simpler
 * to declare a use-specific notification callback point. In this case,
 * we are asking to know whenever a job terminates, and we will then
 * know we can exit */
static void release_fn(size_t evhdlr_registration_id, pmix_status_t status,
                       const pmix_proc_t *source, pmix_info_t info[], size_t ninfo,
                       pmix_info_t results[], size_t nresults,
                       pmix_event_notification_cbfunc_fn_t cbfunc, void *cbdata)
{
    myrel_t *lock;
    bool found;
    int exit_code;
    size_t n;
    pmix_proc_t *affected = NULL;

    printf("%s called as callback for event=%s source=%s:%d\n", __FUNCTION__,
           PMIx_Error_string(status), source->nspace, source->rank);
    /* find the return object */
    lock = NULL;
    found = false;
    for (n = 0; n < ninfo; n++) {
        if (0 == strncmp(info[n].key, PMIX_EVENT_RETURN_OBJECT, PMIX_MAX_KEYLEN)) {
            lock = (myrel_t *) info[n].value.data.ptr;
            /* not every RM will provide an exit code, but check if one was given */
        } else if (0 == strncmp(info[n].key, PMIX_EXIT_CODE, PMIX_MAX_KEYLEN)) {
            exit_code = info[n].value.data.integer;
            found = true;
        } else if (0 == strncmp(info[n].key, PMIX_EVENT_AFFECTED_PROC, PMIX_MAX_KEYLEN)) {
            affected = info[n].value.data.proc;
        }
    }
    /* if the object wasn't returned, then that is an error */
    if (NULL == lock) {
        fprintf(stderr, "LOCK WASN'T RETURNED IN RELEASE CALLBACK\n");
        /* let the event handler progress */
        if (NULL != cbfunc) {
            cbfunc(PMIX_EVENT_ACTION_COMPLETE, NULL, 0, NULL, NULL, cbdata);
        }
        return;
    }

    printf("DEBUGGER NOTIFIED THAT JOB %s TERMINATED \n",
           (NULL == affected) ? "NULL" : affected->nspace);
    if (found) {
        if (!lock->exit_code_given) {
            lock->exit_code = exit_code;
            lock->exit_code_given = true;
        }
    }

    /* A system PMIx daemon may have kept track of notifications for
     * termination of previous application runs, and may send those
     * notifications to this process, which has registered a callback for
     * application terminations. Those notifcations need to be ignored.
     *
     * Therefore, in the co-spawn case, we expect one termination notification,
     * which is for the combined application/daemon namespace when the daemon
     * terminates.
     *
     * In the separate spawn case, we expect two terminations, the application
     * and the daemon. */
    if ((0 == strcmp(daemon_nspace, source->nspace))
        || (0 == strcmp(client_nspace, source->nspace))) {
        lock->lock.count--;
        if (0 == lock->lock.count) {
            DEBUG_WAKEUP_THREAD(&lock->lock);
        }
    }

    /* tell the event handler state machine that we are the last step */
    if (NULL != cbfunc) {
        cbfunc(PMIX_EVENT_ACTION_COMPLETE, NULL, 0, NULL, NULL, cbdata);
    }
    return;
}

/* Handle READY-FOR_DEBUG notifications from each application task. The waiting for
 * debug ready state is not complete until all application processes are ready */
static void app_ready(size_t evhdlr_registration_id, pmix_status_t status,
                      const pmix_proc_t *source, pmix_info_t info[], size_t ninfo,
                      pmix_info_t results[], size_t nresults,
                      pmix_event_notification_cbfunc_fn_t cbfunc, void *cbdata)
{
    myrel_t *lock;
    int n;
    printf("All expected READY-FOR-DEBUG notifications received\n");
    lock = NULL;
    for (n = 0; n < ninfo; n++) {
        if (0 == strncmp(info[n].key, PMIX_EVENT_RETURN_OBJECT, PMIX_MAX_KEYLEN)) {
            lock = (myrel_t *) info[n].value.data.ptr;
            break;
        }
    }
    /* if the lock wasn't returned, then that is an error */
    if (NULL == lock) {
        fprintf(stderr, "LOCK WASN'T RETURNED IN RELEASE CALLBACK\n");
        /* let the event handler progress */
        if (NULL != cbfunc) {
            cbfunc(PMIX_EVENT_ACTION_COMPLETE, NULL, 0, NULL, NULL, cbdata);
        }
        return;
    }
    DEBUG_WAKEUP_THREAD(&lock->lock);
}

/* event handler registration is done asynchronously because it
 * may involve the PMIx server registering with the host RM for
 * external events. So we provide a callback function that returns
 * the status of the request (success or an error), plus a numerical index
 * to the registered event. The index is used later on to deregister
 * an event handler - if we don't explicitly deregister it, then the
 * PMIx server will do so when it see us exit */
static void evhandler_reg_callbk(pmix_status_t status, size_t evhandler_ref, void *cbdata)
{
    mylock_t *lock = (mylock_t *) cbdata;

    printf("%s called to register callback\n", __FUNCTION__);
    if (PMIX_SUCCESS != status) {
        fprintf(stderr, "Client %s:%d EVENT HANDLER REGISTRATION FAILED WITH STATUS %d, ref=%lu\n",
                myproc.nspace, myproc.rank, status, (unsigned long) evhandler_ref);
    }
    lock->status = status;
    DEBUG_WAKEUP_THREAD(lock);
}

/* Register a callback for an application event notification */
void register_app_notification(pmix_status_t code, myrel_t *myrel, pmix_notification_fn_t callback)
{
    void *tinfo;
    pmix_info_t *info;
    pmix_status_t rc;
    pmix_proc_t proc;
    size_t ninfo;
    pmix_data_array_t darray;
    mylock_t mylock;

    PMIX_INFO_LIST_START(tinfo);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_EVENT_RETURN_OBJECT, myrel, PMIX_POINTER);
    /* Only call me back when this specific job terminates */
    PMIX_LOAD_PROCID(&proc, client_nspace, PMIX_RANK_WILDCARD);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_EVENT_AFFECTED_PROC, &proc, PMIX_PROC);
    PMIX_INFO_LIST_CONVERT(rc, tinfo, &darray);
    info = (pmix_info_t*)darray.array;
    ninfo = darray.size;
    PMIX_INFO_LIST_RELEASE(tinfo);

    DEBUG_CONSTRUCT_LOCK(&mylock);
    PMIx_Register_event_handler(&code, 1, info, ninfo, callback,
                                evhandler_reg_callbk, (void *) &mylock);
    DEBUG_WAIT_THREAD(&mylock);
    printf("Debugger: Registered for event %s on nspace %s\n",
           PMIx_Error_string(code), client_nspace);
    rc = mylock.status;
    DEBUG_DESTRUCT_LOCK(&mylock);
    PMIX_DATA_ARRAY_DESTRUCT(&darray);
}

/* Parse command line flags */
int parse_command_line(int argc, char **argv)
{
    int i;

    for (i = 1; i < argc; i++) {
        if (0 == strcmp(argv[i], "-h") || 0 == strcmp(argv[i], "--help")) {
            /* print the usage message and exit */
            printf("Direct Launch Example\n");
            printf("$ prte --daemonize\n");
            printf("$ %s [OPTIONS]\n", argv[0]);
            printf("\n");
            printf(" --stop-in-init   Stop application in PMIx_Init (Default)\n");
            printf(" --stop-on-exec   Stop application on exec\n");
            printf(" --app-npernode   Number of processes per node (Default: 2)\n");
            printf(" --app-np         Number of total processes. Must be multiple of "
                   "--app-npernode (Default: 2)\n");
            printf(" --daemon-colocate-per-proc  Test Colaunch with Daemons Per Process (Default: "
                   "0 = off)\n");
            printf(" --daemon-colocate-per-node  Test Colaunch with Daemons Per Node (Default: 0 = "
                   "off)\n");
            return -1;
        } else if (0 == strcmp(argv[i], "--stop-in-init")) {
            stop_in_init = true;
            stop_on_exec = false;
            break;
        } else if (0 == strcmp(argv[i], "--stop-on-exec")) {
            stop_in_init = false;
            stop_on_exec = true;
            break;
        } else if (0 == strcmp(argv[i], "--app-npernode")) {
            ++i;
            if (i >= argc && isdigit(argv[i][0])) {
                fprintf(stderr, "Error: --app-npernode requires a positive integer argument\n");
                return -1;
            }
            app_npernode = atoi(argv[i]);
            if (app_npernode <= 0) {
                fprintf(stderr, "Error: --app-npernode requires a positive integer argument\n");
                return -1;
            }
        } else if (0 == strcmp(argv[i], "--app-np")) {
            ++i;
            if (i >= argc && isdigit(argv[i][0])) {
                fprintf(stderr, "Error: --app-np requires a positive integer argument\n");
                return -1;
            }
            app_np = atoi(argv[i]);
            if (app_np < 0) {
                fprintf(stderr, "Error: --app-np requires a positive integer argument\n");
                return -1;
            }
        } else if (0 == strcmp(argv[i], "--daemon-colocate-per-proc")) {
            ++i;
            if (i >= argc && isdigit(argv[i][0])) {
                fprintf(stderr,
                        "Error: --daemon-colocate-per-proc requires a positive integer argument\n");
                return -1;
            }
            daemon_colocate_per_proc = atoi(argv[i]);
            if (daemon_colocate_per_proc < 0) {
                fprintf(stderr,
                        "Error: --daemon-colocate-per-proc requires a positive integer argument\n");
                return -1;
            }
        } else if (0 == strcmp(argv[i], "--daemon-colocate-per-node")) {
            ++i;
            if (i >= argc && isdigit(argv[i][0])) {
                fprintf(stderr,
                        "Error: --daemon-colocate-per-node requires a positive integer argument\n");
                return -1;
            }
            daemon_colocate_per_node = atoi(argv[i]);
            if (daemon_colocate_per_node < 0) {
                fprintf(stderr,
                        "Error: --daemon-colocate-per-node requires a positive integer argument\n");
                return -1;
            }
        }
    }

    if (daemon_colocate_per_node > 0 && daemon_colocate_per_proc > 0) {
        fprintf(stderr, "Error: Both --daemon-colocate-per-node and --daemon-colocate-per-node "
                        "options present, but are exclusive\n");
        return -1;
    }
    if (app_np < app_npernode || app_np % app_npernode != 0) {
        fprintf(stderr, "Error: --app-np must be a multiple of --app-npernode\n");
        return -1;
    }
    return 0;
}

/* Determine what services are available from the RM */
int query_capabilities(void)
{
    /* This is an initial launch - we need to launch the application
     * plus the debugger daemons, letting the RM know we are debugging
     * so that it will "pause" the app procs until we are ready. First
     * we need to know if this RM supports co-spawning of daemons with
     * the application, or if we need to launch the daemons as a separate
     * spawn command. The former is faster and more scalable, but not
     * every RM may support it. We also need to ask for debug support
     * so we know if the RM can stop-on-exec, or only supports stop-in-init */

    pmix_query_t *query;
    pmix_status_t rc;
    int n, nq = 1;
    myquery_data_t myquery_data;

    PMIX_QUERY_CREATE(query, nq);
    PMIX_ARGV_APPEND(rc, query[0].keys, PMIX_QUERY_SPAWN_SUPPORT);
    PMIX_ARGV_APPEND(rc, query[0].keys, PMIX_QUERY_DEBUG_SUPPORT);
    /* setup the caddy to retrieve the data */
    DEBUG_CONSTRUCT_LOCK(&myquery_data.lock);
    myquery_data.info = NULL;
    myquery_data.ninfo = 0;
    /* execute the query */
    if (PMIX_SUCCESS != (rc = PMIx_Query_info_nb(query, nq, cbfunc, (void *) &myquery_data))) {
        fprintf(stderr, "PMIx_Query_info failed: %d\n", rc);
        return -1;
    }
    DEBUG_WAIT_THREAD(&myquery_data.lock);
    DEBUG_DESTRUCT_LOCK(&myquery_data.lock);

    /* We should have received back two info structs, one containing
     * a comma-delimited list of PMIx spawn attributes the RM supports,
     * and the other containing a comma-delimited list of PMIx debugger
     * attributes it supports */
    if (2 != myquery_data.ninfo) {
        /* this is an error */
        fprintf(stderr, "PMIx Query returned an incorrect number of results: %lu\n",
                myquery_data.ninfo);
        PMIX_INFO_FREE(myquery_data.info, myquery_data.ninfo);
        return -1;
    }

    /* We will check to see if "stop_on_exec" is supported. Few RMs
     * do so, which is why we have to check. The reference server sadly is
     * not one of them, so we shouldn't find it here
     *
     * Note that the PMIx reference server always returns the query results
     * in the same order as the query keys. However, this is not guaranteed,
     * so we should search the returned info structures to find the desired key
     */
    for (n = 0; n < myquery_data.ninfo; n++) {
        if (0 == strcmp(myquery_data.info[n].key, PMIX_QUERY_DEBUG_SUPPORT)) {
            /* See if stop on exec is included */
            if (NULL != strstr(myquery_data.info[n].value.data.string, PMIX_DEBUG_STOP_ON_EXEC)) {
                stop_on_exec_supported = true;
            }
            /* See if stop in init is included */
            if (NULL != strstr(myquery_data.info[n].value.data.string, PMIX_DEBUG_STOP_IN_INIT)) {
                stop_in_init_supported = true;
            }
        }
    }

    if (!stop_on_exec_supported && stop_on_exec) {
        fprintf(stderr, "Error: Stop-on-exec requested but the RM does not support it\n");
        return -1;
    }

    if (!stop_in_init_supported && stop_in_init) {
        fprintf(stderr, "Error: Stop-in-init requested but the RM does not support it\n");
        return -1;
    }
    return 0;
}

/* Query the entire application proctable */
static int query_proctable(void)
{
    pmix_query_t *query;
    pmix_status_t rc;
    myquery_data_t myquery_data;

    /* Get the proctable for this nspace */
    PMIX_QUERY_CREATE(query, 1);
    PMIX_ARGV_APPEND(rc, query[0].keys, PMIX_QUERY_PROC_TABLE);
    query[0].nqual = 1;
    PMIX_INFO_CREATE(query->qualifiers, query[0].nqual);
    PMIX_INFO_LOAD(&query->qualifiers[0], PMIX_NSPACE, client_nspace, PMIX_STRING);

    DEBUG_CONSTRUCT_LOCK(&myquery_data.lock);
    myquery_data.info = NULL;
    myquery_data.ninfo = 0;

    if (PMIX_SUCCESS != (rc = PMIx_Query_info_nb(query, 1, cbfunc, (void *) &myquery_data))) {
        fprintf(stderr, "Debugger[%s:%d] Proctable query failed: %d\n", myproc.nspace,
                myproc.rank, rc);
        return -1;
    }
    /* Wait to get a response */
    DEBUG_WAIT_THREAD(&myquery_data.lock);
    DEBUG_DESTRUCT_LOCK(&myquery_data.lock);
    /* we should have gotten a response */
    if (PMIX_SUCCESS != myquery_data.status) {
        fprintf(stderr, "Debugger[%s:%d] Proctable query failed: %s\n", myproc.nspace,
                myproc.rank, PMIx_Error_string(myquery_data.status));
        return -1;
    }
    /* There should have been data */
    if (NULL == myquery_data.info || 0 == myquery_data.ninfo) {
        fprintf(stderr, "Debugger[%s:%d] Proctable query return no results\n", myproc.nspace,
                myproc.rank);
        return -1;
    }
    /* the query should have returned a data_array */
    if (PMIX_DATA_ARRAY != myquery_data.info[0].value.type) {
        fprintf(stderr, "Debugger[%s:%d] Query returned incorrect data type: %s(%d)\n",
                myproc.nspace, myproc.rank,
                PMIx_Data_type_string(myquery_data.info[0].value.type),
                (int) myquery_data.info[0].value.type);
        return -1;
    }
    if (NULL == myquery_data.info[0].value.data.darray->array) {
        fprintf(stderr, "Debugger[%s:%d] Query returned no proctable info\n", myproc.nspace,
                myproc.rank);
        return -1;
    }
    /* The data array consists of a struct:
     *     size_t size;
     *     void* array;
     *
     * In this case, the array is composed of pmix_proc_info_t structs:
     *     pmix_proc_t proc;   // contains the nspace,rank of this proc
     *     char* hostname;
     *     char* executable_name;
     *     pid_t pid;
     *     int exit_code;
     *     pmix_proc_state_t state;
     */
    printf("Received proc table for %d procs\n",
           (int) myquery_data.info[0].value.data.darray->size);
    return 0;
}

/* Spawn the application processes */
static pmix_status_t spawn_app(void)
{
    void *tinfo;
    pmix_info_t *info;
    size_t ninfo, napps;
    pmix_status_t rc;
    pmix_rank_t all_ranks = PMIX_RANK_WILDCARD;
    pmix_data_array_t darray;
    pmix_app_t app;
    char map_str[30];
    char cwd[_POSIX_PATH_MAX + 1];

    napps = 1;
    PMIX_APP_CONSTRUCT(&app);
    /* Setup the executable */
    app.cmd = strdup("hello");
    PMIX_ARGV_APPEND(rc, app.argv, "./hello");
    if (NULL == getcwd(cwd, _POSIX_PATH_MAX)) { // point us to our current directory
        exit(1);
    }
    app.cwd = strdup(cwd);
    if (app_np > 0) {
        app.maxprocs = app_np;
    }
    app.ninfo = 0;
    /* Provide job-level directives so the apps do what the user requested */
    PMIX_INFO_LIST_START(tinfo);
    if (stop_on_exec) {
        PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_DEBUG_STOP_ON_EXEC, NULL, PMIX_BOOL); // All procs stop at first instruction
    } else {
        PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_DEBUG_STOP_IN_INIT, NULL, PMIX_BOOL); // All procs stop in PMIx_Init
    }
    sprintf(map_str, "ppr:%d:node", app_npernode);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_MAPBY, map_str, PMIX_STRING); // app procs/node
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_RANKBY, "slot", PMIX_STRING); // match baseline
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_FWD_STDOUT, NULL, PMIX_BOOL); // forward stdout to me
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_FWD_STDERR, NULL, PMIX_BOOL); // forward stderr to me
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_NOTIFY_COMPLETION, NULL,
                       PMIX_BOOL); // notify us when the job completes
    PMIX_INFO_LIST_CONVERT(rc, tinfo, &darray);
    info = (pmix_info_t*)darray.array;
    ninfo = darray.size;
    PMIX_INFO_LIST_RELEASE(tinfo);
    /* Spawn the job - the function will return when the app
     * has been launched */
    printf("Debugger: spawning %s\n", app.cmd);
    if (PMIX_SUCCESS != (rc = PMIx_Spawn(info, ninfo, &app, napps, client_nspace))) {
        fprintf(stderr, "Application failed to launch with error: %s(%d)\n",
                PMIx_Error_string(rc), rc);
    }
    PMIX_DATA_ARRAY_DESTRUCT(&darray);
    return rc;
}

/* Spawn the debuger daemons */
static pmix_status_t spawn_debugger(char *appspace, myrel_t *myrel)
{
    pmix_info_t *dinfo;
    pmix_app_t *debugger;
    void *tinfo;
    size_t dninfo;
    pmix_status_t rc;
    pmix_status_t code = PMIX_EVENT_JOB_END;
    pmix_proc_t proc;
    int n;
    mylock_t mylock;
    pmix_data_array_t darray;
    char cwd[_POSIX_PATH_MAX];

    printf("Calling %s to spawn the debugger daemon\n", __FUNCTION__);
    /* Setup the debugger  spawn parameters*/
    PMIX_APP_CREATE(debugger, 1);
    debugger[0].cmd = strdup("./daemon");
    /* Set up debugger command arguments, in this example, just argv[0] */
    PMIX_ARGV_APPEND(rc, debugger[0].argv, "./daemon");
    /* No environment variables */
    debugger[0].env = NULL;
    /* Set the working directory to our current directory */
    if (NULL == getcwd(cwd, _POSIX_PATH_MAX)) {
        exit(1);
    }
    debugger[0].cwd = strdup(cwd);
    /* Spawn daemon processes - 1 per node if not colocating */
    if (daemon_colocate_per_proc < 0 && daemon_colocate_per_node < 0) {
        debugger[0].maxprocs = app_np / app_npernode;
    }
    /* No spawn attributes set here, all are set in dinfo array */
    debugger[0].ninfo = 0;
    debugger[0].info = NULL;
    /* Set attributes for debugger daemon launch and let the RM know these are
     * debugger daemons */
    PMIX_INFO_LIST_START(tinfo);
    /* Indicate a debugger daemon is being spawned */
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_DEBUGGER_DAEMONS, NULL, PMIX_BOOL);
    /* Set the name of the namespace being debugged */
    PMIX_LOAD_PROCID(&proc, appspace, PMIX_RANK_WILDCARD);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_DEBUG_TARGET, &proc, PMIX_PROC);
    /* Number of daemons per node in the application allocation */
    if (daemon_colocate_per_node > 0) {
        PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_DEBUG_DAEMONS_PER_NODE, &daemon_colocate_per_node,
                       PMIX_UINT16);
    }
    /* Number of daemons per proc in the application allocation */
    else if (daemon_colocate_per_proc > 0) {
        PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_DEBUG_DAEMONS_PER_PROC, &daemon_colocate_per_proc,
                       PMIX_UINT16);
    }
    /* Launch one daemon per node -- only needed if co-launch is not supported */
    else {
        PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_MAPBY, "ppr:1:node", PMIX_STRING);
    }
    /* Notify this process when the job completes */
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_NOTIFY_COMPLETION, NULL, PMIX_BOOL);
    /* Forward stdout to this process */
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_FWD_STDOUT, NULL, PMIX_BOOL);
    /* Forward stderr to this process */
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_FWD_STDERR, NULL, PMIX_BOOL);

    PMIX_INFO_LIST_CONVERT(rc, tinfo, &darray);
    dinfo = (pmix_info_t*)darray.array;
    dninfo = darray.size;
    PMIX_INFO_LIST_RELEASE(tinfo);

    /* Spawn the daemons */
    printf("Debugger: spawning %s\n", debugger[0].cmd);
    rc = PMIx_Spawn(dinfo, dninfo, debugger, 1, daemon_nspace);
    PMIX_DATA_ARRAY_DESTRUCT(&darray);
    PMIX_APP_FREE(debugger, 1);
    if (PMIX_SUCCESS != rc) {
        fprintf(stderr, "Debugger daemons failed to launch with error: %s\n",
                PMIx_Error_string(rc));
        return rc;
    }

    /* Register callback for when the daemons terminate */
    myrel->nspace = strdup(daemon_nspace);
    dninfo = 2;
    n = 0;
    PMIX_INFO_CREATE(dinfo, dninfo);
    PMIX_INFO_LOAD(&dinfo[n], PMIX_EVENT_RETURN_OBJECT, myrel, PMIX_POINTER);
    n++;
    /* Only call me back when the daemon job terminates */
    PMIX_LOAD_PROCID(&proc, daemon_nspace, PMIX_RANK_WILDCARD);
    PMIX_INFO_LOAD(&dinfo[n], PMIX_EVENT_AFFECTED_PROC, &proc, PMIX_PROC);
    /* Track that we need both jobs to terminate */
    myrel->lock.count++;

    DEBUG_CONSTRUCT_LOCK(&mylock);
    PMIx_Register_event_handler(&code, 1, dinfo, dninfo, release_fn, evhandler_reg_callbk,
                                (void *) &mylock);
    DEBUG_WAIT_THREAD(&mylock);
    printf("Debugger: Registered for daemon termination on nspace %s\n", daemon_nspace);
    rc = mylock.status;
    DEBUG_DESTRUCT_LOCK(&mylock);
    PMIX_INFO_FREE(dinfo, 2);

    return rc;
}

int main(int argc, char **argv)
{
    pmix_info_t *info;
    void *tinfo;
    size_t ninfo;
    pmix_status_t rc;
    mylock_t mylock;
    myrel_t myrel, ready_rel;
    pid_t pid;
    pmix_data_array_t darray;

    pid = getpid();

    /* Process any arguments we were given */
    if (0 != parse_command_line(argc, argv)) {
        exit(1);
    }

    /* Use the system connection first, if available */
    PMIX_INFO_LIST_START(tinfo);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_CONNECT_SYSTEM_FIRST, NULL, PMIX_BOOL);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_LAUNCHER, NULL, PMIX_BOOL);
    PMIX_INFO_LIST_ADD(rc, tinfo, PMIX_IOF_LOCAL_OUTPUT, NULL, PMIX_BOOL);
    PMIX_INFO_LIST_CONVERT(rc, tinfo, &darray);
    info = (pmix_info_t*)darray.array;
    ninfo = darray.size;
    PMIX_INFO_LIST_RELEASE(tinfo);
    /* Init as a tool */
    if (PMIX_SUCCESS != (rc = PMIx_tool_init(&myproc, info, ninfo))) {
        fprintf(stderr, "PMIx_tool_init failed: %s(%d)\n", PMIx_Error_string(rc), rc);
        exit(rc);
    }
    PMIX_DATA_ARRAY_DESTRUCT(&darray);

    printf("Debugger ns %s rank %d pid %lu: Running\n", myproc.nspace, myproc.rank,
           (unsigned long) pid);

    /* Construct my own release first */
    DEBUG_CONSTRUCT_LOCK(&myrel.lock);

    /* Register a default event handler */
    ninfo = 1;
    PMIX_INFO_CREATE(info, ninfo);
    PMIX_INFO_LOAD(&info[0], PMIX_EVENT_RETURN_OBJECT, &myrel, PMIX_POINTER);
    DEBUG_CONSTRUCT_LOCK(&mylock);
    PMIx_Register_event_handler(NULL, 0, info, ninfo, notification_fn, evhandler_reg_callbk,
                                (void *) &mylock);
    DEBUG_WAIT_THREAD(&mylock);
    DEBUG_DESTRUCT_LOCK(&mylock);
    PMIX_INFO_FREE(info, ninfo);

    if (0 != query_capabilities()) {
        goto done;
    }

    if (PMIX_SUCCESS != spawn_app()) {
        goto done;
    }

    /* Register for notification application is ready for debug
     * (paused on exec or paused in PMIx_Init) */
    DEBUG_CONSTRUCT_LOCK(&ready_rel.lock);
    register_app_notification(PMIX_DEBUG_WAITING_FOR_NOTIFY, &ready_rel, app_ready);

    /* Register callback for when the app terminates */
    register_app_notification(PMIX_EVENT_JOB_END, &myrel, release_fn);

    /* track number of jobs to terminate */
    myrel.lock.count++;

    /* Wait for all app tasks to be paused, ready for debug */
    DEBUG_WAIT_THREAD(&ready_rel.lock);
    DEBUG_DESTRUCT_LOCK(&ready_rel.lock);

    if (0 != query_proctable()) {
        goto done;
    }

    /* now launch the debugger daemons */
    if (PMIX_SUCCESS != (rc = spawn_debugger(client_nspace, &myrel))) {
        fprintf(stderr, "Debugger daemons failed to spawn: %s\n", PMIx_Error_string(rc));
        goto done;
    }

    /* This is where a debugger tool would wait until the debug operation is complete */
    DEBUG_WAIT_THREAD(&myrel.lock);

done:
    DEBUG_DESTRUCT_LOCK(&myrel.lock);
    PMIx_tool_finalize();
    return (rc);
}