def run(server, *args, **kwargs):
    set_progress("Starting the Veeam take backup process...")
    veeam = VeeamManager()
    ci = veeam.get_connection_info()
    result = veeam.take_backup(CREATE_BACKUP, {
        'server': server,
        'veeam_server': ci
    })
    set_progress("Waiting for the backup process to complete...")
    if result.lower() == 'success':
        set_progress("Backup taken successfully")
        return "SUCCESS", "Backup taken successfully", ""
    else:
        set_progress("Backup not taken successfully")
        return "SUCCESS", "Backup not taken successfully", ""
Beispiel #2
0
def run(server, *args, **kwargs):
    set_progress(f"Starting Veeam Backup restoration... ")
    veeam_manager = VeeamManager()
    context = {}
    context.update(kwargs.get('script_context'))

    connection_info = veeam_manager.get_connection_info()
    context.update({'connection_info': connection_info})

    try:
        set_progress(
            "Starting backup restoration to EC2. This might take a while...")
        result = veeam_manager.restore_backup_to_cloud(template=RESTORE_TO_EC2,
                                                       context=context)
        set_progress(f"Result from the backup restoration {result}")

    except Exception as error:
        set_progress("Error occurred while trying to restore backup to ec2")
        return "FAILURE", "", f"{error}"
Beispiel #3
0
def refresh_agent(request, server_id):
    """
    Checks if the server specified has a veeam agent
    """
    veeam = VeeamManager()

    server = Server.objects.get(id=server_id)
    # Start a Job to do the refresh

    server = veeam.refresh_server(server, {
        'server': server,
        'veeam_server': veeam.get_connection_info()
    })

    if server.veeam_agent_id:
        messages.success(request, "Veeam Agent Found")
    else:
        messages.warning(request, "No Veeam Agent Found")
    return HttpResponseRedirect(reverse('server_detail', args=[server_id]))
Beispiel #4
0
def verify_veeam_endpoint(request):
    veeam = VeeamManager()
    endpoint = veeam.get_connection_info()
    if not endpoint:
        messages.warn(request, "No Veeam Endpoint found! Nothing to verify")
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    try:
        veeam.verify_connection()
    except Exception as err:
        msg = format_html(
            'Could not make a connection to the Veeam Server Manager at'
            '<b>"{}"</b>:<br>{}', endpoint, str(err))
    else:
        msg = format_html(
            'Successfully connected to the Veeam Server Manager at '
            '<b>"{}"</b>.', endpoint)

    return {
        'title': 'Verify connection to Veeam Server Manager Endpoint',
        'content': msg,
        'submit': None,
        'cancel': "OK",
    }
Beispiel #5
0
def run(server, *args, **kwargs):
    set_progress(f"Starting Veeam Backup restoration... ")
    veeam = VeeamManager()
    server_ci = veeam.get_connection_info()
    url = f'http://{server_ci.ip}:9399/api/vmRestorePoints/' + \
          kwargs.get('restore_point_href') + '?action=restore'
    session_id = veeam.get_veeam_server_session_id()
    header = {"X-RestSvcSessionId": session_id}

    response = requests.post(url=url, headers=header)
    task = minidom.parseString(response.content.decode('utf-8'))
    items = task.getElementsByTagName('Task')[0].attributes.items()
    restoration_url = [item for item in items if item[0] == 'Href'][0][-1]

    def check_state():

        response = requests.get(restoration_url, headers=header)

        dom = minidom.parseString(response.content.decode('utf-8'))
        state = dom.getElementsByTagName('State')[0]
        child = state.firstChild
        return child

    # Wait until the restoration to completed.

    while check_state().data == 'Running':
        # wait
        set_progress("Waiting for restoration to complete...")
        time.sleep(10)

    if check_state().data == 'Finished':
        set_progress("Server restoration completed successfully")
        return "SUCCESS", "Server restoration completed successfully", ""
    else:
        set_progress("Server restoration didn't complete successfully")
        return "FAILURE", "", "Server restoration didn't complete successfully"
