a
    ŠxdE  ã                   @   sr  d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ d d	lmZ d d
lmZ d dlmZ ddlmZ ddlmZ ddlmZ ddlmZ d dlmZ e e¡Z G dd„ deƒZ!G dd„ de!ƒZ"G dd„ de!ƒZ#G dd„ de!ƒZ$G dd„ de!ƒZ%G dd„ de!ƒZ&G dd„ de!ƒZ'G d d!„ d!e!ƒZ(G d"d#„ d#e!ƒZ)G d$d%„ d%e!ƒZ*dS )&é    N)Údatetime)Úweb)Úgen)ÚIOLoop)Újson_decode)Ú	HTTPError)Ústates)ÚAsyncResult)ÚAbortableAsyncResult)ÚDisabledBackendé   )Útasks)ÚBaseHandler)ÚBroker)ÚControlHandler)ÚOrderedDictc                   @   sD   e Zd ZdZdd„ Zedd„ ƒZdd„ Zdd	„ Zd
d„ Z	dd„ Z
dS )ÚBaseTaskHandlerz%Y-%m-%d %H:%M:%S.%fc              
   C   sž   z| j j}|rt|ƒni }W n2 tyN } ztdt|ƒƒ‚W Y d }~n
d }~0 0 t|tƒsdtddƒ‚| dg ¡}| di ¡}t|t	t
fƒs”tddƒ‚|||fS )Né  zinvalid optionsÚargsÚkwargszargs must be an array)ÚrequestÚbodyr   Ú
ValueErrorr   ÚstrÚ
isinstanceÚdictÚpopÚlistÚtuple)Úselfr   ÚoptionsÚer   r   © r"   úH/var/www/html/Ranjet/env/lib/python3.9/site-packages/flower/api/tasks.pyÚget_task_args   s    $


zBaseTaskHandler.get_task_argsc                 C   s   t | jtƒ S ©N)r   Úbackendr   )Úresultr"   r"   r#   Úbackend_configured0   s    z"BaseTaskHandler.backend_configuredc                 K   s   |   |¡ d S r%   )Z
set_status)r   Ústatus_coder   r"   r"   r#   Úwrite_error4   s    zBaseTaskHandler.write_errorc                 C   sB   |j tjkr(| |  |j¡|jdœ¡ n| d|  |j¡i¡ d S )N)r'   Ú	tracebackr'   )Ústater   ÚFAILUREÚupdateÚsafe_resultr'   r+   )r   Úresponser'   r"   r"   r#   Úupdate_response_result7   s
    ÿ
z&BaseTaskHandler.update_response_resultc                 C   s€   d|v rt  |d | j¡|d< d|v r6t|d ƒ|d< d|v r||d }zt|ƒ}W n  tyr   t  || j¡}Y n0 ||d< d S )NÚetaZ	countdownÚexpires)r   ÚstrptimeÚDATE_FORMATÚfloatr   )r   r    r3   r"   r"   r#   Únormalize_options>   s    
ÿz!BaseTaskHandler.normalize_optionsc                 C   s2   zt  |¡ W n ty(   t|ƒ Y S 0 |S dS )zreturns json encodable resultN)ÚjsonÚdumpsÚ	TypeErrorÚrepr)r   r'   r"   r"   r#   r/   L   s
    zBaseTaskHandler.safe_resultN)Ú__name__Ú
__module__Ú__qualname__r5   r$   Ústaticmethodr(   r*   r1   r7   r/   r"   r"   r"   r#   r      s   
r   c                   @   s(   e Zd Zejejdd„ ƒƒZdd„ ZdS )Ú	TaskApplyc                 c   sÂ   |   ¡ \}}}t d|||¡ z| jj| }W n  tyN   tdd| ƒ‚Y n0 z|  |¡ W n tyz   tddƒ‚Y n0 |j	f ||dœ|¤Ž}d|j
i}t ¡  d| j||¡V }|  |¡ dS )	a#  
Execute a task by name and wait results

**Example request**:

.. sourcecode:: http

  POST /api/task/apply/tasks.add HTTP/1.1
  Accept: application/json
  Accept-Encoding: gzip, deflate, compress
  Content-Length: 16
  Content-Type: application/json; charset=utf-8
  Host: localhost:5555

  {
      "args": [1, 2]
  }

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 71
  Content-Type: application/json; charset=UTF-8

  {
      "state": "SUCCESS",
      "task-id": "c60be250-fe52-48df-befb-ac66174076e6",
      "result": 3
  }

