U
    W¨+dÖ&  ã                   @   sl   d Z ddlZddlmZ ddlmZ ddlZddlZddlm	Z	 ddl
mZ dZdZd	ZG d
d„ de	ƒZdS )a  
Automated installer to attach, format and mount an EBS volume.
This installer assumes that you want the volume formatted as
an XFS file system.  To drive this installer, you need the
following section in the boto config passed to the new instance.
You also need to install dateutil by listing python-dateutil
in the list of packages to be installed in the Pyami seciont
of your boto config file.

If there is already a device mounted at the specified mount point,
the installer assumes that it is the ephemeral drive and unmounts
it, remounts it as /tmp and chmods it to 777.

Config file section::

    [EBS]
    volume_id = <the id of the EBS volume, should look like vol-xxxxxxxx>
    logical_volume_name = <the name of the logical volume that contaings
        a reference to the physical volume to be mounted. If this parameter
        is supplied, it overrides the volume_id setting.>
    device = <the linux device the EBS volume should be mounted on>
    mount_point = <directory to mount device, defaults to /ebs>

é    N)ÚVolume)ÚEC2ResponseError)Ú	Installer)ÚTemplateac  #!/usr/bin/env python
# Backup EBS volume
import boto
from boto.pyami.scriptbase import ScriptBase
import traceback

class Backup(ScriptBase):

    def main(self):
        try:
            ec2 = boto.connect_ec2()
            self.run("/usr/sbin/xfs_freeze -f ${mount_point}", exit_on_error = True)
            snapshot = ec2.create_snapshot('${volume_id}')
            boto.log.info("Snapshot created: %s " %  snapshot)
        except Exception as e:
            self.notify(subject="${instance_id} Backup Failed", body=traceback.format_exc())
            boto.log.info("Snapshot created: ${volume_id}")
        except Exception as e:
            self.notify(subject="${instance_id} Backup Failed", body=traceback.format_exc())
        finally:
            self.run("/usr/sbin/xfs_freeze -u ${mount_point}")

if __name__ == "__main__":
    b = Backup()
    b.main()
zœ#!/usr/bin/env python
import boto
from boto.manage.volume import Volume

# Cleans Backups of EBS volumes

for v in Volume.all():
    v.trim_snapshots(True)
zr#!/usr/bin/env python
import boto

# Cleans Backups of EBS volumes

ec2 = boto.connect_ec2()
ec2.trim_snapshots()
c                       sd   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zddd„Zdd„ Z	dd„ Z
dd„ Zdd„ Z‡  ZS )ÚEBSInstallerz
    Set up the EBS stuff
    Nc                    sh   t t| ƒ |¡ tj dd¡| _tj ddd¡| _tj dd¡| _tj dd¡| _	tj ddd	¡| _
d S )
NZInstancezinstance-idÚEBSÚdevicez/dev/sdpÚ	volume_idÚlogical_volume_nameÚmount_pointz/ebs)Úsuperr   Ú__init__ÚbotoÚconfigÚgetÚinstance_idr   r	   r
   r   )ÚselfÚconfig_file©Ú	__class__© úD/tmp/pip-unpacked-wheel-dlxw5sjy/boto/pyami/installers/ubuntu/ebs.pyr   h   s    zEBSInstaller.__init__c              
   C   sL  t  ¡ }| jr(ttj| jdƒ}|j| _| | jg¡d }| 	¡ dkrjt j
 d|j|jf ¡ t d¡ q:| | jg¡d }d}|rüz| | j| j| j¡ d}W q€ tk
rø } z:|jdkrät j
 d	| j| j|jf ¡ t d
¡ n|‚W 5 d }~X Y q€X q€t j
 d| j| j| jf ¡ tj | j¡sHt j
 d| j ¡ t d
¡ qd S )N)Únamer   Ú	availablez1Volume %s not yet available. Current status = %s.é   TFZIncorrectStatez]Attempt to attach the EBS volume %s to this instance (%s) returned %s. Trying again in a bit.é   z.Attached volume %s to instance %s as device %sz*%s still does not exist, waiting 2 seconds)r   Zconnect_ec2r
   Únextr   ÚfindZ
