Exemplo n.º 1
0
def init_detect(switch_name):
    result = {"errors": [], "network": "", "ip_offset": 0, "macs": []}
    if "ports" not in flask.request.json:
        result["errors"].append("Required parameters: 'ports'")
        return json.dumps(result)
    # Get the network IP from the dnsmasq configuration
    cmd = "grep listen-address /etc/dnsmasq.conf"
    process = subprocess.run(cmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.DEVNULL,
                             universal_newlines=True)
    network_ip = process.stdout.split("=")[1]
    result["network"] = network_ip[:network_ip.rindex(".")]
    if len(result["network"].split(".")) != 3:
        logging.error("Wrong network IP from the dnsmasq configuration: %s" %
                      result["network"])
        result["errors"].append(
            "Wrong network IP from the dnsmasq configuration")
    # Get existing static IP from the dnsmasq configuration
    existing_ips = []
    existing_macs = []
    cmd = "grep ^dhcp-host /etc/dnsmasq.conf"
    process = subprocess.run(cmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.DEVNULL,
                             universal_newlines=True)
    for line in process.stdout.split('\n'):
        if "," in line and not line.startswith("#"):
            existing_ips.append(line.split(",")[2])
            existing_macs.append(line.split(",")[0][-17:])
            result["macs"].append(line.split(",")[0][-17:])
    logging.info("existing ips: %s" % existing_ips)
    logging.info("existing macs: %s" % existing_macs)
    # Check the node IP is available
    db = open_session()
    sw = db.query(RaspSwitch).filter(RaspSwitch.name == switch_name).first()
    ip_offset = sw.first_ip - 1
    close_session(db)
    result["ip_offset"] = ip_offset
    for port in flask.request.json["ports"]:
        node_ip = "%s.%d" % (result["network"], (ip_offset + int(port)))
        if node_ip in existing_ips:
            result["errors"].append(
                "%s already exists in the DHCP configuration!" % node_ip)
            return json.dumps(result)
    # Expose TFTP files to all nodes (boot from the NFS server)
    tftp_files = glob('/tftpboot/rpiboot_uboot/*')
    for f in tftp_files:
        if os.path.isdir(f):
            new_f = '/tftpboot/%s' % os.path.basename(f)
            if not os.path.isdir(new_f):
                shutil.copytree(f, new_f)
        else:
            shutil.copy(f, '/tftpboot/%s' % os.path.basename(f))
    return json.dumps(result)
Exemplo n.º 2
0
def cancel():
    """ Cancel the deployment (that is in the initialized state) """
    db_session = open_session()
    db_user = db_session.query(User).filter_by(email=current_user.id).first()
    # Delete previous deployments still in initialized state
    old_dep = db_session.query(Deployment).filter_by(
        user_id=db_user.id, state="initialized").delete()
    close_session(db_session)
    return flask.redirect(flask.url_for("app.resources"))
Exemplo n.º 3
0
def node_extend(arg_dict):
    result = {}
    # Check POST data
    if "nodes" not in arg_dict or "user" not in arg_dict:
        return json.dumps({
            "parameters": {
                "user": "******",
                "nodes": ["name1", "name2"]
            }
        })
    wanted = arg_dict["nodes"]
    user = arg_dict["user"]
    if len(user) == 0 or '@' not in user:
        for n in wanted:
            result[n] = "no_email"
        return json.dumps(result)
    # Get information about the requested nodes
    db = open_session()
    nodes = db.query(Schedule).filter(
        Schedule.node_name.in_(wanted)).filter(Schedule.owner == user).all()
    for n in nodes:
        # Allow users to extend their reservation 4 hours before the end_date
        if n.end_date - int(time.time()) < 4 * 3600:
            hours_added = int((n.end_date - n.start_date) / 3600)
            api_url = "https://api.grid5000.fr/stable/sites/%s/internal/oarapi/jobs/%s.json" % (
                get_config()["g5k_site"], n.node_name)
            g5k_login = (arg_dict["g5k_user"],
                         decrypt_password(arg_dict["g5k_password"]))
            json_data = {
                "method": "walltime-change",
                "walltime": "+%d:00" % hours_added
            }
            r = requests.post(url=api_url, auth=g5k_login, json=json_data)
            if r.status_code == 202:
                if r.json()["status"] == "Accepted":
                    n.end_date += hours_added * 3600
                    result[n.node_name] = "success"
                else:
                    error_msg = "failure: walltime modification rejected"
                    logging.error(error_msg)
                    logging.error(r.json())
                    result[n.node_name] = error_msg
            else:
                error_msg = "failure: wrong API return code %d" % r.status_code
                logging.error(error_msg)
                result[n.node_name] = error_msg
        else:
            result[
                n.
                node_name] = "failure: it is too early to extend the reservation"
    close_session(db)
    # Build the result
    for n in wanted:
        if n not in result:
            result[n] = "failure"
    return json.dumps(result)
