github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/worker/diskmanager/diskmanager.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package diskmanager 5 6 import ( 7 "reflect" 8 "time" 9 10 "github.com/juju/loggo" 11 12 "github.com/juju/juju/storage" 13 "github.com/juju/juju/worker" 14 ) 15 16 var logger = loggo.GetLogger("juju.worker.diskmanager") 17 18 const ( 19 // listBlockDevicesPeriod is the time period between block device listings. 20 // Unfortunately Linux's inotify does not work with virtual filesystems, so 21 // polling it is. 22 listBlockDevicesPeriod = time.Second * 30 23 24 // bytesInMiB is the number of bytes in a MiB. 25 bytesInMiB = 1024 * 1024 26 ) 27 28 // BlockDeviceSetter is an interface that is supplied to 29 // NewWorker for setting block devices for the local host. 30 type BlockDeviceSetter interface { 31 SetMachineBlockDevices([]storage.BlockDevice) error 32 } 33 34 // ListBlockDevicesFunc is the type of a function that is supplied to 35 // NewWorker for listing block devices available on the local host. 36 type ListBlockDevicesFunc func() ([]storage.BlockDevice, error) 37 38 // DefaultListBlockDevices is the default function for listing block 39 // devices for the operating system of the local host. 40 var DefaultListBlockDevices ListBlockDevicesFunc 41 42 // NewWorker returns a worker that lists block devices 43 // attached to the machine, and records them in state. 44 var NewWorker = func(l ListBlockDevicesFunc, b BlockDeviceSetter) worker.Worker { 45 var old []storage.BlockDevice 46 f := func(stop <-chan struct{}) error { 47 return doWork(l, b, &old) 48 } 49 return worker.NewPeriodicWorker(f, listBlockDevicesPeriod, worker.NewTimer) 50 } 51 52 func doWork(listf ListBlockDevicesFunc, b BlockDeviceSetter, old *[]storage.BlockDevice) error { 53 blockDevices, err := listf() 54 if err != nil { 55 return err 56 } 57 storage.SortBlockDevices(blockDevices) 58 if reflect.DeepEqual(blockDevices, *old) { 59 logger.Tracef("no changes to block devices detected") 60 return nil 61 } 62 logger.Infof("block devices changed: %v", blockDevices) 63 if err := b.SetMachineBlockDevices(blockDevices); err != nil { 64 return err 65 } 66 *old = blockDevices 67 return nil 68 }