Skip to content

Commit

Permalink
Fixed magic commands
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonioSanch3z committed Aug 30, 2024
1 parent dac8559 commit e84f8fa
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 46 deletions.
40 changes: 9 additions & 31 deletions apricot_magics/apricot_magics.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from tabulate import tabulate
from IPython.core.magic import Magics, line_magic, line_cell_magic, magics_class
from subprocess import run, PIPE, CalledProcessError, check_output
from subprocess import run, PIPE, CalledProcessError

import os
import json
Expand All @@ -10,26 +10,12 @@ class Apricot_Magics(Magics):

def __init__(self, shell):
super().__init__(shell)
self.im_client_path = None
self.IM_CLIENT_PATH = os.getenv("IM_CLIENT_PATH")

########################
# Auxiliar functions #
########################

def find_im_client_path(self) -> str:
try:
im_client_path = check_output(['which', 'im_client.py'], text=True).strip()
if not im_client_path:
raise FileNotFoundError("im_client.py not found in the system PATH.")
return im_client_path
except CalledProcessError:
raise FileNotFoundError("Failed to find im_client.py in the system PATH.")

def get_im_client_path(self) -> str:
if self.im_client_path is None:
self.find_im_client_path()
return self.im_client_path

def create_auth_pipe(self, infrastructure_id):
# Get the absolute path to the infrastructuresList.json file
base_dir = os.path.dirname(__file__)
Expand Down Expand Up @@ -139,8 +125,6 @@ def apricot_log(self, line):
if len(line) == 0:
print("Usage: apricot_log infrastructure-id\n")
return "Fail"

im_client_path = self.get_im_client_path()

# Split the input line to extract the infrastructure ID
inf_id = line.split()[0]
Expand All @@ -155,7 +139,7 @@ def apricot_log(self, line):
# Construct the command to retrieve log messages
cmd_getcontmsg = [
"python3",
im_client_path,
self.IM_CLIENT_PATH,
"getcontmsg",
inf_id,
"-a",
Expand All @@ -182,8 +166,7 @@ def apricot_log(self, line):
@line_magic
def apricot_ls(self, line):
infrastructures_list = []
im_client_path = self.get_im_client_path()


base_dir = os.path.dirname(__file__)
file_path = os.path.abspath(os.path.join(base_dir, '..', 'infrastructuresList.json'))

Expand Down Expand Up @@ -211,7 +194,7 @@ def apricot_ls(self, line):

cmd_getstate = [
'python3',
im_client_path,
self.IM_CLIENT_PATH,
'getstate',
infrastructure_info['InfrastructureID'],
'-r',
Expand All @@ -238,7 +221,7 @@ def apricot_ls(self, line):

cmd_getvminfo = [
'python3',
im_client_path,
self.IM_CLIENT_PATH,
'getvminfo',
infrastructure_info['InfrastructureID'],
'0',
Expand Down Expand Up @@ -281,8 +264,6 @@ def apricot_info(self, line):
print("Usage: apricot_info infrastructure-id\n")
return "Fail"

im_client_path = self.get_im_client_path()

# Split the input line to extract the infrastructure ID
inf_id = line.split()[0]

Expand All @@ -296,7 +277,7 @@ def apricot_info(self, line):
# Construct the command to retrieve log messages
cmd_getinfo = [
"python3",
im_client_path,
self.IM_CLIENT_PATH,
"getinfo",
inf_id,
"-a",
Expand Down Expand Up @@ -326,8 +307,6 @@ def apricot_vmls(self, line):
print("Usage: apricot_vmls infrastructure-id\n")
return "Fail"

im_client_path = self.get_im_client_path()

# Split the input line to extract the infrastructure ID
inf_id = line.split()[0]

Expand All @@ -341,7 +320,7 @@ def apricot_vmls(self, line):

cmd_getinfo = [
'python3',
im_client_path,
self.IM_CLIENT_PATH,
'getinfo',
inf_id,
'-r',
Expand Down Expand Up @@ -575,7 +554,6 @@ def apricot(self, code, cell=None):
print("Usage: destroy infrastructure-id")
return "Fail"
else:
im_client_path = self.get_im_client_path()
inf_id = words[1]

try:
Expand All @@ -586,7 +564,7 @@ def apricot(self, code, cell=None):

cmd_destroy = [
'python3',
im_client_path,
self.IM_CLIENT_PATH,
'destroy',
inf_id,
'-r',
Expand Down
39 changes: 24 additions & 15 deletions src/deploymentMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@ interface IDeployInfo {
[key: string]: number | string;
};
childs: string[];
}
};

interface ITemplateInput {
type: string;
description: string;
default: any;
value?: any;
}
};

interface IInfrastructureData {
IMuser: string;
Expand All @@ -75,7 +75,7 @@ interface IInfrastructureData {
domain: string;
vo: string;
EGIToken: string;
}
};

const deployInfo: IDeployInfo = {
IMuser: '',
Expand Down Expand Up @@ -108,6 +108,8 @@ let imageOptions: { uri: string; name: string }[] = [];

let deploying = false; // Flag to prevent multiple deployments at the same time

let imClientPath: string | undefined = undefined;

//*****************//
//* Aux functions *//
//*****************//
Expand All @@ -133,7 +135,7 @@ async function openDeploymentDialog(): Promise<void> {
// Logic to handle form submission
console.log('Form submitted');
});
}
};

const createDialogButtons = (
dialogBody: HTMLElement,
Expand Down Expand Up @@ -194,15 +196,15 @@ const addFormInput = (
function getInputValue(inputId: string): string {
const input = document.getElementById(inputId) as HTMLInputElement;
return input.value;
}
};

async function computeHash(input: string): Promise<string> {
const msgUint8 = new TextEncoder().encode(input);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
};

async function generateIMCredentials(): Promise<void> {
const randomInput = `${Date.now()}-${Math.random()}`;
Expand All @@ -212,7 +214,7 @@ async function generateIMCredentials(): Promise<void> {
const pass = hash.substring(16, 32);
deployInfo.IMuser = user;
deployInfo.IMpass = pass;
}
};

async function createImagesDropdown(
output: string | undefined,
Expand Down Expand Up @@ -262,7 +264,7 @@ async function createImagesDropdown(
} catch (error) {
console.error('Error getting OS images:', error);
}
}
};

async function mergeTOSCARecipes(
parsedConstantTemplate: any,
Expand Down Expand Up @@ -341,7 +343,7 @@ async function mergeTOSCARecipes(
console.error('Error merging TOSCA recipes:', error);
return JSON.parse(JSON.stringify(parsedConstantTemplate)); // Return a copy of the parsed constant template
}
}
};

