def edit(api, request, res_id=None): res_inf = api.template_info(res_id) if request.method=='POST': form = EditTemplateForm(res_id, res_inf['tech']== TypeName.FULL_VIRTUALIZATION, request.POST) if form.is_valid(): formData = form.cleaned_data creation_date = formData['creation_date'] attrs = {'label':formData['label'], 'restricted': formData['restricted'], 'subtype':formData['subtype'], 'preference':formData['preference'], 'description':formData['description'], 'creation_date':dateToTimestamp(creation_date) if creation_date else None, 'nlXTP_installed':formData['nlXTP_installed'], 'icon':formData['icon'], 'show_as_common':formData['show_as_common'], 'urls': filter(lambda x: x, formData['urls'].splitlines())} if res_inf['tech'] == TypeName.FULL_VIRTUALIZATION: attrs['kblang'] = formData['kblang'] api.template_modify(res_id,attrs) return HttpResponseRedirect(reverse("tomato.template.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {'label': label, 'form': form, "heading":"Edit Template Data for '"+label+"' ("+res_inf['tech']+")"}) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_inf['res_id'] = res_id res_inf['creation_date'] = datetime.date.fromtimestamp(float(res_inf['creation_date'] or "0.0")) res_inf['urls'] = "\n".join(res_inf['urls']) form = EditTemplateForm(res_id, (res_inf['tech']==TypeName.FULL_VIRTUALIZATION), res_inf) return render(request, "form.html", {'label': res_inf['label'], 'form': form, "heading":"Edit Template Data for '"+str(res_inf['label'])+"' ("+res_inf['tech']+")"})
def checkModify(self, attrs): """ Checks whether the attribute change can succeed before changing the attributes. If checks whether the attributes are listen in CAP_ATTRS and if the current object state is listed in CAP_ATTRS[NAME]. @param attrs: Attributes to change @type attrs: dict """ self.checkRole(Role.manager) mcon = self.mainConnection() direct = [] if self.DIRECT_ATTRS: if mcon: direct = mcon.getAllowedAttributes().keys() else: caps = getConnectionCapabilities(self.remoteType()) direct = caps["attrs"].keys() if caps else [] for key in attrs.keys(): if key in direct and not key in self.DIRECT_ATTRS_EXCLUDE: continue if key.startswith("_"): continue UserError.check(key in self.CUSTOM_ATTRS, code=UserError.UNSUPPORTED_ATTRIBUTE, message="Unsuported connection attribute: %s" % key, data={ "attribute": key, "id": self.id }) self.CUSTOM_ATTRS[key].check(self, attrs[key])
def group_edit(api, request, group_id): if request.method == 'POST': form = ErrorGroupForm(api, request.POST) if form.is_valid(): formData = form.cleaned_data api.errorgroup_modify(group_id, {"description": formData["description"]}) return HttpResponseRedirect( reverse("tomato.dumpmanager.group_info", kwargs={"group_id": group_id})) if not group_id: group_id = request.POST["group_id"] UserError.check(group_id, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", { "heading": "Editing errorgroup '" + group_id + "'", 'form': form }) else: UserError.check(group_id, UserError.INVALID_DATA, "No error group specified.") errorgroupinfo = api.errorgroup_info(group_id, False) form = EditErrorGroupForm(api, group_id, errorgroupinfo) return render( request, "form.html", { "heading": "Renaming Error Group '" + errorgroupinfo['description'] + "'", 'form': form })
def edit(api, request, res_id=None): if request.method == 'POST': form = EditNetworkForm(res_id, request.POST) if form.is_valid(): formData = form.cleaned_data api.network_modify( formData["res_id"], { 'label': formData['label'], 'preference': formData['preference'], 'description': formData['description'], 'big_icon': formData['big_icon'], 'show_as_common': formData['show_as_common'] }) return HttpResponseRedirect( reverse("tomato.external_network.list")) kind = request.POST["kind"] UserError.check(kind, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", { 'form': form, 'heading': "Edit External Network '" + kind + "'" }) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.network_info(res_id) res_info['res_id'] = res_id form = EditNetworkForm(res_id, res_info) return render( request, "form.html", { 'form': form, 'heading': "Edit External Network '" + res_info['label'] + "'" })
def edit(api, request, res_id=None): if request.method == 'POST': form = EditNetworkInstanceForm(res_id, api, request.POST) if form.is_valid(): formData = form.cleaned_data api.network_instance_modify( formData["res_id"], { 'host': formData['host'], 'bridge': formData['bridge'], 'network': formData['network'] }) return HttpResponseRedirect( reverse( "external_network_instances", kwargs={"network": network_id(api, formData['network'])})) host = request.POST["host"] UserError.check(host, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", { 'form': form, "heading": "Edit External Network Instance on " + host }) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.network_instance_info(res_id) res_info['res_id'] = res_id form = EditNetworkInstanceForm(res_id, api, res_info) return render( request, "form.html", { 'form': form, "heading": "Edit External Network Instance on " + res_info['host'] })
def checkAction(self, action): """ Checks if the action can be executed. This method checks if the action is listed in CAP_ACTIONS and if the current state is listed in CAP_ACTIONS[action]. @param action: Action to check @type action: str """ self.checkRole(Role.manager) if self.DIRECT_ACTIONS and not action in self.DIRECT_ACTIONS_EXCLUDE: mcon = self.mainConnection() if mcon and action in mcon.getAllowedActions(): return UserError.check(action in self.CUSTOM_ACTIONS, code=UserError.UNSUPPORTED_ACTION, message="Unsuported connection action: %s" % action, data={ "action": action, "id": self.id }) UserError.check(self.state in self.CUSTOM_ACTIONS[action], code=UserError.INVALID_STATE, message="Action %s can not be executed in state %s" % (action, self.state), data={ "action": action, "state": self.state, "id": self.id })
def edit(api, request, res_id): res_inf = api.vulnerability_info(res_id) if request.method == 'POST': form = EditVulnerabilityForm(res_id, request.POST) if form.is_valid(): form_data = form.cleaned_data creation_date = form_data['creation_date'] attrs = { # 'id': form_data["res_id"], 'name': form_data['name'], 'type': form_data['type'], 'system': form_data['system'], 'url': form_data['url'], 'description': form_data['description'], 'creation_date': dateToTimestamp(creation_date) if creation_date else None, } api.vulnerability_modify(res_id, attrs) return HttpResponseRedirect(reverse("vulnerability_info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {'label': label, 'form': form, "heading": "Edit Vulnerability Data for '" + label + "' (" + res_inf['name'] + ")"}) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") # res_inf['id'] = res_id res_inf['creation_date'] = datetime.date.fromtimestamp(float(res_inf['creation_date'] or "0.0")) form = EditVulnerabilityForm(res_id, res_inf) return render(request, "form.html", {'name': res_inf['name'], 'form': form, "heading": "Edit Vulnerability Data for '" + str(res_inf['name']) })
def checkModify(self, attrs): """ Checks whether the attribute change can succeed before changing the attributes. If checks whether the attributes are listen in CAP_ATTRS and if the current object state is listed in CAP_ATTRS[NAME]. @param attrs: Attributes to change @type attrs: dict """ self.checkRole(Role.manager) mcon = self.mainConnection() direct = [] if self.DIRECT_ATTRS: if mcon: direct = mcon.getAllowedAttributes().keys() else: caps = getConnectionCapabilities(self.remoteType()) direct = caps["attrs"].keys() if caps else [] for key in attrs.keys(): if key in direct and not key in self.DIRECT_ATTRS_EXCLUDE: continue if key.startswith("_"): continue UserError.check(key in self.CUSTOM_ATTRS, code=UserError.UNSUPPORTED_ATTRIBUTE, message="Unsuported connection attribute: %s" % key, data={"attribute": key, "id": self.id}) self.CUSTOM_ATTRS[key].check(self, attrs[key])
def createOrganization(name, description="", attrs={}): UserError.check(currentUser().hasFlag(Flags.GlobalAdmin), code=UserError.DENIED, message="Not enough permissions") logging.logMessage("create", category="site", name=name, description=description) organization = Organization(name=name) organization.save() attrs.update({"description": description}) organization.init(attrs) return organization
def download_torrent(api, request, res_id): res_inf = api.template_info(res_id, include_torrent_data=True) UserError.check('torrent_data' in res_inf,UserError.NO_DATA_AVAILABLE,"This template does not have a torrent file", data={'id':res_inf['id']}) tdata = base64.b64decode(res_inf['torrent_data']) filename = re.sub('[^\w\-_\. :]', '_', '%s__%s' % (res_inf['name'],res_inf['tech']) ) + ".torrent" response = HttpResponse(tdata, content_type="application/json") response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response
def select(site=None, elementTypes=None, connectionTypes=None, networkKinds=None, hostPrefs=None, sitePrefs=None): # STEP 1: limit host choices to what is possible if not sitePrefs: sitePrefs = {} if not hostPrefs: hostPrefs = {} if not networkKinds: networkKinds = [] if not connectionTypes: connectionTypes = [] if not elementTypes: elementTypes = [] all_ = getAll(site=site) if site else getAll() hosts = [] for host in all_: if host.problems(): continue if set(elementTypes) - set(host.elementTypes.keys()): continue if set(connectionTypes) - set(host.connectionTypes.keys()): continue if set(networkKinds) - set(host.getNetworkKinds()): continue hosts.append(host) UserError.check(hosts, code=UserError.INVALID_CONFIGURATION, message="No hosts found for requirements") # any host in hosts can handle the request prefs = dict([(h, 0.0) for h in hosts]) # STEP 2: calculate preferences based on host load els = 0.0 cons = 0.0 for h in hosts: prefs[h] -= h.componentErrors * 25 # discourage hosts with previous errors prefs[h] -= h.getLoad() * 100 # up to -100 points for load els += h.elements.count() cons += h.connections.count() avgEls = els / len(hosts) avgCons = cons / len(hosts) for h in hosts: # between -30 and +30 points for element/connection over-/under-population if avgEls: prefs[h] -= max(-20.0, min(10.0 * (h.elements.count() - avgEls) / avgEls, 20.0)) if avgCons: prefs[h] -= max(-10.0, min(10.0 * (h.connections.count() - avgCons) / avgCons, 10.0)) # STEP 3: calculate preferences based on host location for h in hosts: if h in hostPrefs: prefs[h] += hostPrefs[h] if h.site in sitePrefs: prefs[h] += sitePrefs[h.site] #STEP 4: select the best host hosts.sort(key=lambda h: prefs[h], reverse=True) logging.logMessage("select", category="host", result=hosts[0].name, prefs=dict([(k.name, v) for k, v in prefs.iteritems()]), site=site.name if site else None, element_types=elementTypes, connection_types=connectionTypes, network_types=networkKinds, host_prefs=dict([(k.name, v) for k, v in hostPrefs.iteritems()]), site_prefs=dict([(k.name, v) for k, v in sitePrefs.iteritems()])) return hosts[0]
def getStatistics(siteA, siteB): _siteA = Site.get(siteA) _siteB = Site.get(siteB) UserError.check(_siteA is not None, UserError.ENTITY_DOES_NOT_EXIST, "site does not exist", data={"site": siteA}) UserError.check(_siteB is not None, UserError.ENTITY_DOES_NOT_EXIST, "site does not exist", data={"site": siteB}) if _siteA.id > _siteB.id: _siteA, _siteB = _siteB, _siteA try: return LinkStatistics.objects.get(siteA=_siteA, siteB=_siteB) except LinkStatistics.DoesNotExist: ping(_siteA, _siteB) return LinkStatistics.objects.get(siteA=_siteA, siteB=_siteB)
def create(name, site, attrs=None): if not attrs: attrs = {} user = currentUser() UserError.check(user.hasFlag(Flags.GlobalHostManager) or user.hasFlag(Flags.OrgaHostManager) and user.organization == site.organization, code=UserError.DENIED, message="Not enough permissions") for attr in ["address", "rpcurl"]: UserError.check(attr in attrs.keys(), code=UserError.INVALID_CONFIGURATION, message="Missing attribute for host: %s" % attr) host = Host(name=name, site=site) host.init(attrs) host.save() logging.logMessage("create", category="host", info=host.info()) return host
def download_torrent(api, request, res_id): res_inf = api.template_info(res_id, include_torrent_data=True) UserError.check('torrent_data' in res_inf, UserError.NO_DATA_AVAILABLE, "This template does not have a torrent file", data={'id': res_inf['id']}) tdata = base64.b64decode(res_inf['torrent_data']) filename = re.sub('[^\w\-_\. :]', '_', '%s__%s' % (res_inf['name'], res_inf['tech'])) + ".torrent" response = HttpResponse(tdata, content_type="application/json") response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response
def ping(siteA, siteB, ignore_missing_site=False): if isinstance(siteA, str): siteA = Site.get(siteA) if isinstance(siteB, str): siteB = Site.get(siteB) if (siteA is None or siteB is None) and ignore_missing_site: return if siteA is None: raise UserError(UserError.ENTITY_DOES_NOT_EXIST, "site does not exist", data={"site": siteA}) if siteB is None: raise UserError(UserError.ENTITY_DOES_NOT_EXIST, "site does not exist", data={"site": siteB}) key = (siteA, siteB) with pingingLock: if key in pinging: return pinging.add(key) try: try: stats = LinkStatistics.objects.get(siteA=siteA, siteB=siteB) except LinkStatistics.DoesNotExist: stats = LinkStatistics(siteA=siteA, siteB=siteB).save() choices = list(siteA.hosts.all()) hostA = None while choices and not hostA: hostA = random.choice(choices) if hostA.problems(): choices.remove(hostA) hostA = None if not hostA: return choices = list(siteB.hosts.all()) if hostA in choices: choices.remove(hostA) hostB = None while choices and not hostB: hostB = random.choice(choices) if hostB.problems(): choices.remove(hostB) hostB = None if not hostB: return begin = time.time() res = hostA.getProxy().host_ping(hostB.address) end = time.time() logging.logMessage("link measurement", category="link", siteA=siteA.name, siteB=siteB.name, hostA=hostA.name, hostB=hostB.name, result=res) stats.add(LinkMeasurement(begin=begin, end=end, loss=res['loss'], delayAvg=res.get("rtt_avg", 0.0)/2.0, delayStddev=res.get("rtt_mdev", 0.0)/2.0, measurements=res["transmitted"])) finally: with pingingLock: pinging.remove(key)
def createSite(name, organization, description="", attrs={}): orga = getOrganization(organization) UserError.check(orga, code=UserError.ENTITY_DOES_NOT_EXIST, message="No organization with that name", data={"name": organization}) user = currentUser() UserError.check(user.hasFlag(Flags.GlobalHostManager) or user.hasFlag(Flags.OrgaHostManager) and user.organization == orga, code=UserError.DENIED, message="Not enough permissions") logging.logMessage("create", category="site", name=name, description=description) site = Site(name=name, organization=orga) site.save() attrs.update({'description':description}) site.init(attrs) return site
def edit(api, request, res_id=None): res_inf = api.template_info(res_id) if request.method == "POST": form = EditTemplateForm(res_id, res_inf["tech"] == TypeName.FULL_VIRTUALIZATION, request.POST) if form.is_valid(): formData = form.cleaned_data creation_date = formData["creation_date"] attrs = { "label": formData["label"], "restricted": formData["restricted"], "subtype": formData["subtype"], "preference": formData["preference"], "description": formData["description"], "creation_date": dateToTimestamp(creation_date) if creation_date else None, "nlXTP_installed": formData["nlXTP_installed"], "icon": formData["icon"], "show_as_common": formData["show_as_common"], "urls": filter(lambda x: x, formData["urls"].splitlines()), } if res_inf["tech"] == TypeName.FULL_VIRTUALIZATION: attrs["kblang"] = formData["kblang"] api.template_modify(res_id, attrs) return HttpResponseRedirect(reverse("tomato.template.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render( request, "form.html", { "label": label, "form": form, "heading": "Edit Template Data for '" + label + "' (" + res_inf["tech"] + ")", }, ) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_inf["res_id"] = res_id res_inf["creation_date"] = datetime.date.fromtimestamp(float(res_inf["creation_date"] or "0.0")) res_inf["urls"] = "\n".join(res_inf["urls"]) form = EditTemplateForm(res_id, (res_inf["tech"] == TypeName.FULL_VIRTUALIZATION), res_inf) return render( request, "form.html", { "label": res_inf["label"], "form": form, "heading": "Edit Template Data for '" + str(res_inf["label"]) + "' (" + res_inf["tech"] + ")", }, )
def group_edit(api, request, group_id): if request.method=='POST': form = ErrorGroupForm(api, request.POST) if form.is_valid(): formData = form.cleaned_data api.errorgroup_modify(group_id,{"description": formData["description"]}) return HttpResponseRedirect(reverse("tomato.dumpmanager.group_info", kwargs={"group_id": group_id})) if not group_id: group_id=request.POST["group_id"] UserError.check(group_id, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {"heading": "Editing errorgroup '"+group_id+"'", 'form': form}) else: UserError.check(group_id, UserError.INVALID_DATA, "No error group specified.") errorgroupinfo=api.errorgroup_info(group_id,False) form = EditErrorGroupForm(api, group_id, errorgroupinfo) return render(request, "form.html", {"heading": "Renaming Error Group '"+errorgroupinfo['description']+"'", 'form': form})
def modify(self, attrs): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") logging.logMessage("modify", category="organization", name=self.name, attrs=attrs) for key, value in attrs.iteritems(): if key == "description": self.description = value elif key == "homepage_url": self.homepage_url = value elif key == "image_url": self.image_url = value elif key == "description_text": self.description_text = value else: raise UserError(code=UserError.UNSUPPORTED_ATTRIBUTE, message="Unknown organization attribute", data={"attribute": key}) self.save()
def getUsers(self): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") res = [] for type_, obj in [("element", el) for el in self.elements.all()] + [("connection", con) for con in self.connections.all()]: data = {"type": type_, "onhost_id": obj.num, "element_id": None, "connection_id": None, "topology_id": None, "state": obj.state} if obj.topology_element: tel = obj.topology_element data["element_id"] = tel.id data["topology_id"] = tel.topology_id if obj.topology_connection: tcon = obj.topology_connection data["connection_id"] = tcon.id data["topology_id"] = tcon.topology_id res.append(data) return res
def edit(api, request, id_): scenario_info = api.scenario_info(id_) if request.method == 'POST': form = EditScenarioForm(id_, request.POST) if form.is_valid(): form_data = form.cleaned_data # create_time = form_data["create_time"] attrs = { 'name': form_data['name'], 'description': form_data['description'], 'accessibility': form_data['accessibility'], 'author': form_data['author'], # TODO: datetime is not serializable # 'create_time': form_data['create_time'], 'topology_info_json': form_data['topology_info_json'] } api.scenario_modify(id_, attrs) return HttpResponseRedirect( reverse("tomato.scenario.info", kwargs={"id_": id_})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render( request, "form.html", { 'label': label, 'form': form, "heading": "Edit Scenario Data for '" + label + "' (" + scenario_info['name'] + ")" }) else: UserError.check(id_, UserError.INVALID_DATA, "No resource specified.") scenario_info['id_'] = id_ # scenario_info['create_date'] = datetime.date.fromtimestamp(float(id_['creation_date'] or "0.0")) form = EditScenarioForm(id_, scenario_info) return render( request, "form.html", { 'name': scenario_info['name'], 'form': form, "heading": "Edit Scenario Data for '" + str(scenario_info['name']) })
def edit(api, request, res_id = None): if request.method=='POST': form = EditNetworkInstanceForm(res_id, api, request.POST) if form.is_valid(): formData = form.cleaned_data api.network_instance_modify(formData["res_id"],{'host':formData['host'], 'bridge':formData['bridge'], 'network':formData['network']}) return HttpResponseRedirect(reverse("external_network_instances", kwargs={"network": network_id(api, formData['network'])})) host = request.POST["host"] UserError.check(host, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {'form': form, "heading":"Edit External Network Instance on "+host}) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.network_instance_info(res_id) res_info['res_id'] = res_id form = EditNetworkInstanceForm(res_id, api, res_info) return render(request, "form.html", {'form': form, "heading":"Edit External Network Instance on "+res_info['host']})
def checkAction(self, action): """ Checks if the action can be executed. This method checks if the action is listed in CAP_ACTIONS and if the current state is listed in CAP_ACTIONS[action]. @param action: Action to check @type action: str """ self.checkRole(Role.manager) if self.DIRECT_ACTIONS and not action in self.DIRECT_ACTIONS_EXCLUDE: mcon = self.mainConnection() if mcon and action in mcon.getAllowedActions(): return UserError.check(action in self.CUSTOM_ACTIONS, code=UserError.UNSUPPORTED_ACTION, message="Unsuported connection action: %s" % action, data={"action": action, "id": self.id}) UserError.check(self.state in self.CUSTOM_ACTIONS[action], code=UserError.INVALID_STATE, message="Action %s can not be executed in state %s" % (action, self.state), data={"action": action, "state": self.state, "id": self.id})
def edit_torrent(api, request, res_id=None): if request.method == 'POST': form = ChangeTemplateTorrentForm(res_id, request.POST, request.FILES) if form.is_valid(): formData = form.cleaned_data f = request.FILES['torrentfile'] torrent_data = base64.b64encode(f.read()) res_info = api.template_info(formData['res_id']) creation_date = formData['creation_date'] api.template_modify( formData["res_id"], { 'torrent_data': torrent_data, 'creation_date': dateToTimestamp(creation_date) if creation_date else None }) return HttpResponseRedirect( reverse("tomato.template.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render( request, "form.html", { 'form': form, "heading": "Edit Template Torrent for '" + label + "' (" + request.POST["tech"] + ")" }) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.template_info(res_id) form = ChangeTemplateTorrentForm(res_id, {'res_id': res_id}) return render( request, "form.html", { 'form': form, "heading": "Edit Template Torrent for '" + res_info['label'] + "' (" + res_info['tech'] + ")" })
def modify(self, attrs): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") logging.logMessage("modify", category="host", name=self.name, attrs=attrs) for key, value in attrs.iteritems(): if key == "site": self.site = getSite(value) elif key == "address": self.address = value elif key == "rpcurl": self.rpcurl = value elif key == "name": self.name = value elif key == "enabled": self.enabled = value elif key == "description_text": self.description_text = value else: raise UserError(code=UserError.UNSUPPORTED_ATTRIBUTE, message="Unknown host attribute", data={"attribute": key}) self.save()
def edit(api, request, res_id = None): if request.method=='POST': form = EditNetworkForm(res_id, request.POST) if form.is_valid(): formData = form.cleaned_data api.network_modify(formData["res_id"],{'label':formData['label'], 'preference':formData['preference'], 'description':formData['description'], 'big_icon':formData['big_icon'], 'show_as_common': formData['show_as_common']}) return HttpResponseRedirect(reverse("tomato.external_network.list")) kind = request.POST["kind"] UserError.check(kind, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {'form': form, 'heading':"Edit External Network '"+kind+"'"}) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.network_info(res_id) res_info['res_id'] = res_id form = EditNetworkForm(res_id, res_info) return render(request, "form.html", {'form': form, 'heading':"Edit External Network '"+res_info['label']+"'"})
def edit_torrent(api, request, res_id=None): if request.method=='POST': form = ChangeTemplateTorrentForm(res_id, request.POST,request.FILES) if form.is_valid(): formData = form.cleaned_data f = request.FILES['torrentfile'] torrent_data = base64.b64encode(f.read()) res_info = api.template_info(formData['res_id']) creation_date = formData['creation_date'] api.template_modify(formData["res_id"],{'torrent_data':torrent_data, 'creation_date':dateToTimestamp(creation_date) if creation_date else None}) return HttpResponseRedirect(reverse("tomato.template.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {'form': form, "heading":"Edit Template Torrent for '"+label+"' ("+request.POST["tech"]+")"}) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.template_info(res_id) form = ChangeTemplateTorrentForm(res_id, {'res_id': res_id}) return render(request, "form.html", {'form': form, "heading":"Edit Template Torrent for '"+res_info['label']+"' ("+res_info['tech']+")"})
def modify(self, attrs): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") logging.logMessage("modify", category="site", name=self.name, attrs=attrs) for key, value in attrs.iteritems(): if key == "description": self.description = value elif key == "location": self.location = value elif key == "geolocation": self.geolocation = value elif key == "description_text": self.description_text = value elif key == "organization": orga = getOrganization(value) UserError.check(orga, code=UserError.ENTITY_DOES_NOT_EXIST, message="No organization with that name", data={"name": value}) self.organization = orga else: raise UserError(code=UserError.UNSUPPORTED_ATTRIBUTE, message="Unknown site attribute", data={"attribute": key}) self.save()
def edit(api, request, res_id=None): if request.method=='POST': tech = request.POST['tech'] if tech == 'repy': form = EditRePyForm(res_id, request.POST) elif tech == 'openvz': form = EditOpenVZForm(res_id, request.POST) else: form = EditKVMqmForm(res_id, request.POST) if form.is_valid(): formData = form.cleaned_data data={'cpus':formData['cpus'], 'ram':formData['ram'], 'label':formData['label'], 'preference':formData['preference'], 'description':formData['description']} if (formData['tech'] != 'repy'): data['diskspace'] = formData['diskspace'] if formData['restricted']: data['restricted'] = formData['restricted'] else: data['restricted'] = False api.profile_modify(formData["res_id"],data) return HttpResponseRedirect(reverse("tomato.profile.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render(request, "form.html", {'form': form, "heading":"Edit Device Profile '"+label+"'"}) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.profile_info(res_id) origData = res_info origData['res_id'] = res_id if origData['tech'] == 'repy': form = EditRePyForm(res_id, origData) elif origData['tech'] == 'openvz': form = EditOpenVZForm(res_id, origData) else: form = EditKVMqmForm(res_id, origData) return render(request, "form.html", {'form': form, "heading":"Edit "+res_info['tech']+" Device Profile '"+res_info['label']+"'"})
def edit(api, request, res_id=None): if request.method == 'POST': form = EditTemplateForm( res_id, (api.resource_info(res_id)['attrs']['tech'] == "kvmqm"), request.POST) if form.is_valid(): formData = form.cleaned_data creation_date = str(formData['creation_date']) res_inf = api.resource_info(res_id) UserError.check(res_inf['type'] == 'template', UserError.INVALID_RESOURCE_TYPE, "This resource is not a template", data={'id': formData['res_id']}) attrs = { 'label': formData['label'], 'restricted': formData['restricted'], 'subtype': formData['subtype'], 'preference': formData['preference'], 'description': formData['description'], 'creation_date': creation_date, 'nlXTP_installed': formData['nlXTP_installed'], 'icon': formData['icon'], 'show_as_common': formData['show_as_common'] } if res_inf['attrs']['tech'] == "kvmqm": attrs['kblang'] = formData['kblang'] api.resource_modify(res_id, attrs) return HttpResponseRedirect( reverse("tomato.template.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render( request, "form.html", { 'label': label, 'form': form, "heading": "Edit Template Data for '" + label + "' (" + request.POST['tech'] + ")" }) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_info = api.resource_info(res_id) origData = res_info['attrs'] origData['res_id'] = res_id form = EditTemplateForm(res_id, (origData['tech'] == "kvmqm"), origData) return render( request, "form.html", { 'label': res_info['attrs']['label'], 'form': form, "heading": "Edit Template Data for '" + res_info['attrs']['label'] + "' (" + res_info['attrs']['tech'] + ")" })
def remove(self): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") UserError.check(not self.sites.all(), code=UserError.NOT_EMPTY, message="Organization still has sites") UserError.check(not self.users.all(), code=UserError.NOT_EMPTY, message="Organization still has users") logging.logMessage("remove", category="organization", name=self.name) self.totalUsage.remove() self.delete()
def remove(self): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") UserError.check(not self.elements.all(), code=UserError.NOT_EMPTY, message="Host still has active elements") UserError.check(not self.connections.all(), code=UserError.NOT_EMPTY, message="Host still has active connections") logging.logMessage("remove", category="host", name=self.name) try: for res in self.getProxy().resource_list(): self.getProxy().resource_remove(res["id"]) except: pass self.totalUsage.remove() self.delete()
def edit(api, request, res_id = None): if request.method=='POST': form = EditNetworkForm(res_id, request.POST) if form.is_valid(): formData = form.cleaned_data UserError.check(api.resource_info(formData['res_id'])['type'] == 'network',UserError.INVALID_PARAMETER, _("This resource is not a template"), data={'id':formData['res_id']}) api.resource_modify(formData["res_id"],{'label':formData['label'], 'preference':formData['preference'], 'description':formData['description'], 'big_icon':formData['big_icon'], 'show_as_common': formData['show_as_common']}) return HttpResponseRedirect(reverse("tomato.external_network.list")) kind = request.POST["kind"] UserError.check(kind, UserError.INVALID_DATA, _("Form transmission failed.")) return render(request, "form.html", {'form': form, 'heading': ("Edit External Network '")+kind+"'"}) else: UserError.check(res_id, UserError.INVALID_DATA, _("No resource specified.")) res_info = api.resource_info(res_id) origData = res_info['attrs'] origData['res_id'] = res_id form = EditNetworkForm(res_id, origData) return render(request, "form.html", {'form': form, 'heading': ("Edit External Network '")+res_info['attrs']['label']+"'"})
def remove(self): UserError.check(self.checkPermissions(), code=UserError.DENIED, message="Not enough permissions") UserError.check(not self.hosts.all(), code=UserError.NOT_EMPTY, message="Site still has hosts") logging.logMessage("remove", category="site", name=self.name) self.delete()
def edit(api, request, res_id=None): res_inf = api.template_info(res_id) if request.method == 'POST': form = EditTemplateForm(res_id, res_inf['tech'] == "kvmqm", request.POST) if form.is_valid(): formData = form.cleaned_data creation_date = formData['creation_date'] attrs = { 'label': formData['label'], 'restricted': formData['restricted'], 'subtype': formData['subtype'], 'preference': formData['preference'], 'description': formData['description'], 'creation_date': dateToTimestamp(creation_date) if creation_date else None, 'nlXTP_installed': formData['nlXTP_installed'], 'icon': formData['icon'], 'show_as_common': formData['show_as_common'] } if res_inf['tech'] == "kvmqm": attrs['kblang'] = formData['kblang'] api.template_modify(res_id, attrs) return HttpResponseRedirect( reverse("tomato.template.info", kwargs={"res_id": res_id})) label = request.POST["label"] UserError.check(label, UserError.INVALID_DATA, "Form transmission failed.") return render( request, "form.html", { 'label': label, 'form': form, "heading": "Edit Template Data for '" + label + "' (" + res_inf['tech'] + ")" }) else: UserError.check(res_id, UserError.INVALID_DATA, "No resource specified.") res_inf['res_id'] = res_id res_inf['creation_date'] = datetime.date.fromtimestamp( float(res_inf['creation_date'] or "0.0")) form = EditTemplateForm(res_id, (res_inf['tech'] == "kvmqm"), res_inf) return render( request, "form.html", { 'label': res_inf['label'], 'form': form, "heading": "Edit Template Data for '" + str(res_inf['label']) + "' (" + res_inf['tech'] + ")" })
def create(el1, el2, attrs=None): if not attrs: attrs = {} UserError.check(el1 != el2, code=UserError.INVALID_CONFIGURATION, message="Cannot connect element with itself") UserError.check(not el1.connection, code=UserError.ALREADY_CONNECTED, message="Element is already connected", data={"element": el1.id}) UserError.check(not el2.connection, code=UserError.ALREADY_CONNECTED, message="Element is already connected", data={"element": el2.id}) UserError.check(el1.CAP_CONNECTABLE, code=UserError.INVALID_VALUE, message="Element can not be connected", data={"element": el1.id}) UserError.check(el2.CAP_CONNECTABLE, code=UserError.INVALID_VALUE, message="Element can not be connected", data={"element": el2.id}) UserError.check(el1.topology == el2.topology, code=UserError.INVALID_VALUE, message="Can only connect elements from same topology") el1.topology.checkRole(Role.manager) con = Connection() con.init(el1.topology, el1, el2, attrs) con.save() con.triggerStart() logging.logMessage("create", category="connection", id=con.id) logging.logMessage("info", category="connection", id=con.id, info=con.info()) return con