// createMachine generates a Machine object and associated Membership objects
// to be uploaded to the registry in the future.
347298
func createMachine(orgID, teamID, creatorID *identity.ID, name string) (
	*envelope.Machine, []envelope.Membership, error) {

	machineBody := &primitive.Machine{
		Name:        name,
		OrgID:       orgID,
		CreatedBy:   creatorID,
		Created:     time.Now().UTC(),
		DestroyedBy: nil,
		Destroyed:   nil,
		State:       primitive.MachineActiveState,
	}
	machineID, err := identity.NewMutable(machineBody)
	if err != nil {
		return nil, nil, err
	}
	machine := envelope.Machine{
		ID:      &machineID,
		Version: 1,
		Body:    machineBody,
	}

	machineTeamID := identity.DeriveMutable(&primitive.Team{}, orgID, primitive.DerivableMachineTeamSymbol)
	teamIDList := []*identity.ID{&machineTeamID, teamID}
	var memberships []envelope.Membership
	for _, curTeamID := range teamIDList {
		body := primitive.Membership{
			OwnerID: &machineID,
			OrgID:   orgID,
			TeamID:  curTeamID,
		}

		ID, err := identity.NewMutable(&body)
		if err != nil {
			return nil, nil, err
		}

		membership := envelope.Membership{
			ID:      &ID,
			Version: 1,
			Body:    &body,
		}
		memberships = append(memberships, membership)
	}

	return &machine, memberships, nil
}
48644
func (c *CloudAPI) CreateMachine(name, pkg, image string, networks []string, metadata, tags map[string]string) (*cloudapi.Machine, error) {
	if err := c.ProcessFunctionHook(c, name, pkg, image); err != nil {
		return nil, err
	}

	machineID, err := localservices.NewUUID()
	if err != nil {
		return nil, err
	}

	mPkg, err := c.GetPackage(pkg)
	if err != nil {
		return nil, err
	}

	mImg, err := c.GetImage(image)
	if err != nil {
		return nil, err
	}

	mNetworks := []string{}
	for _, network := range networks {
		mNetwork, err := c.GetNetwork(network)
		if err != nil {
			return nil, err
		}

		mNetworks = append(mNetworks, mNetwork.Id)
	}

	publicIP := generatePublicIPAddress()

	newMachine := cloudapi.Machine{
		Id:        machineID,
		Name:      name,
		Type:      mImg.Type,
		State:     "running",
		Memory:    mPkg.Memory,
		Disk:      mPkg.Disk,
		IPs:       []string{publicIP, generatePrivateIPAddress()},
		Created:   time.Now().Format("2013-11-26T19:47:13.448Z"),
		Package:   pkg,
		Image:     image,
		Metadata:  metadata,
		Tags:      tags,
		PrimaryIP: publicIP,
		Networks:  mNetworks,
	}

	nics := map[string]*cloudapi.NIC{}
	nicNetworks := map[string]string{}
	for i, network := range mNetworks {
		mac, err := localservices.NewMAC()
		if err != nil {
			return nil, err
		}

		nics[mac] = &cloudapi.NIC{
			IP:      fmt.Sprintf("10.88.88.%d", i),
			MAC:     mac,
			Primary: i == 0,
			Netmask: "255.255.255.0",
			Gateway: "10.88.88.2",
			State:   cloudapi.NICStateRunning,
			Network: network,
		}
		nicNetworks[mac] = network
	}

	c.machines = append(c.machines, &machine{newMachine, nics, nicNetworks})

	return &newMachine, nil
}
1360771
func WithMachineID(machineID int) IDGeneratorOp {
	return func(g *IDGenerator) {
		g.Generator = snowflake.New(machineID & 1023)
	}
}
839600
func machinedRegister() bool {
	// machined has a D-Bus interface following versioning guidelines, see:
	// http://www.freedesktop.org/wiki/Software/systemd/machined/
	// Therefore we can just check if the D-Bus method we need exists and we
	// don't need to check the signature.
	var found int

	conn, err := dbus.SystemBus()
	if err != nil {
		return false
	}
	node, err := introspect.Call(conn.Object("org.freedesktop.machine1", "/org/freedesktop/machine1"))
	if err != nil {
		return false
	}
	for _, iface := range node.Interfaces {
		if iface.Name != "org.freedesktop.machine1.Manager" {
			continue
		}
		// machined v215 supports methods "RegisterMachine" and "CreateMachine" called by nspawn v215.
		// machined v216+ (since commit 5aa4bb) additionally supports methods "CreateMachineWithNetwork"
		// and "RegisterMachineWithNetwork", called by nspawn v216+.
		for _, method := range iface.Methods {
			if method.Name == "CreateMachineWithNetwork" || method.Name == "RegisterMachineWithNetwork" {
				found++
			}
		}
		break
	}
	return found == 2
}
908715
func (c *statusContext) processMachine(machine *state.Machine) (out params.DetailedStatus) {
	wrapped := &contextMachine{machine, c}
	statusInfo, err := c.presence.MachineStatus(wrapped)
	populateStatusFromStatusInfoAndErr(&out, statusInfo, err)

	out.Life = processLife(machine)

	if t, err := machine.AgentTools(); err == nil {
		out.Version = t.Version.Number.String()
	}
	return
}
263597
func (c *Client) Machine(tag names.MachineTag) (MutaterMachine, error) {
	life, err := common.OneLife(c.facade, tag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &Machine{c.facade, tag, life}, nil
}
1225282
func (p *Provider) CreateMachine() (machine *iaas.Machine, err error) {
	err = p.Client.Create(p.Host)
	if err != nil {
		return
	}
	config, err := getConfig(p.Client.GetMachinesDir(), p.Name)
	if err != nil {
		return
	}
	ip, err := p.Host.Driver.GetIP()
	if err != nil {
		return
	}

	machine = &iaas.Machine{
		ID:        "",
		IP:        ip,
		Image:     config.Driver.MachineImage,
		Kind:      config.DriverName,
		Name:      p.Name,
		SSHKeysID: []int{},
		CertsDir:  p.ClientPath + "/certs",
	}
	return
}
1038448
func (vb *VirtualBox) FindMachine(nameOrID string) (*Machine, error) {
	if err := vb.assertMobRef(); err != nil {
		return nil, err
	}

	request := findMachineRequest{VbID: vb.mobref, NameOrID: nameOrID}
	response := new(findMachineResponse)
	err := vb.send(request, response)
	if err != nil {
		return nil, err
	}

	m := &Machine{mobref: response.Returnval, vb: vb}
	return m, nil
}
1229047
func (c *Client) CreateMacro(ctx context.Context, macro *platform.Macro) error {
	op := getOp(platform.OpCreateMacro)
	return c.db.Update(func(tx *bolt.Tx) error {
		macro.ID = c.IDGenerator.ID()
		if pe := c.putMacro(ctx, tx, macro); pe != nil {
			return &platform.Error{
				Op:  op,
				Err: pe,
			}

		}
		return nil
	})
}
946706
func ApplicationMachines(st *State, application string) ([]string, error) {
	machines, err := st.AllMachines()
	if err != nil {
		return nil, err
	}
	applicationName := unitAppName(application)
	var machineIds []string
	for _, machine := range machines {
		principalSet := set.NewStrings()
		for _, principal := range machine.Principals() {
			principalSet.Add(unitAppName(principal))
		}
		if principalSet.Contains(applicationName) {
			machineIds = append(machineIds, machine.Id())
		}
	}
	return machineIds, nil
}
976163
func (c *Conn) DescribeMachine(name string) (machineProps map[string]interface{}, err error) {
	var dbusProps map[string]dbus.Variant
	path, pathErr := c.GetMachine(name)
	if pathErr != nil {
		return nil, pathErr
	}
	obj := c.conn.Object("org.freedesktop.machine1", path)
	err = obj.Call("org.freedesktop.DBus.Properties.GetAll", 0, "").Store(&dbusProps)
	if err != nil {
		return nil, err
	}
	machineProps = make(map[string]interface{}, len(dbusProps))
	for key, val := range dbusProps {
		machineProps[key] = val.Value()
	}
	return
}
347528
func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) {
	defer func() {
		if machineId != "" && err != nil {
			logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err)
			if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil {
				logger.Errorf("error cleaning up machine: %s", cleanupErr)
			}
			machineId = ""
		}
	}()

	// Create the "ubuntu" user and initialise passwordless sudo. We populate
	// the ubuntu user's authorized_keys file with the public keys in the current
	// user's ~/.ssh directory. The authenticationworker will later update the
	// ubuntu user's authorized_keys.
	if err = InitUbuntuUser(args.Host, args.User,
		args.AuthorizedKeys, args.Stdin, args.Stdout); err != nil {
		return "", err
	}

	machineParams, err := gatherMachineParams(args.Host)
	if err != nil {
		return "", err
	}

	// Inform Juju that the machine exists.
	machineId, err = manual.RecordMachineInState(args.Client, *machineParams)
	if err != nil {
		return "", err
	}

	provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{
		MachineId:              machineId,
		Nonce:                  machineParams.Nonce,
		DisablePackageCommands: !args.EnableOSRefreshUpdate && !args.EnableOSUpgrade,
	})

	if err != nil {
		logger.Errorf("cannot obtain provisioning script")
		return "", err
	}

	// Finally, provision the machine agent.
	err = runProvisionScript(provisioningScript, args.Host, args.Stderr)
	if err != nil {
		return machineId, err
	}

	logger.Infof("Provisioned machine %v", machineId)
	return machineId, nil
}
185906
func (client *Client) AddMachines(machineParams []params.AddMachineParams) ([]params.AddMachinesResult, error) {
	args := params.AddMachines{
		MachineParams: machineParams,
	}
	results := new(params.AddMachinesResults)
	err := client.facade.FacadeCall("AddMachines", args, results)
	if len(results.Machines) != len(machineParams) {
		return nil, errors.Errorf("expected %d result, got %d", len(machineParams), len(results.Machines))
	}
	return results.Machines, err
}
1103
func (client *Client) DestroyMachines(machines ...string) ([]params.DestroyMachineResult, error) {
	return client.destroyMachines("DestroyMachine", machines)
}
796736
func (c *Client) CreateMachineSnapshot(machineID string, opts SnapshotOpts) (*Snapshot, error) {
	var resp Snapshot
	req := request{
		method:         client.POST,
		url:            makeURL(apiMachines, machineID, apiSnapshots),
		reqValue:       opts,
		resp:           &resp,
		expectedStatus: http.StatusCreated,
	}
	if _, err := c.sendRequest(req); err != nil {
		return nil, errors.Newf(err, "failed to create snapshot %s from machine with id %s", opts.Name, machineID)
	}
	return &resp, nil
}
1162921
func commonApplicationMachineId(st *state.State, m *state.Machine) ([]string, error) {
	applications := m.Principals()
	var union set.Strings
	for _, app := range applications {
		machines, err := state.ApplicationMachines(st, app)
		if err != nil {
			return nil, err
		}
		union = union.Union(set.NewStrings(machines...))
	}
	union.Remove(m.Id())
	return union.SortedValues(), nil
}
1002636
func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) {
	defer func() {
		if machineId != "" && err != nil {
			logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err)
			if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil {
				logger.Errorf("error cleaning up machine: %s", cleanupErr)
			}
			machineId = ""
		}
	}()

	if err = InitAdministratorUser(&args); err != nil {
		return "", errors.Annotatef(err,
			"Cannot provision machine because no WinRM http/https standard listener is enabled for user %q, on host %q",
			args.User, args.Host)
	}

	machineParams, err := gatherMachineParams(args.Host, args.WinRM.Client)
	if err != nil {
		return "", err
	}

	machineId, err = manual.RecordMachineInState(args.Client, *machineParams)
	if err != nil {
		return "", err
	}

	provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{
		MachineId:              machineId,
		Nonce:                  machineParams.Nonce,
		DisablePackageCommands: true,
	})

	if err != nil {
		return "", err
	}

	// Finally, provision the machine agent.
	err = runProvisionScript(provisioningScript, args.WinRM.Client, args.Stdout, args.Stderr)
	if err != nil {
		return "", err
	}

	logger.Infof("Provisioned machine %v", machineId)
	return machineId, nil
}