func main() { usage := du.NewDiskUsage("C:\\") fmt.Println("Free:", usage.Free()/(KB*KB)) fmt.Println("Available:", usage.Available()/(KB*KB)) fmt.Println("Size:", usage.Size()/(KB*KB)) fmt.Println("Used:", usage.Used()/(KB*KB)) fmt.Println("Usage:", usage.Usage()*100, "%") }
func configureServer(cmd *cobra.Command, args []string) { if version { fmt.Printf("torusd\nVersion: %s\n", torus.Version) os.Exit(0) } switch { case debug: capnslog.SetGlobalLogLevel(capnslog.DEBUG) default: capnslog.SetGlobalLogLevel(capnslog.INFO) } if logpkg != "" { capnslog.SetGlobalLogLevel(capnslog.NOTICE) rl := capnslog.MustRepoLogger("github.com/coreos/torus") llc, err := rl.ParseLogLevelConfig(logpkg) if err != nil { fmt.Fprintf(os.Stderr, "error parsing logpkg: %s\n", err) os.Exit(1) } rl.SetLogLevel(llc) } if host != "" { httpAddress = fmt.Sprintf("%s:%d", host, port) } var ( err error size uint64 ) if strings.Contains(sizeStr, "%") { percent, err := parsePercentage(sizeStr) if err != nil { fmt.Fprintf(os.Stderr, "error parsing size %s: %s\n", sizeStr, err) os.Exit(1) } directory, _ := filepath.Abs(dataDir) size = du.NewDiskUsage(directory).Size() * percent / 100 } else { size, err = humanize.ParseBytes(sizeStr) if err != nil { fmt.Fprintf(os.Stderr, "error parsing size %s: %s\n", sizeStr, err) os.Exit(1) } } cfg = flagconfig.BuildConfigFromFlags() cfg.DataDir = dataDir cfg.StorageSize = size }
func updateStatus() { if mySituation.Quality == 2 { globalStatus.GPS_solution = "GPS + SBAS (WAAS)" } else if mySituation.Quality == 1 { globalStatus.GPS_solution = "3D GPS" } else if mySituation.Quality == 6 { globalStatus.GPS_solution = "Dead Reckoning" } else if mySituation.Quality == 0 { globalStatus.GPS_solution = "No Fix" } else { globalStatus.GPS_solution = "Unknown" } if !(globalStatus.GPS_connected) || !(isGPSConnected()) { // isGPSConnected looks for valid NMEA messages. GPS_connected is set by gpsSerialReader and will immediately fail on disconnected USB devices, or in a few seconds after "blocked" comms on ttyAMA0. satelliteMutex.Lock() Satellites = make(map[string]SatelliteInfo) satelliteMutex.Unlock() mySituation.Satellites = 0 mySituation.SatellitesSeen = 0 mySituation.SatellitesTracked = 0 mySituation.Quality = 0 globalStatus.GPS_solution = "Disconnected" globalStatus.GPS_connected = false } globalStatus.GPS_satellites_locked = mySituation.Satellites globalStatus.GPS_satellites_seen = mySituation.SatellitesSeen globalStatus.GPS_satellites_tracked = mySituation.SatellitesTracked globalStatus.GPS_position_accuracy = mySituation.Accuracy // Update Uptime value globalStatus.Uptime = int64(stratuxClock.Milliseconds) globalStatus.UptimeClock = stratuxClock.Time usage = du.NewDiskUsage("/") globalStatus.DiskBytesFree = usage.Free() }
// initialize sets up an openstack scheduler. func (s *opst) initialize(config interface{}) (err error) { s.config = config.(*ConfigOpenStack) if s.config.OSRAM == 0 { s.config.OSRAM = 2048 } // create a cloud provider for openstack, that we'll use to interact with // openstack provider, err := cloud.New("openstack", s.config.ResourceName, s.config.SavePath) if err != nil { return } s.provider = provider err = provider.Deploy(s.config.ServerPorts) if err != nil { return } // query our quota maximums for cpu and memory and total number of // instances; 0 will mean unlimited quota, err := provider.GetQuota() if err != nil { return } s.quotaMaxCores = quota.MaxCores s.quotaMaxRAM = quota.MaxRAM s.quotaMaxInstances = quota.MaxInstances if s.config.MaxInstances > 0 && s.config.MaxInstances < s.quotaMaxInstances { s.quotaMaxInstances = s.config.MaxInstances } // initialize our job queue and other trackers s.queue = queue.New(localPlace) s.running = make(map[string]int) // initialise our servers with details of ourself s.servers = make(map[string]*cloud.Server) maxRAM, err := s.procMeminfoMBs() if err != nil { return } usage := du.NewDiskUsage(".") s.servers["localhost"] = &cloud.Server{ IP: "127.0.0.1", Flavor: cloud.Flavor{ RAM: maxRAM, Cores: runtime.NumCPU(), Disk: int(usage.Size() / gb), }, } // set our functions for use in schedule() and processQueue() s.reqCheckFunc = s.reqCheck s.canCountFunc = s.canCount s.runCmdFunc = s.runCmd // pass through our shell config to our local embed s.local.config = &ConfigLocal{Shell: s.config.Shell} s.standins = make(map[string]*standin) s.stopWaitingToSpawn = make(chan bool) return }
func (store *defaultValueStore) watcherLauncher(notifyChan chan *bgNotification) { interval := float64(store.watcherState.interval) * float64(time.Second) store.randMutex.Lock() nextRun := time.Now().Add(time.Duration(interval + interval*store.rand.NormFloat64()*0.1)) store.randMutex.Unlock() disabled := false running := true for running { var notification *bgNotification sleep := nextRun.Sub(time.Now()) if sleep > 0 { select { case notification = <-notifyChan: case <-time.After(sleep): } } else { select { case notification = <-notifyChan: default: } } store.randMutex.Lock() nextRun = time.Now().Add(time.Duration(interval + interval*store.rand.NormFloat64()*0.1)) store.randMutex.Unlock() if notification != nil { if notification.action == _BG_DISABLE { running = false } else { store.logCritical("watcher: invalid action requested: %d", notification.action) } notification.doneChan <- struct{}{} continue } u := du.NewDiskUsage(store.path) utoc := u if store.pathtoc != store.path { utoc = du.NewDiskUsage(store.pathtoc) } diskFree := u.Free() diskUsed := u.Used() diskSize := u.Size() diskUsage := u.Usage() diskFreeTOC := utoc.Free() diskUsedTOC := utoc.Used() diskSizeTOC := utoc.Size() diskUsageTOC := utoc.Usage() atomic.StoreUint64(&store.watcherState.diskFree, diskFree) atomic.StoreUint64(&store.watcherState.diskUsed, diskUsed) atomic.StoreUint64(&store.watcherState.diskSize, diskSize) atomic.StoreUint64(&store.watcherState.diskFreeTOC, diskFreeTOC) atomic.StoreUint64(&store.watcherState.diskUsedTOC, diskUsedTOC) atomic.StoreUint64(&store.watcherState.diskSizeTOC, diskSizeTOC) store.logDebug("watcher: disk: %d free, %d used, %d size, %.02f%% usage; toc: %d free, %d used, %d size, %.02f%% usage", diskFree, diskUsed, diskSize, diskUsage*100, diskFreeTOC, diskUsedTOC, diskSizeTOC, diskUsageTOC*100) m := &sigar.Mem{} var memUsage float32 if err := m.Get(); err != nil { m = nil store.logDebug("watcher: could not stat memory: %s", err) } else { memUsage = float32(m.ActualUsed) / float32(m.Total) atomic.StoreUint64(&store.watcherState.memFree, m.ActualFree) atomic.StoreUint64(&store.watcherState.memUsed, m.ActualUsed) atomic.StoreUint64(&store.watcherState.memSize, m.Total) store.logDebug("watcher: mem: %d free, %d used, %d size, %.02f%% usage", m.ActualFree, m.ActualUsed, m.Total, memUsage*100) } var wantToDisable string var wantToReenable string if store.watcherState.diskFreeDisableThreshold > 1 && (diskFree <= store.watcherState.diskFreeDisableThreshold || diskFreeTOC <= store.watcherState.diskFreeDisableThreshold) { wantToDisable = "watcher: passed the disk free threshold for automatic disabling" } if store.watcherState.diskUsageDisableThreshold > 0 && (diskUsage >= store.watcherState.diskUsageDisableThreshold || diskUsageTOC >= store.watcherState.diskUsageDisableThreshold) { wantToDisable = "watcher: passed the disk usage threshold for automatic disabling" } if store.watcherState.memFreeDisableThreshold > 1 && m != nil && m.ActualFree <= store.watcherState.memFreeDisableThreshold { wantToDisable = "watcher: passed the mem free threshold for automatic disabling" } if store.watcherState.memUsageDisableThreshold > 0 && m != nil && memUsage >= store.watcherState.memUsageDisableThreshold { wantToDisable = "watcher: passed the mem usage threshold for automatic disabling" } if store.watcherState.diskFreeReenableThreshold > 1 && diskFree >= store.watcherState.diskFreeReenableThreshold && diskFreeTOC >= store.watcherState.diskFreeReenableThreshold { wantToReenable = "watcher: passed the disk free threshold for automatic re-enabling" } if store.watcherState.diskUsageReenableThreshold > 0 && diskUsage <= store.watcherState.diskUsageReenableThreshold && diskUsageTOC <= store.watcherState.diskUsageReenableThreshold { wantToReenable = "watcher: passed the disk usage threshold for automatic re-enabling" } if store.watcherState.memFreeReenableThreshold > 1 && m != nil && m.ActualFree >= store.watcherState.memFreeReenableThreshold { wantToReenable = "watcher: passed the mem free threshold for automatic re-enabling" } if store.watcherState.memUsageReenableThreshold > 0 && m != nil && memUsage <= store.watcherState.memUsageReenableThreshold { wantToReenable = "watcher: passed the mem usage threshold for automatic re-enabling" } if wantToDisable != "" { if !disabled { store.logCritical(wantToDisable) store.disableWrites(false) // false indicates non-user call disabled = true } } else if wantToReenable != "" { if disabled { store.logCritical(wantToReenable) store.enableWrites(false) disabled = false } } } }
func (store *DefaultValueStore) diskWatcherLauncher(notifyChan chan *bgNotification) { interval := float64(store.diskWatcherState.interval) * float64(time.Second) store.randMutex.Lock() nextRun := time.Now().Add(time.Duration(interval + interval*store.rand.NormFloat64()*0.1)) store.randMutex.Unlock() disabled := false running := true for running { var notification *bgNotification sleep := nextRun.Sub(time.Now()) if sleep > 0 { select { case notification = <-notifyChan: case <-time.After(sleep): } } else { select { case notification = <-notifyChan: default: } } store.randMutex.Lock() nextRun = time.Now().Add(time.Duration(interval + interval*store.rand.NormFloat64()*0.1)) store.randMutex.Unlock() if notification != nil { if notification.action == _BG_DISABLE { running = false } else { store.logCritical("disk watcher: invalid action requested: %d", notification.action) } notification.doneChan <- struct{}{} continue } u := du.NewDiskUsage(store.path) utoc := u if store.pathtoc != store.path { utoc = du.NewDiskUsage(store.pathtoc) } free := u.Free() used := u.Used() size := u.Size() usage := u.Usage() freetoc := utoc.Free() usedtoc := utoc.Used() sizetoc := utoc.Size() usagetoc := utoc.Usage() atomic.StoreUint64(&store.diskWatcherState.free, free) atomic.StoreUint64(&store.diskWatcherState.used, used) atomic.StoreUint64(&store.diskWatcherState.size, size) atomic.StoreUint64(&store.diskWatcherState.freetoc, freetoc) atomic.StoreUint64(&store.diskWatcherState.usedtoc, usedtoc) atomic.StoreUint64(&store.diskWatcherState.sizetoc, sizetoc) if !disabled && store.diskWatcherState.freeDisableThreshold > 1 && (free <= store.diskWatcherState.freeDisableThreshold || freetoc <= store.diskWatcherState.freeDisableThreshold) { store.logCritical("disk watcher: passed the free threshold for automatic disabling\n") store.enableWrites(false) // false indicates non-user call disabled = false } if !disabled && store.diskWatcherState.usageDisableThreshold > 0 && (usage >= store.diskWatcherState.usageDisableThreshold || usagetoc >= store.diskWatcherState.usageDisableThreshold) { store.logCritical("disk watcher: passed the usage threshold for automatic disabling\n") store.enableWrites(false) // false indicates non-user call disabled = false } if disabled && store.diskWatcherState.freeReenableThreshold > 1 && free >= store.diskWatcherState.freeReenableThreshold && freetoc >= store.diskWatcherState.freeReenableThreshold { store.logCritical("disk watcher: passed the free threshold for automatic re-enabling\n") store.enableWrites(false) // false indicates non-user call disabled = false } if disabled && store.diskWatcherState.usageReenableThreshold > 0 && usage <= store.diskWatcherState.usageReenableThreshold && usagetoc <= store.diskWatcherState.usageReenableThreshold { store.logCritical("disk watcher: passed the usage threshold for automatic re-enabling\n") store.enableWrites(false) // false indicates non-user call disabled = false } } }
func CreateDisk(sshKey string, size int) error { if strings.Contains(sshKey, "$HOME") { username := os.Getenv("SUDO_USER") if username == "" { username = os.Getenv("USER") } me, err := user.Lookup(username) if err != nil { return err } sshKey = strings.Replace(sshKey, "$HOME", me.HomeDir, -1) } usage := du.NewDiskUsage(os.ExpandEnv("$HOME/.dlite")) if (usage.Free() / (1024 * 1024 * 1024)) < uint64(size) { return fmt.Errorf("Not enough free space to allocate a %dGiB disk image", size) } sshKey = os.ExpandEnv(sshKey) keyBytes, err := ioutil.ReadFile(sshKey) if err != nil { return err } buffer := new(bytes.Buffer) tarball := tar.NewWriter(buffer) files := []struct { Name string Body []byte }{ {"dhyve, please format-me", []byte("dhyve, please format-me")}, {".ssh/authorized_keys", keyBytes}, } for _, file := range files { if err = tarball.WriteHeader(&tar.Header{ Name: file.Name, Mode: 0644, Size: int64(len(file.Body)), }); err != nil { return err } if _, err = tarball.Write(file.Body); err != nil { return err } } if err = tarball.Close(); err != nil { return err } path := os.ExpandEnv("$HOME/.dlite/disk.img") f, err := os.Create(path) if err != nil { return err } defer f.Close() _, err = f.Write(buffer.Bytes()) if err != nil { return err } _, err = f.Seek(int64(size*1073741824-1), 0) if err != nil { return err } _, err = f.Write([]byte{0}) if err != nil { return err } return changePermissions(path) }
func (v *Volume) AvailableBytes() uint64 { return du.NewDiskUsage(v.Path).Available() }