Exemplo n.º 4
0
def ssh_put():
    """ Create/update the SSH key of the user account """
    my_ssh = flask.request.form.get("ssh_key")
    if my_ssh is not None and len(my_ssh) > 0:
        db_session = open_session()
        db_user = db_session.query(User).filter_by(
            email=current_user.id).first()
        db_user.ssh_key = my_ssh
        close_session(db_session)
    return flask.redirect(flask.url_for("app.user"))
Exemplo n.º 5
0
def switch_nodes(switch_name):
    result = {"errors": [], "nodes": {}}
    db = open_session()
    sw = db.query(RaspSwitch).filter(RaspSwitch.name == switch_name).first()
    if sw.master_port > 0:
        result["nodes"][sw.master_port] = "pimaster"
    # Build the node information
    for n in db.query(RaspNode).filter(RaspNode.switch == sw.name).all():
        result["nodes"][str(n.port_number)] = n.name
    close_session(db)
    return json.dumps(result)
Exemplo n.º 6
0
def load_user(user_email):
    db = open_session()
    db_user = db.query(User).filter(User.email == user_email).first()
    auth_user = None
    if db_user is not None and db_user.is_authorized:
        flask_user = LoginUser()
        flask_user.email = db_user.email
        flask_user.is_admin = db_user.is_admin
        auth_user = flask_user
    close_session(db)
    return auth_user
Exemplo n.º 7
0
def node_list(arg_dict):
    result = {}
    db = open_session()
    # Get the node properties
    for node in db.query(RaspNode).filter(RaspNode.name != "pimaster").all():
        result[node.name] = {}
        for col_name in RaspNode.__table__.columns:
            name_str = str(col_name).split(".")[1]
            result[node.name][name_str] = getattr(node, name_str)
    close_session(db)
    return json.dumps(result)
Exemplo n.º 8
0
def node_deployagain(arg_dict):
    result = {}
    for job_id in arg_dict["nodes"]:
        cmd = "iotlab-experiment -u %s -p %s reload -i %s" % (
            arg_dict["iot_user"], decrypt_password(
                arg_dict["iot_password"]), job_id)
        process = subprocess.run(cmd,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.DEVNULL,
                                 universal_newlines=True)
        json_data = json.loads(process.stdout)
        if "id" in json_data:
            result[job_id] = "success"
            # Get information about the new job
            cmd = "iotlab-experiment -u %s -p %s get -i %d -p" % (
                arg_dict["iot_user"], decrypt_password(
                    arg_dict["iot_password"]), json_data["id"])
            process = subprocess.run(cmd,
                                     shell=True,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.DEVNULL,
                                     universal_newlines=True)
            job_data = json.loads(process.stdout)
            # Compute the dates of the job
            start_date = datetime.strptime(job_data["start_date"],
                                           "%Y-%m-%dT%H:%M:%SZ")
            start_date = start_date.replace(tzinfo=pytz.UTC)
            start_time = start_date.timestamp()
            end_time = start_time + job_data["submitted_duration"] * 60
            # Add the new job to the schedule
            db = open_session()
            job_org = db.query(Schedule).filter(
                Schedule.node_name == job_id).first()
            schedule = Schedule()
            schedule.node_name = job_data["id"]
            schedule.owner = arg_dict["user"]
            schedule.bin = job_org.bin
            schedule.start_date = start_time
            schedule.end_date = end_time
            schedule.state = "ready"
            schedule.action_state = ""
            db.add(schedule)
            # Add the assigned nodes
            assigned_nodes = []
            for n in job_data["nodes"]:
                assigned_nodes.append(n.split(".")[0] + "@" + n.split(".")[1])
            nodes_str = ",".join(assigned_nodes)
            nodes_db = IotNodes()
            nodes_db.job_id = job_data["id"]
            nodes_db.assigned_nodes = nodes_str
            db.add(nodes_db)
            close_session(db)
    return json.dumps(result)
