gitee.com/leisunstar/runtime@v0.0.0-20200521203717-5cef3e7b53f9/virtcontainers/factory/grpccache/grpccache.go (about)

     1  // Copyright (c) 2019 HyperHQ Inc.
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  // grpccache implements base vm factory that get base vm from grpc
     6  
     7  package grpccache
     8  
     9  import (
    10  	"context"
    11  	"fmt"
    12  
    13  	types "github.com/gogo/protobuf/types"
    14  	pb "github.com/kata-containers/runtime/protocols/cache"
    15  	vc "github.com/kata-containers/runtime/virtcontainers"
    16  	"github.com/kata-containers/runtime/virtcontainers/factory/base"
    17  	"github.com/pkg/errors"
    18  	"google.golang.org/grpc"
    19  )
    20  
    21  type grpccache struct {
    22  	conn   *grpc.ClientConn
    23  	config *vc.VMConfig
    24  }
    25  
    26  // New returns a new direct vm factory.
    27  func New(ctx context.Context, endpoint string) (base.FactoryBase, error) {
    28  	conn, err := grpc.Dial(fmt.Sprintf("unix://%s", endpoint), grpc.WithInsecure())
    29  	if err != nil {
    30  		return nil, errors.Wrapf(err, "failed to connect %q", endpoint)
    31  	}
    32  
    33  	jConfig, err := pb.NewCacheServiceClient(conn).Config(ctx, &types.Empty{})
    34  	if err != nil {
    35  		return nil, errors.Wrapf(err, "failed to Config")
    36  	}
    37  
    38  	config, err := vc.GrpcToVMConfig(jConfig)
    39  	if err != nil {
    40  		return nil, errors.Wrapf(err, "failed to convert JSON to VMConfig")
    41  	}
    42  
    43  	return &grpccache{conn: conn, config: config}, nil
    44  }
    45  
    46  // Config returns the direct factory's configuration.
    47  func (g *grpccache) Config() vc.VMConfig {
    48  	return *g.config
    49  }
    50  
    51  // GetBaseVM create a new VM directly.
    52  func (g *grpccache) GetBaseVM(ctx context.Context, config vc.VMConfig) (*vc.VM, error) {
    53  	defer g.conn.Close()
    54  	gVM, err := pb.NewCacheServiceClient(g.conn).GetBaseVM(ctx, &types.Empty{})
    55  	if err != nil {
    56  		return nil, errors.Wrapf(err, "failed to GetBaseVM")
    57  	}
    58  	return vc.NewVMFromGrpc(ctx, gVM, *g.config)
    59  }
    60  
    61  // CloseFactory closes the direct vm factory.
    62  func (g *grpccache) CloseFactory(ctx context.Context) {
    63  }
    64  
    65  // GetVMStatus is not supported
    66  func (g *grpccache) GetVMStatus() []*pb.GrpcVMStatus {
    67  	panic("ERROR: package grpccache does not support GetVMStatus")
    68  }