
    z;                         d Z ddlmZ ddlmZ ddlmZ 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ZddlmZ d Zd Zd Zd Zd Zd Zd Zd Z	 	 	 	 	 	 	 	 ddZy)zModule for making API requests.    )absolute_import)division)unicode_literalsN)batch_helper)single_request_helper)utils)waiters)log)
properties)zipc                     | D cg c]
  \  }}}|dv  }}}t        |      ryt        |      syt        d      c c}}w )z,Checks if all requests are of list requests.)ListAggregatedListListInstancesListManagedInstancesTFz?All requests must be either list requests or non-list requests.)allany
ValueError)requests_methodlist_requestss       4lib/googlecloudsdk/api_lib/compute/request_helper.py_RequestsAreListRequestsr   #   se    
 !) !)61    (  
 	}
IK Ks   ;c                    g }t        j                  |       } |dv r| j                  dg       }n|dk(  r| j                  dg       }n|dk(  r|j                  d      j                  j                  d      d   }t        j                  | d         D ]U  }|j                  dd	      }|r|d
   dk(  r|j                  d	|d   f       |j                  |j                  |g              W || j                  dd	      fS )a  Extracts data from one *List response page as JSON and stores in dicts.

  Args:
    response: str, The *List response in JSON
    service: The service which responded to *List request
    method: str, Method used to list resources. One of 'List' or
      'AggregatedList'.
    errors: list, Errors from response will be appended to  this list.

  Returns:
    Pair of:
    - List of items returned in response as dicts
    - Next page token (if present, otherwise None).
  r   r   itemsr   managedInstancesr   /warningNcodeUNREACHABLEmessagenextPageToken)
jsonloadsgetGetMethodConfigrelative_pathsplitsix
itervaluesappendextendresponseservicer   errorsr   items_field_namescope_resultr!   s           r   _HandleJsonListr6   3   s    %ZZ!( ((LL"%E''LL+R0E !!..'-c
27x'89   D1g	WV_5tWY/01ll<##$4b9: : 
_d3	33    c                    g }|dv r| j                   }n|dk(  r| j                  }n|j                  d      j                  j	                  d      d   }| j                   j
                  D ]  }|j                  j                  }|r@|j                  |j                  j                  k(  r|j                  d|j                  f       |j                  t        |j                  |              || j                  fS )z=Extracts data from one *List response page as Message object.r   r   r   r   r    N)r   r   r)   r*   r+   additionalPropertiesvaluer!   r"   CodeValueValuesEnumr#   r.   r$   r/   getattrr%   r0   s           r   _HandleMessageListr=   _   s    
% ((NNE''%%E ..'-c
27 ;; ""**g	W\\W%@%@%L%LLtW__-.ll7<--/?@A < 
&&	&&r7   c              #     K   | rt               sCt        |       dk(  r5| d   \  }}}t        j                  |||      \  }}	|j	                  |	       n,t        j                  | ||      \  }}	|j	                  |	       g }
t        |      D ]]  \  }}|s	| |   \  }}} |||||      \  }}|D ]  }|  |s.t        j                  |      }||_
        |