Beispiel #6
0
def admin_page(request):
    veeam = VeeamManager()
    endpoint = veeam.get_connection_info()
    # If no Connection info, show a dialog for adding a connection info.
    if not endpoint:
        veeam_context = {
            'tabs':
            TabGroup(
                template_dir='veeam/templates',
                context={},
                request=request,
                tabs=[(_(""), 'dashboard', dict(context={}))],
            )
        }
        return render(request, 'veeam/templates/admin_page.html',
                      veeam_context)

    jobs = veeam.get_jobs()
    backups = veeam.get_backups()
    summary = veeam.get_summary()

    context = {}
    ip = veeam.get_connection_info().ip
    try:
        server = Server.objects.get(ip=ip)
    except Exception:
        messages.error(request,
                       message="The server running Veeam could not be found.")
        return render(request, 'veeam/templates/admin_page.html', {})

    restore_to_ec2_job = server.jobs.filter(
        job_parameters__hookparameters__hook__name='Restore Veeam Backup To EC2'
    ).last()

    restore_to_ec2_job_running = False
    if restore_to_ec2_job and restore_to_ec2_job.is_active():
        restore_to_ec2_job_running = True
        context.update(
            {'restore_to_ec2_job_url': restore_to_ec2_job.get_absolute_url()})
    context.update({'restore_to_ec2_job_running': restore_to_ec2_job_running})

    restore_to_azure_job = server.jobs.filter(
        job_parameters__hookparameters__hook__name=
        'Restore Veeam Backup To Azure').last()
    restore_to_azure_job_running = False
    if restore_to_azure_job and restore_to_azure_job.is_active():
        restore_to_azure_job_running = True
        context.update({
            'restore_to_azure_job_url':
            restore_to_azure_job.get_absolute_url()
        })
    context.update(
        {'restore_to_azure_job_running': restore_to_azure_job_running})

    context.update({'jobs': jobs, 'backups': backups, 'endpoint': endpoint})

    veeam_context = {
        'tabs':
        TabGroup(
            template_dir='veeam/templates',
            context=context,
            request=request,
            tabs=[
                # First tab uses template 'groups/tabs/tab-main.html'
                # (_("Configuration"), 'configuration', {}),
                # Tab 2 is conditionally-shown in this slot and
                # uses template 'groups/tabs/tab-related-items.html'
                (_("Dashboard"), 'dashboard', dict(context=summary)),
                (_("Jobs"), 'jobs', {}),
                (_("Backups"), 'backups', {})
            ],
        )
    }
    return render(request, 'veeam/templates/admin_page.html', veeam_context)
Beispiel #7
0
def restore_backup_to_ec2_cloud(request, backup_name):
    if request.method == 'GET':
        content = _("Provide the information below to restore to EC2")
        form = EC2RestoreForm()
        return {
            'title':
            _("Restore Backup"),
            'content':
            content,
            'form':
            form,
            'use_ajax':
            True,
            'action_url':
            reverse('restore_to_ec2_cloud',
                    kwargs={"backup_name": backup_name}),
            'submit':
            _("Restore"),
            'extra_onready_js':
            mark_safe(
                """
                                        $('#div_id_environment').on('change',(function () {
                                        var env_id = $('#div_id_environment option:selected').val();
                                        $.getJSON('%s?env_id='+env_id, function (vpc_ids) {
                                            var $selectElement = $("#id_vpc_id");
                                            $selectElement.empty();
                                            $.each(vpc_ids, function (key, value) {
                                                $selectElement.append($("<option></option>").attr("value", value).text(value));
                                            });
                                        });
                                        $.getJSON('%s?env_id='+env_id, function (sg_ids) {
                                            var $securityGroupElement = $("#id_sgroup_name");
                                            $securityGroupElement.empty();
                                            $.each(sg_ids, function (key, value) {
                                                $securityGroupElement.append($("<option></option>").attr("value", value).text(value));
                                            });
                                        });
                                        $.getJSON('%s?env_id='+env_id, function (availability_zones) {
                                            var $availabilityZoneElement = $("#id_availability_zone");
                                            $availabilityZoneElement.empty();
                                            $.each(availability_zones, function (key, value) {
                                                $availabilityZoneElement.append($("<option></option>").attr("value", value).text(value));
                                            });
                                        });
                                    })).change();
                            """ %
                (reverse('get_aws_vpc'), reverse('get_aws_security_groups'),
                 reverse('get_aws_availability_zones')))
        }
    if request.method == 'POST':
        veeam_manager = VeeamManager()

        form = EC2RestoreForm(request.POST)
        # Since the choices fields have not been declared during form creation, we need to dynamically declare them.
        vpc_id = request.POST.get('vpc_id')
        sgroup_name = request.POST.get('sgroup_name')
        availability_zone = request.POST.get('availability_zone')

        form.fields['vpc_id'].choices = [(vpc_id, vpc_id)]
        form.fields['sgroup_name'].choices = [(sgroup_name, sgroup_name)]
        form.fields['availability_zone'].choices = [(availability_zone,
                                                     availability_zone)]

        if form.is_valid():
            environment = form.cleaned_data['environment']
            env = Environment.objects.get(id=environment)
            resource_handler = env.resource_handler

            context = {
                'vm_name': form.cleaned_data['vm_name'],
                'environment': environment,
                'backup_name': backup_name,
                'amazon_access_key': resource_handler.serviceaccount,
                'region_name': env.aws_region,
                'region_type': form.cleaned_data['region_type'],
                'disk_type': form.cleaned_data['disk_type'],
                'instance_type': form.cleaned_data['instance_type'],
                'license_type': form.cleaned_data['license_type'],
                'vpc_id': form.cleaned_data['vpc_id'],
                'sgroup_name': form.cleaned_data['sgroup_name'],
                'reason': form.cleaned_data['reason'],
                'availability_zone': form.cleaned_data['availability_zone'],
            }
            try:
                restore_backup_action = CloudBoltHook.objects.get(
                    name="Restore Veeam Backup To EC2")
            except Exception:
                veeam_manager.setup_restore_backup_to_ec2__action()
                restore_backup_action = CloudBoltHook.objects.get(
                    name="Restore Veeam Backup To EC2")

            # Server running this job will be the veeam server. We can find it using the IP address in the connection Info
            ip = veeam_manager.get_connection_info().ip
            try:
                server = Server.objects.get(ip=ip)
            except Exception as error:
                # No server associated with the connection info IP address exists.
                messages.error(request, "The Veeam server could not be found.")
                return HttpResponseRedirect(
                    request.META.get('HTTP_REFERER', '/'))

            restore_backup_job = restore_backup_action.run_as_job(
                server=server, script_context=context)[0]
            messages.success(
                request,
                mark_safe(
                    f"<a href='{restore_backup_job.get_absolute_url()}'>Job {restore_backup_job.id}</a> to restore backup started"
                ))
        else:
            raise Exception(form.errors)

        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
