
    d;                         d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmc m	Z	 d dl
mZ d dlmc mZ d dlmZmZ d dlmc mc mZ d dlmc mc mZ d dlmZ d dlmZ d dlmZ dZd	Z G d
 de      Zy)    N)sleep)ustr)	add_eventWALAEventOperation)ResourceDiskError)
get_osutil)
AGENT_NAMEzDATALOSS_WARNING_README.txtaM  WARNING: THIS IS A TEMPORARY DISK.

Any data stored on this drive is SUBJECT TO LOSS and THERE IS NO WAY TO RECOVER IT.

Please do not use this disk for storing any personal or application data.

For additional details to please refer to the MSDN documentation at :
http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx
c                   ^    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zed
        Zd Zd Zy)ResourceDiskHandlerc                 T    t               | _        t        j                         | _        y N)r   osutilconfget_resourcedisk_filesystemfs)selfs    M/usr/lib/python3/dist-packages/azurelinuxagent/daemon/resourcedisk/default.py__init__zResourceDiskHandler.__init__1   s     l224    c                 d    t        j                  | j                        }|j                          y )N)target)	threadingThreadrunstart)r   disk_threads     r   start_activate_resource_diskz0ResourceDiskHandler.start_activate_resource_disk5   s"    &&dhh7r   c                     d }t        j                         r| j                         }|'t        j                         r| j	                  |       y y y r   )r   get_resourcedisk_formatactivate_resource_diskget_resourcedisk_enable_swapenable_swap)r   mount_points     r   r   zResourceDiskHandler.run9   sK    '')557K"113[) 4 #r   c                     t        j                  d       	 t        j                         }| j	                  |      }t
        j                  j                  |t              }	 t        j                  |t               |S # t        $ r!}t        j                  d|       Y d }~|S d }~ww xY w# t        $ rJ}t        j                  d|       t!        t"        dt%        |      t&        j(                         Y d }~y d }~ww xY w)NzActivate resource diskz%Failed to write data loss warning:{0}z!Failed to mount resource disk {0}F)name
is_successmessageop)loggerinfor   get_resourcedisk_mountpointmount_resource_diskospathjoinDATALOSS_WARNING_FILE_NAMEfileutil
write_fileDATA_LOSS_WARNINGIOErrorwarnr   errorr   r	   r   r   ActivateResourceDisk)r   r#   warning_filees       r   r    z*ResourceDiskHandler.activate_resource_diskA   s    ,-	B::<K22;?K77<<(BDLH##L2CD   HCQGGH ! 	BLL<a@:%a+@@B B		BsC   A	B* !A= ;B* =	B'B"B* "B''B* *	C=3A C88C=c                     t        j                  d       	 t        j                         }| j	                  ||       y # t
        $ r }t        j                  d|       Y d }~y d }~ww xY w)NzEnable swapzFailed to enable swap {0})r)   r*   r   get_resourcedisk_swap_size_mbcreate_swap_spacer   r6   )r   r#   size_mbr9   s       r   r"   zResourceDiskHandler.enable_swapS   sS    M"	988:G"";8  	9LL4a88	9s   &> 	A'A""A'c                     t        j                  dj                  |      d      r't        j                  dj                  |      d       y y )Nzsfdisk -R {0}Fchk_errzblockdev --rereadpt {0})	shellutilr   format)r   devices     r   reread_partition_tablez*ResourceDiskHandler.reread_partition_table[   s>    ==//7GMM3::6B"') Hr   c                 l   | j                   j                  d      }|t        d      dj                  |      }|dz   }t	        j
                  d      d   }| j                   j                  ||      }|rt        j                  d||       |S 	 t        j                  |d       t        j                  d       t	        j
                  dj                  |            }|d   rt        dj                  ||d               d}	| j                  dk(  rd}	dj                  | j                  ||	      }
