#๐Ÿ”’ Worker threads getting killed if an exception occurs

67 messages ยท Page 1 of 1 (latest)

torn umbra
#

I have a function that is being run in 3 worker threads, they keep running until an exception occurs after which the worker thread that was executing it is killed. after a while all my worker threads are dead.

def process_tasks(worker_id):
    try:
        while True:
            payload = task_queue.get()
            if payload is None:  # Exit signal
                break
            logger.debug("Worker %d processing task %s :", worker_id, payload.get('pod'))

            command = f"kubectl --kubeconfig {path} exec '{payload.get('pod')}' -- /usr/bin/thread-dump"
            result = subprocess.run(
                command,
                check=True,
                shell=True,
                capture_output=True
            )
            logger.info("stdout: %s", result.stdout.decode('utf-8'))
            task_queue.task_done()

    except KeyError as key_error:
        logger.error("KeyError: %s", key_error, exc_info=True)

    except subprocess.CalledProcessError as e:
        logger.error("CalledProcessError: %s", e)
        logger.error("stdout: %s", e.stdout.decode('utf-8'))
        logger.error("stderr: %s", e.stderr.decode('utf-8'))

    except Exception as e:
        logger.error("Exception: %s", e, exc_info=True)
    
    finally:
        task_queue.task_done()

@app.post("/enqueue", dependencies=[Depends(k8s_utils.kubeconfig_status)])
async def enqueue_task(alert_data: PromAlertData):
    logger.debug(f"Received alert data for alert {alert_data.alertname} in namespace {alert_data.namespace}, pod {alert_data.pod}")
    task_queue.put(alert_data.model_dump())
    return {"message": "Task added to queue"}

@app.on_event("startup")
def startup():
    startscript()


    global worker_threads
    worker_threads = []
    for _ in range(3):
        worker_thread = threading.Thread(target=process_tasks, args=(_,), daemon=True)
        worker_thread.start()
        worker_threads.append(worker_thread)```

Need help in fixing this behavior
barren isleBOT
#

@torn umbra

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

jaunty atlas
#

You could go with the old try, except, pass method to ignore the exception

torn umbra
#

I don't quite understand. Try except is already in place, I am catching all general exceptions

jaunty atlas
#

Yeah sure but then youre quiting the process

#

U should pass here instead if you want to keep it running

torn umbra
#

i am executing task_queue.task_done() even if there was no error, inside the try block. and all 3 of my worker threads continue to run

jaunty atlas
#

Hmm

#

What exception are u getting when theyre quiting

torn umbra
#

i added pass and still one of my thread died

#

no execption

jaunty atlas
#

Ah I see

torn umbra
#
2025-02-17 13:29:05,486 k8s_sentry.app: ERROR    stdout: 
2025-02-17 13:29:05,487 k8s_sentry.app: ERROR    stderr: error: Internal error occurred: Internal error occurred: error executing command in container: failed to exec in container: failed to start exec "84ebc69ff4651c3a7579d4e0cb0b926b62f4b68f2dfcf13106627cb65f447309": OCI runtime exec failed: exec failed: unable to start container process: exec: "/usr/bin/thread-dump": stat /usr/bin/thread-dump: no such file or directory: unknown```
jaunty atlas
#

Well put that part in an try and pass the exception

#

Like this part

torn umbra
#

you want me to put this line inside a try except block?

jaunty atlas
#

Yes

torn umbra
#

okay

jaunty atlas
#

Since thats causing the error

torn umbra
#

it is already inside a try except block, it is being handled

#

here, still the same

torn umbra
#

yes

autumn pollen
#

Oh just use BackgroundTasks

torn umbra
#

I dont want to

autumn pollen
#

Because?

torn umbra
#

becuase this is a part of a larger project and this is how its running a lot of this

autumn pollen
#

Oh well that's silly

#

How many kloc?

torn umbra
#
  • background task are not necessarily queued, they can run concurrently
autumn pollen
#

But you have 3 workers so they do run concurrently

#

Also you're building that command insecurely

torn umbra
#

man, we can have a discussion on design choices later, I understand your point, we tried using background tasks it didn't work for us. for the time being i just want to know why my threads are dying

torn umbra
autumn pollen
#

You also don't need shell=True

torn umbra
#

forget it

autumn pollen
autumn pollen
#

What

#

Anyway why are you using task_done here?

#

Can you show your full file, including imports

torn umbra
#

nope

#

that will not be possible

autumn pollen
#

Oh it's pretty obvious

#

You put the try and the while the wrong way around

torn umbra
#

okay, what should i change

autumn pollen
#

Your attitude

torn umbra
#

try inside while?

torn umbra
torn umbra
autumn pollen
#

But you should just use a CapacityLimitor and async subprocess and BackgroundTasks

#

Making your own thread pool is kinda silly when FastAPI ships with one

#

And using threads for subprocess is also a bit odd when you can use async functions

torn umbra
#

we used that approach, I can't discuss why we are not using that because then I'll have to give you context on the application and for my workplace that is a big no no.

torn umbra
autumn pollen
#

Ok well at least use lifespan_context and 3 anyio.to_thread.run_sync tasks

torn umbra
#

okay

#

i'll take a look

#

thank you

#

!clode

barren isleBOT
#
Did you mean:

!close

torn umbra
#

!close

barren isleBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.