
    .                        d 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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ZdZdZdZ dZ!dZ"dZ#e
jH                   e
jJ                  e
jL                  jN                         G d de
jP                                      Z) e
jJ                  e
jL                  jT                         G d de)             Z+ G d dejX                        Z(y)z8Scan a container image using the On-Demand Scanning API.    )absolute_import)division)unicode_literalsN)util)base)flags)ondemandscanning_util)binary_operations)	arg_utils)log)
properties)progress_tracker)local_state)update_manager)	platformszScanning container imagez@Locally extracting packages and versions from {} container imagez5Remotely initiating analysis of packages and versionsz*Waiting for analysis operation to completezExtraction failed: image extraction was either stopped or crashed (possibly due to a lack of available memory) with exit code {exit_code}z9Extraction failed: unknown error (exit code: {exit_code})c                   B    e Zd ZdZdddZed        Zd Zd Zd Z	d	 Z
y
)ScanBeta[  Perform a vulnerability scan on a container image.

  You can scan a container image in a Google Cloud registry (Artifact Registry
  or Container Registry), or a local container image.

  Reference an image by tag or digest using any of the formats:

    Artifact Registry:
      LOCATION-docker.pkg.dev/PROJECT-ID/REPOSITORY-ID/IMAGE[:tag]
      LOCATION-docker.pkg.dev/PROJECT-ID/REPOSITORY-ID/IMAGE@sha256:digest

    Container Registry:
      [LOCATION.]gcr.io/PROJECT-ID/REPOSITORY-ID/IMAGE[:tag]
      [LOCATION.]gcr.io/PROJECT-ID/REPOSITORY-ID/IMAGE@sha256:digest

    Local:
      IMAGE[:tag]
  z{description}a	      Start a scan of a container image stored in Artifact Registry:

        $ {command} us-west1-docker.pkg.dev/my-project/my-repository/busy-box@sha256:abcxyz --remote

    Start a scan of a container image stored in the Container Registry, and perform the analysis in Europe:

        $ {command} eu.gcr.io/my-project/my-repository/my-image:latest --remote --location=europe

    Start a scan of a container image stored locally, and perform the analysis in Asia:

        $ {command} ubuntu:latest --location=asia
    )DESCRIPTIONEXAMPLESc                 r   t        j                         j                  |        t        j                         j                  |        t        j                         j                  |        t        j
                         j                  |        t        j                         j                  |        t        j                         j                  |        t        j                         j                  |        t        j                         j                  |        t        j                  j                  |        y )N)r   GetResourceURIArgAddToParserGetRemoteFlag%GetOnDemandScanningFakeExtractionFlagGetOnDemandScanningLocationFlagGetAdditionalPackageTypesFlagGetExperimentalPackageTypesFlagGetSkipPackageTypesFlagGetVerboseErrorsFlagr   
ASYNC_FLAG)parsers    +lib/surface/artifacts/docker/images/scan.pyArgszScanBeta.Args^   s    	))&1	%%f-	//1==fE	))+77?	'')55f=	))+77?	!!#//7	 ,,V4OO'    c           
      <   t         j                  j                         rt        j                  d      	 t
        j                  j                  dg       t               }t        j                  t        j                  |j                   rdnd      d      t        j                  t"        d      g}|j$                  s|t        j                  t&        d      gz  }| j)                         }t        j*                  t,        |	      5 }|j/                  d        ||j0                  |j                   |j2                  |j4                  |j6                  |j8                  |j:                  
      }|j<                  rd}|j>                  rHdjA                  |j>                  jC                         D cg c]  }|jE                  d      r| c}      }|sP|j<                  dk  r!tF        j                  |j<                        }n tH        j                  |j<                        }|jK                  dt        jL                  |             	 ddd       yg }	tO        jP                  |jR                        D ]i  }