Exemplo n.º 9
0
def switch_list(arg_dict):
    db = open_session()
    # Get the switches
    result = {}
    for s in db.query(RaspSwitch).all():
        result[s.name] = {}
        for col_name in RaspSwitch.__table__.columns:
            name_str = str(col_name).split(".")[1]
            result[s.name][name_str] = getattr(s, name_str)
    close_session(db)
    return json.dumps(result)
Exemplo n.º 10
0
def environment_list(arg_dict):
    db = open_session()
    # Get the environments
    result = {}
    for e in db.query(RaspEnvironment).all():
        result[e.name] = {}
        for col_name in RaspEnvironment.__table__.columns:
            name_str = str(col_name).split(".")[1]
            result[e.name][name_str] = getattr(e, name_str)
    close_session(db)
    return json.dumps(result)
Exemplo n.º 11
0
def node_deploying():
    result = {
        "errors": [],
        "nodes": {},
        "states": {
            "raspberry": [],
            "iot-lab": [],
            "g5k": []
        }
    }
    db = open_session()
    for agent in db.query(Agent).filter(Agent.state == "connected").all():
        try:
            r_data = post_data(db, current_user.email, agent.type, agent.token)
            r = requests.post(url="http://%s:%s/v1/user/node/mine" %
                              (agent.ip, agent.port),
                              timeout=POST_TIMEOUT,
                              json=r_data)
            if r.status_code == 200:
                json_data = r.json()
                result["states"][agent.type] = json_data["states"]
                for node in json_data["nodes"]:
                    # Sort the nodes by bin
                    bin_name = json_data["nodes"][node].pop("bin")
                    # Add the agent name to the node information
                    json_data["nodes"][node]["agent"] = agent.name
                    # No bin for nodes in 'configuring' state
                    if len(bin_name) > 0:
                        # Sort nodes by bin name
                        if bin_name not in result["nodes"]:
                            result["nodes"][bin_name] = {
                                "raspberry": [],
                                "iot-lab": [],
                                "g5k": []
                            }
                        result["nodes"][bin_name][agent.type].append(
                            json_data["nodes"][node])
            else:
                error_msg = "deploying error: wrong answer from the agent '%s' (return code %d)" % (
                    agent.name, r.status_code)
                logging.error(error_msg)
                result["errors"].append(error_msg)
        except (ConnectionError, ConnectTimeout):
            agent.state = "disconnected"
            error_msg = "agent '%s' does not respond" % agent.name
            result["errors"].append(error_msg)
            logging.exception(error_msg)
        except:
            error_msg = "connection failure to the agent '%s'" % agent.name
            result["errors"].append(error_msg)
            logging.exception(error_msg)
    close_session(db)
    return json.dumps(result)
Exemplo n.º 12
0
def user_ssh():
    msg = ""
    form_data = flask.request.form
    db = open_session()
    user = db.query(User).filter(User.email == current_user.email).first()
    if "ssh_key" in form_data:
        user.ssh_key = form_data["ssh_key"]
        msg = "SSH key updated!"
    else:
        msg = "Missing data in the request. SSH key unchanged!"
    close_session(db)
    return flask.redirect("/user/settings?msg=" + msg)
