GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Pub / Sub doesn't work with multiprocessing · Issue #3890 · googleapis/google-cloud-python

Pub / Sub doesn't work with multiprocessing #3890

New issue
Copy link
New issue
Copy link
Closed
Closed
Pub / Sub doesn't work with multiprocessing#3890
Copy link
Assignees
theacodes
Labels
api: pubsubIssues related to the Pub/Sub API.priority: p1Important issue which blocks shipping the next release. Will be fixed prior to next release.release blockingRequired feature/issue must be fixed prior to next release.triaged for GAtype: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Description

@theacodes
theacodes
opened on Aug 28, 2017
Issue body actions

This code fails with a pickle error:

def multiprocessing_callback(message):
    print('Received message: {}'.format(message))
    message.ack()


def receive_messages_with_multiprocessing(
        project, topic_name, subscription_name):
    """Receives messages from a pull subscription using multiprocessing."""
    import concurrent.futures
    import functools
    import multiprocessing

    import google.cloud.pubsub_v1.subscriber.policy.thread

    # Create a process pool and a queue for sending messages. This will
    # be used by the subscriber policy to execute callbacks.
    executor = concurrent.futures.ProcessPoolExecutor()
    manager = multiprocessing.Manager()
    queue = manager.Queue()

    policy_factory = functools.partial(
        google.cloud.pubsub_v1.subscriber.policy.thread.Policy,
        executor=executor,
        queue=queue)
    subscriber = pubsub_v1.SubscriberClient(policy_class=policy_factory)
    subscription_path = subscriber.subscription_path(
        project, subscription_name)

    subscriber.subscribe(subscription_path, callback=multiprocessing_callback)

    # The subscriber is non-blocking, so we must keep the main thread from
    # exiting to allow it to process messages in the background.
    print('Listening for messages on {}'.format(subscription_path))
    while True:
        time.sleep(60)
Reacted by Stuart Axelbrooke

