Commit c36742f3 authored by Nicolas Wavrant's avatar Nicolas Wavrant

runner: opening Software Release supplies a new one, instead of destroying all data

Creates a new view with a more fitting name, replacing an older one.
Also, requesting instance should happen only if there is no current
instance, otherwise it may erase data.
parent 9e6e36bb
...@@ -229,10 +229,10 @@ class SlaprunnerTestSuite(ResiliencyTestSuite): ...@@ -229,10 +229,10 @@ class SlaprunnerTestSuite(ResiliencyTestSuite):
def _openSoftwareRelease(self, software_release='erp5testnode/testsuite/dummy'): def _openSoftwareRelease(self, software_release='erp5testnode/testsuite/dummy'):
self.logger.debug('Opening %s software release...' % software_release) self.logger.debug('Opening %s software release...' % software_release)
data = self._connectToSlaprunner( data = self._connectToSlaprunner(
resource='setCurrentProject', resource='supplySoftwareRelease',
data='path=workspace/slapos/software/%s/' % software_release data='path=workspace/slapos/software/%s/' % software_release
) )
assert json.loads(data)['code'] != 0, 'Unexpecting result in call to setCurrentProject: %s' % data assert json.loads(data)['code'] != 0, 'Unexpecting result in call to supplySoftwareRelease: %s' % data
def generateData(self): def generateData(self):
""" """
......
...@@ -327,7 +327,7 @@ setuptools = 33.1.1 ...@@ -327,7 +327,7 @@ setuptools = 33.1.1
"""Scenario 3: Open software release""" """Scenario 3: Open software release"""
self.test_cloneProject() self.test_cloneProject()
software = os.path.join(self.software, 'helloworld') # Drupal SR must exist in SR folder software = os.path.join(self.software, 'helloworld') # Drupal SR must exist in SR folder
response = loadJson(self.app.post('/setCurrentProject', response = loadJson(self.app.post('/supplySoftwareRelease',
data=dict(path=software), data=dict(path=software),
follow_redirects=True)) follow_redirects=True))
self.assertEqual(response['result'], "") self.assertEqual(response['result'], "")
...@@ -378,7 +378,7 @@ setuptools = 33.1.1 ...@@ -378,7 +378,7 @@ setuptools = 33.1.1
self.setupTestSoftware() self.setupTestSoftware()
#Set current projet and run Slapgrid-cp #Set current projet and run Slapgrid-cp
software = self.software + 'slaprunner-test/' software = self.software + 'slaprunner-test/'
response = loadJson(self.app.post('/setCurrentProject', response = loadJson(self.app.post('/supplySoftwareRelease',
data=dict(path=software), data=dict(path=software),
follow_redirects=True)) follow_redirects=True))
self.assertEqual(response['result'], "") self.assertEqual(response['result'], "")
...@@ -567,7 +567,7 @@ setuptools = 33.1.1 ...@@ -567,7 +567,7 @@ setuptools = 33.1.1
), ),
follow_redirects=True)).get(u'code') follow_redirects=True)).get(u'code')
self.assertEqual(response, 1) self.assertEqual(response, 1)
response = loadJson(self.app.post('/setCurrentProject', response = loadJson(self.app.post('/supplySoftwareRelease',
data=dict(path=software), data=dict(path=software),
follow_redirects=True)).get(u'code') follow_redirects=True)).get(u'code')
self.assertEqual(response, 1) self.assertEqual(response, 1)
......
...@@ -27,7 +27,7 @@ $(document).ready(function () { ...@@ -27,7 +27,7 @@ $(document).ready(function () {
} }
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: $SCRIPT_ROOT + '/setCurrentProject', url: $SCRIPT_ROOT + '/supplySoftwareRelease',
data: "path=" + elt.attr('rel'), data: "path=" + elt.attr('rel'),
success: function (data) { success: function (data) {
if (data.code === 1) { if (data.code === 1) {
......
...@@ -106,7 +106,7 @@ $(document).ready(function () { ...@@ -106,7 +106,7 @@ $(document).ready(function () {
} }
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: $SCRIPT_ROOT + '/setCurrentProject', url: $SCRIPT_ROOT + '/supplySoftwareRelease',
data: "path=" + $("input#path").val(), data: "path=" + $("input#path").val(),
success: function (data) { success: function (data) {
if (data.code === 1) { if (data.code === 1) {
......
...@@ -33,7 +33,6 @@ ...@@ -33,7 +33,6 @@
<div id="fileTree" class="file_tree"></div> <div id="fileTree" class="file_tree"></div>
<div id="file_info" class="file_info"> <div id="file_info" class="file_info">
<img src="{{ url_for('static', filename='images/check.png') }}" class="check" id="check" alt=""/> <img src="{{ url_for('static', filename='images/check.png') }}" class="check" id="check" alt=""/>
<p><font color="red">WARNING:</font> Opening a new software release <font color="red">WILL ERASE YOUR EXISTING INSTANCE</font>. Proceed with caution!</p></div>
<input type="hidden" name="path" id="path" value="" /> <input type="hidden" name="path" id="path" value="" />
<input type="submit" name="open" id ="open" value="Open Software" class="button"/> <input type="submit" name="open" id ="open" value="Open Software" class="button"/>
</div> </div>
......
...@@ -28,6 +28,7 @@ from slapos.runner.process import Popen ...@@ -28,6 +28,7 @@ from slapos.runner.process import Popen
from passlib.apache import HtpasswdFile from passlib.apache import HtpasswdFile
import slapos.slap import slapos.slap
from slapos.grid.utils import md5digest from slapos.grid.utils import md5digest
from slapos.slap.exception import NotFoundError
from slapos.util import str2bytes from slapos.util import str2bytes
logger = logging.getLogger('slaprunner') logger = logging.getLogger('slaprunner')
...@@ -134,6 +135,21 @@ def getCurrentSoftwareReleaseProfile(config): ...@@ -134,6 +135,21 @@ def getCurrentSoftwareReleaseProfile(config):
except IOError: except IOError:
return '' return ''
def getCurrentUsedSoftwareReleaseProfile(config):
"""
Returns used Software Release profile as a string.
"""
slap = slapos.slap.slap()
slap.initializeConnection(config['master_url'])
# Try to return the SR related to the current instance
try:
computer_partition = slap.registerComputerPartition(config['computer_id'], 'slappart0')
software_release = computer_partition.getSoftwareRelease()
return software_release.getURI()
# If there are no instances, return the last requested Software Release
except NotFoundError:
return ''
def requestInstance(config, software_type=None): def requestInstance(config, software_type=None):
""" """
...@@ -162,7 +178,7 @@ def requestInstance(config, software_type=None): ...@@ -162,7 +178,7 @@ def requestInstance(config, software_type=None):
return slap.registerOpenOrder().request( return slap.registerOpenOrder().request(
profile, profile,
partition_reference=getSoftwareReleaseName(config), partition_reference='slaprunner', # we want only one instance in webrunner
partition_parameter_kw=partition_parameter_kw, partition_parameter_kw=partition_parameter_kw,
software_type=software_type, software_type=software_type,
filter_kw=None, filter_kw=None,
...@@ -170,6 +186,29 @@ def requestInstance(config, software_type=None): ...@@ -170,6 +186,29 @@ def requestInstance(config, software_type=None):
shared=False) shared=False)
def supplySoftwareRelease(config, sr_path):
"""
Act like "slapos node supply" by registering a new SR to current slapproxy
"""
folder = realpath(config, sr_path)
if not folder:
return
sup_process.stopProcess(config, 'slapgrid-cp')
sup_process.stopProcess(config, 'slapgrid-sr')
updateProxy(config)
slap = slapos.slap.slap()
slap.initializeConnection(config['master_url'])
slap.registerSupply().supply(
os.path.join(realpath(config, sr_path), config['software_profile']),
computer_guid=config['computer_id'],
)
# Don't replace .project if there is a running instance
if not getCurrentUsedSoftwareReleaseProfile(config):
setCurrentSoftwareRelease(config, sr_path)
def updateProxy(config): def updateProxy(config):
""" """
Configure Slapos Node computer and partitions. Configure Slapos Node computer and partitions.
...@@ -179,10 +218,8 @@ def updateProxy(config): ...@@ -179,10 +218,8 @@ def updateProxy(config):
if not os.path.exists(config['instance_root']): if not os.path.exists(config['instance_root']):
os.mkdir(config['instance_root']) os.mkdir(config['instance_root'])
slap = slapos.slap.slap() slap = slapos.slap.slap()
profile = getCurrentSoftwareReleaseProfile(config)
slap.initializeConnection(config['master_url']) slap.initializeConnection(config['master_url'])
slap.registerSupply().supply(profile, computer_guid=config['computer_id'])
computer = slap.registerComputer(config['computer_id']) computer = slap.registerComputer(config['computer_id'])
prefix = 'slappart' prefix = 'slappart'
slap_config = { slap_config = {
...@@ -303,7 +340,7 @@ def runSlapgridWithLock(config, step, process_name, lock=False): ...@@ -303,7 +340,7 @@ def runSlapgridWithLock(config, step, process_name, lock=False):
os.remove(log_file) os.remove(log_file)
if not updateProxy(config): if not updateProxy(config):
return 1 return 1
if step == 'instance' and not requestInstance(config): if step == 'instance' and not getCurrentUsedSoftwareReleaseProfile(config):
return 1 return 1
try: try:
sup_process.runProcess(config, process_name) sup_process.runProcess(config, process_name)
...@@ -565,17 +602,12 @@ def configNewSR(config, projectpath): ...@@ -565,17 +602,12 @@ def configNewSR(config, projectpath):
Returns: Returns:
True if all is done well, otherwise return false. True if all is done well, otherwise return false.
""" """
folder = realpath(config, projectpath) supplySoftwareRelease(config, projectpath)
if folder:
sup_process.stopProcess(config, 'slapgrid-cp')
sup_process.stopProcess(config, 'slapgrid-sr') def setCurrentSoftwareRelease(config, relative_project_path):
logger.warning("User opened a new SR. Removing all instances...") with open(os.path.join(config['etc_dir'], ".project"), 'w') as f:
removeCurrentInstance(config) f.write(relative_project_path)
with open(os.path.join(config['etc_dir'], ".project"), 'w') as f:
f.write(projectpath)
return True
else:
return False
def newSoftware(folder, config, session): def newSoftware(folder, config, session):
......
...@@ -16,6 +16,7 @@ from flask import (Flask, request, redirect, url_for, render_template, ...@@ -16,6 +16,7 @@ from flask import (Flask, request, redirect, url_for, render_template,
import slapos import slapos
from slapos.util import bytes2str from slapos.util import bytes2str
import utils
from slapos.runner.utils import (checkSoftwareFolder, configNewSR, checkUserCredential, from slapos.runner.utils import (checkSoftwareFolder, configNewSR, checkUserCredential,
createNewUser, getBuildAndRunParams, createNewUser, getBuildAndRunParams,
getProfilePath, getSlapgridResult, getProfilePath, getSlapgridResult,
...@@ -313,12 +314,17 @@ def checkFolder(): ...@@ -313,12 +314,17 @@ def checkFolder():
return checkSoftwareFolder(request.form['path'], app.config) return checkSoftwareFolder(request.form['path'], app.config)
def setCurrentProject(): def supplySoftwareRelease():
if configNewSR(app.config, request.form['path']): if request.form['path']:
session['title'] = getProjectTitle(app.config) sr_absolute_path = realpath(app.config, request.form['path'])
return jsonify(code=1, result="") sr_absolute_path = sr_absolute_path and os.path.join(sr_absolute_path, 'software.cfg') # XXX: find where this one was added before
else: if os.path.exists(sr_absolute_path):
return jsonify(code=0, result=("Can not setup this Software Release")) utils.supplySoftwareRelease(app.config, request.form['path'])
# request instance if no instance has been requested yet
if not utils.getCurrentUsedSoftwareReleaseProfile(app.config):
utils.requestInstance(app.config)
return jsonify(code=1, result="")
return jsonify(code=0, result=("Can not setup this Software Release"))
def getProjectStatus(): def getProjectStatus():
...@@ -866,7 +872,7 @@ app.add_url_rule("/getProjectStatus", 'getProjectStatus', getProjectStatus, ...@@ -866,7 +872,7 @@ app.add_url_rule("/getProjectStatus", 'getProjectStatus', getProjectStatus,
methods=['POST']) methods=['POST'])
app.add_url_rule('/openProject/<method>', 'openProject', openProject, app.add_url_rule('/openProject/<method>', 'openProject', openProject,
methods=['GET']) methods=['GET'])
app.add_url_rule("/setCurrentProject", 'setCurrentProject', setCurrentProject, app.add_url_rule("/supplySoftwareRelease", 'supplySoftwareRelease', supplySoftwareRelease,
methods=['POST']) methods=['POST'])
app.add_url_rule("/checkFolder", 'checkFolder', checkFolder, methods=['POST']) app.add_url_rule("/checkFolder", 'checkFolder', checkFolder, methods=['POST'])
app.add_url_rule('/createSoftware', 'createSoftware', createSoftware, app.add_url_rule('/createSoftware', 'createSoftware', createSoftware,
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment