
    f%                        d dl Z d dlZd dlZd dlmZ d dlmZmZmZ d dlm	Z	m
Z
mZmZmZ d dlmZ  e
j                          Z ej$                   ej&                  e            Z G d d      Z G d d	e      Z G d
 d      Zy)    N)datetime)AnyDictOptional)defaultsevent_logger
exceptionssystemutil)PublicMachineTokenDatac                       e Zd Zej                  dfdededefdZedefd       Z	edefd       Z
ed	        Zd
efdZdee   fdZd Zy)UAFileTname	directoryprivatec                     || _         || _        || _        t        j                  j                  | j                   | j                        | _        y N)
_directory
_file_name_is_privateospathjoin_path)selfr   r   r   s       6/usr/lib/python3/dist-packages/uaclient/files/files.py__init__zUAFile.__init__   s8     $"WW\\$//4??C
    returnc                     | j                   S r   )r   r   s    r   r   zUAFile.path   s    zzr   c                     | j                   S r   )r   r!   s    r   
is_privatezUAFile.is_private   s    r   c                 T    t         j                  j                  | j                        S r   )r   r   existsr!   s    r   
is_presentzUAFile.is_present"   s    ww~~dii((r   contentc                    | j                   rt        j                  nt        j                  }	 t        j
                  j                  | j                        t        j                  k(  r"t	        j                  | j                  d       nt	        j                  | j                         t        j                  | j
                  ||       y # t        $ r Y -w xY w)Ni  )mode)r#   r   ROOT_READABLE_MODEWORLD_READABLE_MODEr   r   basenamer   PRIVATE_SUBDIRmakedirsOSErrorr
   
write_file)r   r'   	file_modes      r   writezUAFile.write&   s      ''-- 		ww0H4K4KKDOO%8DOO, 	$))Wi8  		s   A;C 	CCc                     d }	 t        j                  | j                        }|S # t        $ r$ t        j                  d| j                         Y |S w xY w)Nz(Tried to load %s but file does not exist)r
   	load_filer   FileNotFoundErrorLOGdebug)r   r'   s     r   readzUAFile.read7   sS    	M&&tyy1G  ! 	MII@$))L	Ms   % )AAc                 B    t        j                  | j                         y r   )r
   ensure_file_absentr   r!   s    r   deletezUAFile.delete?   s    !!$)),r   N)__name__
__module____qualname__r   DEFAULT_DATA_DIRstrboolr   propertyr   r#   r&   r2   r   r8   r;    r   r   r   r      s     "22		D	D 	D 		D c    D     ) )9S 9"hsm -r   r   c                   $     e Zd Zdef fdZ xZS )UserCacheFiler   c                 N    t         |   |t        j                         d       y )NF)r   r   )superr   r
   get_user_cache_dir)r   r   	__class__s     r   r   zUserCacheFile.__init__D   s%    F557 	 	
r   )r<   r=   r>   r@   r   __classcell__)rI   s   @r   rE   rE   C   s    
S 
 
r   rE   c                   f   e Zd Zej                  dfdedee   fdZdefdZ	d Z
dee   fd	Zed
        Zed        Zd Zedee   fd       Zed        Zedefd       Zedee   fd       Zed        Zedee   fd       Zedd       Zedd       Zedd       Zed        Zed        Zy)MachineTokenFileNr   machine_token_overlay_pathc                     t         j                  }t        ||dz   t         j                  z         | _        t        ||d      | _        || _        d | _        d | _        d | _	        y )N/F)
r   MACHINE_TOKEN_FILEr   r-   private_filepublic_filerM   _machine_token_entitlements_contract_expiry_datetime)r   r   rM   	file_names       r   r   zMachineTokenFile.__init__K   sc    
 //	"y3)@)@@
 ")Y>*D'"!)-&r   private_contentc                    t        j                         rt        j                  |t         j                        }| j
                  j                  |       t        j                  |      j                  d      }t        j                  |t         j                        }| j                  j                  |       d| _        d| _        d| _        yt        j                         )z8Update the machine_token file for both pub/private filesclsF)	keep_noneN)r   we_are_currently_rootjsondumpsDatetimeAwareJSONEncoderrQ   r2   r   	from_dictto_dictrR   rS   rT   rU   r	   NonRootUserError)r   rW   private_content_strpublic_contentpublic_content_strs        r   r2   zMachineTokenFile.writeZ   s    %%'"&**T%B%B# ##$78 4==gg&  "&D$A$A" ""#56"&D!%D-1D*--//r   c                     t        j                         rJ| j                  j                          | j                  j                          d| _        d| _        d| _        yt        j                         )z!Delete both pub and private filesN)
