Skip to content

Commit

Permalink
factory: add direct and cache factory
Browse files Browse the repository at this point in the history
direct factory just creates the vm directly.
cache factory uses the base factory (either direct or template) to
create the vm.

Fixes: #52

Signed-off-by: Peng Tao <[email protected]>
  • Loading branch information
bergwolf committed May 14, 2018
1 parent 66772c8 commit 162ae20
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 5 deletions.
61 changes: 57 additions & 4 deletions virtcontainers/factory/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,80 @@
package cache

import (
"fmt"
"sync"

vc "github.com/kata-containers/runtime/virtcontainers"
"github.com/kata-containers/runtime/virtcontainers/factory/base"
)

type cache struct {
count uint

base base.FactoryBase

cachech chan *vc.VM
closed chan<- int
wg sync.WaitGroup
closeOnce sync.Once
}

func New(count uint, b base.FactoryBase) base.FactoryBase {
return &cache{count, b}
if count < 1 {
return b
}

cachech := make(chan *vc.VM)
closed := make(chan int, count)
c := cache{base: b, cachech: cachech, closed: closed}
for i := 0; i < int(count); i++ {
c.wg.Add(1)
go func() {
for {
vm, err := b.GetBaseVM()
if err != nil {
//glog.Errorf("cache factory get error when allocate vm: %v", err)
c.wg.Done()
c.CloseFactory()
return
}
//glog.V(3).Infof("cache factory get vm from lower layer: %s", vm.Id)

select {
case cachech <- vm:
//glog.V(3).Infof("cache factory sent one vm: %s", vm.Id)
case _ = <-closed:
//glog.V(3).Infof("cache factory is going to close")
vm.Kill()
c.wg.Done()
return
}
}
}()
}
return &c
}

func (c *cache) Config() (vc.HypervisorType, *vc.HypervisorConfig) {
return c.base.Config()
}

func (c *cache) GetBaseVM() (*vc.VM, error) {
return c.base.GetBaseVM()
vm, ok := <-c.cachech
if ok {
//glog.V(3).Infof("cache factory get vm from cache: %s", vm.Id)
return vm, nil
}
return nil, fmt.Errorf("cache factory is closed")
}

func (c *cache) CloseFactory() {
c.closeOnce.Do(func() {
//glog.V(3).Infof("CloseFactory() close cache factory")
for len(c.closed) < cap(c.closed) { // send sufficient closed signal
c.closed <- 0
}
//glog.V(3).Infof("CloseFactory() sent close signal")
c.wg.Wait()
close(c.cachech)
c.base.CloseFactory()
})
}
2 changes: 1 addition & 1 deletion virtcontainers/factory/direct/direct.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (d *direct) Config() (vc.HypervisorType, *vc.HypervisorConfig) {
}

func (d *direct) GetBaseVM() (*vc.VM, error) {
return nil, nil
return vc.NewVM(d.hypervisorType, d.hypervisorConfig)
}

func (d *direct) CloseFactory() {
Expand Down

0 comments on commit 162ae20

Please sign in to comment.