|jU                  |
d   |
d   |
d         }d|
v r2tW        jX                  |
d   |jT                  jZ                        |_.        d|
v r
|
d   |_/        |	|gz  }	k |ja                  d       |j/                  d       | jc                  ||	      }|ja                  d       d}|j$                  s^|j/                  d       |je                  ddj                  |jf                               | ji                  |      }|ja                  d       ddd       |j$                  r:tj        jl                  jo                  dj                  jf                               |S S # t
        j                  $ r  t        j                  $ r Y w xY wc c}w # 1 sw Y   xY w)a1  Runs local extraction then calls ODS with the results.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      AnalyzePackages operation.

    Raises:
      UnsupportedOS: when the command is run on a Windows machine.
    z.On-Demand Scanning is not supported on Windowslocal-extractremotelocalextract)keyrpcpoll)stages)resource_urir(   fake_extractionadditional_package_typesexperimental_package_typesskip_package_typesverbose_errorsN
zExtraction failedr   )	exit_codepackageversioncpe_uri)r7   r8   cpeUripackage_typehash_digestz[{}]z Check operation [{}] for status.)8r   OperatingSystem	IsWindowsods_utilUnsupportedOSr   UpdateManagerEnsureInstalledAndRestartMissingRequiredComponentsErrorr   InvalidSDKRootErrorCommandr   StageEXTRACT_MESSAGEformatr(   RPC_MESSAGEasync_POLL_MESSAGEGetMessagesStagedProgressTrackerSCAN_MESSAGE
StartStageRESOURCE_URIr0   r1   r2   r3   r4   r6   stderrjoin
splitlines
startswith EXTRACTION_KILLED_ERROR_TEMPLATE!UNKNOWN_EXTRACTION_ERROR_TEMPLATE	FailStageExtractionFailedErrorjsonloadsstdoutPackageDatar   ChoiceToEnumPackageTypeValueValuesEnumpackageType
hashDigestCompleteStageAnalyzePackagesUpdateStagenameWaitForOperationr   statusPrint)selfargscmdr.   messagestrackeroperation_resultextraction_errorlinepkgspkgpkg_dataopresponses                 r#   RunzScanBeta.Runj   s      **,""
:< <
 ""<<o=NO )C 	""t{{8H	 	{6	F ;;!''&ABBf!H		/	/V
%(/#((..#'#@#@%)%D%D!44,, 
	#	#  ""!YY/66AAC(Ct!45 C( 
  ''!+?FF*44  G  7  AGG*44  H  7)"889IJ	L?
% 
%D d,334#''	N	Ny> ( 

 S !*!7!7.!""=="?(
 C #M 2(

 5 I& d+bE" h[[6"FFMM"''$:;((,f%{
%~ {{	jj9@@IJiOA 88  ** 
P(%
% 
%s8    O  B(P0P

A?PD>P &P
	P
PPc                     t        j                  t        j                  j                  j
                  j                  d      |j                  |j                  |      S NT)required)	api_utilAnalyzePackagesBetar   VALUEScoreprojectGetlocationrP   rh   ri   rp   s      r#   rb   zScanBeta.AnalyzePackages   sK    ''&&**D*9	 r%   c                 ,    t        j                  d      S Nv1beta1ry   rL   rh   s    r#   rL   zScanBeta.GetMessages   s    	**r%   c                 .    t        j                  |d      S r   r?   re   rh   rs   s     r#   re   zScanBeta.WaitForOperation   s    $$R33r%   N)__name__
__module____qualname____doc__detailed_helpstaticmethodr$   ru   rb   rL   re    r%   r#   r   r   5   sB    * 	-& 	( 	(xt+4r%   r   c                   "    e Zd ZdZd Zd Zd Zy)ScanGAr   c                     t        j                  t        j                  j                  j
                  j                  d      |j                  |j                  |      S rw   )	ry   AnalyzePackagesGAr   r{   r|   r}   r~   r   rP   r   s      r#   rb   zScanGA.AnalyzePackages  sK    %%&&**D*9	 r%   c                 ,    t        j                  d      S Nv1r   r   s    r#   rL   zScanGA.GetMessages  s    %%r%   c                 .    t        j                  |d      S r   r   r   s     r#   re   zScanGA.WaitForOperation  s    $$R..r%   N)r   r   r   r   rb   rL   re   r   r%   r#   r   r      s    &&/r%   r   c                   (     e Zd ZdZ fdZd Z xZS )rE   z"Wrapper for call to the Go binary.c                 0    t        t        | 
  dddi| y )Nbinaryr'   r   )superrE   __init__)rh   kwargs	__class__s     r#   r   zCommand.__init__  s    	'4!CCFCr%   c                    d|z   dt        j                  |      z   dt        j                  |      z   ddj                  g d      z   g}	g }
|r|
|z  }
|r|
|z  }
|
r6|	j                  dt        j                  dj                  |
            z          |r6|	j                  dt        j                  dj                  |            z          |r'|	j                  d	t        j                  |      z          |	j                  d
       |	S )Nz--resource_uri=z	--remote=z--provide_fake_results=z
--undefok=,)r1   r3   r4   use_scalibrz--additional_package_types=z--skip_package_types=z--verbose_errors=z--use_scalibr)six	text_typerR   append)rh   r/   r(   r0   r1   r2   r3   r4   r   ri   package_typess              r#   _ParseArgsForCommandzCommand._ParseArgsForCommand  s     	L(cmmF++!CMM/$BB
 	
(( 
 	D" M//m!11m
kk/-- 789 : 
kk
!CMM#((;M2N$O
O 
kk%n(EEFKK Kr%   )r   r   r   r   r   r   __classcell__)r   s   @r#   rE   rE     s    *D0r%   rE   )-r   
__future__r   r   r   rY   'googlecloudsdk.api_lib.ondemandscanningr   ry   googlecloudsdk.callioper   $googlecloudsdk.command_lib.artifactsr   r	   r?   &googlecloudsdk.command_lib.util.anthosr
   $googlecloudsdk.command_lib.util.apisr   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   googlecloudsdk.core.updaterr   r   googlecloudsdk.core.utilr   r   rN   rG   rI   rK   rU   rV   DefaultUniverseOnlyReleaseTracksReleaseTrackBETArE   r   GAr   BinaryBackedOperationr   r%   r#   <module>r      s    ? &  '  D ( 6 R D : # * 8 3 6 . 
 *%E; !
 @ " D%%**+x4t|| x4 , x4v D%%(()/X / */D655 6r%   