o
    ȷe&                     @   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 )
N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__ W/var/www/ideatree/venv/lib/python3.10/site-packages/boto/pyami/installers/ubuntu/ebs.pyr   h   s   zEBSInstaller.__init__c              
   C   sf  t  }| jrttj| jd}|j| _|| jgd }|	 dkr:t j
d|j|jf  td |	 dks#|| jgd }d}|rz|| j| j| j d}W n- ty } z!|jdkrvt j
d	| j| j|jf  td
 n|W Y d }~nd }~ww |sGt j
d| j| j| jf  tj| jst j
d| j  td
 tj| jrd S d S )N)namer   	availablez1Volume %s not yet available. Current status = %s.   TF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   connect_ec2r   nextr   find
_volume_idr
   get_all_volumesupdateloginfoidstatustimesleepget_only_instancesr   attach_volumer	   r   
error_codeerrorsospathexists)r   ec2logical_volumevolumeinstanceattempt_attacher   r   r   attachp   s:   


zEBSInstaller.attachc                 C   s<   t jd | d| j }|dkr| d| j  d S d S )Nz
make_fs...zfsck %sr   zmkfs -t xfs %s)r   r$   r%   runr	   )r   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closer8   )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_cleanupr<   z*chmod +x /usr/local/bin/ebs_backup_cleanup)r?   r@   TagBasedBackupCleanupScriptBackupCleanupScriptrA   r8   )r   use_tag_based_cleanuprD   r   r   r   create_backup_cleanup_script   s   

z)EBSInstaller.create_backup_cleanup_scriptc                 C   s   t jd tj| jst jd | d| j  n>t jd | d | jj	
d}|D ])}|
 }|rY|d | jkrY|d | jkrY| d	| j  | d
|d    nq0| 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   r8   last_commandoutputsplitr	   )r   lineslinerB   r   r   r   rK      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
)r?   r@   r	   r   rA   )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 urY|d urYtj	dd}| 
| | jdd||d	 |   d S )Nz#apt-get -y install xfsprogs xfsdumpr   backup_cron_minute0backup_cron_hourz4,16
ebs_backupr;   )minutehourbackup_cleanup_cron_minutebackup_cleanup_cron_houruse_tag_based_snapshot_cleanupebs_backup_cleanuprF   )r7   r8   r:   rK   rE   r   r   r   add_cron
has_optionrJ   rU   )r   rZ   r[   rI   r   r   r   install   s   

zEBSInstaller.installc                 C   s0   t j| js|   d S tjd| j  d S )Nz5Device %s is already attached, skipping EBS Installer)r.   r/   r0   r	   rb   r   r$   r%   )r   r   r   r   main   s   zEBSInstaller.main)N)F)__name__
__module____qualname____doc__r   r7   r:   rE   rJ   rK   rU   rb   rc   __classcell__r   r   r   r   r   c   s    !
		$r   )rg   r   boto.manage.volumer   boto.exceptionr   r.   r(   &boto.pyami.installers.ubuntu.installerr   stringr   r=   rH   rG   r   r   r   r   r   <module>   s   
	