Skip to content

Commit

Permalink
Merge pull request #387 from stakwork/handle-image-version
Browse files Browse the repository at this point in the history
Handle image version
  • Loading branch information
Evanfeenstra authored Nov 11, 2024
2 parents 667078a + ff31277 commit 84ecf06
Show file tree
Hide file tree
Showing 13 changed files with 308 additions and 122 deletions.
19 changes: 8 additions & 11 deletions app/src/Dashboard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,17 @@
import type { Node, Stack } from "./nodes";
import User from "carbon-icons-svelte/lib/User.svelte";
import ChangePassword from "./auth/ChangePassword.svelte";
import { get_signedin_user_details, type Container } from "./api/swarm";
import {
get_all_image_actual_version,
get_signedin_user_details,
type Container,
} from "./api/swarm";
import { getImageVersion } from "./helpers/swarm";
import RestartNode from "./nodes/RestartNode.svelte";
let selectedName = "";
async function getNodeVersion(nodes: Node[]) {
//loop throug nodes
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
// if node version is latest get digest
if (node.version === "latest") {
await getImageVersion(node.name, stack, selectedNode);
}
}
async function getNodeVersion() {
await getImageVersion(stack, selectedNode);
}
async function pollConfig() {
Expand All @@ -55,7 +52,7 @@
if (stackRemote.nodes !== $stack.nodes) {
stack.set(stackRemote);
// get node version
getNodeVersion(stackRemote.nodes);
getNodeVersion();
}
return stackRemote.ready;
}
Expand Down
4 changes: 3 additions & 1 deletion app/src/api/cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ export type Cmd =
| "RestartChildSwarmContainers"
| "GetSignedInUserDetails"
| "UpdateAwsInstanceType"
| "GetInstanceType";
| "GetInstanceType"
| "GetAllImageActualVersion"
| "GetSwarmChildImageVersions";

interface CmdData {
cmd: Cmd;
Expand Down
11 changes: 11 additions & 0 deletions app/src/api/swarm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,17 @@ export async function delete_swarm(data: { host: string }) {
return await swarmCmd("DeleteSwarm", { ...data });
}

export async function get_all_image_actual_version() {
return await swarmCmd("GetAllImageActualVersion");
}
export async function get_child_swarm_image_versions({
host,
}: {
host: string;
}) {
return await swarmCmd("GetSwarmChildImageVersions", { host });
}

export async function login(username, password) {
const r = await fetch(`${root}/login`, {
method: "POST",
Expand Down
128 changes: 24 additions & 104 deletions app/src/helpers/swarm.ts
Original file line number Diff line number Diff line change
@@ -1,117 +1,37 @@
import type { Writable } from "svelte/store";
import { get_image_tags } from "../api/swarm";
import { get_all_image_actual_version, get_image_tags } from "../api/swarm";
import type { Stack, Node } from "../nodes";
import { swarm } from "../api";

export async function getVersionFromDigest(
digest: string,
org_image_name: string,
page: string,
page_size: string
) {
try {
const splittedDigest = digest.split("@")[1];
const response = await get_image_tags(org_image_name, page, page_size);

const tags = JSON.parse(response);

for (let i = 0; i < tags.results.length; i++) {
const result = tags.results[i];
if (result.digest === splittedDigest) {
if (result.name !== "latest") {
return result.name;
} else {
const architectureDigests = [];
for (let j = 0; j < result.images.length; j++) {
architectureDigests.push(result.images[j].digest);
}
return findArchitectureDigest(architectureDigests, tags.results);
}
}
}

if (tags.next) {
const urlString = tags.next;
const url = new URL(urlString);
const params = new URLSearchParams(url.search);

const page = params.get("page");
const page_size = params.get("page_size");

return await getVersionFromDigest(
digest,
org_image_name,
page,
page_size
);
}
} catch (error) {
throw error;
}
}

function findArchitectureDigest(architectureDigests, results) {
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.name !== "latest") {
for (let j = 0; j < result.images.length; j++) {
const image = result.images[j];
if (architectureDigests.includes(image.digest)) {
return result.name;
}
}
}
}
}

export async function getImageVersion(
node_name: string,
stack: Writable<Stack>,
selectedNode: Writable<Node>
) {
let image_name = `sphinx-${node_name}`;
if (node_name === "relay") {
image_name = `sphinx-relay-swarm`;
} else if (node_name === "cln") {
image_name = `cln-sphinx`;
} else if (node_name === "navfiber") {
image_name = `sphinx-nav-fiber`;
} else if (node_name === "cache") {
image_name = ``;
} else if (node_name === "jarvis") {
image_name = `sphinx-jarvis-backend`;
}
const image_digest_response = await swarm.get_image_digest(
`sphinxlightning/${image_name}`
);
if (image_digest_response.success) {
const version = await getVersionFromDigest(
image_digest_response.digest,
`sphinxlightning/${image_name}`,
"1",
"100"
);
const image_versions = await get_all_image_actual_version();
console.log(image_versions);
if (image_versions.success) {
let version_object = {};

for (let i = 0; i < image_versions.data.length; i++) {
const image_version = image_versions.data[i];
version_object[image_version.name] = image_version.version;
}

if (version) {
stack.update((stack) => {
for (let i = 0; i < stack.nodes.length; i++) {
const oldNode = { ...stack.nodes[i] };
if (oldNode.name === node_name) {
const newNode = {
...oldNode,
version,
};
stack.update((stack) => {
for (let i = 0; i < stack.nodes.length; i++) {
const newNode = {
...stack.nodes[i],
version: version_object[stack.nodes[i].name],
};

selectedNode.update((node) =>
node && node.name === newNode.name ? { ...newNode } : node
);
selectedNode.update((node) =>
node && node.name === newNode.name ? { ...newNode } : node
);

stack.nodes[i] = { ...newNode };
break;
}
}
return stack;
});
}
stack.nodes[i] = { ...newNode };
}

return stack;
});
}
}
2 changes: 1 addition & 1 deletion app/src/nodes/NodeUpdate.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
if (!name) return;
updating = true;
await api.swarm.update_node(name);
await getImageVersion(name, stack, selectedNode);
await getImageVersion(stack, selectedNode);
updating = false;
}
</script>
Expand Down
2 changes: 1 addition & 1 deletion app/src/nodes/RestartNode.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
console.log("restart!", name);
restarting = true;
await api.swarm.restart_node(name);
await getImageVersion(name, stack, selectedNode);
await getImageVersion(stack, selectedNode);
restarting = false;
}
</script>
Expand Down
1 change: 1 addition & 0 deletions src/bin/super/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub enum SwarmCmd {
GetAwsInstanceTypes,
UpdateAwsInstanceType(UpdateInstanceDetails),
GetInstanceType(GetInstanceTypeByInstanceId),
GetSwarmChildImageVersions(ChildSwarmIdentifier),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down
27 changes: 25 additions & 2 deletions src/bin/super/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use state::RemoteStack;
use state::Super;
use util::{
accessing_child_container_controller, add_new_swarm_details, add_new_swarm_from_child_swarm,
get_aws_instance_types, get_child_swarm_config, get_child_swarm_containers, get_config,
get_swarm_instance_type, update_aws_instance_type,
get_aws_instance_types, get_child_swarm_config, get_child_swarm_containers,
get_child_swarm_image_versions, get_config, get_swarm_instance_type, update_aws_instance_type,
};

use crate::checker::swarm_checker;
Expand Down Expand Up @@ -373,6 +373,29 @@ pub async fn super_handle(
}
Some(serde_json::to_string(&res)?)
}
SwarmCmd::GetSwarmChildImageVersions(info) => {
let res: SuperSwarmResponse;
match state.find_swarm_by_host(&info.host) {
Some(swarm) => match get_child_swarm_image_versions(&swarm).await {
Ok(result) => res = result,
Err(err) => {
res = SuperSwarmResponse {
success: false,
message: err.to_string(),
data: None,
}
}
},
None => {
res = SuperSwarmResponse {
success: false,
message: "Swarm does not exist".to_string(),
data: None,
}
}
}
Some(serde_json::to_string(&res)?)
}
},
};