:query args: a list of arguments
:query kwargs: a dictionary of arguments
:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 404: unknown task
        ú'Invoking a task '%s' with '%s' and '%s'é”  úUnknown task '%s'r   úInvalid option©r   r   útask-idN)r$   ÚloggerÚdebugÚcappr   ÚKeyErrorr   r7   r   Úapply_asyncÚtask_idr   ÚcurrentZrun_in_executorÚwait_resultsÚwrite©r   Útasknamer   r   r    Útaskr'   r0   r"   r"   r#   ÚpostW   s$    *ÿ

ÿzTaskApply.postc                 C   s4   |j dd |  ||¡ |  |¡r0|j|jd |S )NF)Ú	propagate©r,   )Úgetr1   r(   r.   r,   )r   r'   r0   r"   r"   r#   rN   –   s
    
zTaskApply.wait_resultsN)	r<   r=   r>   r   Úauthenticatedr   Ú	coroutinerS   rN   r"   r"   r"   r#   r@   V   s   =r@   c                   @   s   e Zd Zejdd„ ƒZdS )ÚTaskAsyncApplyc                 C   sÂ   |   ¡ \}}}t d|||¡ z| jj| }W n  tyN   tdd| ƒ‚Y n0 z|  |¡ W n tyz   tddƒ‚Y n0 |j	f ||dœ|¤Ž}d|j
i}|  |¡r´|j|jd |  |¡ d	S )
ac  
Execute a task

**Example request**:

.. sourcecode:: http

  POST /api/task/async-apply/tasks.add HTTP/1.1
  Accept: application/json
  Accept-Encoding: gzip, deflate, compress
  Content-Length: 16
  Content-Type: application/json; charset=utf-8
  Host: localhost:5555

  {
      "args": [1, 2]
  }

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 71
  Content-Type: application/json; charset=UTF-8
  Date: Sun, 13 Apr 2014 15:55:00 GMT

  {
      "state": "PENDING",
      "task-id": "abc300c7-2922-4069-97b6-a635cc2ac47c"
  }

:query args: a list of arguments
:query kwargs: a dictionary of arguments
:query options: a dictionary of `apply_async` keyword arguments
:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 404: unknown task
        rA   rB   rC   r   rD   rE   rF   rU   N)r$   rG   rH   rI   r   rJ   r   r7   r   rK   rL   r(   r.   r,   rO   rP   r"   r"   r#   rS   ¢   s"    *ÿ

zTaskAsyncApply.postN©r<   r=   r>   r   rW   rS   r"   r"   r"   r#   rY       s   rY   c                   @   s   e Zd Zejdd„ ƒZdS )ÚTaskSendc                 C   sh   |   ¡ \}}}t d|||¡ | jj|f||dœ|¤Ž}d|ji}|  |¡rZ|j|jd |  	|¡ dS )a"  
Execute a task by name (doesn't require task sources)

**Example request**:

.. sourcecode:: http

  POST /api/task/send-task/tasks.add HTTP/1.1
  Accept: application/json
  Accept-Encoding: gzip, deflate, compress
  Content-Length: 16
  Content-Type: application/json; charset=utf-8
  Host: localhost:5555

  {
      "args": [1, 2]
  }

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 71
  Content-Type: application/json; charset=UTF-8

  {
      "state": "SUCCESS",
      "task-id": "c60be250-fe52-48df-befb-ac66174076e6"
  }

:query args: a list of arguments
:query kwargs: a dictionary of arguments
:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 404: unknown task
        z%Invoking task '%s' with '%s' and '%s'rE   rF   rU   N)
r$   rG   rH   rI   Z	send_taskrL   r(   r.   r,   rO   )r   rQ   r   r   r    r'   r0   r"   r"   r#   rS   â   s    (ÿÿÿÿ

zTaskSend.postNrZ   r"   r"   r"   r#   r[   á   s   r[   c                   @   s   e Zd Zejdd„ ƒZdS )Ú
TaskResultc                 C   sˆ   |   dd¡}|durt|ƒnd}t|ƒ}|  |¡s:tdƒ‚||jdœ}|rf|j|dd |  ||¡ n| ¡ rz|  ||¡ |  	|¡ dS )a–  
Get a task result

**Example request**:

.. sourcecode:: http

  GET /api/task/result/c60be250-fe52-48df-befb-ac66174076e6 HTTP/1.1
  Host: localhost:5555

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 84
  Content-Type: application/json; charset=UTF-8

  {
      "result": 3,
      "state": "SUCCESS",
      "task-id": "c60be250-fe52-48df-befb-ac66174076e6"
  }

:query timeout: how long to wait, in seconds, before the operation times out
:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 503: result backend is not configured
        ÚtimeoutNé÷  )rF   r,   F)r]   rT   )
