
                          B   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mZ ddlmZ dZddZd Z G d dej0                        Z G d dej0                        Z G d dej0                        Z G d de      Zy);High-level client for interacting with the Cloud Build API.    )absolute_import)division)unicode_literalsN)encoding)cloudbuild_util)logs)requests)
exceptions)log)
properties)rangezZError Response:{status_code? [{?}]}{status_message? {?}}{url?
{?}}{details?

Details:
{?}}c                 f   | j                   | j                   j                  D ]p  }|j                  dk(  s|j                  j                  j
                  D ];  }|j                  |k(  s|j                  j                  }|xs |j                  c c S  r |rt        dj                  |            y)a  Extract the value of a build's prop_key from a build operation.

  Args:
    build_op: A Google Cloud Builder build operation.
    prop_key: str, The property name.
    required: If True, raise an OperationError if prop_key isn't present.

  Returns:
    The corresponding build operation value indexed by prop_key.

  Raises:
    OperationError: The required prop_key was not found.
  Nbuildz7Build operation does not contain required property [{}])	metadataadditionalPropertieskeyvalueobject_valuer   string_valueOperationErrorformat)build_opprop_keyrequiredprop
build_propr   s         .lib/googlecloudsdk/api_lib/cloudbuild/build.pyGetBuildPropr   '   s     "!!66	W	**11<<J^^x'%++88L3:#3#33 = 7 
 ))/)9; ;     c                     | j                   rX| j                   j                  rB| j                   j                  D ])  }|j                  dk(  s|j                  j                  c S  y)a  Get the Cloud Build Status from an Operation object.

  The op.response field is supposed to have a copy of the build object; however,
  the wire JSON from the server doesn't get deserialized into an actual build
  object. Instead, it is stored as a generic ResponseValue object, so we have
  to root around a bit.

  Args:
    op: the Operation object from a CloudBuild build request.

  Returns:
    string status, likely "SUCCESS" or "ERROR".
  statusUNKNOWN)responser   r   r   r   )opr   s     r   _GetStatusFromOpr&   A   sL     [[R[[5500	X	zz&&& 1 
r    c                       e Zd ZdZy)BuildFailedErrorz/Raised when a Google Cloud Builder build fails.N__name__
__module____qualname____doc__ r    r   r(   r(   V   s    7r    r(   c                       e Zd ZdZy)OperationTimeoutErrorz#Raised when an operation times out.Nr)   r.   r    r   r0   r0   Z   s    +r    r0   c                       e Zd ZdZy)r   z+Raised when an operation contains an error.Nr)   r.   r    r   r   r   _   s    3r    r   c                   L    e Zd ZdZdZdZdZdZddZddZ	dd	Z
d
 ZddZd Zy)CloudBuildClientr      i  SUCCESSzlog-{build_id}.txtNc                 x    |xs t        j                         | _        |xs t        j                         | _        y N)r   GetClientInstanceclientGetMessagesModulemessages)selfr9   r;   s      r   __init__zCloudBuildClient.__init__l   s,    ?O==?DKC A A CDMr    c                     |4t         j                  j                  j                  j	                  d      }| j
                  j                  j                  | j                  j                  ||            }|S )a]  Execute a call to CloudBuild service and return the build operation.


    Args:
      build: Build object. The Build to execute.
      project: The project to execute, or None to use the current project
          property.

    Raises:
      BuildFailedError: when the build fails.

    Returns:
      build_op, an in-progress build operation.
    Tr   )	projectIdr   )
r   VALUEScoreprojectGetr9   projects_buildsCreater;   %CloudbuildProjectsBuildsCreateRequestr<   r   rC   r   s       r   ExecuteCloudBuildAsyncz'CloudBuildClient.ExecuteCloudBuildAsyncp   sl     !!&&..22D2Ag{{**11;; 	< 	H Or    c                 J    | j                  ||      }| j                  |       y)a  Execute a call to CloudBuild service and wait for it to finish.


    Args:
      build: Build object. The Build to execute.
      project: The project to execute, or None to use the current project
          property.

    Raises:
      BuildFailedError: when the build fails.
    N)rI   WaitAndStreamLogsrH   s       r   ExecuteCloudBuildz"CloudBuildClient.ExecuteCloudBuild   s$     **5':H8$r    c                 R   t        |dd      }t        |d      }t        |d      }t        j                  j                  dj	                  |             d}d	}|r|| j
                  j	                  |      }t        j                  ||
      }|r(t        j                  j                  d|z          d|z   }nt        j                  j                  d       d	}|r|j                  }	 | j                  ||      }	|r|j                  d       t        |	      }