async function createChildsForm(
app: string,
Expand Down Expand Up @@ -435,15 +437,14 @@ async function createChildsForm(
nodeTemplates,
outputs
};
}
};

//*********************//
//* Bash commands *//
//*********************//

async function selectImage(obj: IDeployInfo): Promise<string> {
const pipeAuth = `${obj.infName}-auth-pipe`;
const imClientPath = await getIMClientPath();

let cmd = `%%bash
PWD=$(pwd)
Expand Down Expand Up @@ -484,7 +485,7 @@ async function selectImage(obj: IDeployInfo): Promise<string> {

console.log('cmd', cmd);
return cmd;
}
};

const getEGIToken = async () => {
const code = `%%bash
Expand Down Expand Up @@ -554,7 +555,7 @@ async function deployIMCommand(

console.log('cmd', cmd);
return cmd;
}
};

async function saveToInfrastructureList(obj: IInfrastructureData) {
const filePath = path.resolve(__dirname, '..', 'infrastructuresList.json');
Expand All @@ -570,7 +571,7 @@ async function saveToInfrastructureList(obj: IInfrastructureData) {

console.log('Bash command:', cmd);
return cmd;
}
};

//****************//
//* Deployment *//
Expand All @@ -584,6 +585,14 @@ generateIMCredentials().then(() => {
);
});

getIMClientPath().then(path => {
process.env.IM_CLIENT_PATH = path;
imClientPath = path;
console.log('IM Client Path:', imClientPath);
}).catch(error => {
console.error('Error getting IM Client Path:', error);
});

const deployChooseProvider = (dialogBody: HTMLElement): void => {
// Clear dialog body
dialogBody.innerHTML = '';
Expand Down Expand Up @@ -1135,7 +1144,7 @@ async function deployFinalRecipe(
console.error('Error during deployment:', error);
deploying = false;
}
}
};

const handleFinalDeployOutput = async (
output: string | undefined,
Expand Down

0 comments on commit e84f8fa

Please sign in to comment.