Exemplo n.º 13
0
def set_power_port(switch_name, port, value):
    db = open_session()
    sw = db.query(RaspSwitch).filter(RaspSwitch.name == switch_name).first()
    snmp_address = "%s.%d" % (sw.poe_oid, sw.oid_offset + int(port))
    cmd = "snmpset -v2c -c %s %s %s i %s" % (sw.community, sw.ip, snmp_address,
                                             value)
    close_session(db)
    subprocess.run(cmd.split(),
                   check=True,
                   stdout=subprocess.DEVNULL,
                   stderr=subprocess.DEVNULL)
    return True
Exemplo n.º 14
0
def node_mine(arg_dict):
    if "user" not in arg_dict or "@" not in arg_dict["user"]:
        return json.dumps({ "parameters": "user: '******'" })
    result = { "states": [], "nodes": {} }
    # Get the list of the states for the 'deploy' process
    py_module = import_module("%s.states" % get_config()["node_type"])
    PROCESS = getattr(py_module, "PROCESS")
    for p in PROCESS["deploy"]:
        if len(p["states"]) > len(result["states"]):
            result["states"] = p["states"]
    db = open_session()
    # Get my nodes
    node_names = []
    nodes = db.query(Schedule
            ).filter(Schedule.owner == arg_dict["user"]
            ).filter(Schedule.state != "configuring"
            ).all()
    for n in nodes:
        result["nodes"][n.node_name] = {
            "node_name": n.node_name,
            "bin": n.bin,
            "start_date": n.start_date,
            "end_date": n.end_date,
            "state": n.state,
            "action_state": n.action_state
        }
    nodes = db.query(RaspNode).filter(RaspNode.name.in_(result["nodes"].keys())).all()
    for n in nodes:
        result["nodes"][n.name]["ip"] = n.ip
        result["nodes"][n.name]["switch"] = n.switch
        result["nodes"][n.name]["port_number"] = n.port_number
        result["nodes"][n.name]["model"] = n.model
        result["nodes"][n.name]["serial"] = n.serial
    envs = db.query(ActionProperty
        ).filter(ActionProperty.node_name.in_(result["nodes"].keys())
        ).filter(ActionProperty.prop_name.in_(["environment", "os_password"])
        ).all()
    env_web = {}
    for e in envs:
        if e.prop_name == "environment":
            # Check if the environment provides a web interface
            if e.prop_value not in env_web:
                has_web = db.query(RaspEnvironment).filter(RaspEnvironment.name == e.prop_value
                    ).first().web
                env_web[e.prop_value] = has_web
            if env_web[e.prop_value]:
                #result["nodes"][e.node_name]["url"] = "http://%s:8181" % result["nodes"][e.node_name]["ip"]
                # Hack for the PiSeduce cluster
                result["nodes"][e.node_name]["url"] = "https://pi%02d.seduce.fr" % (
                        int(result["nodes"][e.node_name]["port_number"]))
        result["nodes"][e.node_name][e.prop_name] = e.prop_value
    close_session(db)
    return json.dumps(result)
Exemplo n.º 15
0
def save_env(n_name):
    """ Display the form to configure the 'save environment' action """
    db_session = open_session()
    db_user = db_session.query(User).filter_by(email=current_user.id).first()
    deployment = db_session.query(Deployment).filter_by(
        user_id=db_user.id,
        node_name=n_name).filter(Deployment.state != "destroyed").first()
    env_name = deployment.environment
    close_session(db_session)
    return flask.render_template("form_save_env.html.jinja2",
                                 environment=env_name,
                                 node_name=n_name)
