Пример #1
0
Файл: list.go Проект: vmware/vic
func (l *List) prettyPrint(cli *cli.Context, ctx context.Context, vchs []*vm.VirtualMachine, executor *management.Dispatcher) {
	data := []items{
		{"ID", "PATH", "NAME", "VERSION", "UPGRADE STATUS"},
	}
	installerVer := version.GetBuild()
	for _, vch := range vchs {

		vchConfig, err := executor.GetVCHConfig(vch)
		var version string
		if err != nil {
			log.Error("Failed to get Virtual Container Host configuration")
			log.Error(err)
			version = "unknown"
		} else {
			version = vchConfig.Version.ShortVersion()
		}

		parentPath := path.Dir(path.Dir(vch.InventoryPath))
		name := path.Base(vch.InventoryPath)
		upgradeStatus := l.upgradeStatusMessage(ctx, vch, installerVer, vchConfig.Version)
		data = append(data,
			items{vch.Reference().Value, parentPath, name, version, upgradeStatus})
	}
	t := template.New("vic-machine ls")
	t, _ = t.Parse(templ)
	w := tabwriter.NewWriter(cli.App.Writer, 8, 8, 8, ' ', 0)
	if err := t.Execute(w, data); err != nil {
		log.Fatal(err)
	}
	w.Flush()
}
Пример #2
0
func (i *Images) checkImageVersion(img string, force bool) (string, error) {
	defer trace.End(trace.Begin(""))

	ver, err := i.GetImageVersion(img)
	if err != nil {
		return "", err
	}
	sv := i.getNoCommitHashVersion(ver)
	if sv == "" {
		log.Debugf("Version is not set in %q", img)
		ver = ""
	}

	installerSV := i.getNoCommitHashVersion(version.GetBuild().ShortVersion())

	// here compare version without last commit hash, to make developer life easier
	if !strings.EqualFold(installerSV, sv) {
		message := fmt.Sprintf("iso file %q version %q inconsistent with installer version %q", img, strings.ToLower(ver), version.GetBuild().ShortVersion())
		if !force {
			return "", errors.Errorf("%s. Specify --force to force create. ", message)
		}
		log.Warn(message)
	}
	return ver, nil
}
Пример #3
0
func (v *Validator) basics(ctx context.Context, input *data.Data, conf *config.VirtualContainerHostConfigSpec) {
	defer trace.End(trace.Begin(""))

	// TODO: ensure that displayname doesn't violate constraints (length, characters, etc)
	conf.SetName(input.DisplayName)
	conf.SetDebug(input.Debug.Debug)
	conf.Name = input.DisplayName
	conf.Version = version.GetBuild()

	scratchSize, err := units.FromHumanSize(input.ScratchSize)
	if err != nil { // TODO set minimum size of scratch disk
		v.NoteIssue(errors.Errorf("Invalid default image size %s provided; error from parser: %s", input.ScratchSize, err.Error()))
	} else {
		conf.ScratchSize = scratchSize / units.KB
		log.Debugf("Setting scratch image size to %d KB in VCHConfig", conf.ScratchSize)
	}

}
Пример #4
0
func (v *Validator) assertVersion(conf *config.VirtualContainerHostConfigSpec) {
	defer trace.End(trace.Begin(""))
	if conf.Version == nil {
		v.NoteIssue(errors.Errorf("Unknown version of VCH %q", conf.Name))
		return
	}
	installerBuild := version.GetBuild()
	if installerBuild.Equal(conf.Version) {
		v.NoteIssue(errors.Errorf("%q has same version as installer. No upgrade is available.", conf.Name))
		return
	}
	older, err := installerBuild.IsOlder(conf.Version)
	if err != nil {
		v.NoteIssue(errors.Errorf("Failed to compare VCH version %q with installer version %q: %s", conf.Version.ShortVersion(), installerBuild.ShortVersion(), err))
		return
	}
	if older {
		v.NoteIssue(errors.Errorf("VCH version %q is newer than installer version %q", conf.Version.ShortVersion(), installerBuild.ShortVersion()))
		return
	}
}
Пример #5
0
// CreateHandler creates a new container
func (handler *ContainersHandlersImpl) CreateHandler(params containers.CreateParams) middleware.Responder {
	defer trace.End(trace.Begin(""))

	var err error

	session := handler.handlerCtx.Session

	ctx := context.Background()

	log.Debugf("Path: %#v", params.CreateConfig.Path)
	log.Debugf("Args: %#v", params.CreateConfig.Args)
	log.Debugf("Env: %#v", params.CreateConfig.Env)
	log.Debugf("WorkingDir: %#v", params.CreateConfig.WorkingDir)
	id := uid.New().String()

	// Init key for tether
	privateKey, err := rsa.GenerateKey(rand.Reader, 512)
	if err != nil {
		return containers.NewCreateNotFound().WithPayload(&models.Error{Message: err.Error()})
	}
	privateKeyBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   x509.MarshalPKCS1PrivateKey(privateKey),
	}

	m := &executor.ExecutorConfig{
		Common: executor.Common{
			ID:   id,
			Name: *params.CreateConfig.Name,
		},
		CreateTime: time.Now().UTC().Unix(),
		Version:    version.GetBuild(),
		Sessions: map[string]*executor.SessionConfig{
			id: &executor.SessionConfig{
				Common: executor.Common{
					ID:   id,
					Name: *params.CreateConfig.Name,
				},
				Tty:    *params.CreateConfig.Tty,
				Attach: *params.CreateConfig.Attach,
				Cmd: executor.Cmd{
					Env:  params.CreateConfig.Env,
					Dir:  *params.CreateConfig.WorkingDir,
					Path: *params.CreateConfig.Path,
					Args: append([]string{*params.CreateConfig.Path}, params.CreateConfig.Args...),
				},
				StopSignal: *params.CreateConfig.StopSignal,
			},
		},
		Key:      pem.EncodeToMemory(&privateKeyBlock),
		LayerID:  *params.CreateConfig.Image,
		RepoName: *params.CreateConfig.RepoName,
	}

	if params.CreateConfig.Annotations != nil && len(params.CreateConfig.Annotations) > 0 {
		m.Annotations = make(map[string]string)
		for k, v := range params.CreateConfig.Annotations {
			m.Annotations[k] = v
		}
	}

	log.Infof("CreateHandler Metadata: %#v", m)

	// Create the executor.ExecutorCreateConfig
	c := &exec.ContainerCreateConfig{
		Metadata:       m,
		ParentImageID:  *params.CreateConfig.Image,
		ImageStoreName: params.CreateConfig.ImageStore.Name,
		Resources: exec.Resources{
			NumCPUs:  *params.CreateConfig.NumCpus,
			MemoryMB: *params.CreateConfig.MemoryMB,
		},
	}

	h, err := exec.Create(ctx, session, c)
	if err != nil {
		log.Errorf("ContainerCreate error: %s", err.Error())
		return containers.NewCreateNotFound().WithPayload(&models.Error{Message: err.Error()})
	}

	//  send the container id back to the caller
	return containers.NewCreateOK().WithPayload(&models.ContainerCreatedInfo{ID: id, Handle: h.String()})
}
Пример #6
0
Файл: main.go Проект: vmware/vic
func main() {
	app := cli.NewApp()

	app.Name = filepath.Base(os.Args[0])
	app.Usage = "Create and manage Virtual Container Hosts"
	app.EnableBashCompletion = true

	create := create.NewCreate()
	uninstall := uninstall.NewUninstall()
	inspect := inspect.NewInspect()
	list := list.NewList()
	upgrade := upgrade.NewUpgrade()
	debug := debug.NewDebug()
	app.Commands = []cli.Command{
		{
			Name:   "create",
			Usage:  "Deploy VCH",
			Action: create.Run,
			Flags:  create.Flags(),
		},
		{
			Name:   "delete",
			Usage:  "Delete VCH and associated resources",
			Action: uninstall.Run,
			Flags:  uninstall.Flags(),
		},
		{
			Name:   "ls",
			Usage:  "List VCHs",
			Action: list.Run,
			Flags:  list.Flags(),
		},
		{
			Name:   "inspect",
			Usage:  "Inspect VCH",
			Action: inspect.Run,
			Flags:  inspect.Flags(),
		},
		{
			Name:   "upgrade",
			Usage:  "Upgrade VCH to latest version",
			Action: upgrade.Run,
			Flags:  upgrade.Flags(),
		},
		{
			Name:   "version",
			Usage:  "Show VIC version information",
			Action: showVersion,
		},
		{
			Name:   "debug",
			Usage:  "Debug VCH",
			Action: debug.Run,
			Flags:  debug.Flags(),
		},
	}

	app.Version = version.GetBuild().ShortVersion()

	logs := []io.Writer{app.Writer}
	// Open log file
	f, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error opening logfile %s: %v\n", LogFile, err)
	} else {
		defer f.Close()
		logs = append(logs, f)
	}

	// Initiliaze logger with default TextFormatter
	log.SetFormatter(&log.TextFormatter{ForceColors: true, FullTimestamp: true})
	// SetOutput to io.MultiWriter so that we can log to stdout and a file
	log.SetOutput(io.MultiWriter(logs...))

	if err := app.Run(os.Args); err != nil {
		log.Errorf("--------------------")
		log.Errorf("%s failed: %s\n", app.Name, errors.ErrorStack(err))
		os.Exit(1)
	}
}
Пример #7
0
func (v *Validator) migrateData(ctx context.Context, conf *config.VirtualContainerHostConfigSpec) (*config.VirtualContainerHostConfigSpec, error) {
	conf.Version = version.GetBuild()
	return conf, nil
}
Пример #8
0
func (d *Debug) Run(cli *cli.Context) error {
	var err error
	if err = d.processParams(); err != nil {
		return err
	}

	if d.Debug.Debug > 0 {
		log.SetLevel(log.DebugLevel)
		trace.Logger.Level = log.DebugLevel
	}

	if len(cli.Args()) > 0 {
		log.Errorf("Unknown argument: %s", cli.Args()[0])
		return errors.New("invalid CLI arguments")
	}

	log.Infof("### Configuring VCH for debug ####")

	ctx, cancel := context.WithTimeout(context.Background(), d.Timeout)
	defer cancel()

	validator, err := validate.NewValidator(ctx, d.Data)
	if err != nil {
		log.Errorf("Debug cannot continue - failed to create validator: %s", err)
		return errors.New("Debug failed")
	}
	executor := management.NewDispatcher(validator.Context, validator.Session, nil, d.Force)

	var vch *vm.VirtualMachine
	if d.Data.ID != "" {
		vch, err = executor.NewVCHFromID(d.Data.ID)
	} else {
		vch, err = executor.NewVCHFromComputePath(d.Data.ComputeResourcePath, d.Data.DisplayName, validator)
	}
	if err != nil {
		log.Errorf("Failed to get Virtual Container Host %s", d.DisplayName)
		log.Error(err)
		return errors.New("Debug failed")
	}

	log.Infof("")
	log.Infof("VCH ID: %s", vch.Reference().String())

	vchConfig, err := executor.GetVCHConfig(vch)
	if err != nil {
		log.Error("Failed to get Virtual Container Host configuration")
		log.Error(err)
		return errors.New("Debug failed")
	}
	executor.InitDiagnosticLogs(vchConfig)

	installerVer := version.GetBuild()

	log.Info("")
	log.Infof("Installer version: %s", installerVer.ShortVersion())
	log.Infof("VCH version: %s", vchConfig.Version.ShortVersion())

	// load the key file if set
	var key []byte
	if d.authorizedKey != "" {
		key, err = ioutil.ReadFile(d.authorizedKey)
		if err != nil {
			log.Errorf("Unable to read public key from %s: %s", d.authorizedKey, err)
			return errors.New("unable to load public key")
		}
	}

	if err = executor.DebugVCH(vch, vchConfig, d.password, string(key)); err != nil {
		executor.CollectDiagnosticLogs()
		log.Errorf("%s", err)
		return errors.New("Debug failed")
	}

	// display the VCH endpoints again for convenience
	if err = executor.InspectVCH(vch, vchConfig); err != nil {
		executor.CollectDiagnosticLogs()
		log.Errorf("%s", err)
		return errors.New("inspect failed")
	}

	log.Infof("Completed successfully")

	return nil
}
Пример #9
0
func (i *Inspect) Run(cli *cli.Context) error {
	var err error
	if err = i.processParams(); err != nil {
		return err
	}

	if i.Debug.Debug > 0 {
		log.SetLevel(log.DebugLevel)
		trace.Logger.Level = log.DebugLevel
	}

	if len(cli.Args()) > 0 {
		log.Errorf("Unknown argument: %s", cli.Args()[0])
		return errors.New("invalid CLI arguments")
	}

	log.Infof("### Inspecting VCH ####")

	ctx, cancel := context.WithTimeout(context.Background(), i.Timeout)
	defer cancel()

	validator, err := validate.NewValidator(ctx, i.Data)
	if err != nil {
		log.Errorf("Inspect cannot continue - failed to create validator: %s", err)
		return errors.New("inspect failed")
	}
	executor := management.NewDispatcher(validator.Context, validator.Session, nil, i.Force)

	var vch *vm.VirtualMachine
	if i.Data.ID != "" {
		vch, err = executor.NewVCHFromID(i.Data.ID)
	} else {
		vch, err = executor.NewVCHFromComputePath(i.Data.ComputeResourcePath, i.Data.DisplayName, validator)
	}
	if err != nil {
		log.Errorf("Failed to get Virtual Container Host %s", i.DisplayName)
		log.Error(err)
		return errors.New("inspect failed")
	}

	log.Infof("")
	log.Infof("VCH ID: %s", vch.Reference().String())

	vchConfig, err := executor.GetVCHConfig(vch)
	if err != nil {
		log.Error("Failed to get Virtual Container Host configuration")
		log.Error(err)
		return errors.New("inspect failed")
	}
	executor.InitDiagnosticLogs(vchConfig)

	installerVer := version.GetBuild()

	log.Info("")
	log.Infof("Installer version: %s", installerVer.ShortVersion())
	log.Infof("VCH version: %s", vchConfig.Version.ShortVersion())
	log.Info("")
	log.Info("VCH upgrade status:")
	i.upgradeStatusMessage(ctx, vch, installerVer, vchConfig.Version)

	if err = executor.InspectVCH(vch, vchConfig); err != nil {
		executor.CollectDiagnosticLogs()
		log.Errorf("%s", err)
		return errors.New("inspect failed")
	}

	log.Infof("Completed successfully")

	return nil
}