Activity

  1. theacodes
    added
    api: pubsubIssues related to the Pub/Sub API.
    blocks-docs-samples
    devex
    on Aug 28, 2017
  2. theacodes
    assigned
    lukesneeringer
    on Aug 28, 2017
  3. lukesneeringer commented on Aug 29, 2017

    @lukesneeringer
    lukesneeringer
    on Aug 29, 2017
    Contributor
    More actions

    Can you provide the traceback, too? ;-)

  4. theacodes commented on Aug 29, 2017

    @theacodes
    theacodes
    on Aug 29, 2017
    ContributorAuthor
    More actions

    It's pretty unhelpful:

    Traceback (most recent call last):
      File "/Users/jonwayne/.pyenv/versions/3.6.0/lib/python3.6/multiprocessing/queues.py", line 241, in _feed
        obj = _ForkingPickler.dumps(obj)
      File "/Users/jonwayne/.pyenv/versions/3.6.0/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
        cls(buf, protocol).dump(obj)
    TypeError: can't pickle _thread.lock objects
    
  5. danoscarmike
    added
    priority: p1Important issue which blocks shipping the next release. Will be fixed prior to next release.
    on Sep 13, 2017
  6. danoscarmike commented on Sep 13, 2017

    @danoscarmike
    danoscarmike
    on Sep 13, 2017
    Contributor
    More actions

    Hi @lukesneeringer what's the next step here?

  7. michaelplaing commented on Sep 18, 2017

    @michaelplaing
    michaelplaing
    on Sep 18, 2017
    More actions

    This occurs when using the "spawn" context of multiprocessing. However the "fork" context will also fail (but silently) when using grpcio==0.1.6. A workaround for "fork" is to specify grpcio==0.1.4.

  8. lukesneeringer
    removed
    blocks-docs-samples
    devex
    on Nov 8, 2017
  9. dhermes
    changed the title [-]Pubsub doesn't work with multiprocessing[/-] [+]Pub / Sub doesn't work with multiprocessing[/+] on Dec 15, 2017
  10. dhermes commented on Dec 19, 2017

    @dhermes
    dhermes
    on Dec 19, 2017
    Contributor
    More actions

    So I can't reproduce the pickling error with google-cloud-pubsub==0.30.0, but it still fails (eventually) with a

    E1219 12:19:30.755077995   16917 ssl_transport_security.cc:436] Corruption detected.
    E1219 12:19:30.755141409   16917 ssl_transport_security.cc:412] error:100003fc:SSL routines:OPENSSL_internal:SSLV3_ALERT_BAD_RECORD_MAC
    E1219 12:19:30.755162457   16917 secure_endpoint.cc:185]     Decryption error: TSI_DATA_CORRUPTED
    
  11. dhermes commented on Dec 20, 2017

    @dhermes
    dhermes
    on Dec 20, 2017
    Contributor
    More actions

    I think I need to use OS X to see what @jonparrott was seeing. Or just an older version of google-cloud-pubsub.

  12. dhermes commented on Dec 21, 2017

    @dhermes
    dhermes
    on Dec 21, 2017
    Contributor
    More actions

    Some work towards making it feasible for an "alternate" implementation:

    • Allowing over-ride for lock used in publisher client. #4628 (Making publisher Batch define a make_lock() rather than using a threading.Lock in a PublisherClient)
    • Use a UUID (rather than a sentinel object) for sentinel on Pub / Sub Future. #4634 (Use a UUID rather than a sentinel object on Pub / Sub Future)
    • Allowed a custom Event type in Pub / Sub futures. #4643 (allow Future-s to have a custom Event rather than using threading.Event)

    I'm not sure how grpcio's use of the threading module will impact such an alternate implementation.

  13. danoscarmike
    assigned
    dhermes
    and unassigned
    lukesneeringer
    on Jan 3, 2018
  14. danoscarmike commented on Jan 3, 2018

    @danoscarmike
    danoscarmike
    on Jan 3, 2018
    Contributor
    More actions

    @dhermes reassigning this one to you. Please update when you have something. Thanks.

  15. chemelnucfin
    added
    type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.
    on Jan 9, 2018
  16. danoscarmike commented on Jan 19, 2018

    @danoscarmike
    danoscarmike
    on Jan 19, 2018
    Contributor
    More actions

    Ping. Next steps here?

  17. danoscarmike
    added
    release blockingRequired feature/issue must be fixed prior to next release.
    triaged for GA
    on Jan 19, 2018
  18. theacodes commented on Jan 19, 2018

    @theacodes
    theacodes
    on Jan 19, 2018
    ContributorAuthor
    More actions

    I'm going to close this.

    Multiprocessing in general is a dead-end with grpc clients because grpc does not work at all in multiprocessing environments. Even if we made the pubsub subscriber be able to execute callbacks in using multiprocessing, they wouldn't be able to do any useful work that involves any other client libraries calls.

    @dhermes's work has made it feasible for us to support it in the future if grpcio does.

  19. theacodes
    closed this as completedon Jan 19, 2018
  20. theacodes
    unassigned
    dhermes
    on Sep 28, 2018
  21. jrmlhermitte commented on Jul 29, 2019

    @jrmlhermitte
    jrmlhermitte
    on Jul 29, 2019
    More actions

    I think this feature would be useful. Does this still work? Or is it unsupported?

    Is this feature in particular still supported?

    policy_factory = functools.partial(
            google.cloud.pubsub_v1.subscriber.policy.thread.Policy,
            executor=executor,
            queue=queue)
        subscriber = pubsub_v1.SubscriberClient(policy_class=policy_factory)

    seems to not exist in the latest version of pubsub. (Please point me to any documentation if I'm wrong)
    thanks!

  22. tseaver commented on Jul 29, 2019

    @tseaver
    tseaver
    on Jul 29, 2019
    Contributor
    More actions

    A more complete / up-to-date example, which still fails with the pickling error:

    import concurrent.futures
    import functools
    import multiprocessing
    import os
    import time
    
    
    PROJECT = os.getenv('GOOGLE_CLOUD_PROJECT')
    SUBSCRIPTION_NAME = 'repro-gcp-3980-sub'
    
    
    def multiprocessing_callback(message):
        print('Received message: {}'.format(message))
        message.ack()
    
    
    def create_client(executor, queue):
        # Defer import of gRPC-related modules until after multiprocessing forks.
        from google.cloud.pubsub_v1 import SubscriberClient
        from google.cloud.pubsub_v1.subscriber.scheduler import Scheduler
    
        class MultiprocessingScheduler(Scheduler):
    
            def __init__(self, executor, queue):
                self._executor = executor
                self._queue = queue
    
            @property
            def queue(self):
                return self._queue
    
            def schedule(self, callback, *args, **kwargs):
                self._executor.submit(callback, *args, **kwargs)
    
            def shutdown(self):
                try:
                    while True:
                        self._executor._work_queue.get(block=False)
                except queue.Empty:
                    pass
                self._executor.shutdown()
    
        scheduler = MultiprocessingScheduler(executor, queue)
        subscriber = SubscriberClient()
    
        return subscriber, scheduler
    
    
    def receive_messages_with_multiprocessing():
        """Receives messages from a pull subscription using multiprocessing."""
    
        # Create a process pool and a queue for sending messages. This will
        # be used by the subscriber policy to execute callbacks.
        executor = concurrent.futures.ProcessPoolExecutor()
        manager = multiprocessing.Manager()
        queue = manager.Queue()
    
        subscriber, scheduler = create_client(executor, queue)
    
        subscription_path = subscriber.subscription_path(
            PROJECT, SUBSCRIPTION_NAME)
    
        subscriber.subscribe(
            subscription_path,
            callback=multiprocessing_callback,
            scheduler=scheduler,
        )
    
        # The subscriber is non-blocking, so we must keep the main thread from
        # exiting to allow it to process messages in the background.
        print('Listening for messages on {}'.format(subscription_path))
        while True:
            time.sleep(60)
    
    
    if __name__ == '__main__':
        receive_messages_with_multiprocessing()
  23. JustinBeckwith
    assigned
    theacodes
    on Feb 1, 2021
  24. parthea
    added a commit that references this issue on Sep 22, 2023

    chore: move samples from python-docs-sample (#33)

    This issue will close once commit 69c4425 is merged into the 'main' branch.
    69c4425
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @theacodes
    theacodes

Labels

api: pubsubIssues related to the Pub/Sub API.priority: p1Important issue which blocks shipping the next release. Will be fixed prior to next release.release blockingRequired feature/issue must be fixed prior to next release.triaged for GAtype: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.