Úget_argumentr6   r	   r(   r   r,   rV   r1   ÚreadyrO   )r   Útaskidr]   r'   r0   r"   r"   r#   rV     s     
zTaskResult.getN©r<   r=   r>   r   rW   rV   r"   r"   r"   r#   r\     s   r\   c                   @   s   e Zd Zejdd„ ƒZdS )Ú	TaskAbortc                 C   sF   t  d|¡ t|ƒ}|  |¡s&tdƒ‚| ¡  |  td| d¡ dS )a)  
Abort a running task

**Example request**:

.. sourcecode:: http

  POST /api/task/abort/c60be250-fe52-48df-befb-ac66174076e6 HTTP/1.1
  Host: localhost:5555

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 61
  Content-Type: application/json; charset=UTF-8

  {
      "message": "Aborted '1480b55c-b8b2-462c-985e-24af3e9158f9'"
  }

:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 503: result backend is not configured
        zAborting task '%s'r^   zAborted '%s')ÚmessageN)rG   Úinfor
   r(   r   ÚabortrO   r   )r   ra   r'   r"   r"   r#   rS   G  s    
zTaskAbort.postNrZ   r"   r"   r"   r#   rc   F  s   rc   c                   @   s    e Zd Zejejdd„ ƒƒZdS )ÚGetQueueLengthsc                 c   s¾   | j }| jjj}d}|jdkr.|jjr.|jj}d}| jjjrF| jjj}t|j 	¡ j
dd|||d}|  ¡ }|sœt| jjjgƒtdd„ | jjjp’g D ƒƒB }| t|ƒ¡V }|  d|i¡ dS )	aH  
Return length of all active queues

**Example request**:

.. sourcecode:: http

  GET /api/queues/length
  Host: localhost:5555

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 94
  Content-Type: application/json; charset=UTF-8

  {
      "active_queues": [
          {"name": "celery", "messages": 0},
          {"name": "video-queue", "messages": 5}
      ]
  }

:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 503: result backend is not configured
        NZamqpT)Zinclude_password)Úhttp_apiÚbroker_optionsÚbroker_use_sslc                 S   s   g | ]}|j r|j ‘qS r"   )Úname)Ú.0Úqr"   r"   r#   Ú
<listcomp>£  ó    z'GetQueueLengths.get.<locals>.<listcomp>Zactive_queues)ÚapplicationrI   ÚconfZBROKER_TRANSPORT_OPTIONSÚ	transportr    Z
broker_apiZBROKER_USE_SSLr   Ú
connectionÚas_uriZget_active_queue_namesÚsetZCELERY_DEFAULT_QUEUEZCELERY_QUEUESÚqueuesÚsortedrO   )r   Úappri   rh   rj   ZbrokerZqueue_namesrv   r"   r"   r#   rV   p  s$    !


ÿÿzGetQueueLengths.getN)r<   r=   r>   r   rW   r   rX   rV   r"   r"   r"   r#   rg   o  s   rg   c                   @   s   e Zd Zejdd„ ƒZdS )Ú	ListTasksc                 C   s&  | j }|  dd¡}| jddtd}|  dd¡}|  dd¡}|  dd¡}|  d	d¡}|  d
d¡}|  dd¡}	|ott|ƒ}t|dƒ}|dkrŒ|nd}|dkrœ|nd}|dkr¬|nd}g }
tj|j|||	|||||d	D ]@\}}t |¡}| dd¡}|dur|j	|d< |
 
||f¡ qÒ|  t|
ƒ¡ dS )aU
  
List tasks

**Example request**:

.. sourcecode:: http

  GET /api/tasks HTTP/1.1
  Host: localhost:5555
  User-Agent: HTTPie/0.8.0

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 1109
  Content-Type: application/json; charset=UTF-8
  Etag: "b2478118015c8b825f7b88ce6b660e5449746c37"
  Server: TornadoServer/3.1.1

  {
      "e42ceb2d-8730-47b5-8b4d-8e0d2a1ef7c9": {
          "args": "[3, 4]",
          "client": null,
          "clock": 1079,
          "eta": null,
          "exception": null,
          "exchange": null,
          "expires": null,
          "failed": null,
          "kwargs": "{}",
          "name": "tasks.add",
          "received": 1398505411.107885,
          "result": "'7'",
          "retried": null,
          "retries": 0,
          "revoked": null,
          "routing_key": null,
          "runtime": 0.01610181899741292,
          "sent": null,
          "started": 1398505411.108985,
          "state": "SUCCESS",
          "succeeded": 1398505411.124802,
          "timestamp": 1398505411.124802,
          "traceback": null,
          "uuid": "e42ceb2d-8730-47b5-8b4d-8e0d2a1ef7c9",
          "worker": "celery@worker1"
      },
      "f67ea225-ae9e-42a8-90b0-5de0b24507e0": {
          "args": "[1, 2]",
          "client": null,
          "clock": 1042,
          "eta": null,
          "exception": null,
          "exchange": null,
          "expires": null,
          "failed": null,
          "kwargs": "{}",
          "name": "tasks.add",
          "received": 1398505395.327208,
          "result": "'3'",
          "retried": null,
          "retries": 0,
          "revoked": null,
          "routing_key": null,
          "runtime": 0.012884548006695695,
          "sent": null,
          "started": 1398505395.3289,
          "state": "SUCCESS",
          "succeeded": 1398505395.341089,
          "timestamp": 1398505395.341089,
          "traceback": null,
          "uuid": "f67ea225-ae9e-42a8-90b0-5de0b24507e0",
          "worker": "celery@worker1"
      }
  }