|
| j                  k7  rLt        j                   t#        j$                  |	j&                              }t        d|z   dz   |
z   dz   |z         y	# t        $ r& t        j                  dd       t        d|z         w xY w)z=Wait for a Cloud Build to finish, streaming logs if possible.idTr?   logUrl
logsBucketz!Started cloud build [{build_id}].)build_idzin the Cloud Console.N)bucketobjz"To see logs in the Cloud Console: zat z'Logs can be found in the Cloud Console.)	operationretry_callback )exc_infoz"Cloud build timed out. Check logs )is_lastzCloud build failed. Check logs z Failure status: z: )r   r   r"   Printr   CLOUDBUILD_LOGFILE_FMT_STRINGcloudbuild_logsGCSLogTailerPollWaitForOperationr0   debugr(   r&   CLOUDBUILD_SUCCESSr
   ExtractErrorMessager   MessageToPyValueerror)r<   r   rQ   logs_urilogs_bucketlog_loc
log_tailer
log_objectcallbackr%   final_statusmessages               r   rK   z"CloudBuildClient.WaitAndStreamLogs   s   HdT:HHh/Hx6KJJ+22H2EG%GJ55<<h<Oj"//j 


=HI("

BCHhM  8H Mb oodo##B'Lt...,,

#
#BHH
-/g>H235ABDHI&' ( ( / ! M	iiT"AGKLLMs   )E7 7/F&c                 v    | j                  ||      }|s$t        dj                  |j                              |S )a  Wait until the operation is complete or times out.

    This does not use the core api_lib.util.waiter because the cloud build logs
    serve as a progress tracker.

    Args:
      operation: The operation resource to wait on
      retry_callback: A callback to be executed before each retry, if desired.
    Returns:
      The operation resource when it has completed
    Raises:
      OperationTimeoutError: when the operation polling times out
    z@Operation [{0}] timed out. This operation may still be underway.)_PollUntilDoner0   r   name)r<   rT   rU   completed_operations       r   r^   z!CloudBuildClient.WaitForOperation   sE     --iH! $<=CV'0~~>78 8 r    c                    |j                   r|S | j                  j                  j                  d      } ||j                        }t        | j                        D ]  }| j                  j                  j                  |      }|j                   r[t        j                  dj                  |j                  t        j                  t        j                  |      d                   |c S t        j                  dj                  |j                  | j                               t!        j"                  | j                         | |         y)z?Polls the operation resource until it is complete or times out.rD   )rn   z%Operation [{0}] complete. Result: {1}   )indentz+Operation [{0}] not complete. Waiting {1}s.N)doner9   
operationsGetRequestTypern   r   _MAX_RETRIESrD   r   r_   r   jsondumpsr   MessageToDict_RETRY_INTERVALtimesleep)r<   rT   rU   request_typerequest_s         r   rm   zCloudBuildClient._PollUntilDone   s    ~~;;))88?L	/G4$$%++((,,W5i			9@@NNJJx--i8CE 	F 	ii=DD
..$..0 1
jj%%&		# & r    )NNr7   )r*   r+   r,   r-   rz   rv   r`   rZ   r=   rI   rL   rK   r^   rm   r.   r    r   r3   r3   d   s;    C/, "6D0% +(Z.r    r3   )F)r-   
__future__r   r   r   rw   r{   apitools.base.pyr   !googlecloudsdk.api_lib.cloudbuildr   r	   r[   googlecloudsdk.api_lib.utilr
   googlecloudsdk.corer   r   r   	six.movesr   _ERROR_FORMAT_STRINGr   r&   Errorr(   r0   r   objectr3   r.   r    r   <module>r      s    B &  '   % = E 0 * # * 6 
;4*8z'' 8J,, 
Z%% 
Mv Mr    