Beispiel #8
0
 def should_display(self):
     veeam = VeeamManager()
     if not veeam.get_connection_info():
         return False
     return True
Beispiel #9
0
def restore_backup_to_cloud(request, backup_name):
    if request.method == 'GET':
        content = _(
            "Provide the information below to restore to Microsoft Azure.")
        form = AzureRestoreForm()
        return {
            'title':
            _("Restore Backup"),
            'content':
            content,
            'form':
            form,
            'use_ajax':
            True,
            'action_url':
            '/veeam/restore_backup_to_cloud/{backup_name}/'.format(
                backup_name=backup_name),
            'submit':
            _("Restore"),
        }
    if request.method == 'POST':
        veeam_manager = VeeamManager()
        form = AzureRestoreForm(request.POST)
        if form.is_valid():
            context = {
                'vmname': form.cleaned_data['vm_name'],
                'backup_name': backup_name,
                'network_name': form.cleaned_data['network_name'],
                'vm_size': form.cleaned_data['vm_size'],
                'location': form.cleaned_data['location'],
                'storage_account': form.cleaned_data['storage_account'],
                'resource_group': form.cleaned_data['resource_group'],
            }
            try:
                restore_backup_action = CloudBoltHook.objects.get(
                    name="Restore Veeam Backup To Azure")
            except Exception:
                veeam_manager.setup_restore_backup_to_azure_action()
                restore_backup_action = CloudBoltHook.objects.get(
                    name="Restore Veeam Backup To Azure")

                # Server running this job will be the veeam server. We can find it using the IP address in the
                # connection Info
            ip = veeam_manager.get_connection_info().ip
            try:
                server = Server.objects.get(ip=ip)
            except Exception:
                # No server associated with the connection info IP address exists.
                messages.error(request, "The Veeam server could not be found.")
                return HttpResponseRedirect(
                    request.META.get('HTTP_REFERER', '/'))

            restore_backup_to_azure_job = restore_backup_action.run_as_job(
                server=server, script_context=context)[0]
            messages.success(
                request,
                mark_safe(
                    f"<a href='{restore_backup_to_azure_job.get_absolute_url()}'>Job {restore_backup_to_azure_job.id}</a> to restore backup started"
                ))
        else:
            raise Exception(form.errors)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))