Exemplo n.º 16
0
def make_deploy():
    form_data = flask.request.form
    dep_name = None
    duration = None
    result = {}
    json_result = {"errors": []}
    for prop in form_data:
        if prop == "bin":
            bin_name = form_data[prop]
        else:
            node_name, _, prop_name = prop.rpartition("-")
            if prop_name == "agent":
                last_agent = form_data[prop]
                if last_agent not in result:
                    result[last_agent] = {}
                result[last_agent][node_name] = {"node_bin": bin_name}
            else:
                result[last_agent][node_name][prop_name] = form_data[prop]
    if len(result) == 0:
        return flask.redirect("/user/configure?msg=%s" %
                              "No data available to deploy nodes")
    db = open_session()
    for agent_name in result:
        # Send the user SSH key to the agent
        user_db = db.query(User).filter(
            User.email == current_user.email).first()
        if user_db.ssh_key is not None and len(user_db.ssh_key) > 256:
            for node in result[agent_name]:
                result[agent_name][node]["account_ssh_key"] = user_db.ssh_key
        agent = db.query(Agent).filter(Agent.name == agent_name).first()
        r_data = post_data(db, current_user.email, agent.type, agent.token)
        r_data["nodes"] = result[agent_name]
        r = requests.post(url="http://%s:%s/v1/user/deploy" %
                          (agent.ip, agent.port),
                          timeout=POST_TIMEOUT,
                          json=r_data)
        if r.status_code == 200:
            r_json = r.json()
            if "error" in r_json and len(r_json["error"]) > 0:
                json_result["errors"].append(r_json["error"][0])
            else:
                json_result.update(r.json())
        else:
            json_result["errors"].append("wrong answer from the agent '%s'" %
                                         agent_name)
    close_session(db)
    if len(json_result["errors"]) > 0:
        return flask.redirect("/user/configure?msg=%s" %
                              ",".join(json_result["errors"]))
    else:
        return flask.redirect("/user/manage")
    return json.dumps(json_result)
Exemplo n.º 17
0
def ask_destruction(deployment_ids):
    """ Destroy multiple deployments from their id """
    db_session = open_session()
    db_user = db_session.query(User).filter_by(email=current_user.id).first()
    for d in deployment_ids.split(","):
        deployment = db_session.query(Deployment).filter_by(
            id=d, user_id=db_user.id).first()
        if deployment is not None:
            deployment.process = 'destroy'
            deployment.state = select_process('destroy',
                                              deployment.environment)[0]
    close_session(db_session)
    return flask.redirect(flask.url_for("app.home"))
Exemplo n.º 18
0
def pwd_put():
    """ Create/update the password of the user account """
    pwd = flask.request.form.get("password")
    confirm_pwd = flask.request.form.get("confirm_password")
    if pwd == confirm_pwd:
        db_session = open_session()
        db_user = db_session.query(User).filter_by(
            email=current_user.id).first()
        db_user._set_password = pwd
        close_session(db_session)
        return flask.redirect(flask.url_for("app.user"))
    else:
        return 'The two passwords are not identical!<a href="/user">Try again</a>'
Exemplo n.º 19
0
def ask_redeploy(n_name):
    """ Deploy again the environment on the server """
    db_session = open_session()
    db_user = db_session.query(User).filter_by(email=current_user.id).first()
    # Verify the node belongs to my deployments
    my_deployment = db_session.query(Deployment).filter_by(
        user_id=db_user.id,
        node_name=n_name).filter(Deployment.state != "destroyed").first()
    my_deployment.process = "deploy"
    my_deployment.state = select_process("deploy",
                                         my_deployment.environment)[0]
    close_session(db_session)
    return flask.redirect(flask.url_for("app.home"))
Exemplo n.º 20
0
def temp_data_helper(agent_name=None, period_str=None):
    # Add the temperature consumption
    node_data = {}
    db = open_session()
    if agent_name is None or len(agent_name) == 0:
        agent_list = db.query(Agent).filter(Agent.type == "raspberry").filter(
            Agent.state == "connected").all()
    else:
        agent_list = db.query(Agent).filter(Agent.type == "raspberry").filter(
            Agent.state == "connected").filter(Agent.name == agent_name).all()
    for agent in agent_list:
        r_data = post_data(db, current_user.email, agent.type, agent.token)
        if isinstance(period_str, str) and len(period_str) > 0:
            r_data["period"] = period_str
        r = requests.post(url="http://%s:%s/v1/user/node/temperature" %
                          (agent.ip, agent.port),
                          timeout=POST_TIMEOUT,
                          json=r_data)
        if r.status_code == 200:
            r_json = r.json()
            for cons in r_json:
                if agent.name not in node_data:
                    node_data[agent.name] = {}
                node_name = cons["node"]
                if node_name not in node_data[agent.name]:
                    node_data[agent.name][node_name] = {"consumptions": []}
                node_data[agent.name][node_name]["consumptions"].append({
                    "time":
                    cons["time"],
                    "consumption":
                    cons["consumption"]
                })
        else:
            logging.error(
                "Can not retrieve temperature monitoring values from agent '%s' (status code: %d)"
                % (agent.name, r.status_code))
    close_session(db)
    # Remove the switch ports without consumptions or with every consumption equal to 0
    for agent in list(node_data.keys()):
        agent_w_cons = False
        for node in list(node_data[agent].keys()):
            node_w_cons = False
            for cons in node_data[agent][node]["consumptions"]:
                if cons["consumption"] > 0:
                    node_w_cons = True
                    agent_w_cons = True
            if not node_w_cons:
                del node_data[agent][node]
        if not agent_w_cons:
            del node_data[agent]
    return node_data
