Commit 4fda9a30 authored by duanjinfei's avatar duanjinfei

system info contract

parents
File added
node_modules
.env
coverage
coverage.json
typechain
typechain-types
#Hardhat files
cache
artifacts
node_modules
.env
coverage
coverage.json
typechain
typechain-types
#Hardhat files
cache
artifacts
# Sample Hardhat Project
This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a script that deploys that contract.
Try running some of the following tasks:
```shell
npx hardhat help
npx hardhat test
REPORT_GAS=true npx hardhat test
npx hardhat node
npx hardhat run scripts/deploy.js
```
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./interface/ICloudConstant.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Admin is Ownable {
mapping(address => bool) private _admins;
modifier onlyAdmin() {
require(_admins[msg.sender], "Only admin can call it");
_;
}
function addAdmin(address _admin) public onlyOwner {
_admins[_admin] = true;
}
function delAdmin(address _admin) public onlyOwner {
_admins[_admin] = false;
}
function isAdmin(address _addr) public view returns (bool) {
return _admins[_addr];
}
}
contract AuthVerify is Admin {
mapping(string => address) authVerify;
function addCaller(
string[] memory keys,
address[] memory caller
) external onlyOwner {
for (uint i = 0; i < keys.length; i++) {
authVerify[keys[i]] = caller[i];
}
}
function getCaller(string memory key) external view returns (address) {
return authVerify[key];
}
function onlyCaller(
string memory key,
address caller
) external view returns (bool) {
return caller == authVerify[key];
}
}
contract Callee is Admin {
ICloudConstant public _const;
constructor(address const) {
_const = ICloudConstant(const);
}
function setConstant(address const) external onlyOwner {
_const = ICloudConstant(const);
}
modifier onlyCaller(string memory caller) {
require(
_const.onlyCaller(caller, msg.sender),
"The caller does not have permission"
);
_;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
contract CloudConstant is AuthVerify {
uint8 constant enable = 1;
uint8 constant disable = 2;
uint8 constant reboot = 3;
uint8 constant del = 4;
mapping(string => uint8) constMap;
function setConstMap(string memory key, uint8 value) external onlyOwner {
require(constMap[key] == 0 && value > 0, "");
constMap[key] = value;
}
// Common Key
function CREATING() external view returns (uint8) {
return constMap["creating"];
}
function CREATED() external view returns (uint8) {
return constMap["created"];
}
function USER() external view returns (uint8) {
return constMap["user"];
}
function PASSWORD() external view returns (uint8) {
return constMap["password"];
}
function CLUSTER() external view returns (uint8) {
return constMap["cluster"];
}
function GLOBAL_ID() external view returns (uint8) {
return constMap["global_id"];
}
function HOST() external view returns (uint8) {
return constMap["host"];
}
function NAME() external view returns (uint8) {
return constMap["name"];
}
function STAGE() external view returns (uint8) {
return constMap["stage"];
}
function PROGRESS() external view returns (uint8) {
return constMap["progress"];
}
function IS_EXISTS() external view returns (uint8) {
return constMap["is_exists"];
}
// VM NET INFO KEY
function EXTERNAL_IP() external view returns (uint8) {
return constMap["external_ip"];
}
function INTERNAL_IP() external view returns (uint8) {
return constMap["internal_ip"];
}
function EX_SSH_PORT() external view returns (uint8) {
return constMap["external_ssh_port"];
}
function EX_VNC_PORT() external view returns (uint8) {
return constMap["external_vnc_port"];
}
function IN_VNC_PORT() external view returns (uint8) {
return constMap["internal_vnc_port"];
}
function IN_SSH_PORT() external view returns (uint8) {
return constMap["internal_ssh_port"];
}
// VM CONFIG INFO KEY
function STATUS() external view returns (uint8) {
return constMap["status"];
}
function MEM_NUM() external view returns (uint8) {
return constMap["memory"];
}
function CPU_LOGIC_UINTS() external view returns (uint8) {
return constMap["cpu_logic_units"];
}
function CPU_NUM() external view returns (uint8) {
return constMap["cpu_num"];
}
function CPU_MODEL() external view returns (uint8) {
return constMap["cpu_model"];
}
function CPU_CORES() external view returns (uint8) {
return constMap["cpu_cores"];
}
function GPU_MODEL() external view returns (uint8) {
return constMap["gpu_model"];
}
function GPU_NUM() external view returns (uint8) {
return constMap["gpu_num"];
}
function DISK() external view returns (uint8) {
return constMap["disk"];
}
function OS() external view returns (uint8) {
return constMap["os"];
}
function BIND_WIDTH() external view returns (uint8) {
return constMap["bind_width"];
}
// Gateway Config Info Key
function NPS_VNC_END_PORT() external view returns (uint8) {
return constMap["nps_vnc_end_port"];
}
function NPS_VNC_START_PORT() external view returns (uint8) {
return constMap["nps_vnc_start_port"];
}
function NPS_SSH_END_PORT() external view returns (uint8) {
return constMap["nps_ssh_end_port"];
}
function NPS_SSH_START_PORT() external view returns (uint8) {
return constMap["nps_ssh_start_port"];
}
function SINGALLING_PORT() external view returns (uint8) {
return constMap["signalling_port"];
}
function TURN_PORT() external view returns (uint8) {
return constMap["turn_port"];
}
function STUN_PORT() external view returns (uint8) {
return constMap["stun_port"];
}
function VERSION() external view returns (uint8) {
return constMap["version"];
}
function SUPPORT_TYPE() external view returns (uint8) {
return constMap["support_type"];
}
function ENABLE() external pure returns (uint8) {
return enable;
}
function DISABLE() external pure returns (uint8) {
return disable;
}
function RE_BOOT() external pure returns (uint8) {
return reboot;
}
function DELETE() external pure returns (uint8) {
return del;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
contract CloudGateway is Callee {
constructor(address const) Callee(const) {}
uint256 public gatewayCount = 0;
address[] public gatewayMsgSenders;
mapping(address => mapping(uint256 => string)) public gatewayData;
event AddGateWayEvent(
address owner,
string externalIp,
string stunPort,
string turnPort,
string npsSshStartPort,
string npsSshEndPort,
string npsVncStartPort,
string npsVncEndPort,
string signallingPort
);
function addGateway(
string memory externalIp,
string memory stunPort,
string memory turnPort,
string memory npsSshStartPort,
string memory npsSshEndPort,
string memory npsVncStartPort,
string memory npsVncEndPort,
string memory signallingPort
) external {
gatewayMsgSenders.push(msg.sender);
gatewayData[msg.sender][_const.EXTERNAL_IP()] = externalIp;
gatewayData[msg.sender][_const.STUN_PORT()] = stunPort;
gatewayData[msg.sender][_const.TURN_PORT()] = turnPort;
gatewayData[msg.sender][_const.NPS_SSH_START_PORT()] = npsSshStartPort;
gatewayData[msg.sender][_const.NPS_SSH_END_PORT()] = npsSshEndPort;
gatewayData[msg.sender][_const.NPS_VNC_START_PORT()] = npsVncStartPort;
gatewayData[msg.sender][_const.NPS_VNC_END_PORT()] = npsVncEndPort;
gatewayData[msg.sender][_const.SINGALLING_PORT()] = signallingPort;
gatewayCount++;
emit AddGateWayEvent(
msg.sender,
externalIp,
stunPort,
turnPort,
npsSshStartPort,
npsSshEndPort,
npsVncStartPort,
npsVncEndPort,
signallingPort
);
}
function getGateWay(
address acc
)
external
view
returns (
string memory ip,
string memory stunPort,
string memory turnPort,
string memory npsSshStartPort,
string memory npsSshEndPort,
string memory npsVncStratPort,
string memory npsVncEndPort,
string memory signallingPort
)
{
ip = gatewayData[acc][_const.EXTERNAL_IP()];
stunPort = gatewayData[acc][_const.STUN_PORT()];
turnPort = gatewayData[acc][_const.TURN_PORT()];
npsSshStartPort = gatewayData[acc][_const.NPS_SSH_START_PORT()];
npsSshEndPort = gatewayData[acc][_const.NPS_SSH_END_PORT()];
npsVncStratPort = gatewayData[acc][_const.NPS_VNC_START_PORT()];
npsVncEndPort = gatewayData[acc][_const.NPS_VNC_END_PORT()];
signallingPort = gatewayData[acc][_const.SINGALLING_PORT()];
}
// function getGateways()
// external
// view
// returns (
// string[] memory ipArr,
// string[] memory stunPortArr,
// string[] memory turnPortArr,
// string[] memory npsSshStartPortArr,
// string[] memory npsSshEndPortArr,
// string[] memory npsVncStartPortArr,
// string[] memory npsVncEndPortArr,
// string[] memory signallingPortArr
// )
// {
// uint256 length = gatewayMsgSenders.length;
// ipArr = new string[](length);
// stunPortArr = new string[](length);
// turnPortArr = new string[](length);
// npsSshStartPortArr = new string[](length);
// npsSshEndPortArr = new string[](length);
// npsVncStartPortArr = new string[](length);
// npsVncEndPortArr = new string[](length);
// signallingPortArr = new string[](length);
// uint8 externalIpConst = _const.EXTERNAL_IP();
// uint8 stunPortConst = _const.STUN_PORT();
// uint8 turnPortConst = _const.TURN_PORT();
// uint8 npsSshStartPortConst = _const.NPS_SSH_START_PORT();
// uint8 npsSshEndPortConst = _const.NPS_SSH_END_PORT();
// uint8 npsVncStartPortConst = _const.NPS_VNC_START_PORT();
// uint8 npsVncEndPortConst = _const.NPS_VNC_END_PORT();
// uint8 signallingPortConst = _const.SINGALLING_PORT();
// for (uint8 i = 0; i < length; i++) {
// ipArr[i] = gatewayData[gatewayMsgSenders[i]][externalIpConst];
// ipArr[i] = gatewayData[gatewayMsgSenders[i]][stunPortConst];
// stunPortArr[i] = gatewayData[gatewayMsgSenders[i]][turnPortConst];
// turnPortArr[i] = gatewayData[gatewayMsgSenders[i]][
// npsSshStartPortConst
// ];
// npsSshStartPortArr[i] = gatewayData[gatewayMsgSenders[i]][
// npsSshEndPortConst
// ];
// npsSshEndPortArr[i] = gatewayData[gatewayMsgSenders[i]][
// npsVncStartPortConst
// ];
// npsVncStartPortArr[i] = gatewayData[gatewayMsgSenders[i]][
// npsVncEndPortConst
// ];
// npsVncEndPortArr[i] = gatewayData[gatewayMsgSenders[i]][
// signallingPortConst
// ];
// signallingPortArr[i] = gatewayData[gatewayMsgSenders[i]][
// signallingPortConst
// ];
// }
// }
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
contract CloudHost is Callee {
constructor(address const) Callee(const) {}
uint256 IdIncrement = 0;
mapping(uint256 => mapping(uint256 => string)) public hostData;
mapping(uint256 => address) public globalIdMap;
event AddCreateVmEvent(string ip, string vmId);
event UpdateHostResourceInfoEvent(
uint256 hostId,
string free_cpu,
string free_gpu,
string free_memory,
string free_disk,
string used_cpu,
string used_gpu,
string used_memory,
string used_disk
);
event AddHostEvent(uint256 hostId, address global_identify);
function addHost(
address global_identify,
string memory host_name,
string memory cluster_id
) public returns (uint256, address) {
IdIncrement++;
hostData[IdIncrement][_const.NAME()] = host_name;
hostData[IdIncrement][_const.CLUSTER()] = cluster_id;
globalIdMap[IdIncrement] = global_identify;
emit AddHostEvent(IdIncrement, global_identify);
return (IdIncrement, global_identify);
}
function addHostResouce(
uint256 id,
string memory cpu_num,
string memory cpuLogicUints,
string memory memoryNum,
string memory disk,
string memory gpuNum,
string memory cpu_model,
string memory gpu_model,
string memory cpu_cores
) external {
require(id <= IdIncrement, "");
hostData[id][_const.CPU_LOGIC_UINTS()] = cpuLogicUints;
hostData[id][_const.CPU_MODEL()] = cpu_cores;
hostData[id][_const.CPU_NUM()] = cpu_num;
hostData[id][_const.MEM_NUM()] = memoryNum;
hostData[id][_const.GPU_NUM()] = gpuNum;
hostData[id][_const.DISK()] = disk;
hostData[id][_const.CPU_MODEL()] = cpu_model;
hostData[id][_const.GPU_MODEL()] = gpu_model;
}
function addHostNetwork(
uint256 id,
string memory intranet_ip,
string memory external_ip,
string memory bind_width,
string memory ex_ssh_endpoint,
string memory in_ssh_endpoint
) external {
require(id <= IdIncrement, "");
hostData[IdIncrement][_const.INTERNAL_IP()] = intranet_ip;
hostData[IdIncrement][_const.EXTERNAL_IP()] = external_ip;
hostData[IdIncrement][_const.BIND_WIDTH()] = bind_width;
hostData[IdIncrement][_const.EX_SSH_PORT()] = ex_ssh_endpoint;
hostData[IdIncrement][_const.IN_SSH_PORT()] = in_ssh_endpoint;
}
function getHosts(
uint256 start,
uint256 count
)
external
view
returns (
string[] memory hostNameArr,
string[] memory internalIpArr,
string[] memory externalIpArr
)
{
require(start + count <= IdIncrement, "please input ");
hostNameArr = new string[](count);
internalIpArr = new string[](count);
externalIpArr = new string[](count);
uint8 nameConst = _const.NAME();
uint8 externalIpConst = _const.EXTERNAL_IP();
uint8 internalIpConst = _const.INTERNAL_IP();
for (uint256 i = start; i < start + count; i++) {
uint256 j = 0;
hostNameArr[j] = hostData[i][nameConst];
externalIpArr[j] = hostData[i][externalIpConst];
internalIpArr[j] = hostData[i][internalIpConst];
j++;
}
}
function updateResourceInfo(
uint256 hostId,
string memory free_cpu,
string memory free_gpu,
string memory free_memory,
string memory free_disk,
string memory used_cpu,
string memory used_gpu,
string memory used_memory,
string memory used_disk
) external {
emit UpdateHostResourceInfoEvent(
hostId,
free_cpu,
free_gpu,
free_memory,
free_disk,
used_cpu,
used_gpu,
used_memory,
used_disk
);
}
function addCreateVmEvent(string memory ip, string memory vmId) external {
emit AddCreateVmEvent(ip, vmId);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
contract CloudScheduler is Callee {
constructor(address const) Callee(const) {}
address[] public schedulerMsgSenders;
mapping(address => mapping(uint256 => string)) public schedulerData;
mapping(address => bool) public schedulerDataIsExist;
event AddSchedulerEvent(
address schedulerNodeOwner,
string externalIp,
string port
);
function addScheduler(
string memory externalIp,
string memory externalPort
) external {
address msgSender = msg.sender;
require(!schedulerDataIsExist[msgSender], "scheduler data is exists");
schedulerMsgSenders.push(msgSender);
schedulerData[msgSender][_const.EXTERNAL_IP()] = externalIp;
schedulerData[msgSender][_const.EX_SSH_PORT()] = externalPort;
schedulerDataIsExist[msgSender] = true;
emit AddSchedulerEvent(msgSender, externalIp, externalPort);
}
function getSchedulerInfos(
uint256 start,
uint256 count
) external view returns (string[] memory ipArr, string[] memory portArr) {
uint256 length = schedulerMsgSenders.length;
ipArr = new string[](length);
portArr = new string[](length);
uint8 externalIpConst = _const.EXTERNAL_IP();
uint8 externalPortConst = _const.EX_SSH_PORT();
for (uint256 i = start; i < count; i++) {
ipArr[i] = schedulerData[schedulerMsgSenders[i]][externalIpConst];
portArr[i] = schedulerData[schedulerMsgSenders[i]][
externalPortConst
];
}
}
function delSchedulerData() external {
schedulerDataIsExist[msg.sender] = false;
}
function getSchedulerInfo()
external
view
returns (string memory ip, string memory port)
{
require(
schedulerDataIsExist[msg.sender],
"scheduler data is not exists"
);
uint8 externalIpConst = _const.EXTERNAL_IP();
uint8 externalPortConst = _const.EX_SSH_PORT();
ip = schedulerData[msg.sender][externalIpConst];
port = schedulerData[msg.sender][externalPortConst];
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
contract CloudSystem is Callee {
constructor(address const) Callee(const) {}
uint256 id = 1;
mapping(uint256 => mapping(uint8 => string)) systemInfo;
function addSystem(
string memory name,
string memory version,
string memory supportType
) external {
systemInfo[id][_const.NAME()] = name;
systemInfo[id][_const.VERSION()] = version;
systemInfo[id][_const.SUPPORT_TYPE()] = supportType;
}
function getSystem() external pure returns (string memory) {
return "";
}
function maxId() external view returns (uint256) {
return id;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract CloudVm is Callee {
using Strings for string;
constructor(address const) Callee(const) {}
mapping(address => uint256[]) public vmIds;
mapping(uint256 => address) public vmIdCreator;
mapping(uint256 => address) public vmIdOwner;
mapping(uint256 => mapping(uint256 => string)) public vmInfo;
mapping(uint256 => uint8) public vmStatus;
mapping(uint256 => mapping(uint256 => uint256)) public vmConigData;
// 更新虚拟机网络信息事件
event UpdateNetworkInfoEvent(
uint256 vmId,
string intranetIp,
string externalIp,
string exSshPort,
string exVncPort,
string inSshPort,
string inVncPort
);
// 更新虚拟机资源信息事件
event UpdateResourceInfoEvent(
uint256 vmId,
string cpuCost,
string memoryCost,
string gpuCost,
string diskCost
);
// 更新虚拟机配置信息事件
event UpdateVMInfoEvent(
uint256 vmId,
uint64 cpuNum,
uint64 memorySize,
uint64 gpuNum,
uint256 diskSize
);
event UpdateVmStatus(uint256 vmId, uint8 status);
modifier CheckVmOwner(uint256 vmId) {
require(vmIdOwner[vmId] == msg.sender, "");
require(vmStatus[vmId] != _const.DELETE(), "");
_;
}
modifier CheckVmCreator(uint256 vmId) {
require(
vmIdCreator[vmId] == msg.sender,
"The caller is not creator of vm"
);
_;
}
/**
* 添加虚拟机
* @param owner 虚拟机拥有者
* @param vmId 虚拟机唯一标识
* @param clusterId 虚拟机所属集群唯一标识
* @param globalIdentify 虚拟机全局唯一标识
* @param hostId 虚拟机所属物理机唯一标识
* @param vmName 虚拟机名字
* @param os 虚拟机所用系统
*/
function addVirtualMachine(
address owner,
uint256 vmId,
string memory clusterId,
string memory globalIdentify,
string memory hostId,
string memory vmName,
string memory os
) public {
vmIds[owner].push(vmId);
vmIdCreator[vmId] = msg.sender;
vmIdOwner[vmId] = owner;
vmInfo[vmId][_const.CLUSTER()] = clusterId;
vmInfo[vmId][_const.NAME()] = vmName;
vmInfo[vmId][_const.HOST()] = hostId;
vmInfo[vmId][_const.GLOBAL_ID()] = globalIdentify;
vmInfo[vmId][_const.OS()] = os;
vmStatus[vmId] = _const.ENABLE();
}
/**
* 更新虚拟机的配置信息
* @param vmId 虚拟机唯一标识
* @param cpuNum 虚拟机CPU数量
* @param memorySize 内存大小
* @param gpuNum GPU数量
* @param diskSize 磁盘大小
*/
function updateVmInfo(
uint256 vmId,
uint64 cpuNum,
uint64 memorySize,
uint64 gpuNum,
uint256 diskSize
) external {
vmConigData[vmId][_const.CPU_NUM()] = cpuNum;
vmConigData[vmId][_const.MEM_NUM()] = memorySize;
vmConigData[vmId][_const.GPU_NUM()] = gpuNum;
vmConigData[vmId][_const.DISK()] = diskSize;
emit UpdateVMInfoEvent(vmId, cpuNum, memorySize, gpuNum, diskSize);
}
/**
* 更新虚拟机的资源信息
* @param vmId 虚拟机唯一标识
* @param cpuCost 虚拟机CPU占用率
* @param memoryCost 虚拟机内存占用率
* @param gpuCost 虚拟机GPU占用率
* @param diskCost 虚拟机磁盘占用率
*/
function updateResourceInfo(
uint256 vmId,
string memory cpuCost,
string memory memoryCost,
string memory gpuCost,
string memory diskCost
) external {
emit UpdateResourceInfoEvent(
vmId,
cpuCost,
memoryCost,
gpuCost,
diskCost
);
}
/**
* 更新虚拟机的网络信息
* @param vmId 虚拟机唯一标识
* @param intranetIp 内网IP
* @param externalIp 外网IP
* @param exSshPort 外网SSH端口
* @param exVncPort 外网VNC端口
* @param inSshPort 内网SSH端口
* @param inVncPort 内网VNC端口
*/
function updateVmNetworkInfo(
uint256 vmId,
string memory intranetIp,
string memory externalIp,
string memory exSshPort,
string memory exVncPort,
string memory inSshPort,
string memory inVncPort
) external {
vmInfo[vmId][_const.INTERNAL_IP()] = intranetIp;
vmInfo[vmId][_const.EXTERNAL_IP()] = externalIp;
vmInfo[vmId][_const.EX_SSH_PORT()] = exSshPort;
vmInfo[vmId][_const.EX_VNC_PORT()] = exVncPort;
vmInfo[vmId][_const.IN_SSH_PORT()] = inSshPort;
vmInfo[vmId][_const.IN_VNC_PORT()] = inVncPort;
emit UpdateNetworkInfoEvent(
vmId,
intranetIp,
externalIp,
exSshPort,
exVncPort,
inSshPort,
inVncPort
);
}
/**
* 更新虚拟机的登陆信息
* @param vmid 虚拟机唯一标识
* @param user 用户名
* @param pwd 密码
*/
function addVmUser(
uint256 vmid,
string memory user,
string memory pwd
) external {
vmInfo[vmid][_const.USER()] = user;
vmInfo[vmid][_const.PASSWORD()] = pwd;
}
function getVmUser(
uint256 vmId
)
external
view
CheckVmOwner(vmId)
returns (string memory username, string memory password)
{
username = vmInfo[vmId][_const.USER()];
password = vmInfo[vmId][_const.PASSWORD()];
}
function getVmIds(
uint8 start,
uint8 count
) external view returns (uint256[] memory res) {
address msgSender = msg.sender;
uint256 vmIdCount = vmIds[msgSender].length;
uint256 end = start + count;
if (end > vmIdCount) {
end = vmIdCount;
}
res = new uint256[](end - start);
if (vmIdCount >= start) {
for (uint8 i = start; i < end; i++) {
if (vmStatus[vmIds[msgSender][i]] == _const.DELETE()) {
continue;
}
res[i - start] = vmIds[msgSender][i];
}
}
return res;
}
function getVmInfo(
uint256 vmId
)
external
view
CheckVmOwner(vmId)
returns (
string memory externalIp,
string memory ex_ssh_port,
string memory ex_vnc_port
)
{
externalIp = vmInfo[vmId][_const.EXTERNAL_IP()];
ex_ssh_port = vmInfo[vmId][_const.EX_SSH_PORT()];
ex_vnc_port = vmInfo[vmId][_const.EX_VNC_PORT()];
}
function getVmConfigInfo(
uint256 vmId
)
external
view
CheckVmOwner(vmId)
returns (
uint256 cpuCores,
uint256 memNum,
uint256 gpuNum,
string memory osName
)
{
cpuCores = vmConigData[vmId][_const.CPU_NUM()];
memNum = vmConigData[vmId][_const.MEM_NUM()];
gpuNum = vmConigData[vmId][_const.GPU_NUM()];
osName = vmInfo[vmId][_const.OS()];
}
function getVmStatus(
uint256 vmId
) external view CheckVmOwner(vmId) returns (uint8 status) {
status = vmStatus[vmId];
}
function updateVmStatus(
uint256 vmId,
uint8 status
) external CheckVmCreator(vmId) {
require(
status == _const.DELETE() ||
status == _const.ENABLE() ||
status == _const.DISABLE() ||
status == _const.RE_BOOT(),
"Update vm status failed"
);
vmStatus[vmId] = status;
}
function enableVm(uint256 vmId) external CheckVmOwner(vmId) {
require(vmStatus[vmId] != _const.ENABLE(), "The vm is enabled");
emit UpdateVmStatus(vmId, _const.ENABLE());
}
function disableVm(uint256 vmId) external CheckVmOwner(vmId) {
emit UpdateVmStatus(vmId, _const.DISABLE());
}
function rebootVm(uint256 vmId) external CheckVmOwner(vmId) {
require(
vmStatus[vmId] != _const.DISABLE() &&
vmStatus[vmId] != _const.RE_BOOT(),
"The vm is enabled"
);
vmStatus[vmId] = _const.RE_BOOT();
emit UpdateVmStatus(vmId, _const.RE_BOOT());
}
function delVm(uint256 vmId) external CheckVmOwner(vmId) {
emit UpdateVmStatus(vmId, _const.RE_BOOT());
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "./BaseAuth.sol";
contract CloudVmCreate is Callee {
constructor(address const) Callee(const) {}
mapping(address => string[]) public taskOwnerMapping;
mapping(string => address) public taskSnatchMapping;
mapping(string => uint256) public taskTimeMapping;
mapping(address => mapping(string => uint256)) public taskVmidMapping;
// taskId->taskProgress VM 创建 阶段+进度
mapping(string => mapping(uint8 => uint256)) public taskProgress;
mapping(string => string) taskErrorMsg;
event AddCreateVMInfoEvent(
string taskId,
address owner,
string callerIp,
string cpuModel,
uint64 cpuNum,
uint64 cpuCores,
string gpuModel,
uint64 gpuNum,
uint64 memNum,
string os,
string vmName
);
event SnatchTaskEvent(string taskId, address creater, address snatcher);
/**
* 添加任务
* @param taskId 任务ID
* @param callerIp 调用者IP
* @param cpuModel CPU型号
* @param cpuNum CPU数量
* @param cpuCores CPU核心数
* @param gpuModel GPU型号
* @param gpuNum GPU数量
* @param memSize 内存大小
* @param os 系统信息
* @param vmName 虚拟机名称
*/
function addVirtualMachine(
string memory taskId,
string memory callerIp,
string memory cpuModel,
uint64 cpuNum,
uint64 cpuCores,
string memory gpuModel,
uint64 gpuNum,
uint64 memSize,
string memory os,
string memory vmName
) public {
require(
cpuNum >= 1 && cpuCores >= 1 && gpuNum >= 1 && memSize >= 1024,
"Verify param error"
);
require(
taskSnatchMapping[taskId] == address(0),
"The task is snatched"
);
taskProgress[taskId][_const.STAGE()] = 1;
taskProgress[taskId][_const.PROGRESS()] = 10;
taskOwnerMapping[msg.sender].push(taskId);
taskTimeMapping[taskId] = block.timestamp;
emit AddCreateVMInfoEvent(
taskId,
msg.sender,
callerIp,
cpuModel,
cpuNum,
cpuCores,
gpuModel,
gpuNum,
memSize,
os,
vmName
);
}
/**
* 更新任务的创建进度
* @param taskId 任务ID
* @param createStage 创建阶段
* @param createProgress 创建进度
*/
function updateVmCreateProgress(
string calldata taskId,
uint256 createStage,
uint256 createProgress
) public {
require(
taskSnatchMapping[taskId] == msg.sender,
"The msg sender is not snatcher"
);
require(
createProgress >= 0 && createProgress <= 100,
"create progress is not beyond 100"
);
taskProgress[taskId][_const.STAGE()] = createStage;
taskProgress[taskId][_const.PROGRESS()] = createProgress;
}
// 节点抢占
function snatchTask(string memory taskId, address creater) public {
// todo 需要校验调用者是否为算力节点
require(
taskSnatchMapping[taskId] == address(0) && creater != address(0),
"Snatch task failed"
);
taskSnatchMapping[taskId] = msg.sender;
emit SnatchTaskEvent(taskId, creater, msg.sender);
}
function finishTask(
address owner,
string memory taskId,
uint256 vmId
) external {
require(
taskSnatchMapping[taskId] == msg.sender &&
taskVmidMapping[owner][taskId] == 0,
"Finish task error"
);
taskVmidMapping[owner][taskId] = vmId;
}
function getVmId(string memory taskId) external view returns (uint256) {
return taskVmidMapping[msg.sender][taskId];
}
function getTaskId(
uint8 start,
uint8 count
) external view returns (string[] memory res) {
address msgSender = msg.sender;
uint256 vmIdCount = taskOwnerMapping[msgSender].length;
uint256 end = start + count;
if (end > vmIdCount) {
end = vmIdCount;
}
res = new string[](end - start);
if (vmIdCount >= start) {
for (uint8 i = start; i < end; i++) {
res[i - start] = taskOwnerMapping[msgSender][i];
}
}
return res;
}
function getVmCreateProgress(
string calldata taskId
) public view returns (uint256, uint256) {
return (
taskProgress[taskId][_const.STAGE()],
taskProgress[taskId][_const.PROGRESS()]
);
}
function getTaskTimestamp(
string memory taskId
) external view returns (uint256) {
return taskTimeMapping[taskId];
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
interface ICloudConstant {
function onlyCaller(
string memory key,
address caller
) external view returns (bool);
function getCaller(string memory key) external view returns (address);
// Common Key
function CREATING() external view returns (uint8);
function CREATED() external view returns (uint8);
function USER() external view returns (uint8);
function PASSWORD() external view returns (uint8);
function CLUSTER() external view returns (uint8);
function GLOBAL_ID() external view returns (uint8);
function HOST() external view returns (uint8);
function NAME() external view returns (uint8);
function STAGE() external view returns (uint8);
function PROGRESS() external view returns (uint8);
function IS_EXISTS() external view returns (uint8);
// VM NET INFO KEY
function EXTERNAL_IP() external view returns (uint8);
function INTERNAL_IP() external view returns (uint8);
function EX_SSH_PORT() external view returns (uint8);
function EX_VNC_PORT() external view returns (uint8);
function IN_VNC_PORT() external view returns (uint8);
function IN_SSH_PORT() external view returns (uint8);
// VM CONFIG INFO KEY
function STATUS() external view returns (uint8);
function MEM_NUM() external view returns (uint8);
function CPU_LOGIC_UINTS() external view returns (uint8);
function CPU_NUM() external view returns (uint8);
function CPU_MODEL() external view returns (uint8);
function CPU_CORES() external view returns (uint8);
function GPU_MODEL() external view returns (uint8);
function GPU_NUM() external view returns (uint8);
function DISK() external view returns (uint8);
function OS() external view returns (uint8);
function BIND_WIDTH() external view returns (uint8);
// Gateway Config Info Key
function NPS_VNC_END_PORT() external view returns (uint8);
function NPS_VNC_START_PORT() external view returns (uint8);
function NPS_SSH_END_PORT() external view returns (uint8);
function NPS_SSH_START_PORT() external view returns (uint8);
function SINGALLING_PORT() external view returns (uint8);
function TURN_PORT() external view returns (uint8);
function STUN_PORT() external view returns (uint8);
function ENABLE() external pure returns (uint8);
function DISABLE() external pure returns (uint8);
function RE_BOOT() external pure returns (uint8);
function DELETE() external pure returns (uint8);
function VERSION() external view returns (uint8);
function SUPPORT_TYPE() external view returns (uint8);
}
require("dotenv").config()
require("@nomicfoundation/hardhat-toolbox");
let mnemonic = process.env.MNEMONIC;
if (!mnemonic) {
// NOTE: this fallback is for development only!
// When using other networks, set the secret in .env.
// DO NOT commit or share your mnemonic with others!
mnemonic = 'test test test test test test test test test test test test';
}
let privateKey = process.env.PRIVATE_KEY
const accounts = { mnemonic };
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.9",
settings: {
optimizer: {
enabled: true,
runs: 200
}
},
networks: {
hardhat: {
accounts,
gas: 10000000,
gasPrice: 10000000000,
},
testnet: {
accounts: [privateKey],
url: 'http://15.161.177.5:26658',
gas: 110000000,
gasLimit: 110000000,
gasPrice: 10000000000,
},
local: {
accounts: [privateKey],
url: 'http://192.168.1.125:7545',
gas: 11000000,
gasLimit: 110000000,
gasPrice: 1100000000,
},
},
};
This diff is collapsed.
{
"name": "hardhat-project",
"devDependencies": {
"@nomicfoundation/hardhat-toolbox": "^2.0.2",
"hardhat": "^2.17.0"
},
"dependencies": {
"@openzeppelin/contracts": "^4.9.2",
"dotenv": "^16.3.1",
"web3": "^4.1.1"
}
}
const getContractFactory = require("./deploy");
async function main() {
let constantContract = await getContractFactory("CloudConstant");
let constantArr = [
"creating",
"created",
"user",
"password",
"cluster",
"global_id",
"host",
"name",
"stage",
"progress",
"is_exists",
"external_ip",
"internal_ip",
"external_ssh_port",
"external_vnc_port",
"internal_vnc_port",
"internal_ssh_port",
"status",
"memory",
"cpu_logic_units",
"cpu_num",
"cpu_model",
"cpu_cores",
"gpu_model",
"gpu_num",
"disk",
"os",
"bind_width",
"nps_vnc_end_port",
"nps_vnc_start_port",
"nps_ssh_end_port",
"nps_ssh_start_port",
"signalling_port",
"turn_port",
"stun_port"
];
for (let i = 1; i <= constantArr.length; i++) {
let res = await constantContract.setConstMap(constantArr[i - 1], i);
await res.wait();
console.log("Add constant index:", i);
}
let EX_SSH_START_PORT = await constantContract.EX_SSH_PORT();
console.log("external_ssh_port:", EX_SSH_START_PORT);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
\ No newline at end of file
const getContractFactory = require("./deploy");
async function main() {
let hostContract = await getContractFactory("CloudHost");
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
\ No newline at end of file
const getContractFactory = require("./deploy");
async function main() {
let schedulerContract = await getContractFactory("CloudScheduler");
let addRes = await schedulerContract.addScheduler("189.164.15.25", "5000");
await addRes.wait();
console.log("addRes", addRes);
let getRes = await schedulerContract.getSchedulerInfo();
console.log("getRes", getRes);
getRes = await schedulerContract.getSchedulerInfos(0, 1);
console.log("getRes", getRes);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
\ No newline at end of file
const getContractFactory = require("./deploy");
async function main() {
let vmContract = await getContractFactory("CloudVm");
let vmId = 104;
// await GetVmInfo(vmContract, vmId);
// await GetVmUser(vmContract, vmId);
// await GetVmIds(vmContract, 0, 10);
// await enableVm(vmContract, vmId);
// await disableVm(vmContract, vmId);
await getVmStatus(vmContract, vmId);
}
async function enableVm(vmContract, vmId) {
let enableVm = await vmContract.enableVm(vmId);
await enableVm.wait();
console.log("enableVm", enableVm);
}
async function disableVm(vmContract, vmId) {
let disableVm = await vmContract.disableVm(vmId);
await disableVm.wait();
console.log("disableVm", disableVm);
}
async function getVmStatus(vmContract, vmId) {
let getVmStatus = await vmContract.getVmStatus(vmId);
console.log("getVmStatus:", getVmStatus);
}
async function GetVmUser(vmContract, vmId) {
let addRes = await vmContract.getVmUser(vmId);
console.log("addRes", addRes);
}
async function GetVmIds(vmContract, start, count) {
let getRes = await vmContract.getVmIds(start, count);
console.log("getRes", getRes);
}
async function GetVmInfo(vmContract, vmId) {
let getRes = await vmContract.getVmInfo(vmId);
console.log("getRes", getRes);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
\ No newline at end of file
const getContractFactory = require("./deploy");
async function main() {
let vmCreateContract = await getContractFactory("CloudVmCreate");
let taskId = "111-222-254";
// await AddVirtualMachine(vmCreateContract, taskId);
// await GetVmId(vmCreateContract, taskId);
await GetVmCreateProgress(vmCreateContract, taskId);
}
async function AddVirtualMachine(vmCreateContract, taskId) {
let addRes = await vmCreateContract.addVirtualMachine(taskId, "192.168.1.109", "Inter", 1, 8, "A100", 1, 4096, "windows-10", "aws");
await addRes.wait();
console.log("addRes", addRes);
}
async function GetVmId(vmCreateContract, taskId) {
let getRes = await vmCreateContract.getVmId(taskId);
console.log("getRes", getRes);
}
async function GetTaskId(vmCreateContract, start, count) {
let getRes = await vmCreateContract.getTaskId(start, count);
console.log("getRes", getRes);
}
async function GetVmCreateProgress(vmCreateContract, taskId) {
let getRes = await vmCreateContract.getVmCreateProgress(taskId);
console.log("getRes", getRes);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
\ No newline at end of file
const hre = require("hardhat");
let isDeploy = true;
let contractName = [
"CloudConstant",
// "CloudGateway",
// "CloudScheduler",
"CloudVm",
"CloudVmCreate",
// "CloudHost"
];
// let contractAddress = [
// "0x511017c4A67e6f3DAb0158538d72568D74C5909C",
// // "0x993C630B94E4FfC2e9Cd39F9B5D65cE8c0B5B425",
// // "0x06425aa6a39E7eB09fC1E12C9653A1efA80ba46d",
// "0x15A5aac5D5bc2B7D0389a1054701a6583169FB00",
// "0xFAbE2869D0E0a13b6776C31bD78505Ed9c2FAbec",
// // "0xF465eD8D34653Dc984d47c7Bb91890e7cDfCB297"
// ];
let contractAddress = [
"0xA427EC72294E9A8fA652CD6649689e35F3632A21",
// "0x993C630B94E4FfC2e9Cd39F9B5D65cE8c0B5B425",
// "0x06425aa6a39E7eB09fC1E12C9653A1efA80ba46d",
"0x94F0EaC13064181C94a8D25DCaf9FAD8C97e105F",
"0x01AB479187FBcd228BF808C9c2B2c1D655029444",
// "0xF465eD8D34653Dc984d47c7Bb91890e7cDfCB297"
];
async function deployConst() {
let constContract = await hre.ethers.getContractFactory("CloudConstant");
let constDeploy = await constContract.deploy();
await constDeploy.deployed();
console.log("deploy CloudConstant contract address:", constDeploy.address);
return constDeploy.address;
}
async function deployOtherContract(constContract, contractName) {
for (let i = 1; i < contractName.length; i++) {
let name = contractName[i];
let contract = await hre.ethers.getContractFactory(name);
let deplyContract = await contract.deploy(constContract);
await deplyContract.deployed();
console.log("deploy " + name + " contract address ", deplyContract.address);
}
}
async function getContractFactory(param) {
for (let i = 0; i < contractName.length; i++) {
let name = contractName[i];
if (name == param) {
let contract = await hre.ethers.getContractAt(param, contractAddress[i]);
return contract;
}
}
}
async function main() {
if (isDeploy) {
// let constAddress = await deployConst();
await deployOtherContract("0xA427EC72294E9A8fA652CD6649689e35F3632A21", contractName);
}
}
async function getTranRes(txHash) {
let txRes = await hre.ethers.provider.getTransaction(txHash);
await txRes.wait();
console.log("txRes:", txRes);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
module.exports = getContractFactory
\ No newline at end of file
const {
time,
loadFixture,
} = require("@nomicfoundation/hardhat-network-helpers");
const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs");
const { expect } = require("chai");
describe("Lock", function () {
// We define a fixture to reuse the same setup in every test.
// We use loadFixture to run this setup once, snapshot that state,
// and reset Hardhat Network to that snapshot in every test.
async function deployOneYearLockFixture() {
const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60;
const ONE_GWEI = 1_000_000_000;
const lockedAmount = ONE_GWEI;
const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS;
// Contracts are deployed using the first signer/account by default
const [owner, otherAccount] = await ethers.getSigners();
const Lock = await ethers.getContractFactory("Lock");
const lock = await Lock.deploy(unlockTime, { value: lockedAmount });
return { lock, unlockTime, lockedAmount, owner, otherAccount };
}
describe("Deployment", function () {
it("Should set the right unlockTime", async function () {
const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture);
expect(await lock.unlockTime()).to.equal(unlockTime);
});
it("Should set the right owner", async function () {
const { lock, owner } = await loadFixture(deployOneYearLockFixture);
expect(await lock.owner()).to.equal(owner.address);
});
it("Should receive and store the funds to lock", async function () {
const { lock, lockedAmount } = await loadFixture(
deployOneYearLockFixture
);
expect(await ethers.provider.getBalance(lock.address)).to.equal(
lockedAmount
);
});
it("Should fail if the unlockTime is not in the future", async function () {
// We don't use the fixture here because we want a different deployment
const latestTime = await time.latest();
const Lock = await ethers.getContractFactory("Lock");
await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith(
"Unlock time should be in the future"
);
});
});
describe("Withdrawals", function () {
describe("Validations", function () {
it("Should revert with the right error if called too soon", async function () {
const { lock } = await loadFixture(deployOneYearLockFixture);
await expect(lock.withdraw()).to.be.revertedWith(
"You can't withdraw yet"
);
});
it("Should revert with the right error if called from another account", async function () {
const { lock, unlockTime, otherAccount } = await loadFixture(
deployOneYearLockFixture
);
// We can increase the time in Hardhat Network
await time.increaseTo(unlockTime);
// We use lock.connect() to send a transaction from another account
await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith(
"You aren't the owner"
);
});
it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () {
const { lock, unlockTime } = await loadFixture(
deployOneYearLockFixture
);
// Transactions are sent using the first signer by default
await time.increaseTo(unlockTime);
await expect(lock.withdraw()).not.to.be.reverted;
});
});
describe("Events", function () {
it("Should emit an event on withdrawals", async function () {
const { lock, unlockTime, lockedAmount } = await loadFixture(
deployOneYearLockFixture
);
await time.increaseTo(unlockTime);
await expect(lock.withdraw())
.to.emit(lock, "Withdrawal")
.withArgs(lockedAmount, anyValue); // We accept any value as `when` arg
});
});
describe("Transfers", function () {
it("Should transfer the funds to the owner", async function () {
const { lock, unlockTime, lockedAmount, owner } = await loadFixture(
deployOneYearLockFixture
);
await time.increaseTo(unlockTime);
await expect(lock.withdraw()).to.changeEtherBalances(
[owner, lock],
[lockedAmount, -lockedAmount]
);
});
});
});
});
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