d|d   v rLt        j                  d       |d   j                  d      D cg c]  }t        j                   d|      r| }}t        j                  dt#        |             t#        |      dkD  rt        j                  d       t%        dt#        |      dz         D ]=  }t        j                  d|       t	        j&                  dj                  ||             ? t        j                  d       t	        j&                  dj                  |             t        j                  d|
       t	        j&                  |
       nt        j                  d       | j)                  dd j                  |      !      }|d   j+                         }|d"k(  r| j                  d#k7  rtt        j                  d$       | j)                  d%d&j                  |      !       | j-                  |       t        j                  d|
       t	        j&                  |
       nt        j                  d'|       t/        j0                         }| j3                  |||      }d(}t4        j6                  j9                  |      sQ|dkD  rLt        j                  d)||       t;        d(       |dz  }t4        j6                  j9                  |      s|dkD  rLt4        j6                  j9                  |      st        d*j                  |            t        j                  d+|       t	        j
                  |d%,      \  }}|d-k(  r+|j=                  d.      d/k7  rt        j>                  d0|       n|dk7  rt        j>                  d1       | j-                  |       t	        j
                  |d%,      \  }}|rat        j>                  d2|       t	        j&                  |
       t	        j
                  |      \  }}|rt        d3j                  |||            t        j                  d4||| j                         |S # t        $ r9}d	j                  ||      }t        j                  |       t        ||
      d }~ww xY wc c}w )5N   zunable to detect disk topologyz/dev/{0}1mountz,Resource disk [{0}] is already mounted [{1}]i  )modez1Failed to create mount point directory [{0}]: {1})msginnerzExamining partition tablezparted {0} printr   z/Could not determine partition info for {0}: {1}Fxfsfzmkfs.{0} -{2} {1}gptz GPT detected, finding partitions