:query limit: maximum number of tasks
:query offset: skip first n tasks
:query sort_by: sort tasks by attribute (name, state, received, started)
:query workername: filter task by workername
:query taskname: filter tasks by taskname
:query state: filter tasks by state
:query received_start: filter tasks by received date (must be greater than) format %Y-%m-%d %H:%M
:query received_end: filter tasks by received date (must be less than) format %Y-%m-%d %H:%M
:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
        ÚlimitNÚoffsetr   )ÚdefaultÚtypeZ
workernamerQ   r,   Úreceived_startÚreceived_endÚsort_byZAll)rz   r{   r€   r}   Úworkerr,   r~   r   r   )rp   r_   ÚintÚmaxr   Z
iter_tasksÚeventsÚas_dictr   ÚhostnameÚappendrO   r   )r   rx   rz   r{   r   r}   r,   r~   r   r€   r'   rL   rR   r"   r"   r#   rV   ª  s6    \
ü


zListTasks.getNrb   r"   r"   r"   r#   ry   ©  s   ry   c                   @   s   e Zd Zejdd„ ƒZdS )ÚListTaskTypesc                 C   s(   | j jj ¡ }i }||d< |  |¡ dS )aÞ  
List (seen) task types

**Example request**:

.. sourcecode:: http

  GET /api/task/types HTTP/1.1
  Host: localhost:5555

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 44
  Content-Type: application/json; charset=UTF-8

  {
      "task-types": [
          "tasks.add",
          "tasks.sleep"
      ]
  }

:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
        z
task-typesN)rp   r„   r,   Z
task_typesrO   )r   Zseen_task_typesr0   r"   r"   r#   rV   %  s    zListTaskTypes.getNrb   r"   r"   r"   r#   rˆ   $  s   rˆ   c                   @   s   e Zd Zejdd„ ƒZdS )ÚTaskInfoc                 C   sN   t  | jj|¡}|s"tdd| ƒ‚| ¡ }|jdur@|jj|d< |  |¡ dS )a¼  
Get a task info

**Example request**:

.. sourcecode:: http

  GET /api/task/info/91396550-c228-4111-9da4-9d88cfd5ddc6 HTTP/1.1
  Accept: */*
  Accept-Encoding: gzip, deflate, compress
  Host: localhost:5555


**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 575
  Content-Type: application/json; charset=UTF-8

  {
      "args": "[2, 2]",
      "client": null,
      "clock": 25,
      "eta": null,
      "exception": null,
      "exchange": null,
      "expires": null,
      "failed": null,
      "kwargs": "{}",
      "name": "tasks.add",
      "received": 1400806241.970742,
      "result": "'4'",
      "retried": null,
      "retries": null,
      "revoked": null,
      "routing_key": null,
      "runtime": 2.0037889280356467,
      "sent": null,
      "started": 1400806241.972624,
      "state": "SUCCESS",
      "succeeded": 1400806243.975336,
      "task-id": "91396550-c228-4111-9da4-9d88cfd5ddc6",
      "timestamp": 1400806243.975336,
      "traceback": null,
      "worker": "celery@worker1"
  }

:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
:statuscode 404: unknown task
        rB   rC   Nr   )	r   Zget_task_by_idrp   r„   r   r…   r   r†   rO   )r   ra   rR   r0   r"   r"   r#   rV   L  s    9
zTaskInfo.getNrb   r"   r"   r"   r#   r‰   K  s   r‰   )+r8   Úloggingr   Ztornador   r   Ztornado.ioloopr   Ztornado.escaper   Ztornado.webr   Zceleryr   Zcelery.resultr	   Zcelery.contrib.abortabler
   Zcelery.backends.baser   Úutilsr   Zviewsr   Zutils.brokerr   Zapi.controlr   Úcollectionsr   Ú	getLoggerr<   rG   r   r@   rY   r[   r\   rc   rg   ry   rˆ   r‰   r"   r"   r"   r#   Ú<module>   s6   
;JA41):{'