Exemplo n.º 21
0
def delete(el_type):
    data = flask.request.json
    props = ["name"]
    # Check if all properties belong to the POST data
    missing_data = [
        key_data for key_data in props if key_data not in data.keys()
    ]
    if len(missing_data) == 0:
        if el_type == "node":
            db = open_session()
            existing = db.query(RaspNode).filter(
                RaspNode.name == data["name"]).all()
            for to_del in existing:
                db.delete(to_del)
            close_session(db)
        elif el_type == "switch":
            db = open_session()
            existing = db.query(RaspSwitch).filter(
                RaspSwitch.name == data["name"]).all()
            for to_del in existing:
                db.delete(to_del)
            close_session(db)
        elif el_type == "environment":
            db = open_session()
            existing = db.query(RaspEnvironment).filter_by(
                name=data["name"]).all()
            for to_del in existing:
                db.delete(to_del)
            close_session(db)
        elif el_type == "client":
            # Delete a DHCP client (IP address is in the 'name' attribute)
            delele_dhcp_ip(data["name"])
            existing = [data["name"]]
        else:
            return json.dumps({"type_error": data["type"]})
        return json.dumps({"delete": len(existing)})
    else:
        return json.dumps({"missing": missing_data})
Exemplo n.º 22
0
def get_poe_status(switch_name):
    db = open_session()
    sw = db.query(RaspSwitch).filter(RaspSwitch.name == switch_name).first()
    oid = sw.poe_oid
    cmd = "snmpwalk -v2c -c %s %s %s" % (sw.community, sw.ip,
                                         oid[:oid.rindex(".")])
    close_session(db)
    process = subprocess.run(cmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.DEVNULL,
                             universal_newlines=True)
    power_state = process.stdout.split("\n")
    return [p[-1] for p in power_state if len(p) > 0]
Exemplo n.º 23
0
def ask_release_node(n_name):
    """ Delete the deployment associated to the server """
    db_session = open_session()
    db_user = db_session.query(User).filter_by(email=current_user.id).first()
    # Get the deployment associated to the node
    my_deployment = db_session.query(Deployment).filter_by(
        user_id=db_user.id,
        node_name=n_name).filter(Deployment.state != "destroyed").first()
    if my_deployment is not None:
        my_deployment.process = 'destroy'
        my_deployment.state = select_process('destroy',
                                             my_deployment.environment)[0]
    close_session(db_session)
    return flask.redirect(flask.url_for("app.home"))
