
                            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 Z G d dej"                        Zej&                  j(                  dej&                  j*                  dej&                  j,                  dej&                  j.                  dej&                  j0                  dej&                  j2                  diZdZddZd Zd ZeeddddfdZd Z d Z! G d d      Z"y)z3Used to collect anonymous transfer-related metrics.    )absolute_import)division)unicode_literalsN)storage_url)	task_util)metrics)
properties)files)	platformsc                  t   t         j                  j                  j                  j	                         rt         j                  j
                  j                  j                         j                  dd      } t         j                  j                  t         j                  j
                  j                  | d       yy)aE  Transform the user agent when the gsutil shim is used to run gcloud.

  This transforms `gcloud.storage.command` to `gcloud.gsutil.command`.

  This needs to be called by every command, so the best place to put this is
  likely surface/storage/__init__.py, but if there's a better place it could be
  called there instead.
  zgcloud.storage.zgcloud.gslibshim.N)
r	   VALUESstoragerun_by_gsutil_shimGetBoolr   command_nameGetreplaceSetInvocationValue)command_path_strings    6lib/googlecloudsdk/command_lib/storage/metrics_util.pyfix_user_agent_for_gsutil_shimr      s     1199;$++33@@DDFNN.0((!!..0CTK <    c                       e Zd ZdZdZy)ParallelismStrategy      N)__name__
__module____qualname__
SEQUENTIALPARALLEL r   r   r   r   /   s    *(r   r   r   r               c                     t         j                  j                  j                  j	                         }t        j
                  |d| z   |       y)zCommon code for processing an event.

  Args:
    metric (str): The metric being recorded.
    value (mixed): The value being recorded.
  zStorage-N)r	   r   r   r   r   CustomKeyValue)metricvaluer   s      r   _record_storage_eventr+   A   s;     ""**77;;=,	zF':EBr   c                      t        j                         rt        j                  j                  S t        j
                  j                  S N)r   should_use_parallelismr   r!   r*   r    r"   r   r   _get_parallelism_strategyr/   L   s2    %%'''---		'	'	-	--r   c                  n    t         j                  j                  j                  j	                         rdS dS )Nr   r   )r	   r   r   r   r   r"   r   r   _get_run_by_gsutil_shimr1   R   s*    ''::BBDK!Kr   c                     t        dt                      t        dt                      t        d|        t        d|       t        d|       t        d|       t        d|       t        d|       y	)
a  Reports metrics for a transfer.

  Args:
    source_scheme (int): The source scheme, i.e. 'gs' or 's3'.
    destination_scheme (int): The destination scheme i.e. 'gs' or 's3'.
    num_files (int): The number of files transferred.
    size (int): The size of the files transferred, in bytes.
    avg_speed (int): The average throughput of a transfer in bytes/sec.
    disk_io_time (int): The time spent on disk of a transfer in ms.
  r   RunByGsutilShimSourceSchemeDestinationSchemeNumberOfFilesSizeOfFilesBytesAverageSpeedBytesPerSecDiskIoTimeMsN)r+   r/   r1   source_schemedestination_scheme	num_filessize	avg_speeddisk_io_times         r   reportrA   V   sb     -/H/JK)+B+DE6+-?@3*D119=5r   c                  @   g } 	 t        j                  d      5 }|j                         dd }|D ]<  }|j                         \  }}}}|d   j	                         s,| j                  |       > 	 ddd       | S # 1 sw Y   | S xY w# t         j                  $ r Y | S w xY w)z_Retrieves a list of disk partitions.

  Returns:
    An array of partition names as strings.
  z/proc/partitionsr   N)r
   
FileReader	readlinessplitisdigitappendError)
partitionsflinesline_names         r   _get_partitionsrP   l   s     *
				,	-kkmABe$

1a8


D
!  
. 
 
. 
 
 			s5   B AA9A9/B 9B>B B BBc                     d} t               }i }	 t        j                  d      5 }|j                         }|D ]{  }|j	                         dd }|\  }}}}	}}
}}}}}||v s)t        |
      | z  }