r   r\   rR   r;   rQ   rS   rT   rU   r	   rb   r!   s    r   r;   zMachineTokenFile.deleter   sY    %%'##%$$&"&D!%D-1D*--//r   r   c                     t        j                         r| j                  }n| j                  }|j	                         }|sy 	 t        j                  |t         j                        }|S # t        $ r Y |S w xY wNrY   )	r   r\   rQ   rR   r8   r]   loadsDatetimeAwareJSONDecoder	Exception)r   file_handlerr'   s      r   r8   zMachineTokenFile.read~   ss    %%',,L++L##%	jjd.K.KLG   		s   %A) )	A65A6c                     t        j                         r.| j                  j                  xr | j                  j                  S | j                  j                  S r   )r   r\   rR   r&   rQ   r!   s    r   r&   zMachineTokenFile.is_present   sC    %%'##..O43D3D3O3OO##...r   c                     | j                   sY| j                         }|r@| j                  r4| j                  | j                        }|rt	        j
                  ||       || _         | j                   S )zAReturn the machine-token if cached in the machine token response.)	base_dictoverlay_dict)rS   r8   rM   parse_machine_token_overlayr   depth_first_merge_overlay_dict)r   r'   machine_token_overlays      r   machine_tokenzMachineTokenFile.machine_token   sl     ""iikG4::(,(H(H33)% )77")%: #*D"""r   c                 v    t        j                  |      }t        j                  |t        j
                        S rh   )r
   r4   r]   ri   r   rj   )r   rM   machine_token_overlay_contents      r   rq   z,MachineTokenFile.parse_machine_token_overlay   s5    (.(8(8&)
% zz)--
 	
r   c                 R    t        | j                        r| j                  d   d   S y )NmachineTokenInfoaccountInforA   rt   r!   s    r   accountzMachineTokenFile.account   s*    ""#%%&89-HHr   c                     | j                   r| j                   S | j                  si S | j                  | j                        | _         | j                   S )z9Return configured entitlements keyed by entitlement named)rT   rt   get_entitlements_from_tokenr!   s    r   entitlementszMachineTokenFile.entitlements   sQ     %%%!!I!==
 !!!r   rt   c                 Z   ddl m} | si S i }| j                  di       j                  d      }|si S t        d | j                  dg       D              }t        d |j                  dg       D              }|j	                         D ]"  \  }}d	|i}||v r||   |d
<    ||       |||<   $ |S )zReturn a dictionary of entitlements keyed by entitlement name.

        Return an empty dict if no entitlements are present.
        r   )apply_contract_overridesrx   contractInfoc              3   `   K   | ]&  }|j                  d       |j                  d      f ( yw)typetokenNget.0es     r   	<genexpr>z?MachineTokenFile.get_entitlements_from_token.<locals>.<genexpr>   s-      
 UU6]AEE'N+
s   ,.resourceTokensc              3   B   K   | ]  }|j                  d       |f  yw)r   Nr   r   s     r   r   z?MachineTokenFile.get_entitlements_from_token.<locals>.<genexpr>   s%      
 UU6]A
s   resourceEntitlementsentitlementresourceToken)uaclient.contractr   r   dictitems)	rt   r   r~   r   tokens_by_nameent_by_nameentitlement_name	ent_valueentitlement_cfgs	            r   r}   z,MachineTokenFile.get_entitlements_from_token   s     	?I$(();R@DD
 I 
"&&'7<
 
  
!%%&<bA
 
 ,7+<+<+> 	='i,i8O>13A$40 %_5-<L)*	= r   c                     | j                   sA| j                  j                  di       j                  di       j                  dd      | _         | j                   S )z6Return a datetime of the attached contract expiration.rx   r   effectiveToN)rU   rt   r   r!   s    r   contract_expiry_datetimez)MachineTokenFile.contract_expiry_datetime   sR     --""&&'92>^R(]D) * ---r   c                 ,    t        | j                        S )z<Report whether this machine configuration is attached to UA.rz   r!   s    r   is_attachedzMachineTokenFile.is_attached   s     D&&''r   c                     | j                   y| j                   j                         t        j                         j                         z
  }|j                  S )a  Report num days until contract expiration based on effectiveTo

        :return: A positive int representing the number of days the attached
            contract remains in effect. Return a negative int for the number
            of days beyond contract's effectiveTo date.
        N)r   dater   utcnowdays)r   deltas     r   contract_remaining_daysz(MachineTokenFile.contract_remaining_days   sF     ((0--224x7H7M7M7OOzzr   c                 r    | j                   r+| j                   j                  di       j                  d      S y )NactivityInfoactivityTokenrt   r   r!   s    r   activity_tokenzMachineTokenFile.activity_token  s9    %%))."=AA  r   c                 r    | j                   r+| j                   j                  di       j                  d      S y )Nr   
activityIDr   r!   s    r   activity_idzMachineTokenFile.activity_id
  s2    %%))."=AA,OOr   c                 r    | j                   r+| j                   j                  di       j                  d      S y )Nr   activityPingIntervalr   r!   s    r   activity_ping_intervalz'MachineTokenFile.activity_ping_interval  s9    %%))."=AA&  r   c                     | j                   r;| j                   j                  di       j                  di       j                  d      S y )Nrx   r   idr   r!   s    r   contract_idzMachineTokenFile.contract_id  sA    ""&&'92>^R(T
 r   c                 T    | j                   r| j                   j                  dg       S y )Nr   r   r!   s    r   resource_tokensz MachineTokenFile.resource_tokens"  s(    %%))*:B??r   )r   zOptional[str])r   zOptional[int])r<   r=   r>   r   r?   r@   r   r   r   r2   r;   r8   rB   r&   rt   rq   r{   r~   staticmethodr   r}   r   r   r   intr   r   r   r   r   r   rC   r   r   rL   rL   J   s    "2248.. %-SM.0T 00
0htn  / / # #"
 $  
 	" 	" !4 ! !F 	.(8*< 	. 	. ( ( 
# 
 
    
      r   rL   )r]   loggingr   r   typingr   r   r   uaclientr   r   r	   r
   r   uaclient.contract_data_typesr   get_event_loggerevent	getLoggerreplace_top_level_logger_namer<   r6   r   rE   rL   rC   r   r   <module>r      ss      	  & & E E ?%%%'g:::8DE2- 2-j
F 
] ]r   