Exemplo n.º 24
0
def add_node():
    json_data = flask.request.json
    # Required properties to create Raspberry nodes
    node_props = [str(c).split(".")[1] for c in RaspNode.__table__.columns]
    missing_data = {}
    for prop in node_props:
        if prop not in json_data:
            # Create a missing prop without default values
            missing_data[prop] = []
            if prop == "switch":
                db = open_session()
                switches = db.query(distinct(RaspSwitch.name)).all()
                if len(switches) == 0:
                    missing_data[prop].append("no_values")
                else:
                    for sw in switches:
                        missing_data[prop].append(sw[0])
                close_session(db)
    # Check if all properties belong to the POST data
    if len(missing_data) == 0:
        db = open_session()
        existing = db.query(RaspNode).filter(
            RaspNode.name == json_data["name"]).all()
        for to_del in existing:
            db.delete(to_del)
        new_node = RaspNode()
        new_node.name = json_data["name"]
        new_node.ip = json_data["ip"]
        new_node.switch = json_data["switch"]
        new_node.port_number = json_data["port_number"]
        new_node.model = json_data["model"]
        new_node.serial = json_data["serial"]
        db.add(new_node)
        close_session(db)
        return json.dumps({"node": json_data["name"]})
    else:
        return json.dumps({"missing": missing_data})
Exemplo n.º 25
0
def settings():
    result = {}
    db = open_session()
    user = db.query(User).filter(User.email == current_user.email).first()
    if user is not None:
        status = "User"
        if user.is_admin:
            status = "Admin"
        ssh_key = ""
        if user.ssh_key is not None:
            ssh_key = user.ssh_key
        if os.path.isfile("vpn_keys/%s.conf" %
                          current_user.email.replace("@", "_")):
            result = {
                "email": user.email,
                "ssh_key": ssh_key,
                "status": status,
                "vpn_key": True
            }
        else:
            result = {
                "email": user.email,
                "ssh_key": ssh_key,
                "status": status,
                "vpn_key": False
            }
        # G5k credentials
        if user.g5k_user is not None and len(user.g5k_user) > 0:
            result["g5k_user"] = user.g5k_user
        else:
            result["g5k_user"] = "******"
        if user.g5k_pwd is not None and len(user.g5k_pwd) > 0:
            result["g5k_pwd"] = True
        else:
            result["g5k_pwd"] = False
        # Iot-Lab credentials
        if user.iot_user is not None and len(user.iot_user) > 0:
            result["iot_user"] = user.iot_user
        else:
            result["iot_user"] = "******"
        if user.iot_pwd is not None and len(user.iot_pwd) > 0:
            result["iot_pwd"] = True
        else:
            result["iot_pwd"] = False
    close_session(db)
    return flask.render_template("settings.html",
                                 admin=current_user.is_admin,
                                 active_btn="user_settings",
                                 user=result)
Exemplo n.º 26
0
def user_deployments():
    cluster_desc = copy.deepcopy(get_cluster_desc())
    user = current_user
    misc = {}
    session = open_session()
    db_user = session.query(User).filter_by(email=user.id).first()
    deployments = session.query(Deployment).filter(
        Deployment.state != "destroyed").filter_by(
            user_id=db_user.id).order_by(Deployment.node_name).all()
    deployment_info = {}
    for d in deployments:
        deployed = True
        if d.name not in deployment_info.keys():
            # Deployment state is used to show/hide both the 'destroy' and the 'More info' buttons
            deployment_info[d.name] = {
                "name": d.name,
                "state": d.state,
                "user_id": d.user_id,
                "ids": [],
                "server_names": [],
                "server_infos": []
            }
        deployment_info[d.name]["ids"].append(d.id)
        node_desc = cluster_desc["nodes"][d.node_name]
        deployment_info[d.name]["server_names"].append(node_desc["name"])
        if d.environment is not None:
            if d.start_date is not None:
                s_date = datetime.datetime.strptime(str(d.start_date),
                                                    '%Y-%m-%d %H:%M:%S')
                node_desc['starts_at'] = s_date.strftime("%d %b. at %H:%M")
            if d.state == 'lost':
                node_desc['last_state'] = d.temp_info
            env_desc = cluster_desc["environments"][d.environment]
            web_interface = False
            if 'web' in env_desc:
                web_interface = env_desc['web']
            node_desc['number'] = int(node_desc["name"].split('-')[1])
            node_desc['env'] = d.environment
            node_desc['state'] = d.state
            if d.state.endswith('_check'):
                node_desc["progress"] = d.temp_info
            else:
                node_desc["progress"] = 100
            node_desc['password'] = d.system_pwd
            node_desc['web'] = web_interface
            node_desc['desc'] = env_desc['desc']
            deployment_info[d.name]["server_infos"].append(node_desc)
    close_session(session)
    return {"deployments": list(deployment_info.values())}
