
    5                        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iZdZej2                   ej4                  ej6                  j8                  ej6                  j:                         G d dej<                                      Zej2                   ej4                  ej6                  j@                         G d dej<                                      Z!y)z-recommender API recommendations list command.    )absolute_import)division)unicode_literalsN)
exceptions)client_util)	locations)recommendation)recommenders)arg_parsers)base)flags)logEXAMPLESz
          Lists recommendations for a Cloud project.
            $ {command} --project=project-id --location=global --recommender=google.compute.instance.MachineTypeRecommender
        a  
        table(
          name.basename(): label=RECOMMENDATION_ID,
          primaryImpact.category: label=PRIMARY_IMPACT_CATEGORY,
          stateInfo.state: label=RECOMMENDATION_STATE,
          lastRefreshTime: label=LAST_REFRESH_TIME,
          priority: label=PRIORITY,
          recommenderSubtype: label=RECOMMENDER_SUBTYPE,
          description: label=DESCRIPTION
        )
    c                   Z    e Zd ZdZeZed        Zd Zd Z	de
fdZd Zd Zd	 Zd
 Zd Zy)Lista  List recommendations for Google Cloud resources.

  This command lists all recommendations for the specified Google Cloud
  resource, location, and recommender. If a recommender or location is not
  specified, recommendations for all supported recommenders or locations,
  respectively, are listed. If the `--recursive` flag is set,
  recommendations for child resources and projects are also listed.
  Supported recommenders can be found here:
  https://cloud.google.com/recommender/docs/recommenders.
  c                    t        j                  |        | j                  dddd       | j                  dddd       | j                  d	dt        j                  d
       | j
                  j                  t               y)Args is called by calliope to gather arguments for this command.

    Args:
      parser: An argparse parser that you can use to add arguments that go on
        the command line after this command.
    
--locationLOCATIONFzLocation to list recommendations for. If no location is specified, recommendations for all supported locations are listed. Not specifying a location can add 15-20 seconds to the runtime.metavarrequiredhelp--recommenderRECOMMENDERa'  Recommender to list recommendations for. If no recommender is specified, recommendations for all supported recommenders are listed. Supported recommenders can be found here: https://cloud.google.com/recommender/docs/recommenders Not specifying a recommender can add 15-20 seconds to the runtime.z--recursivea  
            In addition to listing the recommendations for the specified
            organization or folder, recursively list all of
            the recommendations for the resource's child resources, including
            their descendants (for example, a folder's sub-folders), and for the
            resource's child projects. For example, when using the
            `--recursive` flag and specifying an organization, the response
            lists all of the recommendations associated with that
            organization, all of the recommendations associated with that
            organization's folders and sub-folders, and all of the
            recommendations associated with that organization's child
            projects.  The maximum number of resources (organization,
            folders, projects, and descendant resources) that can be accessed at
            once with the `--recursive` flag is 100. For a larger
            number of nested resources, use
            [BigQuery export](https://cloud.google.com/recommender/docs/bq-export/export-recommendations-to-bq).
            Using `--recursive` can add 15-20 seconds per resource to the
            runtime.
            )r   actionr   N)r   AddParentFlagsToParseradd_argumentr   StoreTrueFalseActiondisplay_info	AddFormatDISPLAY_FORMATparsers    /lib/surface/recommender/recommendations/list.pyArgsz	List.ArgsH   s     
  (
O  	    //	  0 !!.1    c                    d|_         ddg|_        d|_        d|_        |j                  rd|j                  z   |_        |j                  rd|j                  z   |_        |j                  rd|j                  z   |_        |S )a	  Setups up args to search all resources under a project, folder, or organization.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.

    Returns:
      (argparse.Namespace) args with additional parameters setup
    *+cloudresourcemanager.googleapis.com/Project*cloudresourcemanager.googleapis.com/Folder
createTimez	projects/zorganizations/zfolders/)	read_maskasset_typesorder_byqueryprojectscopeorganizationfolder)selfargss     r%   setArgszList.setArgs   s{     DN 	64	D !DMDJ||-dj#d&7&77dj{{+djKr'   c                 0    t        |t              r|d   S |S )Nr   )
isinstancelist)r5   asset_ins     r%   readz	List.read   s    (D!a[or'   returnc                 X    || j                   vr| j                   j                  |       yy)NTF)resource_locationsappend)r5   resource_locations     r%   AddResourcezList.AddResource   s+     7 77
$$%67r'   c                 N   | j                  |      }t        j                  t        j                        }t	        |j                  |            }g | _        |D ]?  }| j                  |j                         d|j                   }d|vr| j                  |       |j                  dk(  r9| j                  | j                  |j                         d|j                          |j                  dk(  ry| j                  | j                  |j                         d|j                         r@| j                  |j                        |_        |j                  |j                  |             t        | j                        dkD  s-t!        j"                  d       | j                  S )zSearch all nested resources under a project, folder, or organization.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.

    Returns:
      (List): a list of all Google Cloud resource,location pairs
    /locations/r1   r*   r+   d   zThe maximum number of resources (organizations, folders, projects, and descendant resources) that can be accessed to list recommendations is 100. To access a larger number of resources, use BigQuery Export.)r7   r   AssetSearchClientDEFAULT_API_VERSIONr:   SearchAllResourcesr?   r<   r2   locationrB   	assetTyper1   foldersextendlenr   UnsupportedOperationError)r5   r6   client	resourcesrparent_resources         r%   searchAllResourceszList.searchAllResources   sb    <<D**;+J+JKFV..t45I D99TZZ01QZZLIo	/	)) 
