
    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 insights list command.    )absolute_import)division)unicode_literalsN)
exceptions)client_util)insight)insight_types)	locations)arg_parsers)base)flags)logEXAMPLESz
        To list all insights for a billing account:

          $ {command} --project=project-id --location=global --insight-type=google.compute.firewall.Insight
        Q  
        table(
          name.basename(): label=INSIGHT_ID,
          category: label=CATEGORY,
          stateInfo.state: label=INSIGHT_STATE,
          lastRefreshTime: label=LAST_REFRESH_TIME,
          severity: label=SEVERITY,
          insightSubtype: label=INSIGHT_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 insights for Google Cloud resources.

  This command lists all insights for the specified Google Cloud resource,
  location, and insight type. If an insight type or location is not specified,
  insights for all supported insight types or locations, respectively, are
  listed. If the `--recursive` flag is set, insights for child resources and
  projects are also listed. Supported insight types can be found here:
  https://cloud.google.com/recommender/docs/insights/insight-types.
  c                    t        j                  |        | j                  dddd       | j                  dddd       | j                  d	t        j                  d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 insights for. If no location is specified, insights for all supported locations are listed. Not specifying a location can add 15-20 seconds to the runtime.metavarrequiredhelp--insight-typeINSIGHT_TYPEa$  Insight type to list insights for. If no insight type is specified, insights for all supported insight types are listed. Supported insight types can be found here: https://cloud.google.com/recommender/docs/insights/insight-types Not specifying an insight-type can add a minute to the runtime.z--recursivea  
            In addition to listing the insights for the specified organization
            or folder, recursively list all of
            the insights 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 insights associated with that
            organization, all of the insights associated with that
            organization's folders and sub-folders, and all of the
            insights 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.
            )actionr   r   N)r   AddParentFlagsToParseradd_argumentr   StoreTrueFalseActiondisplay_info	AddFormatDISPLAY_FORMATparsers    (lib/surface/recommender/insights/list.pyArgsz	List.ArgsG   s     
  (
O  	 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)r6   asset_ins     r&   readz	List.read   s    (D!a[or(   returnc                 X    || j                   vr| j                   j                  |       yy)NTF)resource_locationsappend)r6   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/r2   r+   r,   d   zThe maximum number of resources (organizations, folders, projects, and descendant resources) that can be accessed to list insights is 100. To access a larger number of resources, use BigQuery Export.)r8   r   AssetSearchClientDEFAULT_API_VERSIONr;   SearchAllResourcesr@   r=   r3   locationrC   	assetTyper2   foldersextendlenr   UnsupportedOperationError)r6   r7   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
 	
% 2 """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...)r2   r4   r5   billing_accountrE   )r   statusPrint	recursiverT   rJ   r
   CreateClientReleaseTrackr   	page_sizer2   r4   r5   rV   namer   GetResourceSegment)r6   r7   r@   
loc_clientlocs        r&   CollectAssetszList.CollectAssets   s     JJIJ~~2248" ! 
	))$*;*;*=>j  __nnll,,[["22 % 	c ((  	  
"
"4
([+H
H 	s   8C7c                     t        j                  | j                               }|j                  |j                        }|D cg c]  }|j
                   c}S c c}w )zList all Insight Types.

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

    Returns:
      (list) all insight-types in a list of strings
    )r	   rZ   r[   r   r\   r]   )r6   r7   insighttypes_clientinsighttypes_responseresponses        r&   ListInsightTypeszList.ListInsightTypes   sQ     (44T5F5F5HI/44T^^D*?@*?hHMM*?@@@s   A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)aW  Collects all insights for a given Google Cloud Resource.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
        with.
      asset_insight_types: list, The list of Google Cloud resource insight types
        URL to collect insights

    Returns:
      (Insights) a iterator for all returned insights
    NzReading Insights for:  /)r   rZ   r[   r   rW   rX   joinr   r\   nextapitools_exceptionsHttpBadRequestErrorBadStatusCodeErrorStopIteration	itertoolschain)r6   r7   asset_insight_typesinsightsinsights_clientresource_prevlocation_prevresourcerJ   insight_typeparent_namenew_insightspeeks                r&   GetInsightszList.GetInsights  s    H**4+<+<+>?OMM,?((L	]	"h-&?

1(1XJGHmmHHh,?@k$))
t~~lL! 
TG\h# -@* 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| f c}        | j                  ||      S c c}w )zRun 'gcloud recommender insights list'.

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

    Returns:
      The list of insights for this Google Cloud Resource.
    ri   N      zinsightTypes/)ra   splitrj   rx   rA   rM   rf   r|   )	r6   r7   r@   rr   assettokensrw   rJ   r]   s	            r&   RunzList.Run+  s     ++D1 #{{3f&!*%h&1+&h				&""x=1B1B0C!DE	
 	""--d3$
3 x=!783$
 	 $ D"566$
s   C
N)__name__
__module____qualname____doc__DETAILED_HELPdetailed_helpstaticmethodr'   r8   r=   boolrC   rT   ra   rf   r|   r    r(   r&   r   r   8   sT      -62 62p:d )#VBA%N7r(   r   c                   *    e Zd ZdZeZed        Zd Zy)ListOriginalau  List insights for a Google Cloud entity.

  This command lists all insights for a given Google Cloud entity, location, and
  insight type. Supported insight-types can be found here:
  https://cloud.google.com/recommender/docs/insights/insight-types. Currently
  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	                  d	       y
)r   r   r   TzLocation to list insights for. r   r   r   zInsight type to list insights for. Supported insight-types can be found here: https://cloud.google.com/recommender/docs/insights/insight-typesr   N)r   r   r   r!   r"   r$   s    r&   r'   zListOriginal.ArgsZ  sp     
  (
.	   O  	 !! 
# 
	r(   c                     t        j                  | j                               }t        j                  |      }|j                  ||j                        S )zRun 'gcloud recommender insights list'.

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

    Returns:
      The list of insights for this project.
    )r   rZ   r[   r   GetInsightTypeNamer   r\   )r6   r7   rt   ry   s       r&   r   zListOriginal.Run  sD     **4+<+<+>?O**40KT^^<<r(   N)	r   r   r   r   r   r   r   r'   r   r   r(   r&   r   r   L  s&      -"	 "	H=r(   r   )"r   
__future__r   r   r   rp   apitools.base.pyr   rl   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#   DefaultUniverseOnlyReleaseTracksr[   ALPHABETAListCommandr   GAr   r   r(   r&   <module>r      s    - &  '  > 4 6 < 8 / ( 8 5 #  
 D%%++T->->-C-CDO74 O7 E O7d D%%(()?=4## ?= * ?=r(   