j                  |||f       _ |
} | ryyw)a  Makes a series of list and/or aggregatedList batch requests.

  Args:
    requests: A list of requests to make. Each element must be a 3-element tuple
      where the first element is the service, the second element is the method
      ('List' or 'AggregatedList'), and the third element is a protocol buffer
      representing either a list or aggregatedList request.
    http: An httplib2.Http-like object.
    batch_url: The handler for making batch requests.
    errors: A list for capturing errors. If any response contains an error, it
      is added to this list.
    response_handler: The function to extract information responses.

  Yields:
    Resources encapsulated in format chosen by response_handler as they are
      received from the server.
     r   r   http	batch_urlN)_ForceBatchRequestlenr   MakeSingleRequestr/   r   MakeRequests	enumeratecopydeepcopy	pageTokenr.   )r   rA   rB   r3   response_handlerr2   r   request_body	responsesrequest_errorsnew_requestsir1   request_protobufr   next_page_tokenitemnew_request_protobufs                     r   	_ListCorerU   {   s    $ 	CMQ$6&.qk#gv|"7"I"I
6<#i mmN#".";";$)#i mmN#L +8*21+'gv'/'606 8e_$
  
#}}-=>)8&Wf.BCD ,  H? 	s   B6C296C20C2c                 (    t        | |||t              S )a  Makes a series of list and/or aggregatedList batch requests.

  Args:
    requests: A list of requests to make. Each element must be a 3-element tuple
      where the first element is the service, the second element is the method
      ('List' or 'AggregatedList'), and the third element is a protocol buffer
      representing either a list or aggregatedList request.
    http: An httplib2.Http-like object.
    batch_url: The handler for making batch requests.
    errors: A list for capturing errors. If any response contains an error, it
      is added to this list.

  Returns:
    Resources encapsulated as protocol buffers as they are received
      from the server.
  )rU   r=   r   rA   rB   r3   s       r   _ListrX      s    " 
8T9f6H	IIr7   c                    t        | |j                  j                  j                        st	        d      | j                         D ]:  }|j                  dk7  s|j                  dk7  s#t        | |j                        : y y)zChecks whether operation argument is empty.

  Args:
    operation: Operation thats checked for emptyness.
    service: Variable used to access service.client.MESSAGES_MODULE.Operation.

  Returns:
    True if operation is empty, False otherwise.
  zEoperation must be instance ofservice.client.MESSAGES_MODULE.OperationkindwarningsFT)
isinstanceclientMESSAGES_MODULE	Operationr   
all_fieldsnamer<   )	operationr2   fields      r   _IsEmptyOperationrd      sx     
Iw~~==GG	H
 B C C ##%e

fz!9	5::&2 & 
r7   c                  f    t         j                  j                  j                  j	                         S )z5Check if compute/force_batch_request property is set.)r   VALUEScomputeforce_batch_requestGetBool r7   r   rC   rC      s#    				"	"	6	6	>	>	@@r7   c              #      K   | d   d   j                   j                         5  t        | |||t              D ]  }|  	 ddd       y# 1 sw Y   yxY ww)aG  Makes a series of list and/or aggregatedList batch requests.

  This function does all of:
  - Sends batch of List/AggregatedList requests
  - Extracts items from responses
  - Handles pagination

  All requests must be sent to the same client - Compute.

  Args:
    requests: A list of requests to make. Each element must be a 3-element tuple
      where the first element is the service, the second element is the method
      ('List' or 'AggregatedList'), and the third element is a protocol buffer
      representing either a list or aggregatedList request.
    http: An httplib2.Http-like object.
    batch_url: The handler for making batch requests.
    errors: A list for capturing errors. If any response contains an error, it
      is added to this list.

  Yields:
    Resources in dicts as they are received from the server.
  r   N)r]   JsonResponseModelrU   r6   )r   rA   rB   r3   rS   s        r   ListJsonrm      sJ     2 {1~..0(D)V_Mj N 100s   !AA
	A
AAc              #     K   t        |       rt        | |||      D ]  }|  yt               s3t        |       dk(  r%| d   \  }}}t	        j
                  |||      \  }}nt        j                  | ||      \  }}|j                  |       d}d}g }|s| D cg c]  }d }}t        | ||      D ]t  \  }}}||\  }}}t        ||j                  j                  j                        r5t        ||      s(|j                  j                   dvr|}d}t#        |d      rn|r|}n|j$                  }|j&                  r|j                  j(                  }nP|j*                  r|j                  j,                  }n-|j                  j.                  }n|j                  j0                  }t#        |d	      rB|j3                  t5        j6                  |||||j8                  j:                  |||
             D|j3                  t5        j6                  |||||||             q| w |rXg }t5        j<                  |||||||	|      D ]  }|  |r-|
