From 08608c726fb20b84b76aa93a0f7793676da2884f Mon Sep 17 00:00:00 2001 From: PCoder <purple.coder@yahoo.co.uk> Date: Tue, 25 Jun 2019 02:11:57 +0200 Subject: [PATCH] Code cleanup: remove updating ssh keys on live VMs --- datacenterlight/tasks.py | 87 +------------------ .../hosting/js/virtual_machine_detail.js | 52 ----------- .../hosting/virtual_machine_detail.html | 35 -------- hosting/urls.py | 4 +- hosting/views.py | 55 ------------ 5 files changed, 4 insertions(+), 229 deletions(-) diff --git a/datacenterlight/tasks.py b/datacenterlight/tasks.py index 641bcf6b..8b4626e8 100644 --- a/datacenterlight/tasks.py +++ b/datacenterlight/tasks.py @@ -1,5 +1,4 @@ from datetime import datetime -from time import sleep from celery import current_task from celery.exceptions import MaxRetriesExceededError @@ -178,7 +177,7 @@ def create_vm_task(self, vm_template_id, user, specs, template, order_id): kwargs={'pk': order_id}), 'page_header': _( 'Your New VM %(vm_name)s at Data Center Light') % { - 'vm_name': vm.get('name')}, + 'vm_name': vm.get('name')}, 'vm_name': vm.get('name') } email_data = { @@ -193,7 +192,8 @@ def create_vm_task(self, vm_template_id, user, specs, template, order_id): email.send() logger.debug("New VM ID is {vm_id}".format(vm_id=vm_id)) - get_or_create_vm_detail(custom_user, manager, vm_id) + if vm_id > 0: + get_or_create_vm_detail(custom_user, manager, vm_id) except Exception as e: logger.error(str(e)) try: @@ -215,84 +215,3 @@ def create_vm_task(self, vm_template_id, user, specs, template, order_id): return return vm_id - - -@app.task(bind=True, max_retries=settings.CELERY_MAX_RETRIES) -def save_ssh_key_in_vm_template_task(self, user, vm_id, ssh_key_str): - logger.debug("Inside save_ssh_key_in_vm_template_task %s" % vm_id) - - on_user = user.get('email') - on_pass = user.get('pass') - - if on_user is None or on_pass is None: - logger.error( - "Either email or password not supplied. Can't save ssh key" - ) - return - - manager = OpenNebulaManager(email=on_user, password=on_pass) - - # poweroff the vm - vm = manager.power_off_vm(vm_id) - - powered_off = False - for t in range(15): - vm = manager.get_vm(vm_id) - if vm.str_state == 'POWEROFF': - logger.debug( - "VM %s has been powered off. Now adding ssh keys" % vm.id - ) - powered_off = True - break - else: - logger.debug( - "VM {} has state {}. Waiting 2 more seconds to see if it " - "powers off".format(vm.id, vm.str_state) - ) - sleep(2) - - if powered_off: - logger.debug( - "VM %s was powered off by api call" % vm.id - ) - if manager.save_key_in_vm_template(vm_id=vm_id, ssh_key=ssh_key_str) > 0: - logger.debug( - "Added ssh_keys of user %s to VM %s successfully" % - (on_user, vm_id) - ) - manager.resume(vm_id) - lang = 'en-us' - if user.get('language') is not None: - logger.debug( - "Language is set to {}".format(user.get('language'))) - lang = user.get('language') - translation.activate(lang) - # Send notification to the user as soon as VM has been booked - context = { - 'page_header': str(_("Adding of SSH key completed")), - 'base_url': "{0}://{1}".format(user.get('request_scheme'), - user.get('request_host')), - 'vm_detail_url': reverse('hosting:virtual_machines', - kwargs={'pk': vm_id}), - 'vm_name': vm.name - } - email_data = { - 'subject': context.get('page_header'), - 'to': user.get('email'), - 'context': context, - 'template_name': 'ssh_key_added_to_vm', - 'template_path': 'hosting/emails/', - 'from_address': settings.DCL_SUPPORT_FROM_ADDRESS, - } - email = BaseEmail(**email_data) - email.send() - else: - logger.error( - "There was an error updating ssh keys of the VM %s" % vm_id - ) - else: - logger.error( - "VM {} did not poweroff within 30 seconds after the poweroff api " - "call. Please, ask the admin to poweroff and add the key " - "manually.".format(vm_id) - ) diff --git a/hosting/static/hosting/js/virtual_machine_detail.js b/hosting/static/hosting/js/virtual_machine_detail.js index e90e73f6..28592883 100644 --- a/hosting/static/hosting/js/virtual_machine_detail.js +++ b/hosting/static/hosting/js/virtual_machine_detail.js @@ -81,58 +81,6 @@ $(document).ready(function() { }) }); - $('#modal-add-ssh-key-button').click(function(e) { - var url = $('#add_ssh_key_to_vm_form').attr('action'); - console.log("Url to POST " + url); - - // Declare a checkbox array - var chkArray = []; - var encoded_data =""; - - // Look for all checkboxes that have a specific class and was checked - $(".chk-ssh-key:checked").each(function() { - chkArray.push($(this).val()); - }); - encoded_data = encodeURIComponent(chkArray.join(",")); - console.log("Encoded data = " + encoded_data); - - fa_icon = $('#ssh-key-modal-icon'); - modal_btn = $('#modal-add-ssh-key-button'); - modal_btn.prop("disabled", true); - modal_btn.html('<i class="fa fa-cog fa-spin" aria-hidden="true"></i>'); - $.post(url, {selected_key: encoded_data}) - .done(function(data) { - console.log("Request Done"); - modal_btn.prop("disabled", false); - modal_btn.html("OK"); - if (data.status === true) { - fa_icon.html('<i class="checkmark" aria-hidden="true"></i>'); - } else { - fa_icon.html('<i class="fa fa-close" aria-hidden="true"></i>'); - modal_btn.attr('class', '').addClass('btn btn-danger btn-ok btn-wide'); - } - console.log("title = " + data.msg_title); - console.log("desc = " + data.msg_body); - $('#ssh-key-modal-title').text(data.msg_title); - $('#ssh-key-modal-description').html(data.msg_body); - console.log("Request Done end"); - }) - .fail(function(data) { - console.log("Request Failed"); - console.log("title " + data.msg_title); - console.log("body " + data.msg_body); - modal_btn.attr('class', '').addClass('btn btn-danger btn-ok btn-wide'); - $('#ssh-key-modal-title').text(data.msg_title); - $('#ssh-key-modal-description').html(data.msg_body); - }) - .always(function () { - console.log("changing href to location: " + location); - $('#modal-add-ssh-key-button').unbind('click').click(function () { - location.reload(); - }); - }) - }); - var hash = window.location.hash; hash && $('ul.nav a[href="' + hash + '"]').tab('show'); diff --git a/hosting/templates/hosting/virtual_machine_detail.html b/hosting/templates/hosting/virtual_machine_detail.html index edbc71f9..bf869f91 100644 --- a/hosting/templates/hosting/virtual_machine_detail.html +++ b/hosting/templates/hosting/virtual_machine_detail.html @@ -113,41 +113,6 @@ <a class="btn btn-vm-back" href="{% url 'hosting:virtual_machines' %}">{% trans "BACK TO LIST" %}</a> </div> </div> - <!-- Add SSH Modal --> - <div class="modal fade" id="modal-add-ssh-key" tabindex="-1" role="dialog" aria-hidden="true"> - <div class="modal-dialog"> - <div class="modal-content"> - <div id="add-ssh-key-orig"> - <form method="POST" id="add_ssh_key_to_vm_form" class="cancel-form" action="{% url 'hosting:add_key_vm' virtual_machine.vm_id %}"> - {% csrf_token %} - - <div class="modal-header"> - <button type="button" class="close" data-dismiss="modal" aria-label="Confirm"><span aria-hidden="true">×</span></button> - </div> - <div class="modal-body"> - <div class="modal-icon" id="ssh-key-modal-icon"><i class="fa fa-key" aria-hidden="true"></i></div> - <h4 class="modal-title" id="ssh-key-modal-title">{% trans "Select the keys that you want to add to the VM" %}</h4> - <div class="modal-text" id="ssh-key-modal-description"> - <p> - <ul> - {% for key in keys %} - <li><input type="checkbox" name="selected_key" value="{{key.name}}" class="chk-ssh-key">{{key.name}}</li> - {% endfor %} - </ul> - </p> - <p>{% trans "The VM will reboot with the new key(s) installed. OK ?" %}</p> - <p><strong>{{virtual_machine.name}}</strong></p> - </div> - <div class="modal-footer"> - <a class="btn btn-ok btn-wide btn-vm-back" id="modal-add-ssh-key-button">{% trans "OK" %}</a> - </div> - </div> - </form> - </div> - </div> - </div> - </div> - <!-- / Add ssh key Modal --> <!-- Cancel Modal --> <div class="modal fade" id="confirm-cancel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> diff --git a/hosting/urls.py b/hosting/urls.py index c596354c..5aa29f88 100644 --- a/hosting/urls.py +++ b/hosting/urls.py @@ -10,7 +10,7 @@ from .views import ( HostingPricingView, CreateVirtualMachinesView, HostingBillListView, HostingBillDetailView, SSHKeyDeleteView, SSHKeyCreateView, SSHKeyListView, SSHKeyChoiceView, DashboardView, SettingsView, ResendActivationEmailView, - InvoiceListView, InvoiceDetailView, AddSshKeyToVMView + InvoiceListView, InvoiceDetailView ) urlpatterns = [ @@ -41,8 +41,6 @@ urlpatterns = [ VirtualMachinesPlanListView.as_view(), name='virtual_machines'), url(r'my-virtual-machines/(?P<pk>\d+)/?$', VirtualMachineView.as_view(), name='virtual_machines'), - url(r'add-key-vm/(?P<pk>\d+)/?$', AddSshKeyToVMView.as_view(), - name='add_key_vm'), url(r'ssh_keys/?$', SSHKeyListView.as_view(), name='ssh_keys'), url(r'ssh_keys_choice/?$', SSHKeyChoiceView.as_view(), diff --git a/hosting/views.py b/hosting/views.py index 5f75f2b9..cedf18f0 100644 --- a/hosting/views.py +++ b/hosting/views.py @@ -2,7 +2,6 @@ import logging import uuid from datetime import datetime from time import sleep -from urllib import parse from django import forms from django.conf import settings @@ -35,7 +34,6 @@ from stored_messages.settings import stored_messages_settings from datacenterlight.cms_models import DCLCalculatorPluginModel from datacenterlight.models import VMTemplate, VMPricing -from datacenterlight.tasks import save_ssh_key_in_vm_template_task from datacenterlight.utils import create_vm, get_cms_integration from hosting.models import UserCardDetail from membership.models import CustomUser, StripeCustomer @@ -1514,59 +1512,6 @@ class CreateVirtualMachinesView(LoginRequiredMixin, View): return redirect(reverse('hosting:payment')) -class AddSshKeyToVMView(LoginRequiredMixin, View): - - def respond_with_error(self): - response = {'status': False} - response['msg_title'] = str(_("No ssh keys provided")) - response['msg_body'] = str( - _("Please retry and select one of the keys")) - json_response = JsonResponse(response) - return json_response - - @method_decorator(decorators) - def post(self, request, *args, **kwargs): - try: - vm_id = int(self.kwargs.get('pk')) - except ValueError as ve: - logger.error("Value error {}".format(str(ve))) - return self.respond_with_error() - if 'selected_key' not in request.POST: - return self.respond_with_error() - else: - posted_keys = parse.unquote_plus(request.POST['selected_key']) - if posted_keys.strip() == "": - return self.respond_with_error() - keys = posted_keys.split(",") - uh_keys = [ - UserHostingKey.objects.get( - user=request.user, name=key) - for key in keys if key is not None and key is not "" - ] - # Add public_keys to vm_id now - public_keys = [uh_key.public_key for uh_key in uh_keys] - keys_str = '\n'.join(public_keys) - user = { - 'email': request.user.email, - 'pass': request.user.password, - 'request_scheme': request.scheme, - 'request_host': request.get_host(), - 'language': get_language(), - } - save_ssh_key_in_vm_template_task.delay(user,vm_id, keys_str) - response = dict() - response['status'] = True - response['msg_title'] = str(_( - "Adding of your SSH key add is under process" - )) - response['msg_body'] = str(_( - "Your keys %s will be added to the VM in the next couple of " - "minutes. You will receive a confirmation email once this has " - "been done. Thank you." % posted_keys - )) - return JsonResponse(response) - - class VirtualMachineView(LoginRequiredMixin, View): template_name = "hosting/virtual_machine_detail.html" login_url = reverse_lazy('hosting:login')