Expand Down
40 changes: 39 additions & 1 deletion src/bin/super/superapp/src/ViewNodes.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
get_aws_instance_types,
update_aws_instance_type,
get_swarm_instance_type,
get_child_swarm_image_versions,
} from "../../../../../app/src/api/swarm";
import {
Button,
Expand Down Expand Up @@ -167,6 +168,8 @@
await getAwsInstanceType();
await get_current_service_details();
await get_image_versions();
});
function findContainer(node_name: string) {
Expand All @@ -178,6 +181,41 @@
}
}
async function get_image_versions() {
try {
const response = await get_child_swarm_image_versions({
host: $selectedNode,
});
if (response.success === true) {
const version_object = {};
for (let i = 0; i < response.data.data.length; i++) {
version_object[response.data.data[i].name] =
response.data.data[i].version;
}
let tempSortedNodes = [];
for (let i = 0; i < sortedNodes.length; i++) {
const node = sortedNodes[i];
tempSortedNodes.push({
...node,
...(node.version === "latest" && {
version: version_object[node.name.toLowerCase()],
}),
});
}
sortedNodes = [...tempSortedNodes];
}
} catch (error) {
console.log(error);
console.log(
`Error getting ${$selectedNode} image version: ${JSON.stringify}`
);
}
}
function sortNodes() {
const tempSortedNodes = [];
for (let i = 0; i < nodes.length; i++) {
Expand Down Expand Up @@ -373,7 +411,7 @@
headers={[
{ key: "sn", value: "S/N" },
{ key: "name", value: "Name" },
// { key: "version", value: "Version" },
{ key: "version", value: "Version" },
{ key: "update", value: "Update" },
{ key: "stop", value: "Stop/Start" },
{ key: "restart", value: "Restart" },
Expand Down
23 changes: 23 additions & 0 deletions src/bin/super/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,29 @@ pub async fn get_child_swarm_containers(
})
}

pub async fn get_child_swarm_image_versions(
swarm_details: &RemoteStack,
) -> Result<SuperSwarmResponse, Error> {
let token = login_to_child_swarm(swarm_details).await?;
let cmd = Cmd::Swarm(SwarmCmd::GetAllImageActualVersion);
let res = swarm_cmd(cmd, swarm_details.default_host.clone(), &token).await?;

if res.status().clone() != 200 {
return Err(anyhow!(format!(
"{} status code gotten from get child swarm container",
res.status()
)));
}

let image_version: Value = res.json().await?;

Ok(SuperSwarmResponse {
success: true,
message: "child swarm image versions successfully retrieved".to_string(),
data: Some(image_version),
})
}

pub async fn access_child_swarm_containers(
swarm_details: &RemoteStack,
nodes: Vec<String>,
Expand Down
1 change: 1 addition & 0 deletions src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ pub enum SwarmCmd {
GetApiToken,
SetGlobalMemLimit(u64),
GetSignedInUserDetails,
GetAllImageActualVersion,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down
Loading

0 comments on commit 84ecf06

Please sign in to comment.