z
^\s*[0-9]+zFound {0} GPT partition(s).zRemoving old GPT partitionszRemove partition {0}zparted {0} rm {1}zCreating new GPT partitionz!parted {0} mkpart primary 0% 100%zFormat partition [{0}]z(GPT not detected, determining filesystemTz{0} 1 -n)suppress_message
option_str7ntfszCThe partition is formatted with ntfs, updating partition type to 83Fz{0} 1 83zThe partition type is {0}   z3Waiting for partition [{0}], {1} attempts remainingzPartition was not created [{0}]zMount resource disk [{0}]r?       zis already mountedz"Could not mount resource disk: {0}zNFailed to mount resource disk. Retry mounting after re-reading partition info.zJFailed to mount resource disk. Attempting to format and retry mount. [{0}]z<Could not mount {0} after syncing partition table: [{1}] {2}z,Resource disk {0} is mounted at {1} with {2}) r   device_for_ide_portr   rB   rA   run_get_outputget_mount_pointr)   r*   r1   mkdirOSErrorr6   r   splitrematchlenranger   change_partition_typestriprD   r   get_resourcedisk_mountoptionsget_mount_stringr-   r.   existsr   findr5   )r   r#   rC   	partition
mount_listexistingoserJ   retforce_optionmkfs_stringxpartsiptypemount_optionsmount_stringattemptsoutputs                      r   r,   z'ResourceDiskHandler.mount_resource_disk`   s   003>#$DEE""6*SL	--g6q9
;;..z6BKKF! " O	8NN;U3 	/0&&'9'@'@'HIq6# %//5vfc!f/EG G 77eL)00GGY. CF?KK:; #AT 2 11XXmQ/  1E 1KK5s5zB5zA~9:q#e*q.1 IAKK 6:MM"5"<"<VQ"GHI 897>>vFH 4kBk*KKBC,,!%%,,V4 - 6C FLLNE|6 1 3 4**%*)008 + : ++F34kBk*7?::<,,]-6-8: ''..+1KKM! " !HMH ''..+1 ww~~i(#188CE E 	/>..|UKV"9%9:b@KK<fEAX KK J K ''/#22<OKC J"$ k*'66|DV+ -88>y?B?E9GH H 	BGG	 Q  	8))/S)A LL#377		8(1s   U, %V1,	V.54V))V.c                 |   d}dj                  ||rdnd|      }t        j                  |dd      \  }}|dk7  rIt        j                  d	|       d
}dj                  ||rdnd|      }t        j                  |d      \  }}|dk(  rt        j                  d|       ||fS t        j
                  d|||       ||fS )z|
            use sfdisk to change partition type.
            First try with --part-type; if fails, fall back to -c
        z--part-typezsfdisk {0} {1} {2}z-f FT)r@   log_cmdr   z6sfdisk with --part-type failed [{0}], retrying with -cz-c)ry   z{0} succeededz{0} failed [{1}: {2}])rB   rA   rY   r)   r*   r6   )r   rQ   rR   option_to_usecommanderr_coderv   s          r   rb   z)ResourceDiskHandler.change_partition_type   s     &&--#34ZI$33UD2& q=KKH !M*11'7tRMG(77NHfq=KK!  LL0 !!
 r   c                 |    |dj                  | j                  |||      S dj                  | j                  ||      S )Nzmount -t {0} -o {1} {2} {3}zmount -t {0} {1} {2})rB   r   )r   rs   rh   r#   s       r   re   z$ResourceDiskHandler.get_mount_string   sM    $077	  *00 r   c                     | |v rt         j                  j                  |       rt         j                  j                  |       |k(  rt	        j
                  d       t        j                  |       j                  }|t        j                  t        j                  z  z  r`|t        j                  t        j                  z   z  }t	        j
                  dj                  | |             t        j                  | |       yy)NzSwap already enabledzChanging mode of {0} to {1:o}TF)r-   r.   isfilegetsizer)   r*   statst_modeS_IRWXGS_IRWXOrB   chmod)swapfileswaplistsizeswapfile_modes       r   check_existing_swap_filez,ResourceDiskHandler.check_existing_swap_file  s    xBGGNN% ggooh74?KK./GGH-55Mt|| ;< -$,,2M0N N3:: -12 =1r   c                 r   |dz  }|dz  }t         j                  j                  |d      }t        j                  d      d   }| j                  |||      ry t         j                  j                  |      rrt         j                  j                  |      |k7  rPt        j                  d       t        j                  dj                  |      d       t        j                  |       t         j                  j                  |      sNt        j                  d	       | j                  ||dz         t        j                  d
j                  |             t        j                  dj                  |            rt        dj                  |            t        j                  dj                  ||             y )Ni   r   z	swapon -srF   zRemove old swap filezswapoff {0}Fr?   zCreate swap filez
mkswap {0}z
swapon {0}z{0}zEnabled {0}KB of swap at {1})r-   r.   r/   rA   rY   r   r   r   r)   r*   r   rB   removemkfiler   )r   r#   r=   size_kbr   r   r   s          r   r<   z%ResourceDiskHandler.create_swap_space  s3   D.~77<<Z8++K8;((8TB77>>(#(AT(IKK./MM-..x8%HIIhww~~h'KK*+KK'D.1MM,--h78==,,X67#ELL$:;;299'8LMr   c                    t        |t              st        |      }|dk  rt        dj                  |            t        j
                  j                  |      rt	        j                  |       d}t        j                  |f      }| j                  dvrt        j                  dk\  rd}	 t	        j                  |t        j                  t        j                  z  t        j                   z  t"        j$                  t"        j&                  z        }t	        j(                  |d|       	 |t	        j*                  |       yyt        j.                  dj                  ||            }|dk(  r|S t1        j2                  d       d}d	}t        ||z        }|dkD  r)t        j.                  |j                  |||            d
z  }t        ||z        }	|	dkD  r)|t        j.                  |j                  |	d|            z  }|dk(  rt1        j2                  d       |S t1        j4                  d       |S # t,        $ r Y nw xY w	 |t	        j*                  |       # |t	        j*                  |       w w xY w)a  
        Create a non-sparse file of that size. Deletes and replaces existing
        file.

        To allow efficient execution, fallocate will be tried first. This
        includes
        ``os.posix_fallocate`` on Python 3.3+ (unix) and the ``fallocate``
        command
        in the popular ``util-linux{,-ng}`` package.

        A dd fallback will be tried too. When size < 64M, perform
        single-pass dd.
        Otherwise do two-pass dd.
        r   zInvalid swap size [{0}])rM   ext4)   r   Nz"umask 0077 && fallocate -l {0} {1}z*fallocate unsuccessful, falling back to ddi   zBumask 0077 && dd if=/dev/zero bs={0} count={1} conv=notrunc of={2}   rF   zdd successfulzdd unsuccessful)
isinstanceintr   rB   r-   r.   r   r   rA   quoter   sysversion_infoopenO_CREATO_WRONLYO_EXCLr   S_IRUSRS_IWUSRposix_fallocatecloseBaseExceptionr   r)   r*   r6   )
r   filenamenbytesrl   fn_shfddd_maxbsdd_cmdblocksremainss
             r   r   zResourceDiskHandler.mkfile3  s     &#&[FQ;#$=$D$DV$LMM77>>(#IIh
 ,77/)6) % 

R[[0299<t||35B &&r1f5
 ~ & --5<<VUKMCax
KKDE "' Vh&'A:--h FG1LCfx'(Q;9==w5!ABBC!8KK( 
 LL*+
C % ~ ~ &s%   +A=H2 2	H>;I =H>>I I7N)__name__
__module____qualname__r   r   r   r    r"   rD   r,   rb   re   staticmethodr   r<   r    r   r   r   r   0   sR    5*$9)
zx B   N,Nr   r   ) r-   r^   r   r   r   timer   azurelinuxagent.common.loggercommonr)   azurelinuxagent.common.futurer   azurelinuxagent.common.confr   azurelinuxagent.common.eventr   r   %azurelinuxagent.common.utils.fileutilutilsr1   &azurelinuxagent.common.utils.shellutilrA    azurelinuxagent.common.exceptionr   azurelinuxagent.common.osutilr   azurelinuxagent.common.versionr	   r0   r3   objectr   r   r   r   <module>r      s\   $ 
 	  
   . . . * * F 8 8 : : > 4 5: 	 Q& Qr   