Skip to content
Snippets Groups Projects
Select Git revision
  • f60e62bc159e88c95c1ad94c55453129790fe036
  • live_exam_os_ubuntu default protected
2 results

vms.go

  • vms.go 12.02 KiB
    package vms
    
    import (
        "os"
        "sort"
        "sync"
        "math"
        "errors"
        "path/filepath"
        "nexus-server/exec"
        "nexus-server/caps"
        "nexus-server/paths"
        "nexus-server/utils"
        "nexus-server/logger"
        "nexus-server/consts"
        "github.com/google/uuid"
    )
    
    type (
        VMKeeperFn func(vm VM) bool
    
        VMs struct {
            m map[string]VM
            dir string             // Base directory where VMs are stored
            rwlock *sync.RWMutex   // RWlock to ensure the coherency of the map (m) of VMs
            usedPorts [65536]bool  // Indicates which ports are used by the VMs
            usedRAM int            // Used RAM by running VMs (in MB)
        }
    )
    
    var log = logger.GetInstance()
    var vms *VMs
    
    // Returns a VMs "singleton".
    // IMPORTANT: the InitVMs function must have been previously called!
    func GetVMsInstance() *VMs {
        return vms
    }
    
    // Creates all VMs from their files on disk.
    // NOTE: path is the root directory where VMs reside.
    func InitVMs() error {
        vmsDir := paths.GetInstance().VMsDir
        vms = &VMs { m: make(map[string]VM), dir: vmsDir, rwlock: new(sync.RWMutex), usedRAM: 0 }
    
        errMsg := "Failed reading VMs directory: "
        dirs1, err := utils.GetSubDirs(vmsDir)
        if err != nil {
            return errors.New(errMsg+err.Error())
        }
    
        for d1 := range(dirs1) {
            dirs2, err := utils.GetSubDirs(dirs1[d1])
            if err != nil {
                return errors.New(errMsg+err.Error())
            }
    
            for d2 := range(dirs2) {
                dirs3, err := utils.GetSubDirs(dirs2[d2])
                if err != nil {
                    return errors.New(errMsg+err.Error())
                }
    
                for i := range(dirs3) {
                    vmDir := dirs3[i]
                    filename := filepath.Join(vmDir, vmConfFile)
                    vm, err := newVMFromFile(filename)
                    if err != nil {
                        log.Warn("Skipping VM: failed reading \""+filename+"\" "+err.Error())
                        continue