Exemplo n.º 27
0
def confirm_email(token):
    logger = logging.getLogger("LOGIN")
    logger.info("Receive the token '%s' to confirm email" % token)
    db_session = open_session()
    user_candidate = db_session.query(User).filter(User.email_confirmation_token == token).first()
    url = "Bad request: could not find the given token '%s'" % (token)
    if user_candidate is not None:
        user_candidate.email_confirmed = True
        if get_cluster_desc()['email_signup']:
            user_candidate.user_authorized = True
            url = flask.redirect(flask.url_for("login.confirmation_authorized_account"))
        else:
            url = flask.redirect(flask.url_for("login.confirmation_email"))
    close_session(db_session)
    return url
Exemplo n.º 28
0
def user_pwd():
    msg = ""
    form_data = flask.request.form
    db = open_session()
    user = db.query(User).filter(User.email == current_user.email).first()
    if "password" in form_data and "confirm_password" in form_data:
        if form_data["password"] == form_data["confirm_password"]:
            user.password = generate_password_hash(form_data["password"],
                                                   method="sha256")
            msg = "Credentials updated!"
        else:
            msg = "The two passwords are different. Credentials unchanged!"
    else:
        msg = "Missing data in the request. Credentials unchanged!"
    close_session(db)
    return flask.redirect("/user/settings?msg=" + msg)
Exemplo n.º 29
0
def user_loader(user_email):
    db_session = open_session()
    db_user = db_session.query(dbUser).filter(
        dbUser.email == user_email).first()
    ret_val = None
    if db_user is not None and db_user.user_authorized:
        user = User()
        user.id = db_user.email
        user.firstname = db_user.firstname
        user.lastname = db_user.lastname
        user.ssh_key = db_user.ssh_key
        user.is_admin = db_user.is_admin
        user.user_authorized = db_user.user_authorized
        ret_val = user
    close_session(db_session)
    return ret_val
Exemplo n.º 30
0
def register_environment(arg_dict):
    db = open_session()
    node = db.query(Schedule
            ).filter(Schedule.node_name == arg_dict["node_name"]
            ).filter(Schedule.owner == arg_dict["user"]
            ).first()
    if node is None:
        close_session(db)
        msg = "No reservation for the node '%s'" % arg_dict["node_name"]
        logging.error("[%s] %s" % (arg_dict["node_name"], msg))
        return json.dumps({ "error": msg })
    # Check the image file does not exist yet
    file_name = os.path.basename(arg_dict["img_path"])
    env_path = get_config()["env_path"]
    if os.path.exists("%s%s" % (env_path, file_name)):
        msg = "The image file '%s' already exists in the server. Please, rename this file." % file_name
        logging.error("[%s] %s" % (arg_dict["node_name"], msg))
        return json.dumps({ "error": msg })
    node_action = db.query(Action).filter(Action.node_name == node.node_name).first()
    if node_action is not None:
        db.delete(node_action)
    # The deployment is completed, add a new action
    node_action = new_action(node, db)
    # The deployment is completed, add a new action
    init_action_process(node_action, "reg_env")
    db.add(node_action)
    # Delete old values
    old_props = db.query(ActionProperty
        ).filter(ActionProperty.node_name == node.node_name
        ).filter(ActionProperty.prop_name.in_(["img_path", "env_name" ])
        ).all()
    for p in old_props:
        db.delete(p)
    act_prop = ActionProperty()
    act_prop.node_name = node.node_name
    act_prop.prop_name = "img_path"
    act_prop.prop_value = arg_dict["img_path"]
    act_prop.owner = node.owner
    db.add(act_prop)
    act_prop = ActionProperty()
    act_prop.node_name = node.node_name
    act_prop.prop_name = "env_name"
    act_prop.prop_value = arg_dict["env_name"]
    act_prop.owner = node.owner
    db.add(act_prop)
    close_session(db)
    return json.dumps({ "success": "environment is registering" })