t        |      | z  }t        |	      }	t        |      }t        |      }t        |      }|	||
|||f||<   } 	 ddd       |S # 1 sw Y   |S xY w# t        j                  $ r Y |S w xY w)a  Retrieves disk I/O statistics for all disks.

  Adapted from the psutil module's psutil._pslinux.disk_io_counters:
    http://code.google.com/p/psutil/source/browse/trunk/psutil/_pslinux.py

  Originally distributed under under a BSD license.
  Original Copyright (c) 2009, Jay Loden, Dave Daeschler, Giampaolo Rodola.

  Returns:
    A dictionary containing disk names mapped to the disk counters from
    /disk/diskstats.
  i   z/proc/diskstatsN   )rP   r
   rD   rE   rF   intrI   )sector_sizerJ   retdictrK   rL   rM   valuesrN   rO   readsrbytesrtimewriteswbyteswtimes                  r   get_disk_countersr]      s     + *'				+	,kkme$cr"HNE1dE1feVQ:v;,&v;,&e*%v;&e*%e*% &&&%G'$-  
-$ 
.% 
-$ 
. 
 		.	s5   C ;C!AC7C CC C C%$C%c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)MetricsReporterz9Mix-in for tracking metrics during task status reporting.c                 N    t         | _        t         | _        t               | _        y r-   )UNSET_source_scheme_destination_schemer]   _disk_counters_start)selfs    r   __init__zMetricsReporter.__init__   s    D$D 1 3Dr   c                 8    |rt         |j                     S t        S )z;Extracts the scheme as an integer value from a storage_url.)PROVIDER_PREFIX_TO_METRICS_KEYschemera   )re   urls     r   _get_scheme_valuez!MetricsReporter._get_scheme_value   s    
+CJJ77Lr   c                     | j                   t        k(  r | j                  |j                        | _         | j                  t        k(  r!| j                  |j
                        | _        yy)zSets source and destination schemes, if available.

    Args:
      status_message (thread_messages.*): Message to process.
    N)rb   ra   rk   
source_urlrc   destination_url)re   status_messages     r   #_set_source_and_destination_schemesz3MetricsReporter._set_source_and_destination_schemes   sZ     e# 22>3L3LMd5(!%!7!7

(
("*d )r   c           	         t         j                  j                         }|t         j                  j                  k(  rw| j                  }t               }t        |j                         D cg c]  }|d   |d   z    c}      t        |j                         D cg c]  }|d   |d   z    c}      z
  S t        S c c}w c c}w )z&Calculate deltas of time spent on I/O.r$   r%   )	r   OperatingSystemCurrentLINUXrd   r]   sumrV   ra   )re   
current_os
disk_startdisk_endstats        r   _calculate_disk_ioz"MetricsReporter._calculate_disk_io   s    **224JY..444,,j"$h1BC1B47T!W$1BCD1B1B1DE1D47T!W$1DEFG HL DEs   )B9B>
c           	          t        t        |      t        |      z        }t        | j                  | j                  |||| j                                y)zReports back all tracked events via report method.

    Args:
      total_bytes (int): Amount of data transferred in bytes.
      time_delta (int): Time elapsed during the transfer in seconds.
      num_files (int): Number of files processed
    r:   N)roundfloatrA   rb   rc   rz   )re   total_bytes
time_deltar=   r?   s        r   _report_metricszMetricsReporter._report_metrics   sL     eK(5+<<=I
))33,,.0r   N)	r   r   r   __doc__rf   rk   rp   rz   r   r"   r   r   r_   r_      s    A4
*	0r   r_   )r   )#r   
__future__r   r   r   enum"googlecloudsdk.command_lib.storager   (googlecloudsdk.command_lib.storage.tasksr   googlecloudsdk.corer   r	   googlecloudsdk.core.utilr
   r   r   Enumr   ProviderPrefixFILEGCSHTTPHTTPSPOSIXS3rh   ra   r+   r/   r1   rA   rP   r]   r_   r"   r   r   <module>r      s    : &  '  : > ' * * .K $))  ##Q""A##Q$$a$$a!!1"  	
C.L 5AQQ6,.(V70 70r   