r*t?        j@                  tC        jD                  d|             yyyyc c}w w)a  Makes one or more requests to the API.

  Each request can be either a synchronous API call or an asynchronous
  one. For synchronous calls (e.g., get and list), the result from the
  server is yielded immediately. For asynchronous calls (e.g., calls
  that return operations like insert), this function waits until the
  operation reaches the DONE state and fetches the corresponding
  object and yields that object (nothing is yielded for deletions).

  Currently, a heterogeneous set of synchronous calls can be made
  (e.g., get request to fetch a disk and instance), however, the
  asynchronous requests must be homogenous (e.g., they must all be the
  same verb on the same collection). In the future, heterogeneous
  asynchronous requests will be supported. For now, it is up to the
  client to ensure that the asynchronous requests are
  homogenous. Synchronous and asynchronous requests can be mixed.

  Args:
    requests: A list of requests to make. Each element must be a 3-element tuple
      where the first element is the service, the second element is the string
      name of the method on the service, and the last element is a protocol
      buffer representing the request.
    http: An httplib2.Http-like object.
    batch_url: The handler for making batch requests.
    errors: A list for capturing errors. If any response contains an error, it
      is added to this list.
    project_override: The override project for the returned operation to poll
      from.
    progress_tracker: progress tracker to be ticked while waiting for operations
      to finish.
    no_followup: If True, do not followup operation with a GET request.
    always_return_operation: If True, return operation object even if operation
      fails.
    followup_overrides: A list of new resource names to GET once the operation
      finishes. Generally used in renaming calls.
    log_result: Whether the Operation Waiter should print the result in past
      tense of each request.
    log_warnings: Whether warnings for completed operation should be printed.
    timeout: The maximum amount of time, in seconds, to wait for the operations
      to reach the DONE state.

  Yields:
    A response for each request. For deletion requests, no corresponding
    responses are returned.
  rW   Nr?   r   )r2   r   rL   r@   )GlobalOperationsServiceRegionOperationsServiceZoneOperationsService#GlobalOrganizationOperationsServiceGlobalAccountsOperationsServiceproject!instanceGroupManagerResizeRequest)rt   resize_request_nameno_followupfollowup_overridealways_return_operation)rt   rw   rx   ry   )operations_datarA   rB   r[   progress_trackerr3   
log_resulttimeoutz!Some requests generated warnings:)#r   rX   rC   rD   r   rE   r   rF   r/   r   r\   r]   r^   r_   rd   	__class____name__hasattrrt   zonezoneOperationsregionregionOperationsglobalOperationsglobalOrganizationOperationsr.   r	   OperationDataru   ra   WaitForOperationsr
   r!   r   ConstructList)r   rA   rB   r3   project_overrider{   rw   ry   followup_overridesr|   log_warningsr}   rS   r2   r   rL   rM   
new_errorsoperation_serviceresource_servicerz   r   requestr1   rx   rt   r[   s                              r   rF   rF      s    v h'	& j  
	#h-1"4$,QK!GV\1CC\Iz )55	;Iz--

 /	(011$1.1(I2D/F*gx*&GQ8W^^;;EEFh0"" +/ 	/
 !g	y	)$' (('==%nn;;
__%nn==
%nn==
#NNGG	B	C!!! $0$R$R$W$W'"3(?		
 	!!! '"3(?A	B no/Fr H--')	 n	 L	kk


A8
LN !x u 2s   BJ	J%G'J)NNFFNTTN)__doc__
__future__r   r   r   rH   r&   googlecloudsdk.api_lib.computer   r   r   r	   googlecloudsdk.corer
   r   r,   	six.movesr   r   r6   r=   rU   rX   rd   rC   rm   rF   rj   r7   r   <module>r      s    & &  '   7 @ 0 2 # * 
 K )4X'81hJ(*A
F !aNr7   