_volume_idr	   Zget_all_volumesÚupdateÚlogÚinfoÚidÚstatusÚtimeÚsleepZget_only_instancesr   Zattach_volumer   r   Z
error_codeÚerrorsÚosÚpathÚexists)r   Zec2Zlogical_volumeÚvolumeÚinstanceZattempt_attachÚer   r   r   Úattachp   s.    
zEBSInstaller.attachc                 C   s8   t j d¡ |  d| j ¡}|dkr4|  d| j ¡ d S )Nz
make_fs...zfsck %sr   zmkfs -t xfs %s)r   r   r    Úrunr   )r   Zhas_fsr   r   r   Úmake_fs‘   s    zEBSInstaller.make_fsc                 C   sH   t tƒ}|j| j| j| jd}tddƒ}| |¡ | ¡  |  	d¡ d S )N)r	   r   r   ú/usr/local/bin/ebs_backupÚwz"chmod +x /usr/local/bin/ebs_backup)
r   ÚBackupScriptTemplateÚ
substituter	   r   r   ÚopenÚwriteÚcloser-   )r   ÚtÚsÚfpr   r   r   Úcreate_backup_script—   s    ÿ

z!EBSInstaller.create_backup_scriptFc                 C   s:   t ddƒ}|r| t¡ n
| t¡ | ¡  |  d¡ d S )Nú!/usr/local/bin/ebs_backup_cleanupr0   z*chmod +x /usr/local/bin/ebs_backup_cleanup)r3   r4   ÚTagBasedBackupCleanupScriptÚBackupCleanupScriptr5   r-   )r   Úuse_tag_based_cleanupr8   r   r   r   Úcreate_backup_cleanup_script    s    

z)EBSInstaller.create_backup_cleanup_scriptc                 C   sè   t j d¡ tj | j¡s8t j d¡ |  d| j ¡ n|t j d¡ |  d¡ | jj	 
d¡}|D ]R}| 
¡ }|r`|d | jkr`|d | jkr`|  d	| j ¡ |  d
|d  ¡  q´q`|  d¡ |  d| j| jf ¡ |  d| j ¡ d S )NÚhandle_mount_pointzmaking directoryzmkdir %szdirectory exists alreadyzmount -lÚ
r   r   z	umount %szmount %s /tmpzchmod 777 /tmpzmount %s %szxfs_growfs %s)r   r   r    r&   r'   Úisdirr   r-   Zlast_commandÚoutputÚsplitr   )r   ÚlinesÚliner6   r   r   r   r?   ©   s"    

zEBSInstaller.handle_mount_pointc                 C   s,   t ddƒ}| d| j| jf ¡ | ¡  d S )Nz
/etc/fstabÚaz%s	%s	xfs	defaults 0 0
)r3   r4   r   r   r5   )r   Úfr   r   r   Úupdate_fstabÁ   s    
zEBSInstaller.update_fstabc                 C   s¾   |   ¡  |  d¡ |  ¡  |  ¡  |  ¡  tj ddd¡}tj ddd¡}| jdd||d	 tj dd
¡}tj dd¡}|d k	r²|d k	r²tj 	dd¡}|  
|¡ | jdd||d	 |  ¡  d S )Nz#apt-get -y install xfsprogs xfsdumpr   Zbackup_cron_minuteÚ0Zbackup_cron_hourz4,16Z
ebs_backupr/   )ÚminuteÚhourZbackup_cleanup_cron_minuteZbackup_cleanup_cron_hourZuse_tag_based_snapshot_cleanupZebs_backup_cleanupr:   )r,   r-   r.   r?   r9   r   r   r   Zadd_cronÚ
has_optionr>   rH   )r   rJ   rK   r=   r   r   r   ÚinstallÆ   s    

zEBSInstaller.installc                 C   s.   t j | j¡s|  ¡  ntj d| j ¡ d S )Nz5Device %s is already attached, skipping EBS Installer)r&   r'   r(   r   rM   r   r   r    )r   r   r   r   Úmainê   s    
zEBSInstaller.main)N)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r,   r.   r9   r>   r?   rH   rM   rN   Ú__classcell__r   r   r   r   r   c   s   !	
	$r   )rR   r   Zboto.manage.volumer   Zboto.exceptionr   r&   r#   Z&boto.pyami.installers.ubuntu.installerr   Ústringr   r1   r<   r;   r   r   r   r   r   Ú<module>   s   
	