Exemplo n.º 1
0
def _wait_on_iterable(iter_obj, compss_mode):
    # type: (typing.Any, int) -> typing.Any
    """ Wait on an iterable object (Recursive).

    Currently supports lists and dictionaries (syncs the values).

    :param iter_obj: Iterable object.
    :return: Synchronized object.
    """
    # check if the object is in our pending_to_synchronize dictionary
    obj_id = OT.is_tracked(iter_obj)
    if OT.is_pending_to_synchronize(obj_id):
        return _synchronize(iter_obj, compss_mode)
    else:
        if type(iter_obj) == list:
            return [_wait_on_iterable(x, compss_mode) for x in iter_obj]
        elif type(iter_obj) == dict:
            return {
                _wait_on_iterable(k, compss_mode):
                _wait_on_iterable(v, compss_mode)
                for k, v in iter_obj.items()
            }
        else:
            return _synchronize(iter_obj, compss_mode)
Exemplo n.º 2
0
def stop(sync=False, _hard_stop=False):
    # type: (bool, bool) -> None
    """ Runtime stop.

    :param sync: Scope variables synchronization [ True | False ]
                 (default: False)
    :param _hard_stop: Stop compss when runtime has died [ True | False ].
                       (default: False)
    :return: None
    """
    logger = logging.getLogger(__name__)
    ipython = globals()["__builtins__"]["get_ipython"]()

    if not context.in_pycompss():
        return __hard_stop__(interactive_helpers.DEBUG, sync, logger, ipython)

    from pycompss.api.api import compss_stop

    print(LINE_SEPARATOR)
    print("*************** STOPPING PyCOMPSs ******************")
    print(LINE_SEPARATOR)
    # Wait 5 seconds to give some time to process the remaining messages
    # of the STDW and check if there is some error that could have stopped
    # the runtime before continuing.
    print("Checking if any issue happened.")
    time.sleep(5)
    messages = STDW.get_messages()
    if messages:
        for message in messages:
            sys.stderr.write("".join((message, "\n")))

    # Uncomment the following lines to see the ipython dictionary
    # in a structured way:
    #   import pprint
    #   pprint.pprint(ipython.__dict__, width=1)
    if sync and not _hard_stop:
        sync_msg = "Synchronizing all future objects left on the user scope."
        print(sync_msg)
        logger.debug(sync_msg)
        from pycompss.api.api import compss_wait_on
        reserved_names = ("quit", "exit", "get_ipython", "APP_PATH",
                          "ipycompss", "In", "Out")
        raw_code = ipython.__dict__["user_ns"]
        for k in raw_code:
            obj_k = raw_code[k]
            if not k.startswith('_'):  # not internal objects
                if type(obj_k) == Future:
                    print("Found a future object: %s" % str(k))
                    logger.debug("Found a future object: %s" % str(k))
                    new_obj_k = compss_wait_on(obj_k)
                    if new_obj_k == obj_k:
                        print("\t - Could not retrieve object: %s" % str(k))
                        logger.debug("\t - Could not retrieve object: %s" %
                                     str(k))
                    else:
                        ipython.__dict__["user_ns"][k] = new_obj_k
                elif k not in reserved_names:
                    try:
                        if OT.is_pending_to_synchronize(obj_k):
                            print("Found an object to synchronize: %s" %
                                  str(k))  # noqa: E501
                            logger.debug("Found an object to synchronize: %s" %
                                         (k, ))  # noqa: E501
                            ipython.__dict__["user_ns"][k] = compss_wait_on(
                                obj_k)  # noqa: E501
                    except TypeError:
                        # Unhashable type: List - could be a collection
                        if isinstance(obj_k, list):
                            print("Found a list to synchronize: %s" % str(k))
                            logger.debug("Found a list to synchronize: %s" %
                                         (k, ))  # noqa: E501
                            ipython.__dict__["user_ns"][k] = compss_wait_on(
                                obj_k)  # noqa: E501
    else:
        print("Warning: some of the variables used with PyCOMPSs may")
        print("         have not been brought to the master.")

    # Stop streaming
    if STREAMING:
        stop_streaming()

    # Stop persistent storage
    if PERSISTENT_STORAGE:
        master_stop_storage(logger)

    # Emit the 0 for the APPLICATION_RUNNING_EVENT emitted on start function.
    emit_manual_event(0)

    # Stop runtime
    compss_stop(_hard_stop=_hard_stop)

    # Cleanup events and files
    release_event_manager(ipython)
    __clean_temp_files__()

    # Stop watching stdout and stderr
    STDW.stop_watching(clean=True)
    # Retrieve the remaining messages that could have been captured.
    last_messages = STDW.get_messages()
    if last_messages:
        for message in last_messages:
            print(message)

    # Let the Python binding know we are not at master anymore
    context.set_pycompss_context(context.OUT_OF_SCOPE)

    print(LINE_SEPARATOR)
    logger.debug("--- END ---")
Exemplo n.º 3
0
def _synchronize(obj, mode):
    # type: (typing.Any, int) -> typing.Any
    """ Synchronization function.

    This method retrieves the value of a future object.
    Calls the runtime in order to wait for the value and returns it when
    received.

    :param obj: Object to synchronize.
    :param mode: Direction of the object to synchronize.
    :return: The value of the object requested.
    """
    # TODO: Add a boolean to differentiate between files and object on the
    # COMPSs.open_file call. This change pretends to obtain better traces.
    # Must be implemented first in the Runtime, then in the bindings common
    # C API and finally add the boolean here
    app_id = 0
    obj_id = ""  # noqa

    if is_psco(obj):
        obj_id = str(get_id(obj))
        if not OT.is_pending_to_synchronize(obj_id):
            return obj
        else:
            # file_path is of the form storage://pscoId or
            # file://sys_path_to_file
            file_path = COMPSs.open_file(app_id, "".join(
                ("storage://", str(obj_id))), mode)
            # TODO: Add switch on protocol (first parameter returned currently ignored)
            _, file_name = file_path.split("://")
            new_obj = get_by_id(file_name)
            OT.stop_tracking(obj)
            return new_obj

    obj_id = OT.is_tracked(obj)
    obj_name = OT.get_obj_name(obj_id)
    if obj_id is None:  # Not being tracked
        return obj
    if not OT.is_pending_to_synchronize(obj_id):
        return obj

    if __debug__:
        logger.debug("Synchronizing object %s with mode %s" % (obj_id, mode))

    file_name = OT.get_file_name(obj_id)
    compss_file = COMPSs.open_file(app_id, file_name, mode)

    # Runtime can return a path or a PSCOId
    if compss_file.startswith('/'):
        # If the real filename is null, then return None. The task that
        # produces the output file may have been ignored or cancelled, so its
        # result does not exist.
        real_file_name = compss_file.split('/')[-1]
        if real_file_name == "null":
            print(
                "WARNING: Could not retrieve the object " + str(file_name) +
                " since the task that produces it may have been IGNORED or CANCELLED. Please, check the logs. Returning None."
            )  # noqa: E501
            return None
        new_obj = deserialize_from_file(compss_file)
        COMPSs.close_file(app_id, file_name, mode)
    else:
        new_obj = get_by_id(compss_file)

    if context.is_nesting_enabled() and context.in_worker():
        # If nesting and in worker, the user wants to synchronize an object.
        # So it is necessary to update the parameter with the new object.
        update_worker_argument_parameter_content(obj_name, new_obj)

    if mode == 'r':
        OT.update_mapping(obj_id, new_obj)

    if mode != 'r':
        COMPSs.delete_file(app_id, OT.get_file_name(obj_id), False)
        OT.stop_tracking(obj)

    return new_obj