id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
165,000 | hashicorp/packer | builder/hyperv/common/driver_ps_4.go | GetVirtualMachineNetworkAdapterAddress | func (d *HypervPS4Driver) GetVirtualMachineNetworkAdapterAddress(vmName string) (string, error) {
return hyperv.GetVirtualMachineNetworkAdapterAddress(vmName)
} | go | func (d *HypervPS4Driver) GetVirtualMachineNetworkAdapterAddress(vmName string) (string, error) {
return hyperv.GetVirtualMachineNetworkAdapterAddress(vmName)
} | [
"func",
"(",
"d",
"*",
"HypervPS4Driver",
")",
"GetVirtualMachineNetworkAdapterAddress",
"(",
"vmName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"hyperv",
".",
"GetVirtualMachineNetworkAdapterAddress",
"(",
"vmName",
")",
"\n",
"}"
] | // Get network adapter address | [
"Get",
"network",
"adapter",
"address"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L136-L138 |
165,001 | hashicorp/packer | builder/hyperv/common/driver_ps_4.go | SetNetworkAdapterVlanId | func (d *HypervPS4Driver) SetNetworkAdapterVlanId(switchName string, vlanId string) error {
return hyperv.SetNetworkAdapterVlanId(switchName, vlanId)
} | go | func (d *HypervPS4Driver) SetNetworkAdapterVlanId(switchName string, vlanId string) error {
return hyperv.SetNetworkAdapterVlanId(switchName, vlanId)
} | [
"func",
"(",
"d",
"*",
"HypervPS4Driver",
")",
"SetNetworkAdapterVlanId",
"(",
"switchName",
"string",
",",
"vlanId",
"string",
")",
"error",
"{",
"return",
"hyperv",
".",
"SetNetworkAdapterVlanId",
"(",
"switchName",
",",
"vlanId",
")",
"\n",
"}"
] | //Set the vlan to use for switch | [
"Set",
"the",
"vlan",
"to",
"use",
"for",
"switch"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L141-L143 |
165,002 | hashicorp/packer | builder/hyperv/common/driver_ps_4.go | SetVirtualMachineVlanId | func (d *HypervPS4Driver) SetVirtualMachineVlanId(vmName string, vlanId string) error {
return hyperv.SetVirtualMachineVlanId(vmName, vlanId)
} | go | func (d *HypervPS4Driver) SetVirtualMachineVlanId(vmName string, vlanId string) error {
return hyperv.SetVirtualMachineVlanId(vmName, vlanId)
} | [
"func",
"(",
"d",
"*",
"HypervPS4Driver",
")",
"SetVirtualMachineVlanId",
"(",
"vmName",
"string",
",",
"vlanId",
"string",
")",
"error",
"{",
"return",
"hyperv",
".",
"SetVirtualMachineVlanId",
"(",
"vmName",
",",
"vlanId",
")",
"\n",
"}"
] | //Set the vlan to use for machine | [
"Set",
"the",
"vlan",
"to",
"use",
"for",
"machine"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L146-L148 |
165,003 | hashicorp/packer | builder/hyperv/common/driver_ps_4.go | Connect | func (d *HypervPS4Driver) Connect(vmName string) (context.CancelFunc, error) {
return hyperv.ConnectVirtualMachine(vmName)
} | go | func (d *HypervPS4Driver) Connect(vmName string) (context.CancelFunc, error) {
return hyperv.ConnectVirtualMachine(vmName)
} | [
"func",
"(",
"d",
"*",
"HypervPS4Driver",
")",
"Connect",
"(",
"vmName",
"string",
")",
"(",
"context",
".",
"CancelFunc",
",",
"error",
")",
"{",
"return",
"hyperv",
".",
"ConnectVirtualMachine",
"(",
"vmName",
")",
"\n",
"}"
] | // Connect connects to a VM specified by the name given. | [
"Connect",
"connects",
"to",
"a",
"VM",
"specified",
"by",
"the",
"name",
"given",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L373-L375 |
165,004 | hashicorp/packer | common/multistep_runner.go | NewRunner | func NewRunner(steps []multistep.Step, config PackerConfig, ui packer.Ui) multistep.Runner {
runner, _ := newRunner(steps, config, ui)
return runner
} | go | func NewRunner(steps []multistep.Step, config PackerConfig, ui packer.Ui) multistep.Runner {
runner, _ := newRunner(steps, config, ui)
return runner
} | [
"func",
"NewRunner",
"(",
"steps",
"[",
"]",
"multistep",
".",
"Step",
",",
"config",
"PackerConfig",
",",
"ui",
"packer",
".",
"Ui",
")",
"multistep",
".",
"Runner",
"{",
"runner",
",",
"_",
":=",
"newRunner",
"(",
"steps",
",",
"config",
",",
"ui",
... | // NewRunner returns a multistep.Runner that runs steps augmented with support
// for -debug and -on-error command line arguments. | [
"NewRunner",
"returns",
"a",
"multistep",
".",
"Runner",
"that",
"runs",
"steps",
"augmented",
"with",
"support",
"for",
"-",
"debug",
"and",
"-",
"on",
"-",
"error",
"command",
"line",
"arguments",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/multistep_runner.go#L39-L42 |
165,005 | hashicorp/packer | common/multistep_runner.go | NewRunnerWithPauseFn | func NewRunnerWithPauseFn(steps []multistep.Step, config PackerConfig, ui packer.Ui, state multistep.StateBag) multistep.Runner {
runner, pauseFn := newRunner(steps, config, ui)
if pauseFn != nil {
state.Put("pauseFn", pauseFn)
}
return runner
} | go | func NewRunnerWithPauseFn(steps []multistep.Step, config PackerConfig, ui packer.Ui, state multistep.StateBag) multistep.Runner {
runner, pauseFn := newRunner(steps, config, ui)
if pauseFn != nil {
state.Put("pauseFn", pauseFn)
}
return runner
} | [
"func",
"NewRunnerWithPauseFn",
"(",
"steps",
"[",
"]",
"multistep",
".",
"Step",
",",
"config",
"PackerConfig",
",",
"ui",
"packer",
".",
"Ui",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"Runner",
"{",
"runner",
",",
"pauseFn",
":=... | // NewRunnerWithPauseFn returns a multistep.Runner that runs steps augmented
// with support for -debug and -on-error command line arguments. With -debug it
// puts the multistep.DebugPauseFn that will pause execution between steps into
// the state under the key "pauseFn". | [
"NewRunnerWithPauseFn",
"returns",
"a",
"multistep",
".",
"Runner",
"that",
"runs",
"steps",
"augmented",
"with",
"support",
"for",
"-",
"debug",
"and",
"-",
"on",
"-",
"error",
"command",
"line",
"arguments",
".",
"With",
"-",
"debug",
"it",
"puts",
"the",
... | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/multistep_runner.go#L48-L54 |
165,006 | hashicorp/packer | builder/amazon/common/errors.go | decodeAWSError | func decodeAWSError(decoder stsDecoder, err error) error {
groups := encodedFailureMessagePattern.FindStringSubmatch(err.Error())
if groups != nil && len(groups) > 1 {
result, decodeErr := decoder.DecodeAuthorizationMessage(&sts.DecodeAuthorizationMessageInput{
EncodedMessage: aws.String(groups[2]),
})
if decodeErr == nil {
msg := aws.StringValue(result.DecodedMessage)
return fmt.Errorf("%s Authorization failure message: '%s'%s", groups[1], msg, groups[3])
}
log.Printf("[WARN] Attempted to decode authorization message, but received: %v", decodeErr)
}
return err
} | go | func decodeAWSError(decoder stsDecoder, err error) error {
groups := encodedFailureMessagePattern.FindStringSubmatch(err.Error())
if groups != nil && len(groups) > 1 {
result, decodeErr := decoder.DecodeAuthorizationMessage(&sts.DecodeAuthorizationMessageInput{
EncodedMessage: aws.String(groups[2]),
})
if decodeErr == nil {
msg := aws.StringValue(result.DecodedMessage)
return fmt.Errorf("%s Authorization failure message: '%s'%s", groups[1], msg, groups[3])
}
log.Printf("[WARN] Attempted to decode authorization message, but received: %v", decodeErr)
}
return err
} | [
"func",
"decodeAWSError",
"(",
"decoder",
"stsDecoder",
",",
"err",
"error",
")",
"error",
"{",
"groups",
":=",
"encodedFailureMessagePattern",
".",
"FindStringSubmatch",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"if",
"groups",
"!=",
"nil",
"&&",
"len"... | // decodeError replaces encoded authorization messages with the
// decoded results | [
"decodeError",
"replaces",
"encoded",
"authorization",
"messages",
"with",
"the",
"decoded",
"results"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/errors.go#L24-L38 |
165,007 | hashicorp/packer | builder/amazon/common/errors.go | DecodeAuthZMessages | func DecodeAuthZMessages(sess *session.Session) {
azd := &authZMessageDecoder{
Decoder: sts.New(sess),
}
sess.Handlers.UnmarshalError.AfterEachFn = azd.afterEachFn
} | go | func DecodeAuthZMessages(sess *session.Session) {
azd := &authZMessageDecoder{
Decoder: sts.New(sess),
}
sess.Handlers.UnmarshalError.AfterEachFn = azd.afterEachFn
} | [
"func",
"DecodeAuthZMessages",
"(",
"sess",
"*",
"session",
".",
"Session",
")",
"{",
"azd",
":=",
"&",
"authZMessageDecoder",
"{",
"Decoder",
":",
"sts",
".",
"New",
"(",
"sess",
")",
",",
"}",
"\n",
"sess",
".",
"Handlers",
".",
"UnmarshalError",
".",
... | // DecodeAuthZMessages enables automatic decoding of any
// encoded authorization messages | [
"DecodeAuthZMessages",
"enables",
"automatic",
"decoding",
"of",
"any",
"encoded",
"authorization",
"messages"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/errors.go#L42-L47 |
165,008 | hashicorp/packer | builder/triton/access_config.go | Prepare | func (c *AccessConfig) Prepare(ctx *interpolate.Context) []error {
var errs []error
if c.Endpoint == "" {
// Use Joyent public cloud as the default endpoint if none is specified
c.Endpoint = "https://us-sw-1.api.joyent.com"
}
if c.Account == "" {
errs = append(errs, errors.New("triton_account is required to use the triton builder"))
}
if c.KeyID == "" {
errs = append(errs, errors.New("triton_key_id is required to use the triton builder"))
}
if c.KeyMaterial == "" {
signer, err := c.createSSHAgentSigner()
if err != nil {
errs = append(errs, err)
}
c.signer = signer
} else {
signer, err := c.createPrivateKeySigner()
if err != nil {
errs = append(errs, err)
}
c.signer = signer
}
if len(errs) > 0 {
return errs
}
return nil
} | go | func (c *AccessConfig) Prepare(ctx *interpolate.Context) []error {
var errs []error
if c.Endpoint == "" {
// Use Joyent public cloud as the default endpoint if none is specified
c.Endpoint = "https://us-sw-1.api.joyent.com"
}
if c.Account == "" {
errs = append(errs, errors.New("triton_account is required to use the triton builder"))
}
if c.KeyID == "" {
errs = append(errs, errors.New("triton_key_id is required to use the triton builder"))
}
if c.KeyMaterial == "" {
signer, err := c.createSSHAgentSigner()
if err != nil {
errs = append(errs, err)
}
c.signer = signer
} else {
signer, err := c.createPrivateKeySigner()
if err != nil {
errs = append(errs, err)
}
c.signer = signer
}
if len(errs) > 0 {
return errs
}
return nil
} | [
"func",
"(",
"c",
"*",
"AccessConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"var",
"errs",
"[",
"]",
"error",
"\n\n",
"if",
"c",
".",
"Endpoint",
"==",
"\"",
"\"",
"{",
"// Use Joyent public cloud... | // Prepare performs basic validation on the AccessConfig and ensures we can sign
// a request. | [
"Prepare",
"performs",
"basic",
"validation",
"on",
"the",
"AccessConfig",
"and",
"ensures",
"we",
"can",
"sign",
"a",
"request",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/triton/access_config.go#L32-L67 |
165,009 | hashicorp/packer | builder/cloudstack/artifact.go | Destroy | func (a *Artifact) Destroy() error {
// Create a new parameter struct.
p := a.client.Template.NewDeleteTemplateParams(a.template.Id)
// Destroy the template.
log.Printf("Destroying template: %s", a.template.Name)
_, err := a.client.Template.DeleteTemplate(p)
if err != nil {
// This is a very poor way to be told the ID does no longer exist :(
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", a.template.Id)) {
return nil
}
return fmt.Errorf("Error destroying template %s: %s", a.template.Name, err)
}
return nil
} | go | func (a *Artifact) Destroy() error {
// Create a new parameter struct.
p := a.client.Template.NewDeleteTemplateParams(a.template.Id)
// Destroy the template.
log.Printf("Destroying template: %s", a.template.Name)
_, err := a.client.Template.DeleteTemplate(p)
if err != nil {
// This is a very poor way to be told the ID does no longer exist :(
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", a.template.Id)) {
return nil
}
return fmt.Errorf("Error destroying template %s: %s", a.template.Name, err)
}
return nil
} | [
"func",
"(",
"a",
"*",
"Artifact",
")",
"Destroy",
"(",
")",
"error",
"{",
"// Create a new parameter struct.",
"p",
":=",
"a",
".",
"client",
".",
"Template",
".",
"NewDeleteTemplateParams",
"(",
"a",
".",
"template",
".",
"Id",
")",
"\n\n",
"// Destroy the... | // Destroy the CloudStack template represented by the artifact. | [
"Destroy",
"the",
"CloudStack",
"template",
"represented",
"by",
"the",
"artifact",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/cloudstack/artifact.go#L24-L43 |
165,010 | hashicorp/packer | builder/googlecompute/step_instance_info.go | Run | func (s *StepInstanceInfo) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
instanceName := state.Get("instance_name").(string)
ui.Say("Waiting for the instance to become running...")
errCh := driver.WaitForInstance("RUNNING", config.Zone, instanceName)
var err error
select {
case err = <-errCh:
case <-time.After(config.stateTimeout):
err = errors.New("time out while waiting for instance to become running")
}
if err != nil {
err := fmt.Errorf("Error waiting for instance: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if config.UseInternalIP {
ip, err := driver.GetInternalIP(config.Zone, instanceName)
if err != nil {
err := fmt.Errorf("Error retrieving instance internal ip address: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if s.Debug {
if ip != "" {
ui.Message(fmt.Sprintf("Internal IP: %s", ip))
}
}
ui.Message(fmt.Sprintf("IP: %s", ip))
state.Put("instance_ip", ip)
return multistep.ActionContinue
} else {
ip, err := driver.GetNatIP(config.Zone, instanceName)
if err != nil {
err := fmt.Errorf("Error retrieving instance nat ip address: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if s.Debug {
if ip != "" {
ui.Message(fmt.Sprintf("Public IP: %s", ip))
}
}
ui.Message(fmt.Sprintf("IP: %s", ip))
state.Put("instance_ip", ip)
return multistep.ActionContinue
}
} | go | func (s *StepInstanceInfo) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
instanceName := state.Get("instance_name").(string)
ui.Say("Waiting for the instance to become running...")
errCh := driver.WaitForInstance("RUNNING", config.Zone, instanceName)
var err error
select {
case err = <-errCh:
case <-time.After(config.stateTimeout):
err = errors.New("time out while waiting for instance to become running")
}
if err != nil {
err := fmt.Errorf("Error waiting for instance: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if config.UseInternalIP {
ip, err := driver.GetInternalIP(config.Zone, instanceName)
if err != nil {
err := fmt.Errorf("Error retrieving instance internal ip address: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if s.Debug {
if ip != "" {
ui.Message(fmt.Sprintf("Internal IP: %s", ip))
}
}
ui.Message(fmt.Sprintf("IP: %s", ip))
state.Put("instance_ip", ip)
return multistep.ActionContinue
} else {
ip, err := driver.GetNatIP(config.Zone, instanceName)
if err != nil {
err := fmt.Errorf("Error retrieving instance nat ip address: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if s.Debug {
if ip != "" {
ui.Message(fmt.Sprintf("Public IP: %s", ip))
}
}
ui.Message(fmt.Sprintf("IP: %s", ip))
state.Put("instance_ip", ip)
return multistep.ActionContinue
}
} | [
"func",
"(",
"s",
"*",
"StepInstanceInfo",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"config",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"... | // Run executes the Packer build step that gathers GCE instance info.
// This adds "instance_ip" to the multistep state. | [
"Run",
"executes",
"the",
"Packer",
"build",
"step",
"that",
"gathers",
"GCE",
"instance",
"info",
".",
"This",
"adds",
"instance_ip",
"to",
"the",
"multistep",
"state",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_instance_info.go#L20-L78 |
165,011 | hashicorp/packer | builder/googlecompute/step_wait_startup_script.go | Run | func (s *StepWaitStartupScript) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
instanceName := state.Get("instance_name").(string)
ui.Say("Waiting for any running startup script to finish...")
// Keep checking the serial port output to see if the startup script is done.
err := retry.Config{
ShouldRetry: func(error) bool {
return true
},
RetryDelay: (&retry.Backoff{InitialBackoff: 10 * time.Second, MaxBackoff: 60 * time.Second, Multiplier: 2}).Linear,
}.Run(ctx, func(ctx context.Context) error {
status, err := driver.GetInstanceMetadata(config.Zone,
instanceName, StartupScriptStatusKey)
if err != nil {
err := fmt.Errorf("Error getting startup script status: %s", err)
return err
}
if status == StartupScriptStatusError {
err = errors.New("Startup script error.")
return err
}
done := status == StartupScriptStatusDone
if !done {
ui.Say("Startup script not finished yet. Waiting...")
return errors.New("Startup script not done.")
}
return nil
})
if err != nil {
err := fmt.Errorf("Error waiting for startup script to finish: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("Startup script, if any, has finished running.")
return multistep.ActionContinue
} | go | func (s *StepWaitStartupScript) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
instanceName := state.Get("instance_name").(string)
ui.Say("Waiting for any running startup script to finish...")
// Keep checking the serial port output to see if the startup script is done.
err := retry.Config{
ShouldRetry: func(error) bool {
return true
},
RetryDelay: (&retry.Backoff{InitialBackoff: 10 * time.Second, MaxBackoff: 60 * time.Second, Multiplier: 2}).Linear,
}.Run(ctx, func(ctx context.Context) error {
status, err := driver.GetInstanceMetadata(config.Zone,
instanceName, StartupScriptStatusKey)
if err != nil {
err := fmt.Errorf("Error getting startup script status: %s", err)
return err
}
if status == StartupScriptStatusError {
err = errors.New("Startup script error.")
return err
}
done := status == StartupScriptStatusDone
if !done {
ui.Say("Startup script not finished yet. Waiting...")
return errors.New("Startup script not done.")
}
return nil
})
if err != nil {
err := fmt.Errorf("Error waiting for startup script to finish: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("Startup script, if any, has finished running.")
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepWaitStartupScript",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"config",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"("... | // Run reads the instance metadata and looks for the log entry
// indicating the startup script finished. | [
"Run",
"reads",
"the",
"instance",
"metadata",
"and",
"looks",
"for",
"the",
"log",
"entry",
"indicating",
"the",
"startup",
"script",
"finished",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_wait_startup_script.go#L18-L63 |
165,012 | hashicorp/packer | common/shell-local/run.go | createInterpolatedCommands | func createInterpolatedCommands(config *Config, script string, flattenedEnvVars string) ([]string, error) {
config.Ctx.Data = &ExecuteCommandTemplate{
Vars: flattenedEnvVars,
Script: script,
Command: script,
WinRMPassword: getWinRMPassword(config.PackerBuildName),
}
interpolatedCmds := make([]string, len(config.ExecuteCommand))
for i, cmd := range config.ExecuteCommand {
interpolatedCmd, err := interpolate.Render(cmd, &config.Ctx)
if err != nil {
return nil, fmt.Errorf("Error processing command: %s", err)
}
interpolatedCmds[i] = interpolatedCmd
}
return interpolatedCmds, nil
} | go | func createInterpolatedCommands(config *Config, script string, flattenedEnvVars string) ([]string, error) {
config.Ctx.Data = &ExecuteCommandTemplate{
Vars: flattenedEnvVars,
Script: script,
Command: script,
WinRMPassword: getWinRMPassword(config.PackerBuildName),
}
interpolatedCmds := make([]string, len(config.ExecuteCommand))
for i, cmd := range config.ExecuteCommand {
interpolatedCmd, err := interpolate.Render(cmd, &config.Ctx)
if err != nil {
return nil, fmt.Errorf("Error processing command: %s", err)
}
interpolatedCmds[i] = interpolatedCmd
}
return interpolatedCmds, nil
} | [
"func",
"createInterpolatedCommands",
"(",
"config",
"*",
"Config",
",",
"script",
"string",
",",
"flattenedEnvVars",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"config",
".",
"Ctx",
".",
"Data",
"=",
"&",
"ExecuteCommandTemplate",
"{",
... | // Generates the final command to send to the communicator, using either the
// user-provided ExecuteCommand or defaulting to something that makes sense for
// the host OS | [
"Generates",
"the",
"final",
"command",
"to",
"send",
"to",
"the",
"communicator",
"using",
"either",
"the",
"user",
"-",
"provided",
"ExecuteCommand",
"or",
"defaulting",
"to",
"something",
"that",
"makes",
"sense",
"for",
"the",
"host",
"OS"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/shell-local/run.go#L157-L174 |
165,013 | hashicorp/packer | builder/vagrant/driver_2_2.go | Init | func (d *Vagrant_2_2_Driver) Init(args []string) error {
_, _, err := d.vagrantCmd(append([]string{"init"}, args...)...)
return err
} | go | func (d *Vagrant_2_2_Driver) Init(args []string) error {
_, _, err := d.vagrantCmd(append([]string{"init"}, args...)...)
return err
} | [
"func",
"(",
"d",
"*",
"Vagrant_2_2_Driver",
")",
"Init",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"d",
".",
"vagrantCmd",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"args",
".... | // Calls "vagrant init" | [
"Calls",
"vagrant",
"init"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/driver_2_2.go#L24-L27 |
165,014 | hashicorp/packer | builder/vagrant/driver_2_2.go | Up | func (d *Vagrant_2_2_Driver) Up(args []string) (string, string, error) {
stdout, stderr, err := d.vagrantCmd(append([]string{"up"}, args...)...)
return stdout, stderr, err
} | go | func (d *Vagrant_2_2_Driver) Up(args []string) (string, string, error) {
stdout, stderr, err := d.vagrantCmd(append([]string{"up"}, args...)...)
return stdout, stderr, err
} | [
"func",
"(",
"d",
"*",
"Vagrant_2_2_Driver",
")",
"Up",
"(",
"args",
"[",
"]",
"string",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"stdout",
",",
"stderr",
",",
"err",
":=",
"d",
".",
"vagrantCmd",
"(",
"append",
"(",
"[",
"]",
"... | // Calls "vagrant up" | [
"Calls",
"vagrant",
"up"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/driver_2_2.go#L37-L40 |
165,015 | hashicorp/packer | builder/vagrant/driver_2_2.go | Halt | func (d *Vagrant_2_2_Driver) Halt(id string) error {
args := []string{"halt"}
if id != "" {
args = append(args, id)
}
_, _, err := d.vagrantCmd(args...)
return err
} | go | func (d *Vagrant_2_2_Driver) Halt(id string) error {
args := []string{"halt"}
if id != "" {
args = append(args, id)
}
_, _, err := d.vagrantCmd(args...)
return err
} | [
"func",
"(",
"d",
"*",
"Vagrant_2_2_Driver",
")",
"Halt",
"(",
"id",
"string",
")",
"error",
"{",
"args",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"\n",
"if",
"id",
"!=",
"\"",
"\"",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"id",
")... | // Calls "vagrant halt" | [
"Calls",
"vagrant",
"halt"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/driver_2_2.go#L43-L50 |
165,016 | hashicorp/packer | builder/vagrant/driver_2_2.go | Package | func (d *Vagrant_2_2_Driver) Package(args []string) error {
args = append(args, "--output", filepath.Join(d.VagrantCWD, "package.box"))
_, _, err := d.vagrantCmd(append([]string{"package"}, args...)...)
return err
} | go | func (d *Vagrant_2_2_Driver) Package(args []string) error {
args = append(args, "--output", filepath.Join(d.VagrantCWD, "package.box"))
_, _, err := d.vagrantCmd(append([]string{"package"}, args...)...)
return err
} | [
"func",
"(",
"d",
"*",
"Vagrant_2_2_Driver",
")",
"Package",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"\"",
"\"",
",",
"filepath",
".",
"Join",
"(",
"d",
".",
"VagrantCWD",
",",
"\"",
"\"",
")",
... | // Calls "vagrant package" | [
"Calls",
"vagrant",
"package"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/driver_2_2.go#L73-L77 |
165,017 | hashicorp/packer | builder/vagrant/driver_2_2.go | Verify | func (d *Vagrant_2_2_Driver) Verify() error {
vagrantPath, err := exec.LookPath(d.vagrantBinary)
if err != nil {
return fmt.Errorf("Can't find Vagrant binary!")
}
_, err = os.Stat(vagrantPath)
if err != nil {
return fmt.Errorf("Can't find Vagrant binary.")
}
constraints, err := version.NewConstraint(VAGRANT_MIN_VERSION)
vers, err := d.Version()
v, err := version.NewVersion(vers)
if err != nil {
return fmt.Errorf("Error figuring out Vagrant version.")
}
if !constraints.Check(v) {
return fmt.Errorf("installed Vagrant version must be >=2.0.2")
}
return nil
} | go | func (d *Vagrant_2_2_Driver) Verify() error {
vagrantPath, err := exec.LookPath(d.vagrantBinary)
if err != nil {
return fmt.Errorf("Can't find Vagrant binary!")
}
_, err = os.Stat(vagrantPath)
if err != nil {
return fmt.Errorf("Can't find Vagrant binary.")
}
constraints, err := version.NewConstraint(VAGRANT_MIN_VERSION)
vers, err := d.Version()
v, err := version.NewVersion(vers)
if err != nil {
return fmt.Errorf("Error figuring out Vagrant version.")
}
if !constraints.Check(v) {
return fmt.Errorf("installed Vagrant version must be >=2.0.2")
}
return nil
} | [
"func",
"(",
"d",
"*",
"Vagrant_2_2_Driver",
")",
"Verify",
"(",
")",
"error",
"{",
"vagrantPath",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"d",
".",
"vagrantBinary",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(... | // Verify makes sure that Vagrant exists at the given path | [
"Verify",
"makes",
"sure",
"that",
"Vagrant",
"exists",
"at",
"the",
"given",
"path"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/driver_2_2.go#L80-L102 |
165,018 | hashicorp/packer | builder/vagrant/driver_2_2.go | Version | func (d *Vagrant_2_2_Driver) Version() (string, error) {
stdoutString, _, err := d.vagrantCmd([]string{"--version"}...)
// Example stdout:
// Installed Version: 2.2.3
//
// Vagrant was unable to check for the latest version of Vagrant.
// Please check manually at https://www.vagrantup.com
// Use regex to find version
reg := regexp.MustCompile(`(\d+\.)?(\d+\.)?(\*|\d+)`)
version := reg.FindString(stdoutString)
if version == "" {
return "", err
}
return version, nil
} | go | func (d *Vagrant_2_2_Driver) Version() (string, error) {
stdoutString, _, err := d.vagrantCmd([]string{"--version"}...)
// Example stdout:
// Installed Version: 2.2.3
//
// Vagrant was unable to check for the latest version of Vagrant.
// Please check manually at https://www.vagrantup.com
// Use regex to find version
reg := regexp.MustCompile(`(\d+\.)?(\d+\.)?(\*|\d+)`)
version := reg.FindString(stdoutString)
if version == "" {
return "", err
}
return version, nil
} | [
"func",
"(",
"d",
"*",
"Vagrant_2_2_Driver",
")",
"Version",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"stdoutString",
",",
"_",
",",
"err",
":=",
"d",
".",
"vagrantCmd",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"...",
")",
"\n",
"//... | // Version reads the version of VirtualBox that is installed. | [
"Version",
"reads",
"the",
"version",
"of",
"VirtualBox",
"that",
"is",
"installed",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/driver_2_2.go#L159-L176 |
165,019 | hashicorp/packer | builder/digitalocean/wait.go | waitForDropletUnlocked | func waitForDropletUnlocked(
client *godo.Client, dropletId int, timeout time.Duration) error {
done := make(chan struct{})
defer close(done)
result := make(chan error, 1)
go func() {
attempts := 0
for {
attempts += 1
log.Printf("[DEBUG] Checking droplet lock state... (attempt: %d)", attempts)
droplet, _, err := client.Droplets.Get(context.TODO(), dropletId)
if err != nil {
result <- err
return
}
if !droplet.Locked {
result <- nil
return
}
// Wait 3 seconds in between
time.Sleep(3 * time.Second)
// Verify we shouldn't exit
select {
case <-done:
// We finished, so just exit the goroutine
return
default:
// Keep going
}
}
}()
log.Printf("[DEBUG] Waiting for up to %d seconds for droplet to unlock", timeout/time.Second)
select {
case err := <-result:
return err
case <-time.After(timeout):
return fmt.Errorf(
"Timeout while waiting to for droplet to unlock")
}
} | go | func waitForDropletUnlocked(
client *godo.Client, dropletId int, timeout time.Duration) error {
done := make(chan struct{})
defer close(done)
result := make(chan error, 1)
go func() {
attempts := 0
for {
attempts += 1
log.Printf("[DEBUG] Checking droplet lock state... (attempt: %d)", attempts)
droplet, _, err := client.Droplets.Get(context.TODO(), dropletId)
if err != nil {
result <- err
return
}
if !droplet.Locked {
result <- nil
return
}
// Wait 3 seconds in between
time.Sleep(3 * time.Second)
// Verify we shouldn't exit
select {
case <-done:
// We finished, so just exit the goroutine
return
default:
// Keep going
}
}
}()
log.Printf("[DEBUG] Waiting for up to %d seconds for droplet to unlock", timeout/time.Second)
select {
case err := <-result:
return err
case <-time.After(timeout):
return fmt.Errorf(
"Timeout while waiting to for droplet to unlock")
}
} | [
"func",
"waitForDropletUnlocked",
"(",
"client",
"*",
"godo",
".",
"Client",
",",
"dropletId",
"int",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"defer",
"close",
"(",
"... | // waitForDropletUnlocked waits for the Droplet to be unlocked to
// avoid "pending" errors when making state changes. | [
"waitForDropletUnlocked",
"waits",
"for",
"the",
"Droplet",
"to",
"be",
"unlocked",
"to",
"avoid",
"pending",
"errors",
"when",
"making",
"state",
"changes",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/digitalocean/wait.go#L14-L59 |
165,020 | hashicorp/packer | post-processor/vsphere/post-processor.go | escapeWithSpaces | func escapeWithSpaces(stringToEscape string) string {
escapedString := url.QueryEscape(stringToEscape)
escapedString = strings.Replace(escapedString, "+", `%20`, -1)
return escapedString
} | go | func escapeWithSpaces(stringToEscape string) string {
escapedString := url.QueryEscape(stringToEscape)
escapedString = strings.Replace(escapedString, "+", `%20`, -1)
return escapedString
} | [
"func",
"escapeWithSpaces",
"(",
"stringToEscape",
"string",
")",
"string",
"{",
"escapedString",
":=",
"url",
".",
"QueryEscape",
"(",
"stringToEscape",
")",
"\n",
"escapedString",
"=",
"strings",
".",
"Replace",
"(",
"escapedString",
",",
"\"",
"\"",
",",
"`... | // Encode everything except for + signs | [
"Encode",
"everything",
"except",
"for",
"+",
"signs"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/post-processor/vsphere/post-processor.go#L231-L235 |
165,021 | hashicorp/packer | builder/amazon/common/state.go | WaitUntilAMIAvailable | func WaitUntilAMIAvailable(ctx aws.Context, conn *ec2.EC2, imageId string) error {
imageInput := ec2.DescribeImagesInput{
ImageIds: []*string{&imageId},
}
waitOpts := getWaiterOptions()
if len(waitOpts) == 0 {
// Bump this default to 30 minutes because the aws default
// of ten minutes doesn't work for some of our long-running copies.
waitOpts = append(waitOpts, request.WithWaiterMaxAttempts(120))
}
err := conn.WaitUntilImageAvailableWithContext(
ctx,
&imageInput,
waitOpts...)
return err
} | go | func WaitUntilAMIAvailable(ctx aws.Context, conn *ec2.EC2, imageId string) error {
imageInput := ec2.DescribeImagesInput{
ImageIds: []*string{&imageId},
}
waitOpts := getWaiterOptions()
if len(waitOpts) == 0 {
// Bump this default to 30 minutes because the aws default
// of ten minutes doesn't work for some of our long-running copies.
waitOpts = append(waitOpts, request.WithWaiterMaxAttempts(120))
}
err := conn.WaitUntilImageAvailableWithContext(
ctx,
&imageInput,
waitOpts...)
return err
} | [
"func",
"WaitUntilAMIAvailable",
"(",
"ctx",
"aws",
".",
"Context",
",",
"conn",
"*",
"ec2",
".",
"EC2",
",",
"imageId",
"string",
")",
"error",
"{",
"imageInput",
":=",
"ec2",
".",
"DescribeImagesInput",
"{",
"ImageIds",
":",
"[",
"]",
"*",
"string",
"{... | // Following are wrapper functions that use Packer's environment-variables to
// determing retry logic, then call the AWS SDK's built-in waiters. | [
"Following",
"are",
"wrapper",
"functions",
"that",
"use",
"Packer",
"s",
"environment",
"-",
"variables",
"to",
"determing",
"retry",
"logic",
"then",
"call",
"the",
"AWS",
"SDK",
"s",
"built",
"-",
"in",
"waiters",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/state.go#L39-L55 |
165,022 | hashicorp/packer | builder/amazon/common/state.go | WaitUntilSpotRequestFulfilled | func WaitUntilSpotRequestFulfilled(ctx aws.Context, conn *ec2.EC2, spotRequestId string) error {
spotRequestInput := ec2.DescribeSpotInstanceRequestsInput{
SpotInstanceRequestIds: []*string{&spotRequestId},
}
err := conn.WaitUntilSpotInstanceRequestFulfilledWithContext(
ctx,
&spotRequestInput,
getWaiterOptions()...)
return err
} | go | func WaitUntilSpotRequestFulfilled(ctx aws.Context, conn *ec2.EC2, spotRequestId string) error {
spotRequestInput := ec2.DescribeSpotInstanceRequestsInput{
SpotInstanceRequestIds: []*string{&spotRequestId},
}
err := conn.WaitUntilSpotInstanceRequestFulfilledWithContext(
ctx,
&spotRequestInput,
getWaiterOptions()...)
return err
} | [
"func",
"WaitUntilSpotRequestFulfilled",
"(",
"ctx",
"aws",
".",
"Context",
",",
"conn",
"*",
"ec2",
".",
"EC2",
",",
"spotRequestId",
"string",
")",
"error",
"{",
"spotRequestInput",
":=",
"ec2",
".",
"DescribeSpotInstanceRequestsInput",
"{",
"SpotInstanceRequestId... | // This function works for both requesting and cancelling spot instances. | [
"This",
"function",
"works",
"for",
"both",
"requesting",
"and",
"cancelling",
"spot",
"instances",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/state.go#L71-L81 |
165,023 | hashicorp/packer | builder/amazon/common/state.go | WaitUntilVolumeAttached | func WaitUntilVolumeAttached(ctx aws.Context, conn *ec2.EC2, volumeId string) error {
volumeInput := ec2.DescribeVolumesInput{
VolumeIds: []*string{&volumeId},
}
err := WaitForVolumeToBeAttached(conn,
ctx,
&volumeInput,
getWaiterOptions()...)
return err
} | go | func WaitUntilVolumeAttached(ctx aws.Context, conn *ec2.EC2, volumeId string) error {
volumeInput := ec2.DescribeVolumesInput{
VolumeIds: []*string{&volumeId},
}
err := WaitForVolumeToBeAttached(conn,
ctx,
&volumeInput,
getWaiterOptions()...)
return err
} | [
"func",
"WaitUntilVolumeAttached",
"(",
"ctx",
"aws",
".",
"Context",
",",
"conn",
"*",
"ec2",
".",
"EC2",
",",
"volumeId",
"string",
")",
"error",
"{",
"volumeInput",
":=",
"ec2",
".",
"DescribeVolumesInput",
"{",
"VolumeIds",
":",
"[",
"]",
"*",
"string"... | // Wrappers for our custom AWS waiters | [
"Wrappers",
"for",
"our",
"custom",
"AWS",
"waiters"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/state.go#L109-L119 |
165,024 | hashicorp/packer | builder/parallels/common/step_shutdown.go | Run | func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
comm := state.Get("communicator").(packer.Communicator)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
if s.Command != "" {
ui.Say("Gracefully halting virtual machine...")
log.Printf("Executing shutdown command: %s", s.Command)
var stdout, stderr bytes.Buffer
cmd := &packer.RemoteCmd{
Command: s.Command,
Stdout: &stdout,
Stderr: &stderr,
}
if err := comm.Start(ctx, cmd); err != nil {
err := fmt.Errorf("Failed to send shutdown command: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
// Wait for the machine to actually shut down
log.Printf("Waiting max %s for shutdown to complete", s.Timeout)
shutdownTimer := time.After(s.Timeout)
for {
running, _ := driver.IsRunning(vmName)
if !running {
break
}
select {
case <-shutdownTimer:
log.Printf("Shutdown stdout: %s", stdout.String())
log.Printf("Shutdown stderr: %s", stderr.String())
err := errors.New("Timeout while waiting for machine to shut down.")
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
default:
time.Sleep(500 * time.Millisecond)
}
}
} else {
ui.Say("Halting the virtual machine...")
if err := driver.Stop(vmName); err != nil {
err = fmt.Errorf("Error stopping VM: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
log.Println("VM shut down.")
return multistep.ActionContinue
} | go | func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
comm := state.Get("communicator").(packer.Communicator)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
if s.Command != "" {
ui.Say("Gracefully halting virtual machine...")
log.Printf("Executing shutdown command: %s", s.Command)
var stdout, stderr bytes.Buffer
cmd := &packer.RemoteCmd{
Command: s.Command,
Stdout: &stdout,
Stderr: &stderr,
}
if err := comm.Start(ctx, cmd); err != nil {
err := fmt.Errorf("Failed to send shutdown command: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
// Wait for the machine to actually shut down
log.Printf("Waiting max %s for shutdown to complete", s.Timeout)
shutdownTimer := time.After(s.Timeout)
for {
running, _ := driver.IsRunning(vmName)
if !running {
break
}
select {
case <-shutdownTimer:
log.Printf("Shutdown stdout: %s", stdout.String())
log.Printf("Shutdown stderr: %s", stderr.String())
err := errors.New("Timeout while waiting for machine to shut down.")
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
default:
time.Sleep(500 * time.Millisecond)
}
}
} else {
ui.Say("Halting the virtual machine...")
if err := driver.Stop(vmName); err != nil {
err = fmt.Errorf("Error stopping VM: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
log.Println("VM shut down.")
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepShutdown",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"comm",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"packer... | // Run shuts down the VM. | [
"Run",
"shuts",
"down",
"the",
"VM",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_shutdown.go#L32-L88 |
165,025 | hashicorp/packer | packer/progressbar.go | TrackProgress | func (*NoopProgressTracker) TrackProgress(_ string, _, _ int64, stream io.ReadCloser) io.ReadCloser {
return stream
} | go | func (*NoopProgressTracker) TrackProgress(_ string, _, _ int64, stream io.ReadCloser) io.ReadCloser {
return stream
} | [
"func",
"(",
"*",
"NoopProgressTracker",
")",
"TrackProgress",
"(",
"_",
"string",
",",
"_",
",",
"_",
"int64",
",",
"stream",
"io",
".",
"ReadCloser",
")",
"io",
".",
"ReadCloser",
"{",
"return",
"stream",
"\n",
"}"
] | // TrackProgress returns stream | [
"TrackProgress",
"returns",
"stream"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/progressbar.go#L87-L89 |
165,026 | hashicorp/packer | builder/parallels/common/prlctl_config.go | Prepare | func (c *PrlctlConfig) Prepare(ctx *interpolate.Context) []error {
if c.Prlctl == nil {
c.Prlctl = make([][]string, 0)
}
return nil
} | go | func (c *PrlctlConfig) Prepare(ctx *interpolate.Context) []error {
if c.Prlctl == nil {
c.Prlctl = make([][]string, 0)
}
return nil
} | [
"func",
"(",
"c",
"*",
"PrlctlConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"if",
"c",
".",
"Prlctl",
"==",
"nil",
"{",
"c",
".",
"Prlctl",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"string",
... | // Prepare sets the default value of "Prlctl" property. | [
"Prepare",
"sets",
"the",
"default",
"value",
"of",
"Prlctl",
"property",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/prlctl_config.go#L14-L20 |
165,027 | hashicorp/packer | common/powershell/powershell.go | Output | func (ps *PowerShellCmd) Output(fileContents string, params ...string) (string, error) {
path, err := ps.getPowerShellPath()
if err != nil {
return "", fmt.Errorf("Cannot find PowerShell in the path")
}
filename, err := saveScript(fileContents)
if err != nil {
return "", err
}
debug := os.Getenv("PACKER_POWERSHELL_DEBUG") != ""
verbose := debug || os.Getenv("PACKER_POWERSHELL_VERBOSE") != ""
if !debug {
defer os.Remove(filename)
}
args := createArgs(filename, params...)
if verbose {
log.Printf("Run: %s %s", path, args)
}
var stdout, stderr bytes.Buffer
command := exec.Command(path, args...)
command.Stdout = &stdout
command.Stderr = &stderr
err = command.Run()
if ps.Stdout != nil {
stdout.WriteTo(ps.Stdout)
}
if ps.Stderr != nil {
stderr.WriteTo(ps.Stderr)
}
stderrString := strings.TrimSpace(stderr.String())
if _, ok := err.(*exec.ExitError); ok {
err = fmt.Errorf("PowerShell error: %s", stderrString)
}
if len(stderrString) > 0 {
err = fmt.Errorf("PowerShell error: %s", stderrString)
}
stdoutString := strings.TrimSpace(stdout.String())
if verbose && stdoutString != "" {
log.Printf("stdout: %s", stdoutString)
}
// only write the stderr string if verbose because
// the error string will already be in the err return value.
if verbose && stderrString != "" {
log.Printf("stderr: %s", stderrString)
}
return stdoutString, err
} | go | func (ps *PowerShellCmd) Output(fileContents string, params ...string) (string, error) {
path, err := ps.getPowerShellPath()
if err != nil {
return "", fmt.Errorf("Cannot find PowerShell in the path")
}
filename, err := saveScript(fileContents)
if err != nil {
return "", err
}
debug := os.Getenv("PACKER_POWERSHELL_DEBUG") != ""
verbose := debug || os.Getenv("PACKER_POWERSHELL_VERBOSE") != ""
if !debug {
defer os.Remove(filename)
}
args := createArgs(filename, params...)
if verbose {
log.Printf("Run: %s %s", path, args)
}
var stdout, stderr bytes.Buffer
command := exec.Command(path, args...)
command.Stdout = &stdout
command.Stderr = &stderr
err = command.Run()
if ps.Stdout != nil {
stdout.WriteTo(ps.Stdout)
}
if ps.Stderr != nil {
stderr.WriteTo(ps.Stderr)
}
stderrString := strings.TrimSpace(stderr.String())
if _, ok := err.(*exec.ExitError); ok {
err = fmt.Errorf("PowerShell error: %s", stderrString)
}
if len(stderrString) > 0 {
err = fmt.Errorf("PowerShell error: %s", stderrString)
}
stdoutString := strings.TrimSpace(stdout.String())
if verbose && stdoutString != "" {
log.Printf("stdout: %s", stdoutString)
}
// only write the stderr string if verbose because
// the error string will already be in the err return value.
if verbose && stderrString != "" {
log.Printf("stderr: %s", stderrString)
}
return stdoutString, err
} | [
"func",
"(",
"ps",
"*",
"PowerShellCmd",
")",
"Output",
"(",
"fileContents",
"string",
",",
"params",
"...",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"path",
",",
"err",
":=",
"ps",
".",
"getPowerShellPath",
"(",
")",
"\n",
"if",
"err",
... | // Output runs the PowerShell command and returns its standard output. | [
"Output",
"runs",
"the",
"PowerShell",
"command",
"and",
"returns",
"its",
"standard",
"output",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/powershell/powershell.go#L40-L102 |
165,028 | hashicorp/packer | builder/docker/windows_container_communicator.go | Upload | func (c *WindowsContainerCommunicator) Upload(dst string, src io.Reader, fi *os.FileInfo) error {
// Create a temporary file to store the upload
tempfile, err := ioutil.TempFile(c.HostDir, "upload")
if err != nil {
return err
}
defer os.Remove(tempfile.Name())
// Copy the contents to the temporary file
_, err = io.Copy(tempfile, src)
if err != nil {
return err
}
if fi != nil {
tempfile.Chmod((*fi).Mode())
}
tempfile.Close()
// Copy the file into place by copying the temporary file we put
// into the shared folder into the proper location in the container
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("Copy-Item -Path %s/%s -Destination %s", c.ContainerDir,
filepath.Base(tempfile.Name()), dst),
}
ctx := context.TODO()
if err := c.Start(ctx, cmd); err != nil {
return err
}
// Wait for the copy to complete
cmd.Wait()
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Upload failed with non-zero exit status: %d", cmd.ExitStatus())
}
return nil
} | go | func (c *WindowsContainerCommunicator) Upload(dst string, src io.Reader, fi *os.FileInfo) error {
// Create a temporary file to store the upload
tempfile, err := ioutil.TempFile(c.HostDir, "upload")
if err != nil {
return err
}
defer os.Remove(tempfile.Name())
// Copy the contents to the temporary file
_, err = io.Copy(tempfile, src)
if err != nil {
return err
}
if fi != nil {
tempfile.Chmod((*fi).Mode())
}
tempfile.Close()
// Copy the file into place by copying the temporary file we put
// into the shared folder into the proper location in the container
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("Copy-Item -Path %s/%s -Destination %s", c.ContainerDir,
filepath.Base(tempfile.Name()), dst),
}
ctx := context.TODO()
if err := c.Start(ctx, cmd); err != nil {
return err
}
// Wait for the copy to complete
cmd.Wait()
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Upload failed with non-zero exit status: %d", cmd.ExitStatus())
}
return nil
} | [
"func",
"(",
"c",
"*",
"WindowsContainerCommunicator",
")",
"Upload",
"(",
"dst",
"string",
",",
"src",
"io",
".",
"Reader",
",",
"fi",
"*",
"os",
".",
"FileInfo",
")",
"error",
"{",
"// Create a temporary file to store the upload",
"tempfile",
",",
"err",
":=... | // Upload uses docker exec to copy the file from the host to the container | [
"Upload",
"uses",
"docker",
"exec",
"to",
"copy",
"the",
"file",
"from",
"the",
"host",
"to",
"the",
"container"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/windows_container_communicator.go#L29-L65 |
165,029 | hashicorp/packer | builder/docker/windows_container_communicator.go | Download | func (c *WindowsContainerCommunicator) Download(src string, dst io.Writer) error {
log.Printf("Downloading file from container: %s:%s", c.ContainerID, src)
// Copy file onto temp file on mounted volume inside container
var stdout, stderr bytes.Buffer
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("Copy-Item -Path %s -Destination %s/%s", src, c.ContainerDir,
filepath.Base(src)),
Stdout: &stdout,
Stderr: &stderr,
}
ctx := context.TODO()
if err := c.Start(ctx, cmd); err != nil {
return err
}
// Wait for the copy to complete
cmd.Wait()
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Failed to copy file to shared drive: %s, %s, %d", stderr.String(), stdout.String(), cmd.ExitStatus())
}
// Read that copied file into a new file opened on host machine
fsrc, err := os.Open(filepath.Join(c.HostDir, filepath.Base(src)))
if err != nil {
return err
}
defer fsrc.Close()
defer os.Remove(fsrc.Name())
_, err = io.Copy(dst, fsrc)
if err != nil {
return err
}
return nil
} | go | func (c *WindowsContainerCommunicator) Download(src string, dst io.Writer) error {
log.Printf("Downloading file from container: %s:%s", c.ContainerID, src)
// Copy file onto temp file on mounted volume inside container
var stdout, stderr bytes.Buffer
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("Copy-Item -Path %s -Destination %s/%s", src, c.ContainerDir,
filepath.Base(src)),
Stdout: &stdout,
Stderr: &stderr,
}
ctx := context.TODO()
if err := c.Start(ctx, cmd); err != nil {
return err
}
// Wait for the copy to complete
cmd.Wait()
if cmd.ExitStatus() != 0 {
return fmt.Errorf("Failed to copy file to shared drive: %s, %s, %d", stderr.String(), stdout.String(), cmd.ExitStatus())
}
// Read that copied file into a new file opened on host machine
fsrc, err := os.Open(filepath.Join(c.HostDir, filepath.Base(src)))
if err != nil {
return err
}
defer fsrc.Close()
defer os.Remove(fsrc.Name())
_, err = io.Copy(dst, fsrc)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"WindowsContainerCommunicator",
")",
"Download",
"(",
"src",
"string",
",",
"dst",
"io",
".",
"Writer",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"c",
".",
"ContainerID",
",",
"src",
")",
"\n",
"// Copy file ... | // Download pulls a file out of a container using `docker cp`. We have a source
// path and want to write to an io.Writer | [
"Download",
"pulls",
"a",
"file",
"out",
"of",
"a",
"container",
"using",
"docker",
"cp",
".",
"We",
"have",
"a",
"source",
"path",
"and",
"want",
"to",
"write",
"to",
"an",
"io",
".",
"Writer"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/windows_container_communicator.go#L155-L191 |
165,030 | hashicorp/packer | common/template/funcs.go | DeprecatedTemplateFunc | func DeprecatedTemplateFunc(funcName, useInstead string, deprecated func(string) string) func(string) string {
once := sync.Once{}
return func(in string) string {
once.Do(func() {
log.Printf("[WARN]: the `%s` template func is deprecated, please use %s instead",
funcName, useInstead)
})
return deprecated(in)
}
} | go | func DeprecatedTemplateFunc(funcName, useInstead string, deprecated func(string) string) func(string) string {
once := sync.Once{}
return func(in string) string {
once.Do(func() {
log.Printf("[WARN]: the `%s` template func is deprecated, please use %s instead",
funcName, useInstead)
})
return deprecated(in)
}
} | [
"func",
"DeprecatedTemplateFunc",
"(",
"funcName",
",",
"useInstead",
"string",
",",
"deprecated",
"func",
"(",
"string",
")",
"string",
")",
"func",
"(",
"string",
")",
"string",
"{",
"once",
":=",
"sync",
".",
"Once",
"{",
"}",
"\n",
"return",
"func",
... | // DeprecatedTemplateFunc wraps a template func to warn users that it's
// deprecated. The deprecation warning is called only once. | [
"DeprecatedTemplateFunc",
"wraps",
"a",
"template",
"func",
"to",
"warn",
"users",
"that",
"it",
"s",
"deprecated",
".",
"The",
"deprecation",
"warning",
"is",
"called",
"only",
"once",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/template/funcs.go#L10-L19 |
165,031 | hashicorp/packer | builder/oracle/oci/driver_oci.go | NewDriverOCI | func NewDriverOCI(cfg *Config) (Driver, error) {
coreClient, err := core.NewComputeClientWithConfigurationProvider(cfg.ConfigProvider)
if err != nil {
return nil, err
}
vcnClient, err := core.NewVirtualNetworkClientWithConfigurationProvider(cfg.ConfigProvider)
if err != nil {
return nil, err
}
return &driverOCI{
computeClient: coreClient,
vcnClient: vcnClient,
cfg: cfg,
}, nil
} | go | func NewDriverOCI(cfg *Config) (Driver, error) {
coreClient, err := core.NewComputeClientWithConfigurationProvider(cfg.ConfigProvider)
if err != nil {
return nil, err
}
vcnClient, err := core.NewVirtualNetworkClientWithConfigurationProvider(cfg.ConfigProvider)
if err != nil {
return nil, err
}
return &driverOCI{
computeClient: coreClient,
vcnClient: vcnClient,
cfg: cfg,
}, nil
} | [
"func",
"NewDriverOCI",
"(",
"cfg",
"*",
"Config",
")",
"(",
"Driver",
",",
"error",
")",
"{",
"coreClient",
",",
"err",
":=",
"core",
".",
"NewComputeClientWithConfigurationProvider",
"(",
"cfg",
".",
"ConfigProvider",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // NewDriverOCI Creates a new driverOCI with a connected compute client and a connected vcn client. | [
"NewDriverOCI",
"Creates",
"a",
"new",
"driverOCI",
"with",
"a",
"connected",
"compute",
"client",
"and",
"a",
"connected",
"vcn",
"client",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/driver_oci.go#L22-L38 |
165,032 | hashicorp/packer | builder/oracle/oci/driver_oci.go | DeleteImage | func (d *driverOCI) DeleteImage(ctx context.Context, id string) error {
_, err := d.computeClient.DeleteImage(ctx, core.DeleteImageRequest{ImageId: &id})
return err
} | go | func (d *driverOCI) DeleteImage(ctx context.Context, id string) error {
_, err := d.computeClient.DeleteImage(ctx, core.DeleteImageRequest{ImageId: &id})
return err
} | [
"func",
"(",
"d",
"*",
"driverOCI",
")",
"DeleteImage",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"d",
".",
"computeClient",
".",
"DeleteImage",
"(",
"ctx",
",",
"core",
".",
"DeleteImageReque... | // DeleteImage deletes a custom image. | [
"DeleteImage",
"deletes",
"a",
"custom",
"image",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/driver_oci.go#L94-L97 |
165,033 | hashicorp/packer | builder/oracle/oci/driver_oci.go | waitForResourceToReachState | func waitForResourceToReachState(getResourceState func(string) (string, error), id string, waitStates []string, terminalState string, maxRetries int, waitDuration time.Duration) error {
for i := 0; maxRetries == 0 || i < maxRetries; i++ {
state, err := getResourceState(id)
if err != nil {
return err
}
if stringSliceContains(waitStates, state) {
time.Sleep(waitDuration)
continue
} else if state == terminalState {
return nil
}
return fmt.Errorf("Unexpected resource state %q, expecting a waiting state %s or terminal state %q ", state, waitStates, terminalState)
}
return fmt.Errorf("Maximum number of retries (%d) exceeded; resource did not reach state %q", maxRetries, terminalState)
} | go | func waitForResourceToReachState(getResourceState func(string) (string, error), id string, waitStates []string, terminalState string, maxRetries int, waitDuration time.Duration) error {
for i := 0; maxRetries == 0 || i < maxRetries; i++ {
state, err := getResourceState(id)
if err != nil {
return err
}
if stringSliceContains(waitStates, state) {
time.Sleep(waitDuration)
continue
} else if state == terminalState {
return nil
}
return fmt.Errorf("Unexpected resource state %q, expecting a waiting state %s or terminal state %q ", state, waitStates, terminalState)
}
return fmt.Errorf("Maximum number of retries (%d) exceeded; resource did not reach state %q", maxRetries, terminalState)
} | [
"func",
"waitForResourceToReachState",
"(",
"getResourceState",
"func",
"(",
"string",
")",
"(",
"string",
",",
"error",
")",
",",
"id",
"string",
",",
"waitStates",
"[",
"]",
"string",
",",
"terminalState",
"string",
",",
"maxRetries",
"int",
",",
"waitDurati... | // WaitForResourceToReachState checks the response of a request through a
// polled get and waits until the desired state or until the max retried has
// been reached. | [
"WaitForResourceToReachState",
"checks",
"the",
"response",
"of",
"a",
"request",
"through",
"a",
"polled",
"get",
"and",
"waits",
"until",
"the",
"desired",
"state",
"or",
"until",
"the",
"max",
"retried",
"has",
"been",
"reached",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/driver_oci.go#L189-L205 |
165,034 | hashicorp/packer | builder/oracle/oci/driver_oci.go | stringSliceContains | func stringSliceContains(slice []string, value string) bool {
for _, elem := range slice {
if elem == value {
return true
}
}
return false
} | go | func stringSliceContains(slice []string, value string) bool {
for _, elem := range slice {
if elem == value {
return true
}
}
return false
} | [
"func",
"stringSliceContains",
"(",
"slice",
"[",
"]",
"string",
",",
"value",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"elem",
":=",
"range",
"slice",
"{",
"if",
"elem",
"==",
"value",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",... | // stringSliceContains loops through a slice of strings returning a boolean
// based on whether a given value is contained in the slice. | [
"stringSliceContains",
"loops",
"through",
"a",
"slice",
"of",
"strings",
"returning",
"a",
"boolean",
"based",
"on",
"whether",
"a",
"given",
"value",
"is",
"contained",
"in",
"the",
"slice",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/driver_oci.go#L209-L216 |
165,035 | hashicorp/packer | packer/plugin/server.go | Server | func Server() (*packrpc.Server, error) {
if os.Getenv(MagicCookieKey) != MagicCookieValue {
return nil, errors.New(
"Please do not execute plugins directly. Packer will execute these for you.")
}
// If there is no explicit number of Go threads to use, then set it
if os.Getenv("GOMAXPROCS") == "" {
runtime.GOMAXPROCS(runtime.NumCPU())
}
minPort, err := strconv.ParseInt(os.Getenv("PACKER_PLUGIN_MIN_PORT"), 10, 32)
if err != nil {
return nil, err
}
maxPort, err := strconv.ParseInt(os.Getenv("PACKER_PLUGIN_MAX_PORT"), 10, 32)
if err != nil {
return nil, err
}
log.Printf("Plugin minimum port: %d\n", minPort)
log.Printf("Plugin maximum port: %d\n", maxPort)
listener, err := serverListener(minPort, maxPort)
if err != nil {
return nil, err
}
defer listener.Close()
// Output the address to stdout
log.Printf("Plugin address: %s %s\n",
listener.Addr().Network(), listener.Addr().String())
fmt.Printf("%s|%s|%s\n",
APIVersion,
listener.Addr().Network(),
listener.Addr().String())
os.Stdout.Sync()
// Accept a connection
log.Println("Waiting for connection...")
conn, err := listener.Accept()
if err != nil {
log.Printf("Error accepting connection: %s\n", err.Error())
return nil, err
}
// Eat the interrupts
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
go func() {
var count int32 = 0
for {
<-ch
newCount := atomic.AddInt32(&count, 1)
log.Printf("Received interrupt signal (count: %d). Ignoring.", newCount)
}
}()
// Serve a single connection
log.Println("Serving a plugin connection...")
return packrpc.NewServer(conn)
} | go | func Server() (*packrpc.Server, error) {
if os.Getenv(MagicCookieKey) != MagicCookieValue {
return nil, errors.New(
"Please do not execute plugins directly. Packer will execute these for you.")
}
// If there is no explicit number of Go threads to use, then set it
if os.Getenv("GOMAXPROCS") == "" {
runtime.GOMAXPROCS(runtime.NumCPU())
}
minPort, err := strconv.ParseInt(os.Getenv("PACKER_PLUGIN_MIN_PORT"), 10, 32)
if err != nil {
return nil, err
}
maxPort, err := strconv.ParseInt(os.Getenv("PACKER_PLUGIN_MAX_PORT"), 10, 32)
if err != nil {
return nil, err
}
log.Printf("Plugin minimum port: %d\n", minPort)
log.Printf("Plugin maximum port: %d\n", maxPort)
listener, err := serverListener(minPort, maxPort)
if err != nil {
return nil, err
}
defer listener.Close()
// Output the address to stdout
log.Printf("Plugin address: %s %s\n",
listener.Addr().Network(), listener.Addr().String())
fmt.Printf("%s|%s|%s\n",
APIVersion,
listener.Addr().Network(),
listener.Addr().String())
os.Stdout.Sync()
// Accept a connection
log.Println("Waiting for connection...")
conn, err := listener.Accept()
if err != nil {
log.Printf("Error accepting connection: %s\n", err.Error())
return nil, err
}
// Eat the interrupts
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
go func() {
var count int32 = 0
for {
<-ch
newCount := atomic.AddInt32(&count, 1)
log.Printf("Received interrupt signal (count: %d). Ignoring.", newCount)
}
}()
// Serve a single connection
log.Println("Serving a plugin connection...")
return packrpc.NewServer(conn)
} | [
"func",
"Server",
"(",
")",
"(",
"*",
"packrpc",
".",
"Server",
",",
"error",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"MagicCookieKey",
")",
"!=",
"MagicCookieValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}... | // Server waits for a connection to this plugin and returns a Packer
// RPC server that you can use to register components and serve them. | [
"Server",
"waits",
"for",
"a",
"connection",
"to",
"this",
"plugin",
"and",
"returns",
"a",
"Packer",
"RPC",
"server",
"that",
"you",
"can",
"use",
"to",
"register",
"components",
"and",
"serve",
"them",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/plugin/server.go#L43-L105 |
165,036 | hashicorp/packer | builder/triton/driver_triton.go | WaitForMachineState | func (d *driverTriton) WaitForMachineState(machineId string, state string, timeout time.Duration) error {
return waitFor(
func() (bool, error) {
computeClient, _ := d.client.Compute()
machine, err := computeClient.Instances().Get(context.Background(), &compute.GetInstanceInput{
ID: machineId,
})
if machine == nil {
return false, err
}
return machine.State == state, err
},
3*time.Second,
timeout,
)
} | go | func (d *driverTriton) WaitForMachineState(machineId string, state string, timeout time.Duration) error {
return waitFor(
func() (bool, error) {
computeClient, _ := d.client.Compute()
machine, err := computeClient.Instances().Get(context.Background(), &compute.GetInstanceInput{
ID: machineId,
})
if machine == nil {
return false, err
}
return machine.State == state, err
},
3*time.Second,
timeout,
)
} | [
"func",
"(",
"d",
"*",
"driverTriton",
")",
"WaitForMachineState",
"(",
"machineId",
"string",
",",
"state",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"return",
"waitFor",
"(",
"func",
"(",
")",
"(",
"bool",
",",
"error",
")",... | // waitForMachineState uses the supplied client to wait for the state of
// the machine with the given ID to reach the state described in state.
// If timeout is reached before the machine reaches the required state, an
// error is returned. If the machine reaches the target state within the
// timeout, nil is returned. | [
"waitForMachineState",
"uses",
"the",
"supplied",
"client",
"to",
"wait",
"for",
"the",
"state",
"of",
"the",
"machine",
"with",
"the",
"given",
"ID",
"to",
"reach",
"the",
"state",
"described",
"in",
"state",
".",
"If",
"timeout",
"is",
"reached",
"before",... | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/triton/driver_triton.go#L149-L164 |
165,037 | hashicorp/packer | builder/triton/driver_triton.go | WaitForMachineDeletion | func (d *driverTriton) WaitForMachineDeletion(machineId string, timeout time.Duration) error {
return waitFor(
func() (bool, error) {
computeClient, _ := d.client.Compute()
_, err := computeClient.Instances().Get(context.Background(), &compute.GetInstanceInput{
ID: machineId,
})
if err != nil {
// Return true only when we receive a 410 (Gone) response. A 404
// indicates that the machine is being deleted whereas a 410 indicates
// that this process has completed.
if terrors.IsSpecificStatusCode(err, http.StatusGone) {
return true, nil
}
}
return false, err
},
3*time.Second,
timeout,
)
} | go | func (d *driverTriton) WaitForMachineDeletion(machineId string, timeout time.Duration) error {
return waitFor(
func() (bool, error) {
computeClient, _ := d.client.Compute()
_, err := computeClient.Instances().Get(context.Background(), &compute.GetInstanceInput{
ID: machineId,
})
if err != nil {
// Return true only when we receive a 410 (Gone) response. A 404
// indicates that the machine is being deleted whereas a 410 indicates
// that this process has completed.
if terrors.IsSpecificStatusCode(err, http.StatusGone) {
return true, nil
}
}
return false, err
},
3*time.Second,
timeout,
)
} | [
"func",
"(",
"d",
"*",
"driverTriton",
")",
"WaitForMachineDeletion",
"(",
"machineId",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"return",
"waitFor",
"(",
"func",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"computeClient",
... | // waitForMachineDeletion uses the supplied client to wait for the machine
// with the given ID to be deleted. It is expected that the API call to delete
// the machine has already been issued at this point. | [
"waitForMachineDeletion",
"uses",
"the",
"supplied",
"client",
"to",
"wait",
"for",
"the",
"machine",
"with",
"the",
"given",
"ID",
"to",
"be",
"deleted",
".",
"It",
"is",
"expected",
"that",
"the",
"API",
"call",
"to",
"delete",
"the",
"machine",
"has",
"... | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/triton/driver_triton.go#L169-L190 |
165,038 | hashicorp/packer | builder/vmware/common/driver_parser.go | uncomment | func uncomment(eof sentinelSignaller, in <-chan byte) (chan byte, sentinelSignaller) {
out := make(chan byte)
eoc := make(sentinelSignaller)
go func(in <-chan byte, out chan byte) {
var endofline bool
for stillReading := true; stillReading; {
select {
case <-eof:
stillReading = false
case ch := <-in:
switch ch {
case '#':
endofline = true
case '\n':
if endofline {
endofline = false
}
}
if !endofline {
out <- ch
}
}
}
close(eoc)
}(in, out)
return out, eoc
} | go | func uncomment(eof sentinelSignaller, in <-chan byte) (chan byte, sentinelSignaller) {
out := make(chan byte)
eoc := make(sentinelSignaller)
go func(in <-chan byte, out chan byte) {
var endofline bool
for stillReading := true; stillReading; {
select {
case <-eof:
stillReading = false
case ch := <-in:
switch ch {
case '#':
endofline = true
case '\n':
if endofline {
endofline = false
}
}
if !endofline {
out <- ch
}
}
}
close(eoc)
}(in, out)
return out, eoc
} | [
"func",
"uncomment",
"(",
"eof",
"sentinelSignaller",
",",
"in",
"<-",
"chan",
"byte",
")",
"(",
"chan",
"byte",
",",
"sentinelSignaller",
")",
"{",
"out",
":=",
"make",
"(",
"chan",
"byte",
")",
"\n",
"eoc",
":=",
"make",
"(",
"sentinelSignaller",
")",
... | /** low-level parsing */
// strip the comments and extraneous newlines from a byte channel | [
"low",
"-",
"level",
"parsing",
"strip",
"the",
"comments",
"and",
"extraneous",
"newlines",
"from",
"a",
"byte",
"channel"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_parser.go#L20-L47 |
165,039 | hashicorp/packer | builder/vmware/common/driver_parser.go | parseTokenParameter | func parseTokenParameter(in chan string) tkParameter {
var result tkParameter
for {
token := <-in
if result.name == "" {
result.name = token
continue
}
switch token {
case "{":
fallthrough
case "}":
fallthrough
case ";":
goto leave
default:
result.operand = append(result.operand, token)
}
}
leave:
return result
} | go | func parseTokenParameter(in chan string) tkParameter {
var result tkParameter
for {
token := <-in
if result.name == "" {
result.name = token
continue
}
switch token {
case "{":
fallthrough
case "}":
fallthrough
case ";":
goto leave
default:
result.operand = append(result.operand, token)
}
}
leave:
return result
} | [
"func",
"parseTokenParameter",
"(",
"in",
"chan",
"string",
")",
"tkParameter",
"{",
"var",
"result",
"tkParameter",
"\n",
"for",
"{",
"token",
":=",
"<-",
"in",
"\n",
"if",
"result",
".",
"name",
"==",
"\"",
"\"",
"{",
"result",
".",
"name",
"=",
"tok... | // convert a channel of pseudo-tokens into an tkParameter struct | [
"convert",
"a",
"channel",
"of",
"pseudo",
"-",
"tokens",
"into",
"an",
"tkParameter",
"struct"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_parser.go#L156-L177 |
165,040 | hashicorp/packer | builder/vmware/common/driver_parser.go | parseDhcpConfig | func parseDhcpConfig(eof sentinelSignaller, in chan string) (tkGroup, error) {
var tokens []string
var result tkGroup
toParameter := func(tokens []string) tkParameter {
out := make(chan string)
go func(out chan string) {
for _, v := range tokens {
out <- v
}
out <- ";"
}(out)
return parseTokenParameter(out)
}
for stillReading, currentgroup := true, &result; stillReading; {
select {
case <-eof:
stillReading = false
case tk := <-in:
switch tk {
case "{":
grp := &tkGroup{parent: currentgroup}
grp.id = toParameter(tokens)
currentgroup.groups = append(currentgroup.groups, grp)
currentgroup = grp
case "}":
if currentgroup.parent == nil {
return tkGroup{}, fmt.Errorf("Unable to close the global declaration")
}
if len(tokens) > 0 {
return tkGroup{}, fmt.Errorf("List of tokens was left unterminated : %v", tokens)
}
currentgroup = currentgroup.parent
case ";":
arg := toParameter(tokens)
currentgroup.params = append(currentgroup.params, arg)
default:
tokens = append(tokens, tk)
continue
}
tokens = []string{}
}
}
return result, nil
} | go | func parseDhcpConfig(eof sentinelSignaller, in chan string) (tkGroup, error) {
var tokens []string
var result tkGroup
toParameter := func(tokens []string) tkParameter {
out := make(chan string)
go func(out chan string) {
for _, v := range tokens {
out <- v
}
out <- ";"
}(out)
return parseTokenParameter(out)
}
for stillReading, currentgroup := true, &result; stillReading; {
select {
case <-eof:
stillReading = false
case tk := <-in:
switch tk {
case "{":
grp := &tkGroup{parent: currentgroup}
grp.id = toParameter(tokens)
currentgroup.groups = append(currentgroup.groups, grp)
currentgroup = grp
case "}":
if currentgroup.parent == nil {
return tkGroup{}, fmt.Errorf("Unable to close the global declaration")
}
if len(tokens) > 0 {
return tkGroup{}, fmt.Errorf("List of tokens was left unterminated : %v", tokens)
}
currentgroup = currentgroup.parent
case ";":
arg := toParameter(tokens)
currentgroup.params = append(currentgroup.params, arg)
default:
tokens = append(tokens, tk)
continue
}
tokens = []string{}
}
}
return result, nil
} | [
"func",
"parseDhcpConfig",
"(",
"eof",
"sentinelSignaller",
",",
"in",
"chan",
"string",
")",
"(",
"tkGroup",
",",
"error",
")",
"{",
"var",
"tokens",
"[",
"]",
"string",
"\n",
"var",
"result",
"tkGroup",
"\n\n",
"toParameter",
":=",
"func",
"(",
"tokens",... | // convert a channel of pseudo-tokens into an tkGroup tree */ | [
"convert",
"a",
"channel",
"of",
"pseudo",
"-",
"tokens",
"into",
"an",
"tkGroup",
"tree"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_parser.go#L180-L226 |
165,041 | hashicorp/packer | builder/vmware/common/driver_parser.go | parseNetworkingCommand_answer | func parseNetworkingCommand_answer(row []string) (*networkingCommandEntry, error) {
if len(row) != 2 {
return nil, fmt.Errorf("Expected %d arguments. Received only %d.", 2, len(row))
}
vnet := networkingVNET{value: row[0]}
if !vnet.Valid() {
return nil, fmt.Errorf("Invalid format for VNET.")
}
value := row[1]
result := networkingCommandEntry_answer{vnet: vnet, value: value}
return &networkingCommandEntry{entry: result, answer: &result}, nil
} | go | func parseNetworkingCommand_answer(row []string) (*networkingCommandEntry, error) {
if len(row) != 2 {
return nil, fmt.Errorf("Expected %d arguments. Received only %d.", 2, len(row))
}
vnet := networkingVNET{value: row[0]}
if !vnet.Valid() {
return nil, fmt.Errorf("Invalid format for VNET.")
}
value := row[1]
result := networkingCommandEntry_answer{vnet: vnet, value: value}
return &networkingCommandEntry{entry: result, answer: &result}, nil
} | [
"func",
"parseNetworkingCommand_answer",
"(",
"row",
"[",
"]",
"string",
")",
"(",
"*",
"networkingCommandEntry",
",",
"error",
")",
"{",
"if",
"len",
"(",
"row",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
... | // networking command entry parsers | [
"networking",
"command",
"entry",
"parsers"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_parser.go#L1442-L1454 |
165,042 | hashicorp/packer | builder/vmware/common/driver_parser.go | ReadNetworkingConfig | func ReadNetworkingConfig(fd *os.File) (NetworkingConfig, error) {
// start piecing together different parts of the file
fromfile, eof := consumeFile(fd)
tokenized, eot := tokenizeNetworkingConfig(eof, fromfile)
rows, eos := splitNetworkingConfig(eot, tokenized)
entries, eop := parseNetworkingConfig(eos, rows)
// parse the version
parsed_version, err := networkingReadVersion(<-rows)
if err != nil {
return NetworkingConfig{}, err
}
// verify that it's 1.0 since that's all we support.
version := parsed_version.Number()
if version != 1.0 {
return NetworkingConfig{}, fmt.Errorf("Expected version %f of networking file. Received version %f.", 1.0, version)
}
// convert to a configuration
result := flattenNetworkingConfig(eop, entries)
return result, nil
} | go | func ReadNetworkingConfig(fd *os.File) (NetworkingConfig, error) {
// start piecing together different parts of the file
fromfile, eof := consumeFile(fd)
tokenized, eot := tokenizeNetworkingConfig(eof, fromfile)
rows, eos := splitNetworkingConfig(eot, tokenized)
entries, eop := parseNetworkingConfig(eos, rows)
// parse the version
parsed_version, err := networkingReadVersion(<-rows)
if err != nil {
return NetworkingConfig{}, err
}
// verify that it's 1.0 since that's all we support.
version := parsed_version.Number()
if version != 1.0 {
return NetworkingConfig{}, fmt.Errorf("Expected version %f of networking file. Received version %f.", 1.0, version)
}
// convert to a configuration
result := flattenNetworkingConfig(eop, entries)
return result, nil
} | [
"func",
"ReadNetworkingConfig",
"(",
"fd",
"*",
"os",
".",
"File",
")",
"(",
"NetworkingConfig",
",",
"error",
")",
"{",
"// start piecing together different parts of the file",
"fromfile",
",",
"eof",
":=",
"consumeFile",
"(",
"fd",
")",
"\n",
"tokenized",
",",
... | // Constructor for networking file | [
"Constructor",
"for",
"networking",
"file"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_parser.go#L1816-L1838 |
165,043 | hashicorp/packer | builder/vmware/common/driver_parser.go | consumeFile | func consumeFile(fd *os.File) (chan byte, sentinelSignaller) {
fromfile := make(chan byte)
eof := make(sentinelSignaller)
go func() {
b := make([]byte, 1)
for {
_, err := fd.Read(b)
if err == io.EOF {
break
}
fromfile <- b[0]
}
close(eof)
}()
return fromfile, eof
} | go | func consumeFile(fd *os.File) (chan byte, sentinelSignaller) {
fromfile := make(chan byte)
eof := make(sentinelSignaller)
go func() {
b := make([]byte, 1)
for {
_, err := fd.Read(b)
if err == io.EOF {
break
}
fromfile <- b[0]
}
close(eof)
}()
return fromfile, eof
} | [
"func",
"consumeFile",
"(",
"fd",
"*",
"os",
".",
"File",
")",
"(",
"chan",
"byte",
",",
"sentinelSignaller",
")",
"{",
"fromfile",
":=",
"make",
"(",
"chan",
"byte",
")",
"\n",
"eof",
":=",
"make",
"(",
"sentinelSignaller",
")",
"\n",
"go",
"func",
... | /** generic async file reader */ | [
"generic",
"async",
"file",
"reader"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_parser.go#L1958-L1973 |
165,044 | hashicorp/packer | builder/googlecompute/step_check_existing_image.go | Run | func (s *StepCheckExistingImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
c := state.Get("config").(*Config)
d := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Checking image does not exist...")
c.imageAlreadyExists = d.ImageExists(c.ImageName)
if !c.PackerForce && c.imageAlreadyExists {
err := fmt.Errorf("Image %s already exists.\n"+
"Use the force flag to delete it prior to building.", c.ImageName)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
} | go | func (s *StepCheckExistingImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
c := state.Get("config").(*Config)
d := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Checking image does not exist...")
c.imageAlreadyExists = d.ImageExists(c.ImageName)
if !c.PackerForce && c.imageAlreadyExists {
err := fmt.Errorf("Image %s already exists.\n"+
"Use the force flag to delete it prior to building.", c.ImageName)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepCheckExistingImage",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"c",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
... | // Run executes the Packer build step that checks if the image already exists. | [
"Run",
"executes",
"the",
"Packer",
"build",
"step",
"that",
"checks",
"if",
"the",
"image",
"already",
"exists",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_check_existing_image.go#L16-L31 |
165,045 | hashicorp/packer | builder/openstack/run_config.go | getImageVisibility | func getImageVisibility(visibility string) (*images.ImageVisibility, error) {
visibilities := [...]images.ImageVisibility{
images.ImageVisibilityPublic,
images.ImageVisibilityPrivate,
images.ImageVisibilityCommunity,
images.ImageVisibilityShared,
}
for _, v := range visibilities {
if string(v) == visibility {
return &v, nil
}
}
return nil, fmt.Errorf("Not a valid visibility: %s", visibility)
} | go | func getImageVisibility(visibility string) (*images.ImageVisibility, error) {
visibilities := [...]images.ImageVisibility{
images.ImageVisibilityPublic,
images.ImageVisibilityPrivate,
images.ImageVisibilityCommunity,
images.ImageVisibilityShared,
}
for _, v := range visibilities {
if string(v) == visibility {
return &v, nil
}
}
return nil, fmt.Errorf("Not a valid visibility: %s", visibility)
} | [
"func",
"getImageVisibility",
"(",
"visibility",
"string",
")",
"(",
"*",
"images",
".",
"ImageVisibility",
",",
"error",
")",
"{",
"visibilities",
":=",
"[",
"...",
"]",
"images",
".",
"ImageVisibility",
"{",
"images",
".",
"ImageVisibilityPublic",
",",
"imag... | // Retrieve the specific ImageVisibility using the exported const from images | [
"Retrieve",
"the",
"specific",
"ImageVisibility",
"using",
"the",
"exported",
"const",
"from",
"images"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/run_config.go#L175-L190 |
165,046 | hashicorp/packer | builder/triton/source_machine_config.go | Prepare | func (c *SourceMachineConfig) Prepare(ctx *interpolate.Context) []error {
var errs []error
if c.MachinePackage == "" {
errs = append(errs, fmt.Errorf("A source_machine_package must be specified"))
}
if c.MachineImage != "" && c.MachineImageFilters.Name != "" {
errs = append(errs, fmt.Errorf("You cannot specify a Machine Image and also Machine Name filter"))
}
if c.MachineNetworks == nil {
c.MachineNetworks = []string{}
}
if c.MachineMetadata == nil {
c.MachineMetadata = make(map[string]string)
}
if c.MachineTags == nil {
c.MachineTags = make(map[string]string)
}
if len(errs) > 0 {
return errs
}
return nil
} | go | func (c *SourceMachineConfig) Prepare(ctx *interpolate.Context) []error {
var errs []error
if c.MachinePackage == "" {
errs = append(errs, fmt.Errorf("A source_machine_package must be specified"))
}
if c.MachineImage != "" && c.MachineImageFilters.Name != "" {
errs = append(errs, fmt.Errorf("You cannot specify a Machine Image and also Machine Name filter"))
}
if c.MachineNetworks == nil {
c.MachineNetworks = []string{}
}
if c.MachineMetadata == nil {
c.MachineMetadata = make(map[string]string)
}
if c.MachineTags == nil {
c.MachineTags = make(map[string]string)
}
if len(errs) > 0 {
return errs
}
return nil
} | [
"func",
"(",
"c",
"*",
"SourceMachineConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"var",
"errs",
"[",
"]",
"error",
"\n\n",
"if",
"c",
".",
"MachinePackage",
"==",
"\"",
"\"",
"{",
"errs",
"=",... | // Prepare performs basic validation on a SourceMachineConfig struct. | [
"Prepare",
"performs",
"basic",
"validation",
"on",
"a",
"SourceMachineConfig",
"struct",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/triton/source_machine_config.go#L38-L66 |
165,047 | hashicorp/packer | packer/hook.go | Run | func (h *DispatchHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error {
hooks, ok := h.Mapping[name]
if !ok {
// No hooks for that name. No problem.
return nil
}
for _, hook := range hooks {
if err := ctx.Err(); err != nil {
return err
}
if err := hook.Run(ctx, name, ui, comm, data); err != nil {
return err
}
}
return nil
} | go | func (h *DispatchHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error {
hooks, ok := h.Mapping[name]
if !ok {
// No hooks for that name. No problem.
return nil
}
for _, hook := range hooks {
if err := ctx.Err(); err != nil {
return err
}
if err := hook.Run(ctx, name, ui, comm, data); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"h",
"*",
"DispatchHook",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"ui",
"Ui",
",",
"comm",
"Communicator",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"hooks",
",",
"ok",
":=",
"h",
"."... | // Runs the hook with the given name by dispatching it to the proper
// hooks if a mapping exists. If a mapping doesn't exist, then nothing
// happens. | [
"Runs",
"the",
"hook",
"with",
"the",
"given",
"name",
"by",
"dispatching",
"it",
"to",
"the",
"proper",
"hooks",
"if",
"a",
"mapping",
"exists",
".",
"If",
"a",
"mapping",
"doesn",
"t",
"exist",
"then",
"nothing",
"happens",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/hook.go#L35-L54 |
165,048 | hashicorp/packer | builder/proxmox/builder.go | getVMIP | func getVMIP(state multistep.StateBag) (string, error) {
c := state.Get("proxmoxClient").(*proxmox.Client)
vmRef := state.Get("vmRef").(*proxmox.VmRef)
ifs, err := c.GetVmAgentNetworkInterfaces(vmRef)
if err != nil {
return "", err
}
// TODO: Do something smarter here? Allow specifying interface? Or address family?
// For now, just go for first non-loopback
for _, iface := range ifs {
for _, addr := range iface.IPAddresses {
if addr.IsLoopback() {
continue
}
return addr.String(), nil
}
}
return "", fmt.Errorf("Found no IP addresses on VM")
} | go | func getVMIP(state multistep.StateBag) (string, error) {
c := state.Get("proxmoxClient").(*proxmox.Client)
vmRef := state.Get("vmRef").(*proxmox.VmRef)
ifs, err := c.GetVmAgentNetworkInterfaces(vmRef)
if err != nil {
return "", err
}
// TODO: Do something smarter here? Allow specifying interface? Or address family?
// For now, just go for first non-loopback
for _, iface := range ifs {
for _, addr := range iface.IPAddresses {
if addr.IsLoopback() {
continue
}
return addr.String(), nil
}
}
return "", fmt.Errorf("Found no IP addresses on VM")
} | [
"func",
"getVMIP",
"(",
"state",
"multistep",
".",
"StateBag",
")",
"(",
"string",
",",
"error",
")",
"{",
"c",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"proxmox",
".",
"Client",
")",
"\n",
"vmRef",
":=",
"state",
".",
"Get... | // Reads the first non-loopback interface's IP address from the VM.
// qemu-guest-agent package must be installed on the VM | [
"Reads",
"the",
"first",
"non",
"-",
"loopback",
"interface",
"s",
"IP",
"address",
"from",
"the",
"VM",
".",
"qemu",
"-",
"guest",
"-",
"agent",
"package",
"must",
"be",
"installed",
"on",
"the",
"VM"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/proxmox/builder.go#L114-L135 |
165,049 | hashicorp/packer | builder/docker/step_temp_dir.go | ConfigTmpDir | func ConfigTmpDir() (string, error) {
if tmpdir := os.Getenv("PACKER_TMP_DIR"); tmpdir != "" {
return filepath.Abs(tmpdir)
}
configdir, err := packer.ConfigDir()
if err != nil {
return "", err
}
td := filepath.Join(configdir, "tmp")
_, err = os.Stat(td)
if os.IsNotExist(err) {
if err = os.MkdirAll(td, 0755); err != nil {
return "", err
}
} else if err != nil {
return "", err
}
return td, nil
} | go | func ConfigTmpDir() (string, error) {
if tmpdir := os.Getenv("PACKER_TMP_DIR"); tmpdir != "" {
return filepath.Abs(tmpdir)
}
configdir, err := packer.ConfigDir()
if err != nil {
return "", err
}
td := filepath.Join(configdir, "tmp")
_, err = os.Stat(td)
if os.IsNotExist(err) {
if err = os.MkdirAll(td, 0755); err != nil {
return "", err
}
} else if err != nil {
return "", err
}
return td, nil
} | [
"func",
"ConfigTmpDir",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"tmpdir",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"tmpdir",
"!=",
"\"",
"\"",
"{",
"return",
"filepath",
".",
"Abs",
"(",
"tmpdir",
")",
"\n",
"}",
"\n",... | // ConfigTmpDir returns the configuration tmp directory for Docker | [
"ConfigTmpDir",
"returns",
"the",
"configuration",
"tmp",
"directory",
"for",
"Docker"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/step_temp_dir.go#L20-L38 |
165,050 | hashicorp/packer | builder/parallels/common/tools_config.go | Prepare | func (c *ToolsConfig) Prepare(ctx *interpolate.Context) []error {
if c.ParallelsToolsMode == "" {
c.ParallelsToolsMode = ParallelsToolsModeUpload
}
if c.ParallelsToolsGuestPath == "" {
c.ParallelsToolsGuestPath = "prl-tools-{{.Flavor}}.iso"
}
validMode := false
validModes := []string{
ParallelsToolsModeDisable,
ParallelsToolsModeAttach,
ParallelsToolsModeUpload,
}
for _, mode := range validModes {
if c.ParallelsToolsMode == mode {
validMode = true
break
}
}
var errs []error
if !validMode {
errs = append(errs,
fmt.Errorf("parallels_tools_mode is invalid. Must be one of: %v",
validModes))
}
if c.ParallelsToolsFlavor == "" {
if c.ParallelsToolsMode != ParallelsToolsModeDisable {
errs = append(errs, errors.New("parallels_tools_flavor must be specified"))
}
}
return errs
} | go | func (c *ToolsConfig) Prepare(ctx *interpolate.Context) []error {
if c.ParallelsToolsMode == "" {
c.ParallelsToolsMode = ParallelsToolsModeUpload
}
if c.ParallelsToolsGuestPath == "" {
c.ParallelsToolsGuestPath = "prl-tools-{{.Flavor}}.iso"
}
validMode := false
validModes := []string{
ParallelsToolsModeDisable,
ParallelsToolsModeAttach,
ParallelsToolsModeUpload,
}
for _, mode := range validModes {
if c.ParallelsToolsMode == mode {
validMode = true
break
}
}
var errs []error
if !validMode {
errs = append(errs,
fmt.Errorf("parallels_tools_mode is invalid. Must be one of: %v",
validModes))
}
if c.ParallelsToolsFlavor == "" {
if c.ParallelsToolsMode != ParallelsToolsModeDisable {
errs = append(errs, errors.New("parallels_tools_flavor must be specified"))
}
}
return errs
} | [
"func",
"(",
"c",
"*",
"ToolsConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"if",
"c",
".",
"ParallelsToolsMode",
"==",
"\"",
"\"",
"{",
"c",
".",
"ParallelsToolsMode",
"=",
"ParallelsToolsModeUpload",... | // Prepare validates & sets up configuration options related to Parallels Tools. | [
"Prepare",
"validates",
"&",
"sets",
"up",
"configuration",
"options",
"related",
"to",
"Parallels",
"Tools",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/tools_config.go#L26-L63 |
165,051 | hashicorp/packer | builder/hyperv/common/artifact.go | NewArtifact | func NewArtifact(dir string) (packer.Artifact, error) {
files := make([]string, 0, 5)
visit := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
files = append(files, path)
}
return nil
}
if err := filepath.Walk(dir, visit); err != nil {
return nil, err
}
return &artifact{
dir: dir,
f: files,
}, nil
} | go | func NewArtifact(dir string) (packer.Artifact, error) {
files := make([]string, 0, 5)
visit := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
files = append(files, path)
}
return nil
}
if err := filepath.Walk(dir, visit); err != nil {
return nil, err
}
return &artifact{
dir: dir,
f: files,
}, nil
} | [
"func",
"NewArtifact",
"(",
"dir",
"string",
")",
"(",
"packer",
".",
"Artifact",
",",
"error",
")",
"{",
"files",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"\n",
"visit",
":=",
"func",
"(",
"path",
"string",
",",
"info",
"o... | // NewArtifact returns a hyperv artifact containing the files
// in the given directory. | [
"NewArtifact",
"returns",
"a",
"hyperv",
"artifact",
"containing",
"the",
"files",
"in",
"the",
"given",
"directory",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/artifact.go#L23-L44 |
165,052 | hashicorp/packer | builder/docker/communicator.go | Upload | func (c *Communicator) Upload(dst string, src io.Reader, fi *os.FileInfo) error {
if fi == nil {
return c.uploadReader(dst, src)
}
return c.uploadFile(dst, src, fi)
} | go | func (c *Communicator) Upload(dst string, src io.Reader, fi *os.FileInfo) error {
if fi == nil {
return c.uploadReader(dst, src)
}
return c.uploadFile(dst, src, fi)
} | [
"func",
"(",
"c",
"*",
"Communicator",
")",
"Upload",
"(",
"dst",
"string",
",",
"src",
"io",
".",
"Reader",
",",
"fi",
"*",
"os",
".",
"FileInfo",
")",
"error",
"{",
"if",
"fi",
"==",
"nil",
"{",
"return",
"c",
".",
"uploadReader",
"(",
"dst",
"... | // Upload uploads a file to the docker container | [
"Upload",
"uploads",
"a",
"file",
"to",
"the",
"docker",
"container"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/communicator.go#L81-L86 |
165,053 | hashicorp/packer | builder/docker/communicator.go | uploadReader | func (c *Communicator) uploadReader(dst string, src io.Reader) error {
// Create a temporary file to store the upload
tempfile, err := ioutil.TempFile(c.HostDir, "upload")
if err != nil {
return fmt.Errorf("Failed to open temp file for writing: %s", err)
}
defer os.Remove(tempfile.Name())
defer tempfile.Close()
if _, err := io.Copy(tempfile, src); err != nil {
return fmt.Errorf("Failed to copy upload file to tempfile: %s", err)
}
tempfile.Seek(0, 0)
fi, err := tempfile.Stat()
if err != nil {
return fmt.Errorf("Error getting tempfile info: %s", err)
}
return c.uploadFile(dst, tempfile, &fi)
} | go | func (c *Communicator) uploadReader(dst string, src io.Reader) error {
// Create a temporary file to store the upload
tempfile, err := ioutil.TempFile(c.HostDir, "upload")
if err != nil {
return fmt.Errorf("Failed to open temp file for writing: %s", err)
}
defer os.Remove(tempfile.Name())
defer tempfile.Close()
if _, err := io.Copy(tempfile, src); err != nil {
return fmt.Errorf("Failed to copy upload file to tempfile: %s", err)
}
tempfile.Seek(0, 0)
fi, err := tempfile.Stat()
if err != nil {
return fmt.Errorf("Error getting tempfile info: %s", err)
}
return c.uploadFile(dst, tempfile, &fi)
} | [
"func",
"(",
"c",
"*",
"Communicator",
")",
"uploadReader",
"(",
"dst",
"string",
",",
"src",
"io",
".",
"Reader",
")",
"error",
"{",
"// Create a temporary file to store the upload",
"tempfile",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"c",
".",
"H... | // uploadReader writes an io.Reader to a temporary file before uploading | [
"uploadReader",
"writes",
"an",
"io",
".",
"Reader",
"to",
"a",
"temporary",
"file",
"before",
"uploading"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/communicator.go#L89-L107 |
165,054 | hashicorp/packer | builder/docker/communicator.go | uploadFile | func (c *Communicator) uploadFile(dst string, src io.Reader, fi *os.FileInfo) error {
// command format: docker cp /path/to/infile containerid:/path/to/outfile
log.Printf("Copying to %s on container %s.", dst, c.ContainerID)
localCmd := exec.Command("docker", "cp", "-",
fmt.Sprintf("%s:%s", c.ContainerID, filepath.Dir(dst)))
stderrP, err := localCmd.StderrPipe()
if err != nil {
return fmt.Errorf("Failed to open pipe: %s", err)
}
stdin, err := localCmd.StdinPipe()
if err != nil {
return fmt.Errorf("Failed to open pipe: %s", err)
}
if err := localCmd.Start(); err != nil {
return err
}
archive := tar.NewWriter(stdin)
header, err := tar.FileInfoHeader(*fi, "")
if err != nil {
return err
}
header.Name = filepath.Base(dst)
archive.WriteHeader(header)
numBytes, err := io.Copy(archive, src)
if err != nil {
return fmt.Errorf("Failed to pipe upload: %s", err)
}
log.Printf("Copied %d bytes for %s", numBytes, dst)
if err := archive.Close(); err != nil {
return fmt.Errorf("Failed to close archive: %s", err)
}
if err := stdin.Close(); err != nil {
return fmt.Errorf("Failed to close stdin: %s", err)
}
stderrOut, err := ioutil.ReadAll(stderrP)
if err != nil {
return err
}
if err := localCmd.Wait(); err != nil {
return fmt.Errorf("Failed to upload to '%s' in container: %s. %s.", dst, stderrOut, err)
}
if err := c.fixDestinationOwner(dst); err != nil {
return err
}
return nil
} | go | func (c *Communicator) uploadFile(dst string, src io.Reader, fi *os.FileInfo) error {
// command format: docker cp /path/to/infile containerid:/path/to/outfile
log.Printf("Copying to %s on container %s.", dst, c.ContainerID)
localCmd := exec.Command("docker", "cp", "-",
fmt.Sprintf("%s:%s", c.ContainerID, filepath.Dir(dst)))
stderrP, err := localCmd.StderrPipe()
if err != nil {
return fmt.Errorf("Failed to open pipe: %s", err)
}
stdin, err := localCmd.StdinPipe()
if err != nil {
return fmt.Errorf("Failed to open pipe: %s", err)
}
if err := localCmd.Start(); err != nil {
return err
}
archive := tar.NewWriter(stdin)
header, err := tar.FileInfoHeader(*fi, "")
if err != nil {
return err
}
header.Name = filepath.Base(dst)
archive.WriteHeader(header)
numBytes, err := io.Copy(archive, src)
if err != nil {
return fmt.Errorf("Failed to pipe upload: %s", err)
}
log.Printf("Copied %d bytes for %s", numBytes, dst)
if err := archive.Close(); err != nil {
return fmt.Errorf("Failed to close archive: %s", err)
}
if err := stdin.Close(); err != nil {
return fmt.Errorf("Failed to close stdin: %s", err)
}
stderrOut, err := ioutil.ReadAll(stderrP)
if err != nil {
return err
}
if err := localCmd.Wait(); err != nil {
return fmt.Errorf("Failed to upload to '%s' in container: %s. %s.", dst, stderrOut, err)
}
if err := c.fixDestinationOwner(dst); err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"Communicator",
")",
"uploadFile",
"(",
"dst",
"string",
",",
"src",
"io",
".",
"Reader",
",",
"fi",
"*",
"os",
".",
"FileInfo",
")",
"error",
"{",
"// command format: docker cp /path/to/infile containerid:/path/to/outfile",
"log",
".",
"P... | // uploadFile uses docker cp to copy the file from the host to the container | [
"uploadFile",
"uses",
"docker",
"cp",
"to",
"copy",
"the",
"file",
"from",
"the",
"host",
"to",
"the",
"container"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/communicator.go#L110-L165 |
165,055 | hashicorp/packer | builder/docker/communicator.go | Download | func (c *Communicator) Download(src string, dst io.Writer) error {
log.Printf("Downloading file from container: %s:%s", c.ContainerID, src)
localCmd := exec.Command("docker", "cp", fmt.Sprintf("%s:%s", c.ContainerID, src), "-")
pipe, err := localCmd.StdoutPipe()
if err != nil {
return fmt.Errorf("Failed to open pipe: %s", err)
}
stderrP, err := localCmd.StderrPipe()
if err != nil {
return fmt.Errorf("Failed to open stderr pipe: %s", err)
}
if err = localCmd.Start(); err != nil {
return fmt.Errorf("Failed to start download: %s", err)
}
// When you use - to send docker cp to stdout it is streamed as a tar; this
// enables it to work with directories. We don't actually support
// directories in Download() but we still need to handle the tar format.
stderrOut, err := ioutil.ReadAll(stderrP)
if err != nil {
return err
}
if string(stderrOut) != "" {
return fmt.Errorf("Error downloading file: %s", string(stderrOut))
}
archive := tar.NewReader(pipe)
_, err = archive.Next()
if err != nil {
return fmt.Errorf("Failed to read header from tar stream: %s", err)
}
numBytes, err := io.Copy(dst, archive)
if err != nil {
return fmt.Errorf("Failed to pipe download: %s", err)
}
log.Printf("Copied %d bytes for %s", numBytes, src)
if err = localCmd.Wait(); err != nil {
return fmt.Errorf("Failed to download '%s' from container: %s", src, err)
}
return nil
} | go | func (c *Communicator) Download(src string, dst io.Writer) error {
log.Printf("Downloading file from container: %s:%s", c.ContainerID, src)
localCmd := exec.Command("docker", "cp", fmt.Sprintf("%s:%s", c.ContainerID, src), "-")
pipe, err := localCmd.StdoutPipe()
if err != nil {
return fmt.Errorf("Failed to open pipe: %s", err)
}
stderrP, err := localCmd.StderrPipe()
if err != nil {
return fmt.Errorf("Failed to open stderr pipe: %s", err)
}
if err = localCmd.Start(); err != nil {
return fmt.Errorf("Failed to start download: %s", err)
}
// When you use - to send docker cp to stdout it is streamed as a tar; this
// enables it to work with directories. We don't actually support
// directories in Download() but we still need to handle the tar format.
stderrOut, err := ioutil.ReadAll(stderrP)
if err != nil {
return err
}
if string(stderrOut) != "" {
return fmt.Errorf("Error downloading file: %s", string(stderrOut))
}
archive := tar.NewReader(pipe)
_, err = archive.Next()
if err != nil {
return fmt.Errorf("Failed to read header from tar stream: %s", err)
}
numBytes, err := io.Copy(dst, archive)
if err != nil {
return fmt.Errorf("Failed to pipe download: %s", err)
}
log.Printf("Copied %d bytes for %s", numBytes, src)
if err = localCmd.Wait(); err != nil {
return fmt.Errorf("Failed to download '%s' from container: %s", src, err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Communicator",
")",
"Download",
"(",
"src",
"string",
",",
"dst",
"io",
".",
"Writer",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"c",
".",
"ContainerID",
",",
"src",
")",
"\n",
"localCmd",
":=",
"exec",
... | // Download pulls a file out of a container using `docker cp`. We have a source
// path and want to write to an io.Writer, not a file. We use - to make docker
// cp to write to stdout, and then copy the stream to our destination io.Writer. | [
"Download",
"pulls",
"a",
"file",
"out",
"of",
"a",
"container",
"using",
"docker",
"cp",
".",
"We",
"have",
"a",
"source",
"path",
"and",
"want",
"to",
"write",
"to",
"an",
"io",
".",
"Writer",
"not",
"a",
"file",
".",
"We",
"use",
"-",
"to",
"mak... | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/communicator.go#L227-L275 |
165,056 | hashicorp/packer | builder/docker/communicator.go | run | func (c *Communicator) run(cmd *exec.Cmd, remote *packer.RemoteCmd, stdin io.WriteCloser, stdout, stderr io.ReadCloser) {
// For Docker, remote communication must be serialized since it
// only supports single execution.
c.lock.Lock()
defer c.lock.Unlock()
wg := sync.WaitGroup{}
repeat := func(w io.Writer, r io.ReadCloser) {
io.Copy(w, r)
r.Close()
wg.Done()
}
if remote.Stdout != nil {
wg.Add(1)
go repeat(remote.Stdout, stdout)
}
if remote.Stderr != nil {
wg.Add(1)
go repeat(remote.Stderr, stderr)
}
// Start the command
log.Printf("Executing %s:", strings.Join(cmd.Args, " "))
if err := cmd.Start(); err != nil {
log.Printf("Error executing: %s", err)
remote.SetExited(254)
return
}
var exitStatus int
if remote.Stdin != nil {
go func() {
io.Copy(stdin, remote.Stdin)
// close stdin to support commands that wait for stdin to be closed before exiting.
stdin.Close()
}()
}
wg.Wait()
err := cmd.Wait()
if exitErr, ok := err.(*exec.ExitError); ok {
exitStatus = 1
// There is no process-independent way to get the REAL
// exit status so we just try to go deeper.
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
exitStatus = status.ExitStatus()
}
}
// Set the exit status which triggers waiters
remote.SetExited(exitStatus)
} | go | func (c *Communicator) run(cmd *exec.Cmd, remote *packer.RemoteCmd, stdin io.WriteCloser, stdout, stderr io.ReadCloser) {
// For Docker, remote communication must be serialized since it
// only supports single execution.
c.lock.Lock()
defer c.lock.Unlock()
wg := sync.WaitGroup{}
repeat := func(w io.Writer, r io.ReadCloser) {
io.Copy(w, r)
r.Close()
wg.Done()
}
if remote.Stdout != nil {
wg.Add(1)
go repeat(remote.Stdout, stdout)
}
if remote.Stderr != nil {
wg.Add(1)
go repeat(remote.Stderr, stderr)
}
// Start the command
log.Printf("Executing %s:", strings.Join(cmd.Args, " "))
if err := cmd.Start(); err != nil {
log.Printf("Error executing: %s", err)
remote.SetExited(254)
return
}
var exitStatus int
if remote.Stdin != nil {
go func() {
io.Copy(stdin, remote.Stdin)
// close stdin to support commands that wait for stdin to be closed before exiting.
stdin.Close()
}()
}
wg.Wait()
err := cmd.Wait()
if exitErr, ok := err.(*exec.ExitError); ok {
exitStatus = 1
// There is no process-independent way to get the REAL
// exit status so we just try to go deeper.
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
exitStatus = status.ExitStatus()
}
}
// Set the exit status which triggers waiters
remote.SetExited(exitStatus)
} | [
"func",
"(",
"c",
"*",
"Communicator",
")",
"run",
"(",
"cmd",
"*",
"exec",
".",
"Cmd",
",",
"remote",
"*",
"packer",
".",
"RemoteCmd",
",",
"stdin",
"io",
".",
"WriteCloser",
",",
"stdout",
",",
"stderr",
"io",
".",
"ReadCloser",
")",
"{",
"// For D... | // Runs the given command and blocks until completion | [
"Runs",
"the",
"given",
"command",
"and",
"blocks",
"until",
"completion"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/communicator.go#L282-L338 |
165,057 | hashicorp/packer | builder/amazon/common/step_ami_region_copy.go | amiRegionCopy | func amiRegionCopy(ctx context.Context, state multistep.StateBag, config *AccessConfig, name, imageId,
target, source, keyId string, encrypt *bool) (string, []string, error) {
snapshotIds := []string{}
// Connect to the region where the AMI will be copied to
session, err := config.Session()
if err != nil {
return "", snapshotIds, err
}
regionconn := ec2.New(session.Copy(&aws.Config{
Region: aws.String(target),
}))
resp, err := regionconn.CopyImage(&ec2.CopyImageInput{
SourceRegion: &source,
SourceImageId: &imageId,
Name: &name,
Encrypted: encrypt,
KmsKeyId: aws.String(keyId),
})
if err != nil {
return "", snapshotIds, fmt.Errorf("Error Copying AMI (%s) to region (%s): %s",
imageId, target, err)
}
// Wait for the image to become ready
if err := WaitUntilAMIAvailable(ctx, regionconn, *resp.ImageId); err != nil {
return "", snapshotIds, fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s",
*resp.ImageId, target, err)
}
// Getting snapshot IDs out of the copied AMI
describeImageResp, err := regionconn.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{resp.ImageId}})
if err != nil {
return "", snapshotIds, fmt.Errorf("Error describing copied AMI (%s) in region (%s): %s",
imageId, target, err)
}
for _, blockDeviceMapping := range describeImageResp.Images[0].BlockDeviceMappings {
if blockDeviceMapping.Ebs != nil && blockDeviceMapping.Ebs.SnapshotId != nil {
snapshotIds = append(snapshotIds, *blockDeviceMapping.Ebs.SnapshotId)
}
}
return *resp.ImageId, snapshotIds, nil
} | go | func amiRegionCopy(ctx context.Context, state multistep.StateBag, config *AccessConfig, name, imageId,
target, source, keyId string, encrypt *bool) (string, []string, error) {
snapshotIds := []string{}
// Connect to the region where the AMI will be copied to
session, err := config.Session()
if err != nil {
return "", snapshotIds, err
}
regionconn := ec2.New(session.Copy(&aws.Config{
Region: aws.String(target),
}))
resp, err := regionconn.CopyImage(&ec2.CopyImageInput{
SourceRegion: &source,
SourceImageId: &imageId,
Name: &name,
Encrypted: encrypt,
KmsKeyId: aws.String(keyId),
})
if err != nil {
return "", snapshotIds, fmt.Errorf("Error Copying AMI (%s) to region (%s): %s",
imageId, target, err)
}
// Wait for the image to become ready
if err := WaitUntilAMIAvailable(ctx, regionconn, *resp.ImageId); err != nil {
return "", snapshotIds, fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s",
*resp.ImageId, target, err)
}
// Getting snapshot IDs out of the copied AMI
describeImageResp, err := regionconn.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{resp.ImageId}})
if err != nil {
return "", snapshotIds, fmt.Errorf("Error describing copied AMI (%s) in region (%s): %s",
imageId, target, err)
}
for _, blockDeviceMapping := range describeImageResp.Images[0].BlockDeviceMappings {
if blockDeviceMapping.Ebs != nil && blockDeviceMapping.Ebs.SnapshotId != nil {
snapshotIds = append(snapshotIds, *blockDeviceMapping.Ebs.SnapshotId)
}
}
return *resp.ImageId, snapshotIds, nil
} | [
"func",
"amiRegionCopy",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
",",
"config",
"*",
"AccessConfig",
",",
"name",
",",
"imageId",
",",
"target",
",",
"source",
",",
"keyId",
"string",
",",
"encrypt",
"*",
"bool",
... | // amiRegionCopy does a copy for the given AMI to the target region and
// returns the resulting ID and snapshot IDs, or error. | [
"amiRegionCopy",
"does",
"a",
"copy",
"for",
"the",
"given",
"AMI",
"to",
"the",
"target",
"region",
"and",
"returns",
"the",
"resulting",
"ID",
"and",
"snapshot",
"IDs",
"or",
"error",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/step_ami_region_copy.go#L100-L147 |
165,058 | hashicorp/packer | provisioner/powershell/provisioner.go | extractScript | func extractScript(p *Provisioner) (string, error) {
temp, err := tmp.File("powershell-provisioner")
if err != nil {
return "", err
}
defer temp.Close()
writer := bufio.NewWriter(temp)
for _, command := range p.config.Inline {
log.Printf("Found command: %s", command)
if _, err := writer.WriteString(command + "\n"); err != nil {
return "", fmt.Errorf("Error preparing powershell script: %s", err)
}
}
if err := writer.Flush(); err != nil {
return "", fmt.Errorf("Error preparing powershell script: %s", err)
}
return temp.Name(), nil
} | go | func extractScript(p *Provisioner) (string, error) {
temp, err := tmp.File("powershell-provisioner")
if err != nil {
return "", err
}
defer temp.Close()
writer := bufio.NewWriter(temp)
for _, command := range p.config.Inline {
log.Printf("Found command: %s", command)
if _, err := writer.WriteString(command + "\n"); err != nil {
return "", fmt.Errorf("Error preparing powershell script: %s", err)
}
}
if err := writer.Flush(); err != nil {
return "", fmt.Errorf("Error preparing powershell script: %s", err)
}
return temp.Name(), nil
} | [
"func",
"extractScript",
"(",
"p",
"*",
"Provisioner",
")",
"(",
"string",
",",
"error",
")",
"{",
"temp",
",",
"err",
":=",
"tmp",
".",
"File",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
... | // Takes the inline scripts, concatenates them into a temporary file and
// returns a string containing the location of said file. | [
"Takes",
"the",
"inline",
"scripts",
"concatenates",
"them",
"into",
"a",
"temporary",
"file",
"and",
"returns",
"a",
"string",
"containing",
"the",
"location",
"of",
"said",
"file",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/provisioner/powershell/provisioner.go#L199-L218 |
165,059 | hashicorp/packer | provisioner/powershell/provisioner.go | prepareEnvVars | func (p *Provisioner) prepareEnvVars(elevated bool) (err error) {
// Collate all required env vars into a plain string with required
// formatting applied
flattenedEnvVars := p.createFlattenedEnvVars(elevated)
// Create a powershell script on the target build fs containing the
// flattened env vars
err = p.uploadEnvVars(flattenedEnvVars)
if err != nil {
return err
}
return
} | go | func (p *Provisioner) prepareEnvVars(elevated bool) (err error) {
// Collate all required env vars into a plain string with required
// formatting applied
flattenedEnvVars := p.createFlattenedEnvVars(elevated)
// Create a powershell script on the target build fs containing the
// flattened env vars
err = p.uploadEnvVars(flattenedEnvVars)
if err != nil {
return err
}
return
} | [
"func",
"(",
"p",
"*",
"Provisioner",
")",
"prepareEnvVars",
"(",
"elevated",
"bool",
")",
"(",
"err",
"error",
")",
"{",
"// Collate all required env vars into a plain string with required",
"// formatting applied",
"flattenedEnvVars",
":=",
"p",
".",
"createFlattenedEnv... | // Environment variables required within the remote environment are uploaded
// within a PS script and then enabled by 'dot sourcing' the script
// immediately prior to execution of the main command | [
"Environment",
"variables",
"required",
"within",
"the",
"remote",
"environment",
"are",
"uploaded",
"within",
"a",
"PS",
"script",
"and",
"then",
"enabled",
"by",
"dot",
"sourcing",
"the",
"script",
"immediately",
"prior",
"to",
"execution",
"of",
"the",
"main"... | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/provisioner/powershell/provisioner.go#L292-L303 |
165,060 | hashicorp/packer | packer/core.go | NewCore | func NewCore(c *CoreConfig) (*Core, error) {
result := &Core{
Template: c.Template,
components: c.Components,
variables: c.Variables,
version: c.Version,
only: c.Only,
except: c.Except,
}
if err := result.validate(); err != nil {
return nil, err
}
if err := result.init(); err != nil {
return nil, err
}
for _, secret := range result.secrets {
LogSecretFilter.Set(secret)
}
// Go through and interpolate all the build names. We should be able
// to do this at this point with the variables.
result.builds = make(map[string]*template.Builder)
for _, b := range c.Template.Builders {
v, err := interpolate.Render(b.Name, result.Context())
if err != nil {
return nil, fmt.Errorf(
"Error interpolating builder '%s': %s",
b.Name, err)
}
result.builds[v] = b
}
return result, nil
} | go | func NewCore(c *CoreConfig) (*Core, error) {
result := &Core{
Template: c.Template,
components: c.Components,
variables: c.Variables,
version: c.Version,
only: c.Only,
except: c.Except,
}
if err := result.validate(); err != nil {
return nil, err
}
if err := result.init(); err != nil {
return nil, err
}
for _, secret := range result.secrets {
LogSecretFilter.Set(secret)
}
// Go through and interpolate all the build names. We should be able
// to do this at this point with the variables.
result.builds = make(map[string]*template.Builder)
for _, b := range c.Template.Builders {
v, err := interpolate.Render(b.Name, result.Context())
if err != nil {
return nil, fmt.Errorf(
"Error interpolating builder '%s': %s",
b.Name, err)
}
result.builds[v] = b
}
return result, nil
} | [
"func",
"NewCore",
"(",
"c",
"*",
"CoreConfig",
")",
"(",
"*",
"Core",
",",
"error",
")",
"{",
"result",
":=",
"&",
"Core",
"{",
"Template",
":",
"c",
".",
"Template",
",",
"components",
":",
"c",
".",
"Components",
",",
"variables",
":",
"c",
".",... | // NewCore creates a new Core. | [
"NewCore",
"creates",
"a",
"new",
"Core",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/core.go#L67-L102 |
165,061 | hashicorp/packer | packer/core.go | BuildNames | func (c *Core) BuildNames() []string {
r := make([]string, 0, len(c.builds))
for n := range c.builds {
r = append(r, n)
}
sort.Strings(r)
return r
} | go | func (c *Core) BuildNames() []string {
r := make([]string, 0, len(c.builds))
for n := range c.builds {
r = append(r, n)
}
sort.Strings(r)
return r
} | [
"func",
"(",
"c",
"*",
"Core",
")",
"BuildNames",
"(",
")",
"[",
"]",
"string",
"{",
"r",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"c",
".",
"builds",
")",
")",
"\n",
"for",
"n",
":=",
"range",
"c",
".",
"builds",
"... | // BuildNames returns the builds that are available in this configured core. | [
"BuildNames",
"returns",
"the",
"builds",
"that",
"are",
"available",
"in",
"this",
"configured",
"core",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/core.go#L105-L113 |
165,062 | hashicorp/packer | packer/core.go | Context | func (c *Core) Context() *interpolate.Context {
return &interpolate.Context{
TemplatePath: c.Template.Path,
UserVariables: c.variables,
}
} | go | func (c *Core) Context() *interpolate.Context {
return &interpolate.Context{
TemplatePath: c.Template.Path,
UserVariables: c.variables,
}
} | [
"func",
"(",
"c",
"*",
"Core",
")",
"Context",
"(",
")",
"*",
"interpolate",
".",
"Context",
"{",
"return",
"&",
"interpolate",
".",
"Context",
"{",
"TemplatePath",
":",
"c",
".",
"Template",
".",
"Path",
",",
"UserVariables",
":",
"c",
".",
"variables... | // Context returns an interpolation context. | [
"Context",
"returns",
"an",
"interpolation",
"context",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/core.go#L247-L252 |
165,063 | hashicorp/packer | builder/openstack/step_create_image.go | WaitForImage | func WaitForImage(ctx context.Context, client *gophercloud.ServiceClient, imageId string) error {
maxNumErrors := 10
numErrors := 0
for {
if err := ctx.Err(); err != nil {
return err
}
image, err := images.Get(client, imageId).Extract()
if err != nil {
errCode, ok := err.(*gophercloud.ErrUnexpectedResponseCode)
if ok && (errCode.Actual == 500 || errCode.Actual == 404) {
numErrors++
if numErrors >= maxNumErrors {
log.Printf("[ERROR] Maximum number of errors (%d) reached; failing with: %s", numErrors, err)
return err
}
log.Printf("[ERROR] %d error received, will ignore and retry: %s", errCode.Actual, err)
time.Sleep(2 * time.Second)
continue
}
return err
}
if image.Status == "active" {
return nil
}
log.Printf("Waiting for image creation status: %s", image.Status)
time.Sleep(2 * time.Second)
}
} | go | func WaitForImage(ctx context.Context, client *gophercloud.ServiceClient, imageId string) error {
maxNumErrors := 10
numErrors := 0
for {
if err := ctx.Err(); err != nil {
return err
}
image, err := images.Get(client, imageId).Extract()
if err != nil {
errCode, ok := err.(*gophercloud.ErrUnexpectedResponseCode)
if ok && (errCode.Actual == 500 || errCode.Actual == 404) {
numErrors++
if numErrors >= maxNumErrors {
log.Printf("[ERROR] Maximum number of errors (%d) reached; failing with: %s", numErrors, err)
return err
}
log.Printf("[ERROR] %d error received, will ignore and retry: %s", errCode.Actual, err)
time.Sleep(2 * time.Second)
continue
}
return err
}
if image.Status == "active" {
return nil
}
log.Printf("Waiting for image creation status: %s", image.Status)
time.Sleep(2 * time.Second)
}
} | [
"func",
"WaitForImage",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"imageId",
"string",
")",
"error",
"{",
"maxNumErrors",
":=",
"10",
"\n",
"numErrors",
":=",
"0",
"\n\n",
"for",
"{",
"if",
"err",
... | // WaitForImage waits for the given Image ID to become ready. | [
"WaitForImage",
"waits",
"for",
"the",
"given",
"Image",
"ID",
"to",
"become",
"ready",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/step_create_image.go#L102-L134 |
165,064 | hashicorp/packer | builder/vmware/common/driver.go | NewDriver | func NewDriver(dconfig *DriverConfig, config *SSHConfig, vmName string) (Driver, error) {
drivers := []Driver{}
if dconfig.RemoteType != "" {
drivers = []Driver{
&ESX5Driver{
Host: dconfig.RemoteHost,
Port: dconfig.RemotePort,
Username: dconfig.RemoteUser,
Password: dconfig.RemotePassword,
PrivateKeyFile: dconfig.RemotePrivateKey,
Datastore: dconfig.RemoteDatastore,
CacheDatastore: dconfig.RemoteCacheDatastore,
CacheDirectory: dconfig.RemoteCacheDirectory,
VMName: vmName,
CommConfig: config.Comm,
},
}
} else {
switch runtime.GOOS {
case "darwin":
drivers = []Driver{
&Fusion6Driver{
Fusion5Driver: Fusion5Driver{
AppPath: dconfig.FusionAppPath,
SSHConfig: config,
},
},
&Fusion5Driver{
AppPath: dconfig.FusionAppPath,
SSHConfig: config,
},
}
case "linux":
fallthrough
case "windows":
drivers = []Driver{
&Workstation10Driver{
Workstation9Driver: Workstation9Driver{
SSHConfig: config,
},
},
&Workstation9Driver{
SSHConfig: config,
},
&Player6Driver{
Player5Driver: Player5Driver{
SSHConfig: config,
},
},
&Player5Driver{
SSHConfig: config,
},
}
default:
return nil, fmt.Errorf("can't find driver for OS: %s", runtime.GOOS)
}
}
errs := ""
for _, driver := range drivers {
err := driver.Verify()
log.Printf("Testing vmware driver %T. Success: %t",
driver, err == nil)
if err == nil {
return driver, nil
}
errs += "* " + err.Error() + "\n"
}
return nil, fmt.Errorf(
"Unable to initialize any driver for this platform. The errors\n"+
"from each driver are shown below. Please fix at least one driver\n"+
"to continue:\n%s", errs)
} | go | func NewDriver(dconfig *DriverConfig, config *SSHConfig, vmName string) (Driver, error) {
drivers := []Driver{}
if dconfig.RemoteType != "" {
drivers = []Driver{
&ESX5Driver{
Host: dconfig.RemoteHost,
Port: dconfig.RemotePort,
Username: dconfig.RemoteUser,
Password: dconfig.RemotePassword,
PrivateKeyFile: dconfig.RemotePrivateKey,
Datastore: dconfig.RemoteDatastore,
CacheDatastore: dconfig.RemoteCacheDatastore,
CacheDirectory: dconfig.RemoteCacheDirectory,
VMName: vmName,
CommConfig: config.Comm,
},
}
} else {
switch runtime.GOOS {
case "darwin":
drivers = []Driver{
&Fusion6Driver{
Fusion5Driver: Fusion5Driver{
AppPath: dconfig.FusionAppPath,
SSHConfig: config,
},
},
&Fusion5Driver{
AppPath: dconfig.FusionAppPath,
SSHConfig: config,
},
}
case "linux":
fallthrough
case "windows":
drivers = []Driver{
&Workstation10Driver{
Workstation9Driver: Workstation9Driver{
SSHConfig: config,
},
},
&Workstation9Driver{
SSHConfig: config,
},
&Player6Driver{
Player5Driver: Player5Driver{
SSHConfig: config,
},
},
&Player5Driver{
SSHConfig: config,
},
}
default:
return nil, fmt.Errorf("can't find driver for OS: %s", runtime.GOOS)
}
}
errs := ""
for _, driver := range drivers {
err := driver.Verify()
log.Printf("Testing vmware driver %T. Success: %t",
driver, err == nil)
if err == nil {
return driver, nil
}
errs += "* " + err.Error() + "\n"
}
return nil, fmt.Errorf(
"Unable to initialize any driver for this platform. The errors\n"+
"from each driver are shown below. Please fix at least one driver\n"+
"to continue:\n%s", errs)
} | [
"func",
"NewDriver",
"(",
"dconfig",
"*",
"DriverConfig",
",",
"config",
"*",
"SSHConfig",
",",
"vmName",
"string",
")",
"(",
"Driver",
",",
"error",
")",
"{",
"drivers",
":=",
"[",
"]",
"Driver",
"{",
"}",
"\n\n",
"if",
"dconfig",
".",
"RemoteType",
"... | // NewDriver returns a new driver implementation for this operating
// system, or an error if the driver couldn't be initialized. | [
"NewDriver",
"returns",
"a",
"new",
"driver",
"implementation",
"for",
"this",
"operating",
"system",
"or",
"an",
"error",
"if",
"the",
"driver",
"couldn",
"t",
"be",
"initialized",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver.go#L84-L160 |
165,065 | hashicorp/packer | builder/vmware/common/driver.go | ReadDhcpConfig | func ReadDhcpConfig(path string) (DhcpConfiguration, error) {
fd, err := os.Open(path)
if err != nil {
return nil, err
}
defer fd.Close()
return ReadDhcpConfiguration(fd)
} | go | func ReadDhcpConfig(path string) (DhcpConfiguration, error) {
fd, err := os.Open(path)
if err != nil {
return nil, err
}
defer fd.Close()
return ReadDhcpConfiguration(fd)
} | [
"func",
"ReadDhcpConfig",
"(",
"path",
"string",
")",
"(",
"DhcpConfiguration",
",",
"error",
")",
"{",
"fd",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
... | // read the dhcp configuration out of the specified path | [
"read",
"the",
"dhcp",
"configuration",
"out",
"of",
"the",
"specified",
"path"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver.go#L246-L253 |
165,066 | hashicorp/packer | builder/vmware/common/driver.go | readVMXConfig | func readVMXConfig(path string) (map[string]string, error) {
f, err := os.Open(path)
if err != nil {
return map[string]string{}, err
}
defer f.Close()
vmxBytes, err := ioutil.ReadAll(f)
if err != nil {
return map[string]string{}, err
}
return ParseVMX(string(vmxBytes)), nil
} | go | func readVMXConfig(path string) (map[string]string, error) {
f, err := os.Open(path)
if err != nil {
return map[string]string{}, err
}
defer f.Close()
vmxBytes, err := ioutil.ReadAll(f)
if err != nil {
return map[string]string{}, err
}
return ParseVMX(string(vmxBytes)), nil
} | [
"func",
"readVMXConfig",
"(",
"path",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"map",
"[",
"string"... | // read the VMX configuration from the specified path | [
"read",
"the",
"VMX",
"configuration",
"from",
"the",
"specified",
"path"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver.go#L256-L268 |
165,067 | hashicorp/packer | builder/vmware/common/driver.go | readCustomDeviceName | func readCustomDeviceName(vmxData map[string]string) (string, error) {
connectionType, ok := vmxData["ethernet0.connectiontype"]
if !ok || connectionType != "custom" {
return "", fmt.Errorf("Unable to determine the device name for the connection type : %s", connectionType)
}
device, ok := vmxData["ethernet0.vnet"]
if !ok || device == "" {
return "", fmt.Errorf("Unable to determine the device name for the connection type \"%s\" : %s", connectionType, device)
}
return device, nil
} | go | func readCustomDeviceName(vmxData map[string]string) (string, error) {
connectionType, ok := vmxData["ethernet0.connectiontype"]
if !ok || connectionType != "custom" {
return "", fmt.Errorf("Unable to determine the device name for the connection type : %s", connectionType)
}
device, ok := vmxData["ethernet0.vnet"]
if !ok || device == "" {
return "", fmt.Errorf("Unable to determine the device name for the connection type \"%s\" : %s", connectionType, device)
}
return device, nil
} | [
"func",
"readCustomDeviceName",
"(",
"vmxData",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"connectionType",
",",
"ok",
":=",
"vmxData",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"||",
"connectionType",
"!=",
"\... | // read the connection type out of a vmx configuration | [
"read",
"the",
"connection",
"type",
"out",
"of",
"a",
"vmx",
"configuration"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver.go#L271-L283 |
165,068 | hashicorp/packer | builder/parallels/common/output_config.go | Prepare | func (c *OutputConfig) Prepare(ctx *interpolate.Context, pc *common.PackerConfig) []error {
if c.OutputDir == "" {
c.OutputDir = fmt.Sprintf("output-%s", pc.PackerBuildName)
}
var errs []error
if path.IsAbs(c.OutputDir) {
c.OutputDir = path.Clean(c.OutputDir)
} else {
wd, err := os.Getwd()
if err != nil {
errs = append(errs, err)
}
c.OutputDir = path.Clean(path.Join(wd, c.OutputDir))
}
if !pc.PackerForce {
if _, err := os.Stat(c.OutputDir); err == nil {
errs = append(errs, fmt.Errorf(
"Output directory '%s' already exists. It must not exist.", c.OutputDir))
}
}
return errs
} | go | func (c *OutputConfig) Prepare(ctx *interpolate.Context, pc *common.PackerConfig) []error {
if c.OutputDir == "" {
c.OutputDir = fmt.Sprintf("output-%s", pc.PackerBuildName)
}
var errs []error
if path.IsAbs(c.OutputDir) {
c.OutputDir = path.Clean(c.OutputDir)
} else {
wd, err := os.Getwd()
if err != nil {
errs = append(errs, err)
}
c.OutputDir = path.Clean(path.Join(wd, c.OutputDir))
}
if !pc.PackerForce {
if _, err := os.Stat(c.OutputDir); err == nil {
errs = append(errs, fmt.Errorf(
"Output directory '%s' already exists. It must not exist.", c.OutputDir))
}
}
return errs
} | [
"func",
"(",
"c",
"*",
"OutputConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
",",
"pc",
"*",
"common",
".",
"PackerConfig",
")",
"[",
"]",
"error",
"{",
"if",
"c",
".",
"OutputDir",
"==",
"\"",
"\"",
"{",
"c",
".",
"Output... | // Prepare configures the output directory or returns an error if it already exists. | [
"Prepare",
"configures",
"the",
"output",
"directory",
"or",
"returns",
"an",
"error",
"if",
"it",
"already",
"exists",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/output_config.go#L18-L43 |
165,069 | hashicorp/packer | builder/parallels/common/step_upload_parallels_tools.go | Run | func (s *StepUploadParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
comm := state.Get("communicator").(packer.Communicator)
ui := state.Get("ui").(packer.Ui)
// If we're attaching then don't do this, since we attached.
if s.ParallelsToolsMode != ParallelsToolsModeUpload {
log.Println("Not uploading Parallels Tools since mode is not upload")
return multistep.ActionContinue
}
// Get the Parallels Tools path on the host machine
parallelsToolsPath := state.Get("parallels_tools_path").(string)
f, err := os.Open(parallelsToolsPath)
if err != nil {
state.Put("error", fmt.Errorf("Error opening Parallels Tools ISO: %s", err))
return multistep.ActionHalt
}
defer f.Close()
s.Ctx.Data = &toolsPathTemplate{
Flavor: s.ParallelsToolsFlavor,
}
s.ParallelsToolsGuestPath, err = interpolate.Render(s.ParallelsToolsGuestPath, &s.Ctx)
if err != nil {
err = fmt.Errorf("Error preparing Parallels Tools path: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say(fmt.Sprintf("Uploading Parallels Tools for '%s' to path: '%s'",
s.ParallelsToolsFlavor, s.ParallelsToolsGuestPath))
if err := comm.Upload(s.ParallelsToolsGuestPath, f, nil); err != nil {
err = fmt.Errorf("Error uploading Parallels Tools: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
} | go | func (s *StepUploadParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
comm := state.Get("communicator").(packer.Communicator)
ui := state.Get("ui").(packer.Ui)
// If we're attaching then don't do this, since we attached.
if s.ParallelsToolsMode != ParallelsToolsModeUpload {
log.Println("Not uploading Parallels Tools since mode is not upload")
return multistep.ActionContinue
}
// Get the Parallels Tools path on the host machine
parallelsToolsPath := state.Get("parallels_tools_path").(string)
f, err := os.Open(parallelsToolsPath)
if err != nil {
state.Put("error", fmt.Errorf("Error opening Parallels Tools ISO: %s", err))
return multistep.ActionHalt
}
defer f.Close()
s.Ctx.Data = &toolsPathTemplate{
Flavor: s.ParallelsToolsFlavor,
}
s.ParallelsToolsGuestPath, err = interpolate.Render(s.ParallelsToolsGuestPath, &s.Ctx)
if err != nil {
err = fmt.Errorf("Error preparing Parallels Tools path: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say(fmt.Sprintf("Uploading Parallels Tools for '%s' to path: '%s'",
s.ParallelsToolsFlavor, s.ParallelsToolsGuestPath))
if err := comm.Upload(s.ParallelsToolsGuestPath, f, nil); err != nil {
err = fmt.Errorf("Error uploading Parallels Tools: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepUploadParallelsTools",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"comm",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(... | // Run uploads the Parallels Tools ISO to the VM. | [
"Run",
"uploads",
"the",
"Parallels",
"Tools",
"ISO",
"to",
"the",
"VM",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_upload_parallels_tools.go#L41-L83 |
165,070 | hashicorp/packer | builder/ncloud/step_create_block_storage_instance.go | NewStepCreateBlockStorageInstance | func NewStepCreateBlockStorageInstance(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepCreateBlockStorageInstance {
var step = &StepCreateBlockStorageInstance{
Conn: conn,
Say: func(message string) { ui.Say(message) },
Error: func(e error) { ui.Error(e.Error()) },
Config: config,
}
step.CreateBlockStorageInstance = step.createBlockStorageInstance
return step
} | go | func NewStepCreateBlockStorageInstance(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepCreateBlockStorageInstance {
var step = &StepCreateBlockStorageInstance{
Conn: conn,
Say: func(message string) { ui.Say(message) },
Error: func(e error) { ui.Error(e.Error()) },
Config: config,
}
step.CreateBlockStorageInstance = step.createBlockStorageInstance
return step
} | [
"func",
"NewStepCreateBlockStorageInstance",
"(",
"conn",
"*",
"ncloud",
".",
"Conn",
",",
"ui",
"packer",
".",
"Ui",
",",
"config",
"*",
"Config",
")",
"*",
"StepCreateBlockStorageInstance",
"{",
"var",
"step",
"=",
"&",
"StepCreateBlockStorageInstance",
"{",
"... | // NewStepCreateBlockStorageInstance make StepCreateBlockStorage struct to make extra block storage | [
"NewStepCreateBlockStorageInstance",
"make",
"StepCreateBlockStorage",
"struct",
"to",
"make",
"extra",
"block",
"storage"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/ncloud/step_create_block_storage_instance.go#L25-L36 |
165,071 | hashicorp/packer | builder/openstack/ssh.go | CommHost | func CommHost(
client *gophercloud.ServiceClient,
sshinterface string,
sshipversion string) func(multistep.StateBag) (string, error) {
return func(state multistep.StateBag) (string, error) {
s := state.Get("server").(*servers.Server)
// If we have a specific interface, try that
if sshinterface != "" {
if addr := sshAddrFromPool(s, sshinterface, sshipversion); addr != "" {
log.Printf("[DEBUG] Using IP address %s from specified interface %s to connect", addr, sshinterface)
return addr, nil
}
}
// If we have a floating IP, use that
ip := state.Get("access_ip").(*floatingips.FloatingIP)
if ip != nil && ip.FloatingIP != "" {
log.Printf("[DEBUG] Using floating IP %s to connect", ip.FloatingIP)
return ip.FloatingIP, nil
}
if s.AccessIPv4 != "" {
log.Printf("[DEBUG] Using AccessIPv4 %s to connect", s.AccessIPv4)
return s.AccessIPv4, nil
}
// Try to get it from the requested interface
if addr := sshAddrFromPool(s, sshinterface, sshipversion); addr != "" {
log.Printf("[DEBUG] Using IP address %s to connect", addr)
return addr, nil
}
s, err := servers.Get(client, s.ID).Extract()
if err != nil {
return "", err
}
state.Put("server", s)
time.Sleep(1 * time.Second)
return "", errors.New("couldn't determine IP address for server")
}
} | go | func CommHost(
client *gophercloud.ServiceClient,
sshinterface string,
sshipversion string) func(multistep.StateBag) (string, error) {
return func(state multistep.StateBag) (string, error) {
s := state.Get("server").(*servers.Server)
// If we have a specific interface, try that
if sshinterface != "" {
if addr := sshAddrFromPool(s, sshinterface, sshipversion); addr != "" {
log.Printf("[DEBUG] Using IP address %s from specified interface %s to connect", addr, sshinterface)
return addr, nil
}
}
// If we have a floating IP, use that
ip := state.Get("access_ip").(*floatingips.FloatingIP)
if ip != nil && ip.FloatingIP != "" {
log.Printf("[DEBUG] Using floating IP %s to connect", ip.FloatingIP)
return ip.FloatingIP, nil
}
if s.AccessIPv4 != "" {
log.Printf("[DEBUG] Using AccessIPv4 %s to connect", s.AccessIPv4)
return s.AccessIPv4, nil
}
// Try to get it from the requested interface
if addr := sshAddrFromPool(s, sshinterface, sshipversion); addr != "" {
log.Printf("[DEBUG] Using IP address %s to connect", addr)
return addr, nil
}
s, err := servers.Get(client, s.ID).Extract()
if err != nil {
return "", err
}
state.Put("server", s)
time.Sleep(1 * time.Second)
return "", errors.New("couldn't determine IP address for server")
}
} | [
"func",
"CommHost",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"sshinterface",
"string",
",",
"sshipversion",
"string",
")",
"func",
"(",
"multistep",
".",
"StateBag",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"func",
"(",
"s... | // CommHost looks up the host for the communicator. | [
"CommHost",
"looks",
"up",
"the",
"host",
"for",
"the",
"communicator",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/ssh.go#L16-L59 |
165,072 | hashicorp/packer | scripts/generate-plugins.go | listDirectories | func listDirectories(path string) ([]string, error) {
names := []string{}
items, err := ioutil.ReadDir(path)
if err != nil {
return names, err
}
for _, item := range items {
// We only want directories
if item.IsDir() {
currentDir := filepath.Join(path, item.Name())
names = append(names, currentDir)
// Do some recursion
subNames, err := listDirectories(currentDir)
if err == nil {
names = append(names, subNames...)
}
}
}
return names, nil
} | go | func listDirectories(path string) ([]string, error) {
names := []string{}
items, err := ioutil.ReadDir(path)
if err != nil {
return names, err
}
for _, item := range items {
// We only want directories
if item.IsDir() {
currentDir := filepath.Join(path, item.Name())
names = append(names, currentDir)
// Do some recursion
subNames, err := listDirectories(currentDir)
if err == nil {
names = append(names, subNames...)
}
}
}
return names, nil
} | [
"func",
"listDirectories",
"(",
"path",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"names",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"items",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"path",
")",
"\n",
"if",
"err",
"... | // listDirectories recursively lists directories under the specified path | [
"listDirectories",
"recursively",
"lists",
"directories",
"under",
"the",
"specified",
"path"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/scripts/generate-plugins.go#L117-L139 |
165,073 | hashicorp/packer | scripts/generate-plugins.go | discoverTypesInPath | func discoverTypesInPath(path, typeID string) ([]plugin, error) {
postProcessors := []plugin{}
dirs, err := listDirectories(path)
if err != nil {
return postProcessors, err
}
for _, dir := range dirs {
fset := token.NewFileSet()
goPackages, err := parser.ParseDir(fset, dir, nil, parser.AllErrors)
if err != nil {
return postProcessors, fmt.Errorf("Failed parsing directory %s: %s", dir, err)
}
for _, goPackage := range goPackages {
ast.PackageExports(goPackage)
ast.Inspect(goPackage, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.TypeSpec:
if x.Name.Name == typeID {
derivedName := deriveName(path, dir)
postProcessors = append(postProcessors, plugin{
Package: goPackage.Name,
PluginName: derivedName,
ImportName: deriveImport(x.Name.Name, derivedName),
TypeName: x.Name.Name,
Path: dir,
})
// The AST stops parsing when we return false. Once we
// find the symbol we want we can stop parsing.
// DEBUG:
// fmt.Printf("package %#v\n", goPackage)
return false
}
}
return true
})
}
}
return postProcessors, nil
} | go | func discoverTypesInPath(path, typeID string) ([]plugin, error) {
postProcessors := []plugin{}
dirs, err := listDirectories(path)
if err != nil {
return postProcessors, err
}
for _, dir := range dirs {
fset := token.NewFileSet()
goPackages, err := parser.ParseDir(fset, dir, nil, parser.AllErrors)
if err != nil {
return postProcessors, fmt.Errorf("Failed parsing directory %s: %s", dir, err)
}
for _, goPackage := range goPackages {
ast.PackageExports(goPackage)
ast.Inspect(goPackage, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.TypeSpec:
if x.Name.Name == typeID {
derivedName := deriveName(path, dir)
postProcessors = append(postProcessors, plugin{
Package: goPackage.Name,
PluginName: derivedName,
ImportName: deriveImport(x.Name.Name, derivedName),
TypeName: x.Name.Name,
Path: dir,
})
// The AST stops parsing when we return false. Once we
// find the symbol we want we can stop parsing.
// DEBUG:
// fmt.Printf("package %#v\n", goPackage)
return false
}
}
return true
})
}
}
return postProcessors, nil
} | [
"func",
"discoverTypesInPath",
"(",
"path",
",",
"typeID",
"string",
")",
"(",
"[",
"]",
"plugin",
",",
"error",
")",
"{",
"postProcessors",
":=",
"[",
"]",
"plugin",
"{",
"}",
"\n\n",
"dirs",
",",
"err",
":=",
"listDirectories",
"(",
"path",
")",
"\n"... | // discoverTypesInPath searches for types of typeID in path and returns a list
// of plugins it finds. | [
"discoverTypesInPath",
"searches",
"for",
"types",
"of",
"typeID",
"in",
"path",
"and",
"returns",
"a",
"list",
"of",
"plugins",
"it",
"finds",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/scripts/generate-plugins.go#L166-L209 |
165,074 | hashicorp/packer | helper/communicator/config.go | ReadSSHPrivateKeyFile | func (c *Config) ReadSSHPrivateKeyFile() ([]byte, error) {
var privateKey []byte
if c.SSHPrivateKeyFile != "" {
keyPath, err := packer.ExpandUser(c.SSHPrivateKeyFile)
if err != nil {
return []byte{}, fmt.Errorf("Error expanding path for SSH private key: %s", err)
}
privateKey, err = ioutil.ReadFile(keyPath)
if err != nil {
return privateKey, fmt.Errorf("Error on reading SSH private key: %s", err)
}
}
return privateKey, nil
} | go | func (c *Config) ReadSSHPrivateKeyFile() ([]byte, error) {
var privateKey []byte
if c.SSHPrivateKeyFile != "" {
keyPath, err := packer.ExpandUser(c.SSHPrivateKeyFile)
if err != nil {
return []byte{}, fmt.Errorf("Error expanding path for SSH private key: %s", err)
}
privateKey, err = ioutil.ReadFile(keyPath)
if err != nil {
return privateKey, fmt.Errorf("Error on reading SSH private key: %s", err)
}
}
return privateKey, nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"ReadSSHPrivateKeyFile",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"privateKey",
"[",
"]",
"byte",
"\n\n",
"if",
"c",
".",
"SSHPrivateKeyFile",
"!=",
"\"",
"\"",
"{",
"keyPath",
",",
"err",
... | // ReadSSHPrivateKeyFile returns the SSH private key bytes | [
"ReadSSHPrivateKeyFile",
"returns",
"the",
"SSH",
"private",
"key",
"bytes"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/communicator/config.go#L75-L90 |
165,075 | hashicorp/packer | helper/communicator/config.go | SSHConfigFunc | func (c *Config) SSHConfigFunc() func(multistep.StateBag) (*ssh.ClientConfig, error) {
return func(state multistep.StateBag) (*ssh.ClientConfig, error) {
sshConfig := &ssh.ClientConfig{
User: c.SSHUsername,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
if c.SSHAgentAuth {
authSock := os.Getenv("SSH_AUTH_SOCK")
if authSock == "" {
return nil, fmt.Errorf("SSH_AUTH_SOCK is not set")
}
sshAgent, err := net.Dial("unix", authSock)
if err != nil {
return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err)
}
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers))
}
var privateKeys [][]byte
if c.SSHPrivateKeyFile != "" {
privateKey, err := c.ReadSSHPrivateKeyFile()
if err != nil {
return nil, err
}
privateKeys = append(privateKeys, privateKey)
}
// aws,alicloud,cloudstack,digitalOcean,oneAndOne,openstack,oracle & profitbricks key
if iKey, hasKey := state.GetOk("privateKey"); hasKey {
privateKeys = append(privateKeys, []byte(iKey.(string)))
}
if len(c.SSHPrivateKey) != 0 {
privateKeys = append(privateKeys, c.SSHPrivateKey)
}
for _, key := range privateKeys {
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, fmt.Errorf("Error on parsing SSH private key: %s", err)
}
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeys(signer))
}
if c.SSHPassword != "" {
sshConfig.Auth = append(sshConfig.Auth,
ssh.Password(c.SSHPassword),
ssh.KeyboardInteractive(packerssh.PasswordKeyboardInteractive(c.SSHPassword)),
)
}
return sshConfig, nil
}
} | go | func (c *Config) SSHConfigFunc() func(multistep.StateBag) (*ssh.ClientConfig, error) {
return func(state multistep.StateBag) (*ssh.ClientConfig, error) {
sshConfig := &ssh.ClientConfig{
User: c.SSHUsername,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
if c.SSHAgentAuth {
authSock := os.Getenv("SSH_AUTH_SOCK")
if authSock == "" {
return nil, fmt.Errorf("SSH_AUTH_SOCK is not set")
}
sshAgent, err := net.Dial("unix", authSock)
if err != nil {
return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err)
}
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers))
}
var privateKeys [][]byte
if c.SSHPrivateKeyFile != "" {
privateKey, err := c.ReadSSHPrivateKeyFile()
if err != nil {
return nil, err
}
privateKeys = append(privateKeys, privateKey)
}
// aws,alicloud,cloudstack,digitalOcean,oneAndOne,openstack,oracle & profitbricks key
if iKey, hasKey := state.GetOk("privateKey"); hasKey {
privateKeys = append(privateKeys, []byte(iKey.(string)))
}
if len(c.SSHPrivateKey) != 0 {
privateKeys = append(privateKeys, c.SSHPrivateKey)
}
for _, key := range privateKeys {
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, fmt.Errorf("Error on parsing SSH private key: %s", err)
}
sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeys(signer))
}
if c.SSHPassword != "" {
sshConfig.Auth = append(sshConfig.Auth,
ssh.Password(c.SSHPassword),
ssh.KeyboardInteractive(packerssh.PasswordKeyboardInteractive(c.SSHPassword)),
)
}
return sshConfig, nil
}
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"SSHConfigFunc",
"(",
")",
"func",
"(",
"multistep",
".",
"StateBag",
")",
"(",
"*",
"ssh",
".",
"ClientConfig",
",",
"error",
")",
"{",
"return",
"func",
"(",
"state",
"multistep",
".",
"StateBag",
")",
"(",
"*"... | // SSHConfigFunc returns a function that can be used for the SSH communicator
// config for connecting to the instance created over SSH using the private key
// or password. | [
"SSHConfigFunc",
"returns",
"a",
"function",
"that",
"can",
"be",
"used",
"for",
"the",
"SSH",
"communicator",
"config",
"for",
"connecting",
"to",
"the",
"instance",
"created",
"over",
"SSH",
"using",
"the",
"private",
"key",
"or",
"password",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/communicator/config.go#L95-L150 |
165,076 | hashicorp/packer | helper/communicator/config.go | Port | func (c *Config) Port() int {
switch c.Type {
case "ssh":
return c.SSHPort
case "winrm":
return c.WinRMPort
default:
return 0
}
} | go | func (c *Config) Port() int {
switch c.Type {
case "ssh":
return c.SSHPort
case "winrm":
return c.WinRMPort
default:
return 0
}
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Port",
"(",
")",
"int",
"{",
"switch",
"c",
".",
"Type",
"{",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"SSHPort",
"\n",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"WinRMPort",
"\n",
"default",
":",
"... | // Port returns the port that will be used for access based on config. | [
"Port",
"returns",
"the",
"port",
"that",
"will",
"be",
"used",
"for",
"access",
"based",
"on",
"config",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/communicator/config.go#L153-L162 |
165,077 | hashicorp/packer | helper/communicator/config.go | Host | func (c *Config) Host() string {
switch c.Type {
case "ssh":
return c.SSHHost
case "winrm":
return c.WinRMHost
default:
return ""
}
} | go | func (c *Config) Host() string {
switch c.Type {
case "ssh":
return c.SSHHost
case "winrm":
return c.WinRMHost
default:
return ""
}
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Host",
"(",
")",
"string",
"{",
"switch",
"c",
".",
"Type",
"{",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"SSHHost",
"\n",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"WinRMHost",
"\n",
"default",
":",
... | // Host returns the port that will be used for access based on config. | [
"Host",
"returns",
"the",
"port",
"that",
"will",
"be",
"used",
"for",
"access",
"based",
"on",
"config",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/communicator/config.go#L165-L174 |
165,078 | hashicorp/packer | helper/communicator/config.go | User | func (c *Config) User() string {
switch c.Type {
case "ssh":
return c.SSHUsername
case "winrm":
return c.WinRMUser
default:
return ""
}
} | go | func (c *Config) User() string {
switch c.Type {
case "ssh":
return c.SSHUsername
case "winrm":
return c.WinRMUser
default:
return ""
}
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"User",
"(",
")",
"string",
"{",
"switch",
"c",
".",
"Type",
"{",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"SSHUsername",
"\n",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"WinRMUser",
"\n",
"default",
"... | // User returns the port that will be used for access based on config. | [
"User",
"returns",
"the",
"port",
"that",
"will",
"be",
"used",
"for",
"access",
"based",
"on",
"config",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/communicator/config.go#L177-L186 |
165,079 | hashicorp/packer | helper/communicator/config.go | Password | func (c *Config) Password() string {
switch c.Type {
case "ssh":
return c.SSHPassword
case "winrm":
return c.WinRMPassword
default:
return ""
}
} | go | func (c *Config) Password() string {
switch c.Type {
case "ssh":
return c.SSHPassword
case "winrm":
return c.WinRMPassword
default:
return ""
}
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Password",
"(",
")",
"string",
"{",
"switch",
"c",
".",
"Type",
"{",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"SSHPassword",
"\n",
"case",
"\"",
"\"",
":",
"return",
"c",
".",
"WinRMPassword",
"\n",
"defau... | // Password returns the port that will be used for access based on config. | [
"Password",
"returns",
"the",
"port",
"that",
"will",
"be",
"used",
"for",
"access",
"based",
"on",
"config",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/communicator/config.go#L189-L198 |
165,080 | hashicorp/packer | common/bootcommand/boot_command_ast.go | Do | func (s expressionSequence) Do(ctx context.Context, b BCDriver) error {
// validate should never fail here, since it should be called before
// expressionSequence.Do. Only reason we don't panic is so we can clean up.
if errs := s.Validate(); errs != nil {
return fmt.Errorf("Found an invalid boot command. This is likely an error in Packer, so please open a ticket.")
}
for _, exp := range s {
if err := ctx.Err(); err != nil {
return err
}
if err := exp.Do(ctx, b); err != nil {
return err
}
}
return b.Flush()
} | go | func (s expressionSequence) Do(ctx context.Context, b BCDriver) error {
// validate should never fail here, since it should be called before
// expressionSequence.Do. Only reason we don't panic is so we can clean up.
if errs := s.Validate(); errs != nil {
return fmt.Errorf("Found an invalid boot command. This is likely an error in Packer, so please open a ticket.")
}
for _, exp := range s {
if err := ctx.Err(); err != nil {
return err
}
if err := exp.Do(ctx, b); err != nil {
return err
}
}
return b.Flush()
} | [
"func",
"(",
"s",
"expressionSequence",
")",
"Do",
"(",
"ctx",
"context",
".",
"Context",
",",
"b",
"BCDriver",
")",
"error",
"{",
"// validate should never fail here, since it should be called before",
"// expressionSequence.Do. Only reason we don't panic is so we can clean up."... | // Do executes every expression in the sequence and then flushes remaining
// scancodes. | [
"Do",
"executes",
"every",
"expression",
"in",
"the",
"sequence",
"and",
"then",
"flushes",
"remaining",
"scancodes",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L47-L63 |
165,081 | hashicorp/packer | common/bootcommand/boot_command_ast.go | Validate | func (s expressionSequence) Validate() (errs []error) {
for _, exp := range s {
if err := exp.Validate(); err != nil {
errs = append(errs, err)
}
}
return
} | go | func (s expressionSequence) Validate() (errs []error) {
for _, exp := range s {
if err := exp.Validate(); err != nil {
errs = append(errs, err)
}
}
return
} | [
"func",
"(",
"s",
"expressionSequence",
")",
"Validate",
"(",
")",
"(",
"errs",
"[",
"]",
"error",
")",
"{",
"for",
"_",
",",
"exp",
":=",
"range",
"s",
"{",
"if",
"err",
":=",
"exp",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"er... | // Validate tells us if every expression in the sequence is valid. | [
"Validate",
"tells",
"us",
"if",
"every",
"expression",
"in",
"the",
"sequence",
"is",
"valid",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L66-L73 |
165,082 | hashicorp/packer | common/bootcommand/boot_command_ast.go | GenerateExpressionSequence | func GenerateExpressionSequence(command string) (expressionSequence, error) {
seq := expressionSequence{}
if command == "" {
return seq, nil
}
got, err := ParseReader("", strings.NewReader(command))
if err != nil {
return nil, err
}
for _, exp := range got.([]interface{}) {
seq = append(seq, exp.(expression))
}
return seq, nil
} | go | func GenerateExpressionSequence(command string) (expressionSequence, error) {
seq := expressionSequence{}
if command == "" {
return seq, nil
}
got, err := ParseReader("", strings.NewReader(command))
if err != nil {
return nil, err
}
for _, exp := range got.([]interface{}) {
seq = append(seq, exp.(expression))
}
return seq, nil
} | [
"func",
"GenerateExpressionSequence",
"(",
"command",
"string",
")",
"(",
"expressionSequence",
",",
"error",
")",
"{",
"seq",
":=",
"expressionSequence",
"{",
"}",
"\n",
"if",
"command",
"==",
"\"",
"\"",
"{",
"return",
"seq",
",",
"nil",
"\n",
"}",
"\n",... | // GenerateExpressionSequence generates a sequence of expressions from the
// given command. This is the primary entry point to the boot command parser. | [
"GenerateExpressionSequence",
"generates",
"a",
"sequence",
"of",
"expressions",
"from",
"the",
"given",
"command",
".",
"This",
"is",
"the",
"primary",
"entry",
"point",
"to",
"the",
"boot",
"command",
"parser",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L77-L90 |
165,083 | hashicorp/packer | common/bootcommand/boot_command_ast.go | Do | func (w *waitExpression) Do(ctx context.Context, driver BCDriver) error {
driver.Flush()
log.Printf("[INFO] Waiting %s", w.d)
select {
case <-time.After(w.d):
return nil
case <-ctx.Done():
return ctx.Err()
}
} | go | func (w *waitExpression) Do(ctx context.Context, driver BCDriver) error {
driver.Flush()
log.Printf("[INFO] Waiting %s", w.d)
select {
case <-time.After(w.d):
return nil
case <-ctx.Done():
return ctx.Err()
}
} | [
"func",
"(",
"w",
"*",
"waitExpression",
")",
"Do",
"(",
"ctx",
"context",
".",
"Context",
",",
"driver",
"BCDriver",
")",
"error",
"{",
"driver",
".",
"Flush",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"w",
".",
"d",
")",
"\n",... | // Do waits the amount of time described by the expression. It is cancellable
// through the context. | [
"Do",
"waits",
"the",
"amount",
"of",
"time",
"described",
"by",
"the",
"expression",
".",
"It",
"is",
"cancellable",
"through",
"the",
"context",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L98-L107 |
165,084 | hashicorp/packer | common/bootcommand/boot_command_ast.go | Validate | func (w *waitExpression) Validate() error {
if w.d <= 0 {
return fmt.Errorf("Expecting a positive wait value. Got %s", w.d)
}
return nil
} | go | func (w *waitExpression) Validate() error {
if w.d <= 0 {
return fmt.Errorf("Expecting a positive wait value. Got %s", w.d)
}
return nil
} | [
"func",
"(",
"w",
"*",
"waitExpression",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"w",
".",
"d",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"w",
".",
"d",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate returns an error if the time is <= 0 | [
"Validate",
"returns",
"an",
"error",
"if",
"the",
"time",
"is",
"<",
"=",
"0"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L110-L115 |
165,085 | hashicorp/packer | common/bootcommand/boot_command_ast.go | Do | func (s *specialExpression) Do(ctx context.Context, driver BCDriver) error {
return driver.SendSpecial(s.s, s.action)
} | go | func (s *specialExpression) Do(ctx context.Context, driver BCDriver) error {
return driver.SendSpecial(s.s, s.action)
} | [
"func",
"(",
"s",
"*",
"specialExpression",
")",
"Do",
"(",
"ctx",
"context",
".",
"Context",
",",
"driver",
"BCDriver",
")",
"error",
"{",
"return",
"driver",
".",
"SendSpecial",
"(",
"s",
".",
"s",
",",
"s",
".",
"action",
")",
"\n",
"}"
] | // Do sends the special command to the driver, along with the key action. | [
"Do",
"sends",
"the",
"special",
"command",
"to",
"the",
"driver",
"along",
"with",
"the",
"key",
"action",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L127-L129 |
165,086 | hashicorp/packer | common/bootcommand/boot_command_ast.go | Do | func (l *literal) Do(ctx context.Context, driver BCDriver) error {
return driver.SendKey(l.s, l.action)
} | go | func (l *literal) Do(ctx context.Context, driver BCDriver) error {
return driver.SendKey(l.s, l.action)
} | [
"func",
"(",
"l",
"*",
"literal",
")",
"Do",
"(",
"ctx",
"context",
".",
"Context",
",",
"driver",
"BCDriver",
")",
"error",
"{",
"return",
"driver",
".",
"SendKey",
"(",
"l",
".",
"s",
",",
"l",
".",
"action",
")",
"\n",
"}"
] | // Do sends the key to the driver, along with the key action. | [
"Do",
"sends",
"the",
"key",
"to",
"the",
"driver",
"along",
"with",
"the",
"key",
"action",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/boot_command_ast.go#L146-L148 |
165,087 | hashicorp/packer | builder/parallels/common/shutdown_config.go | Prepare | func (c *ShutdownConfig) Prepare(ctx *interpolate.Context) []error {
if c.RawShutdownTimeout == "" {
c.RawShutdownTimeout = "5m"
}
var errs []error
var err error
c.ShutdownTimeout, err = time.ParseDuration(c.RawShutdownTimeout)
if err != nil {
errs = append(errs, fmt.Errorf("Failed parsing shutdown_timeout: %s", err))
}
return errs
} | go | func (c *ShutdownConfig) Prepare(ctx *interpolate.Context) []error {
if c.RawShutdownTimeout == "" {
c.RawShutdownTimeout = "5m"
}
var errs []error
var err error
c.ShutdownTimeout, err = time.ParseDuration(c.RawShutdownTimeout)
if err != nil {
errs = append(errs, fmt.Errorf("Failed parsing shutdown_timeout: %s", err))
}
return errs
} | [
"func",
"(",
"c",
"*",
"ShutdownConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"if",
"c",
".",
"RawShutdownTimeout",
"==",
"\"",
"\"",
"{",
"c",
".",
"RawShutdownTimeout",
"=",
"\"",
"\"",
"\n",
... | // Prepare sets default values to the VM shutdown configuration. | [
"Prepare",
"sets",
"default",
"values",
"to",
"the",
"VM",
"shutdown",
"configuration",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/shutdown_config.go#L19-L32 |
165,088 | hashicorp/packer | builder/hyperv/common/step_collate_artifacts.go | Run | func (s *StepCollateArtifacts) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Collating build artifacts...")
if s.SkipExport {
// Get the path to the main build directory from the statebag
var buildDir string
if v, ok := state.GetOk("build_dir"); ok {
buildDir = v.(string)
}
// If the user has chosen to skip a full export of the VM the only
// artifacts that they are interested in will be the VHDs. The
// called function searches for all disks under the given source
// directory and moves them to a 'Virtual Hard Disks' folder under
// the destination directory
err := driver.MoveCreatedVHDsToOutputDir(buildDir, s.OutputDir)
if err != nil {
err = fmt.Errorf("Error moving VHDs from build dir to output dir: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
} else {
// Get the full path to the export directory from the statebag
var exportPath string
if v, ok := state.GetOk("export_path"); ok {
exportPath = v.(string)
}
// The export process exports the VM into a folder named 'vm name'
// under the output directory. However, to maintain backwards
// compatibility, we now need to shuffle around the exported folders
// so the 'Snapshots', 'Virtual Hard Disks' and 'Virtual Machines'
// directories appear *directly* under <output directory>.
// The empty '<output directory>/<vm name>' directory is removed
// when complete.
// The 'Snapshots' folder will not be moved into the output
// directory if it is empty.
err := driver.PreserveLegacyExportBehaviour(exportPath, s.OutputDir)
if err != nil {
// No need to halt here; Just warn the user instead
err = fmt.Errorf("WARNING: Error restoring legacy export dir structure: %s", err)
ui.Error(err.Error())
}
}
return multistep.ActionContinue
} | go | func (s *StepCollateArtifacts) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Collating build artifacts...")
if s.SkipExport {
// Get the path to the main build directory from the statebag
var buildDir string
if v, ok := state.GetOk("build_dir"); ok {
buildDir = v.(string)
}
// If the user has chosen to skip a full export of the VM the only
// artifacts that they are interested in will be the VHDs. The
// called function searches for all disks under the given source
// directory and moves them to a 'Virtual Hard Disks' folder under
// the destination directory
err := driver.MoveCreatedVHDsToOutputDir(buildDir, s.OutputDir)
if err != nil {
err = fmt.Errorf("Error moving VHDs from build dir to output dir: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
} else {
// Get the full path to the export directory from the statebag
var exportPath string
if v, ok := state.GetOk("export_path"); ok {
exportPath = v.(string)
}
// The export process exports the VM into a folder named 'vm name'
// under the output directory. However, to maintain backwards
// compatibility, we now need to shuffle around the exported folders
// so the 'Snapshots', 'Virtual Hard Disks' and 'Virtual Machines'
// directories appear *directly* under <output directory>.
// The empty '<output directory>/<vm name>' directory is removed
// when complete.
// The 'Snapshots' folder will not be moved into the output
// directory if it is empty.
err := driver.PreserveLegacyExportBehaviour(exportPath, s.OutputDir)
if err != nil {
// No need to halt here; Just warn the user instead
err = fmt.Errorf("WARNING: Error restoring legacy export dir structure: %s", err)
ui.Error(err.Error())
}
}
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepCollateArtifacts",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"driver",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",... | // Runs the step required to collate all build artifacts under the
// specified output directory | [
"Runs",
"the",
"step",
"required",
"to",
"collate",
"all",
"build",
"artifacts",
"under",
"the",
"specified",
"output",
"directory"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/step_collate_artifacts.go#L18-L66 |
165,089 | hashicorp/packer | packer/rpc/server.go | NewServer | func NewServer(conn io.ReadWriteCloser) (*Server, error) {
mux, err := newMuxBrokerServer(conn)
if err != nil {
return nil, err
}
result := newServerWithMux(mux, 0)
result.closeMux = true
go mux.Run()
return result, nil
} | go | func NewServer(conn io.ReadWriteCloser) (*Server, error) {
mux, err := newMuxBrokerServer(conn)
if err != nil {
return nil, err
}
result := newServerWithMux(mux, 0)
result.closeMux = true
go mux.Run()
return result, nil
} | [
"func",
"NewServer",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"mux",
",",
"err",
":=",
"newMuxBrokerServer",
"(",
"conn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
... | // NewServer returns a new Packer RPC server. | [
"NewServer",
"returns",
"a",
"new",
"Packer",
"RPC",
"server",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/rpc/server.go#L35-L44 |
165,090 | hashicorp/packer | packer/rpc/server.go | Serve | func (s *Server) Serve() {
// Accept a connection on stream ID 0, which is always used for
// normal client to server connections.
stream, err := s.mux.Accept(s.streamId)
if err != nil {
log.Printf("[ERR] Error retrieving stream for serving: %s", err)
return
}
defer stream.Close()
h := &codec.MsgpackHandle{
RawToString: true,
WriteExt: true,
}
rpcCodec := codec.GoRpc.ServerCodec(stream, h)
s.server.ServeCodec(rpcCodec)
} | go | func (s *Server) Serve() {
// Accept a connection on stream ID 0, which is always used for
// normal client to server connections.
stream, err := s.mux.Accept(s.streamId)
if err != nil {
log.Printf("[ERR] Error retrieving stream for serving: %s", err)
return
}
defer stream.Close()
h := &codec.MsgpackHandle{
RawToString: true,
WriteExt: true,
}
rpcCodec := codec.GoRpc.ServerCodec(stream, h)
s.server.ServeCodec(rpcCodec)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Serve",
"(",
")",
"{",
"// Accept a connection on stream ID 0, which is always used for",
"// normal client to server connections.",
"stream",
",",
"err",
":=",
"s",
".",
"mux",
".",
"Accept",
"(",
"s",
".",
"streamId",
")",
... | // ServeConn serves a single connection over the RPC server. It is up
// to the caller to obtain a proper io.ReadWriteCloser. | [
"ServeConn",
"serves",
"a",
"single",
"connection",
"over",
"the",
"RPC",
"server",
".",
"It",
"is",
"up",
"to",
"the",
"caller",
"to",
"obtain",
"a",
"proper",
"io",
".",
"ReadWriteCloser",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/rpc/server.go#L121-L137 |
165,091 | hashicorp/packer | fix/helpers.go | ppList | func (pp *PP) ppList() []map[string]interface{} {
pps := make([]map[string]interface{}, 0, len(pp.PostProcessors))
for _, rawPP := range pp.PostProcessors {
switch pp := rawPP.(type) {
case string:
case map[string]interface{}:
pps = append(pps, pp)
case []interface{}:
for _, innerRawPP := range pp {
if innerPP, ok := innerRawPP.(map[string]interface{}); ok {
pps = append(pps, innerPP)
}
}
}
}
return pps
} | go | func (pp *PP) ppList() []map[string]interface{} {
pps := make([]map[string]interface{}, 0, len(pp.PostProcessors))
for _, rawPP := range pp.PostProcessors {
switch pp := rawPP.(type) {
case string:
case map[string]interface{}:
pps = append(pps, pp)
case []interface{}:
for _, innerRawPP := range pp {
if innerPP, ok := innerRawPP.(map[string]interface{}); ok {
pps = append(pps, innerPP)
}
}
}
}
return pps
} | [
"func",
"(",
"pp",
"*",
"PP",
")",
"ppList",
"(",
")",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"pps",
":=",
"make",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"len",
"(",
"pp",
"... | // postProcessors converts the variable structure of the template to a list | [
"postProcessors",
"converts",
"the",
"variable",
"structure",
"of",
"the",
"template",
"to",
"a",
"list"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/fix/helpers.go#L9-L25 |
165,092 | hashicorp/packer | builder/parallels/common/step_attach_floppy.go | Run | func (s *StepAttachFloppy) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
// Determine if we even have a floppy disk to attach
var floppyPath string
if floppyPathRaw, ok := state.GetOk("floppy_path"); ok {
floppyPath = floppyPathRaw.(string)
} else {
log.Println("No floppy disk, not attaching.")
return multistep.ActionContinue
}
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
ui.Say("Deleting any current floppy disk...")
// Delete the floppy disk controller
delCommand := []string{
"set", vmName,
"--device-del", "fdd0",
}
// This will almost certainly fail with 'The fdd0 device does not exist.'
driver.Prlctl(delCommand...)
ui.Say("Attaching floppy disk...")
// Attaching the floppy disk
addCommand := []string{
"set", vmName,
"--device-add", "fdd",
"--image", floppyPath,
"--connect",
}
if err := driver.Prlctl(addCommand...); err != nil {
state.Put("error", fmt.Errorf("Error adding floppy: %s", err))
return multistep.ActionHalt
}
// Track the path so that we can unregister it from Parallels later
s.floppyPath = floppyPath
return multistep.ActionContinue
} | go | func (s *StepAttachFloppy) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
// Determine if we even have a floppy disk to attach
var floppyPath string
if floppyPathRaw, ok := state.GetOk("floppy_path"); ok {
floppyPath = floppyPathRaw.(string)
} else {
log.Println("No floppy disk, not attaching.")
return multistep.ActionContinue
}
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
ui.Say("Deleting any current floppy disk...")
// Delete the floppy disk controller
delCommand := []string{
"set", vmName,
"--device-del", "fdd0",
}
// This will almost certainly fail with 'The fdd0 device does not exist.'
driver.Prlctl(delCommand...)
ui.Say("Attaching floppy disk...")
// Attaching the floppy disk
addCommand := []string{
"set", vmName,
"--device-add", "fdd",
"--image", floppyPath,
"--connect",
}
if err := driver.Prlctl(addCommand...); err != nil {
state.Put("error", fmt.Errorf("Error adding floppy: %s", err))
return multistep.ActionHalt
}
// Track the path so that we can unregister it from Parallels later
s.floppyPath = floppyPath
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepAttachFloppy",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"// Determine if we even have a floppy disk to attach",
"var",
"floppyPath",
"string",... | // Run adds a virtual FDD device to the VM and attaches the image.
// If the image is not specified, then this step will be skipped. | [
"Run",
"adds",
"a",
"virtual",
"FDD",
"device",
"to",
"the",
"VM",
"and",
"attaches",
"the",
"image",
".",
"If",
"the",
"image",
"is",
"not",
"specified",
"then",
"this",
"step",
"will",
"be",
"skipped",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_attach_floppy.go#L26-L66 |
165,093 | hashicorp/packer | builder/parallels/common/step_attach_floppy.go | Cleanup | func (s *StepAttachFloppy) Cleanup(state multistep.StateBag) {
driver := state.Get("driver").(Driver)
vmName := state.Get("vmName").(string)
if s.floppyPath == "" {
return
}
log.Println("Detaching floppy disk...")
command := []string{
"set", vmName,
"--device-del", "fdd0",
}
driver.Prlctl(command...)
} | go | func (s *StepAttachFloppy) Cleanup(state multistep.StateBag) {
driver := state.Get("driver").(Driver)
vmName := state.Get("vmName").(string)
if s.floppyPath == "" {
return
}
log.Println("Detaching floppy disk...")
command := []string{
"set", vmName,
"--device-del", "fdd0",
}
driver.Prlctl(command...)
} | [
"func",
"(",
"s",
"*",
"StepAttachFloppy",
")",
"Cleanup",
"(",
"state",
"multistep",
".",
"StateBag",
")",
"{",
"driver",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"Driver",
")",
"\n",
"vmName",
":=",
"state",
".",
"Get",
"(",
"\"... | // Cleanup removes the virtual FDD device attached to the VM. | [
"Cleanup",
"removes",
"the",
"virtual",
"FDD",
"device",
"attached",
"to",
"the",
"VM",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_attach_floppy.go#L69-L83 |
165,094 | hashicorp/packer | common/bootcommand/pc_xt_driver.go | Flush | func (d *pcXTDriver) Flush() error {
defer func() {
d.buffer = nil
}()
sc, err := chunkScanCodes(d.buffer, d.scancodeChunkSize)
if err != nil {
return err
}
for _, b := range sc {
if err := d.sendImpl(b); err != nil {
return err
}
time.Sleep(d.interval)
}
return nil
} | go | func (d *pcXTDriver) Flush() error {
defer func() {
d.buffer = nil
}()
sc, err := chunkScanCodes(d.buffer, d.scancodeChunkSize)
if err != nil {
return err
}
for _, b := range sc {
if err := d.sendImpl(b); err != nil {
return err
}
time.Sleep(d.interval)
}
return nil
} | [
"func",
"(",
"d",
"*",
"pcXTDriver",
")",
"Flush",
"(",
")",
"error",
"{",
"defer",
"func",
"(",
")",
"{",
"d",
".",
"buffer",
"=",
"nil",
"\n",
"}",
"(",
")",
"\n",
"sc",
",",
"err",
":=",
"chunkScanCodes",
"(",
"d",
".",
"buffer",
",",
"d",
... | // Flush send all scanecodes. | [
"Flush",
"send",
"all",
"scanecodes",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/pc_xt_driver.go#L129-L144 |
165,095 | hashicorp/packer | common/bootcommand/pc_xt_driver.go | send | func (d *pcXTDriver) send(codes []string) {
d.buffer = append(d.buffer, codes)
} | go | func (d *pcXTDriver) send(codes []string) {
d.buffer = append(d.buffer, codes)
} | [
"func",
"(",
"d",
"*",
"pcXTDriver",
")",
"send",
"(",
"codes",
"[",
"]",
"string",
")",
"{",
"d",
".",
"buffer",
"=",
"append",
"(",
"d",
".",
"buffer",
",",
"codes",
")",
"\n",
"}"
] | // send stores the codes in an internal buffer. Use Flush to send them. | [
"send",
"stores",
"the",
"codes",
"in",
"an",
"internal",
"buffer",
".",
"Use",
"Flush",
"to",
"send",
"them",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/bootcommand/pc_xt_driver.go#L193-L195 |
165,096 | hashicorp/packer | helper/ssh/key_pair.go | NewKeyPair | func NewKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
if config.Type == Default {
config.Type = Ecdsa
}
switch config.Type {
case Ecdsa:
return newEcdsaKeyPair(config)
case Rsa:
return newRsaKeyPair(config)
}
return KeyPair{}, fmt.Errorf("Unable to generate new key pair, type %s is not supported",
config.Type.String())
} | go | func NewKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
if config.Type == Default {
config.Type = Ecdsa
}
switch config.Type {
case Ecdsa:
return newEcdsaKeyPair(config)
case Rsa:
return newRsaKeyPair(config)
}
return KeyPair{}, fmt.Errorf("Unable to generate new key pair, type %s is not supported",
config.Type.String())
} | [
"func",
"NewKeyPair",
"(",
"config",
"CreateKeyPairConfig",
")",
"(",
"KeyPair",
",",
"error",
")",
"{",
"if",
"config",
".",
"Type",
"==",
"Default",
"{",
"config",
".",
"Type",
"=",
"Ecdsa",
"\n",
"}",
"\n\n",
"switch",
"config",
".",
"Type",
"{",
"c... | // NewKeyPair generates a new SSH key pair using the specified
// CreateKeyPairConfig. | [
"NewKeyPair",
"generates",
"a",
"new",
"SSH",
"key",
"pair",
"using",
"the",
"specified",
"CreateKeyPairConfig",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/ssh/key_pair.go#L112-L126 |
165,097 | hashicorp/packer | helper/ssh/key_pair.go | newEcdsaKeyPair | func newEcdsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
var curve elliptic.Curve
switch config.Bits {
case 0:
config.Bits = 521
fallthrough
case 521:
curve = elliptic.P521()
case 384:
curve = elliptic.P384()
case 256:
curve = elliptic.P256()
case 224:
// Not supported by "golang.org/x/crypto/ssh".
return KeyPair{}, fmt.Errorf("golang.org/x/crypto/ssh does not support %d bits", config.Bits)
default:
return KeyPair{}, fmt.Errorf("crypto/elliptic does not support %d bits", config.Bits)
}
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return KeyPair{}, err
}
sshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return KeyPair{}, err
}
privateRaw, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return KeyPair{}, err
}
privatePem, err := rawPemBlock(&pem.Block{
Type: "EC PRIVATE KEY",
Headers: nil,
Bytes: privateRaw,
})
if err != nil {
return KeyPair{}, err
}
return KeyPair{
PrivateKeyPemBlock: privatePem,
PublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),
Comment: config.Comment,
}, nil
} | go | func newEcdsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
var curve elliptic.Curve
switch config.Bits {
case 0:
config.Bits = 521
fallthrough
case 521:
curve = elliptic.P521()
case 384:
curve = elliptic.P384()
case 256:
curve = elliptic.P256()
case 224:
// Not supported by "golang.org/x/crypto/ssh".
return KeyPair{}, fmt.Errorf("golang.org/x/crypto/ssh does not support %d bits", config.Bits)
default:
return KeyPair{}, fmt.Errorf("crypto/elliptic does not support %d bits", config.Bits)
}
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return KeyPair{}, err
}
sshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return KeyPair{}, err
}
privateRaw, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return KeyPair{}, err
}
privatePem, err := rawPemBlock(&pem.Block{
Type: "EC PRIVATE KEY",
Headers: nil,
Bytes: privateRaw,
})
if err != nil {
return KeyPair{}, err
}
return KeyPair{
PrivateKeyPemBlock: privatePem,
PublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),
Comment: config.Comment,
}, nil
} | [
"func",
"newEcdsaKeyPair",
"(",
"config",
"CreateKeyPairConfig",
")",
"(",
"KeyPair",
",",
"error",
")",
"{",
"var",
"curve",
"elliptic",
".",
"Curve",
"\n\n",
"switch",
"config",
".",
"Bits",
"{",
"case",
"0",
":",
"config",
".",
"Bits",
"=",
"521",
"\n... | // newEcdsaKeyPair returns a new ECDSA SSH key pair. | [
"newEcdsaKeyPair",
"returns",
"a",
"new",
"ECDSA",
"SSH",
"key",
"pair",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/ssh/key_pair.go#L129-L178 |
165,098 | hashicorp/packer | helper/ssh/key_pair.go | newRsaKeyPair | func newRsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
if config.Bits == 0 {
config.Bits = defaultRsaBits
}
privateKey, err := rsa.GenerateKey(rand.Reader, config.Bits)
if err != nil {
return KeyPair{}, err
}
sshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return KeyPair{}, err
}
privatePemBlock, err := rawPemBlock(&pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
if err != nil {
return KeyPair{}, err
}
return KeyPair{
PrivateKeyPemBlock: privatePemBlock,
PublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),
Comment: config.Comment,
}, nil
} | go | func newRsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {
if config.Bits == 0 {
config.Bits = defaultRsaBits
}
privateKey, err := rsa.GenerateKey(rand.Reader, config.Bits)
if err != nil {
return KeyPair{}, err
}
sshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return KeyPair{}, err
}
privatePemBlock, err := rawPemBlock(&pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
if err != nil {
return KeyPair{}, err
}
return KeyPair{
PrivateKeyPemBlock: privatePemBlock,
PublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),
Comment: config.Comment,
}, nil
} | [
"func",
"newRsaKeyPair",
"(",
"config",
"CreateKeyPairConfig",
")",
"(",
"KeyPair",
",",
"error",
")",
"{",
"if",
"config",
".",
"Bits",
"==",
"0",
"{",
"config",
".",
"Bits",
"=",
"defaultRsaBits",
"\n",
"}",
"\n\n",
"privateKey",
",",
"err",
":=",
"rsa... | // newRsaKeyPair returns a new RSA SSH key pair. | [
"newRsaKeyPair",
"returns",
"a",
"new",
"RSA",
"SSH",
"key",
"pair",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/ssh/key_pair.go#L181-L210 |
165,099 | hashicorp/packer | helper/ssh/key_pair.go | rawPemBlock | func rawPemBlock(block *pem.Block) ([]byte, error) {
buffer := bytes.NewBuffer(nil)
err := pem.Encode(buffer, block)
if err != nil {
return []byte{}, err
}
return buffer.Bytes(), nil
} | go | func rawPemBlock(block *pem.Block) ([]byte, error) {
buffer := bytes.NewBuffer(nil)
err := pem.Encode(buffer, block)
if err != nil {
return []byte{}, err
}
return buffer.Bytes(), nil
} | [
"func",
"rawPemBlock",
"(",
"block",
"*",
"pem",
".",
"Block",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"buffer",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n\n",
"err",
":=",
"pem",
".",
"Encode",
"(",
"buffer",
",",
"block",
... | // rawPemBlock encodes a pem.Block to a slice of bytes. | [
"rawPemBlock",
"encodes",
"a",
"pem",
".",
"Block",
"to",
"a",
"slice",
"of",
"bytes",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/ssh/key_pair.go#L229-L238 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.