E	EDIIaii01QZZLIJ ++E
E$))AII"6!7{1::,OPYYqyy)
22489	T$$	%	+22B
 	
# . """r'   c                    t         j                  j                  d       |j                  r| j	                  |      }|S |j
                  t        j                  | j                               }|j                  |j                  |j                  |j                  |j                  |j                        D cg c]  }|j                   }}|S t!        j"                  |      d|j
                   z   g}|S c c}w )a  Iterate through search all resources response and collects unique Google Cloud resouce,location pairs.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.

    Returns:
      (List): a list of all Google Cloud resource,location pairs
    z2Collecting Resources... This may take some time...)r1   r3   r4   billing_accountrD   )r   statusPrint	recursiverS   rI   r   CreateClientReleaseTrackr   	page_sizer1   r3   r4   rU   namer   GetResourceSegment)r5   r6   r?   
loc_clientlocs        r%   CollectAssetszList.CollectAssets   s     JJIJ~~2248$ ! 
	++D,=,=,?@
 "!..{{ $ 4 4 ' 	
 HH 	 	
  $$T*{4==/-JJ
 	
s   8C7c                     t        j                  | j                               }|j                  |j                        }t        |      S )zList all Recommenders.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.

    Returns:
      (list) all recommenders in a list of strings
    )r
   rY   rZ   r   r[   r:   )r5   r6   recommenders_clientrecommenders_responses       r%   ListRecommenderszList.ListRecommenders   s?     '33D4E4E4GH/44T^^D%&&r'   c                    g }t        j                  | j                               }d}d}|D ]  \  }}}	||k7  s||k7  r%t        j                  j                  d| d|        |}|}dj                  |||	g      }
|j                  |
|j                        }	 t        |      }t        j                  ||f|      } |S # t        j                  t        j                  t        f$ r Y w xY w)ap  Collects all recommendations for a given Google Cloud Resource.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.
      asset_recommenders: list, The list of Google Cloud resource recommender
        URL to collect recommendations

    Returns:
      (Recommendations) a iterator for all returned recommendations
    NzReading Recommendations for:  /)r	   rY   rZ   r   rV   rW   joinr   r[   nextapitools_exceptionsHttpBadRequestErrorBadStatusCodeErrorStopIteration	itertoolschain)r5   r6   asset_recommendersrecommendationsrecommendations_clientresource_prevlocation_prevresourcerI   recommenderparent_namenew_recommendationspeeks                r%   GetRecommendationszList.GetRecommendations  s    O+889J9J9LMMM+='(K	]	"h-&?

8
!H:NOmmHHh+>?k277
t~~'( "
D7$7o# ,>*  
1
1

0
0
 
 	s   B>>(C)(C)c           
         | j                  |      }g }|D ]  }|j                  d      }dj                  |dd       }dj                  |dd       }|j                  "|j	                  ||d|j                   f       j|j                  | j                  |      D cg c]  }||d|j                   f c}        | j                  ||      S c c}w )Run 'gcloud recommender recommendations list'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.

    Returns:
      The list of recommendations for this project.
    rg   N      zrecommenders/)	r`   splitrh   rv   r@   rL   rd   r\   rz   )	r5   r6   r?   rp   assettokensru   rI   responses	            r%   RunzList.Run.  s     ++D1 #{{3f&!*%h&1+&h				%!!x=1A1A0B!CD	
 	!! 11$7#
7 x=!@A7#
 	 $ ""4);<<#
s   C
N)__name__
__module____qualname____doc__DETAILED_HELPdetailed_helpstaticmethodr&   r7   r<   boolrB   rS   r`   rd   rz   r    r'   r%   r   r   8   sS    	  -72 72r:d '#R D''R=r'   r   c                   *    e Zd ZdZeZed        Zd Zy)ListOriginalae  List operations for a recommendation.

  This command lists all recommendations for a given Google Cloud entity ID,
  location, and recommender. Supported recommenders can be found here:
  https://cloud.google.com/recommender/docs/recommenders.
  The following Google Cloud entity types are supported: project,
  billing_account, folder and organization.
  c                     t        j                  |        | j                  dddd       | j                  dddd       | j                  j	                  t
               y	)
r   r   r   Tz%Location to list recommendations for.r   r   r   zRecommender to list recommendations for. Supported recommenders can be found here: https://cloud.google.com/recommender/docs/recommenders.N)r   r   r   r    r!   r"   r#   s    r%   r&   zListOriginal.Args]  sk     
  (
4	   G  	 !!.1r'   c                     t        j                  | j                               }t        j                  |      }|j                  ||j                        S )r|   )r	   rY   rZ   r   GetRecommenderNamer   r[   )r5   r6   rr   rw   s       r%   r   zListOriginal.Runx  sE     ,889J9J9LM**40K!&&{DNNCCr'   N)	r   r   r   r   r   r   r   r&   r   r   r'   r%   r   r   O  s&      -2 24Dr'   r   )"r   
__future__r   r   r   rn   apitools.base.pyr   rj   googlecloudsdk.api_lib.assetr   "googlecloudsdk.api_lib.recommenderr   r	   r
   googlecloudsdk.callioper   r   &googlecloudsdk.command_lib.recommenderr   googlecloudsdk.command_lib.rungooglecloudsdk.corer   r   r"   UniverseCompatibleReleaseTracksrZ   ALPHABETAListCommandr   GAr   r   r'   r%   <module>r      s    4 &  '  > 4 8 = ; / ( 8 5 # 	
 D%%++T->->-C-CDR=4 R= E R=j D%%(()4D4## 4D * 4Dr'   