func fatalOnError(command func(commandLine CommandLine, api libmachine.API) error) func(context *cli.Context) { return func(context *cli.Context) { api := libmachine.NewClient(mcndirs.GetBaseDir()) if context.GlobalBool("native-ssh") { api.SSHClientType = ssh.Native } api.GithubAPIToken = context.GlobalString("github-api-token") api.Filestore.Path = context.GlobalString("storage-path") crashreport.Configure(context.GlobalString("bugsnag-api-token")) // TODO (nathanleclaire): These should ultimately be accessed // through the libmachine client by the rest of the code and // not through their respective modules. For now, however, // they are also being set the way that they originally were // set to preserve backwards compatibility. mcndirs.BaseDir = api.Filestore.Path mcnutils.GithubAPIToken = api.GithubAPIToken ssh.SetDefaultClient(api.SSHClientType) defer rpcdriver.CloseDrivers() if err := command(&contextCommandLine{context}, api); err != nil { log.Fatal(err) } } }
func runStart(cmd *cobra.Command, args []string) { fmt.Println("Starting local Kubernetes cluster...") api := libmachine.NewClient(constants.Minipath, constants.MakeMiniPath("certs")) defer api.Close() config := cluster.MachineConfig{ MinikubeISO: minikubeISO, Memory: memory, CPUs: cpus, DiskSize: int(*disk / units.MB), VMDriver: vmDriver, DockerEnv: dockerEnv, InsecureRegistry: insecureRegistry, } var host *host.Host start := func() (err error) { host, err = cluster.StartHost(api, config) return err } err := util.Retry(3, start) if err != nil { glog.Errorln("Error starting host: ", err) os.Exit(1) } if err := cluster.UpdateCluster(host.Driver); err != nil { glog.Errorln("Error updating cluster: ", err) os.Exit(1) } if err := cluster.SetupCerts(host.Driver); err != nil { glog.Errorln("Error configuring authentication: ", err) os.Exit(1) } if err := cluster.StartCluster(host); err != nil { glog.Errorln("Error starting cluster: ", err) os.Exit(1) } kubeHost, err := host.Driver.GetURL() if err != nil { glog.Errorln("Error connecting to cluster: ", err) } kubeHost = strings.Replace(kubeHost, "tcp://", "https://", -1) kubeHost = strings.Replace(kubeHost, ":2376", ":"+strconv.Itoa(constants.APIServerPort), -1) fmt.Printf("Kubernetes is available at %s.\n", kubeHost) // setup kubeconfig name := constants.MinikubeContext certAuth := constants.MakeMiniPath("ca.crt") clientCert := constants.MakeMiniPath("apiserver.crt") clientKey := constants.MakeMiniPath("apiserver.key") if err := setupKubeconfig(name, kubeHost, certAuth, clientCert, clientKey); err != nil { glog.Errorln("Error setting up kubeconfig: ", err) os.Exit(1) } fmt.Println("Kubectl is now configured to use the cluster.") }
func run() error { machineName := flag.String("machine", "default", "Docker machine name") addr := flag.String("addr", "localhost:2375", "Address of the proxy") help := flag.Bool("help", false, "Show help") flag.Parse() if *help { flag.Usage() return nil } api := libmachine.NewClient(mcndirs.GetBaseDir(), mcndirs.GetMachineCertDir()) defer api.Close() machine, err := api.Load(*machineName) if err != nil { return err } url, err := machine.URL() if err != nil { return err } return http.ListenAndServe(*addr, &proxy.DockerMachineProxy{ Machine: &mcn.DockerMachine{ Url: url, CertPath: filepath.Join(mcndirs.GetBaseDir(), "machines", *machineName), }, }) }
func NewHost(create bool, force bool) (*Host, error) { // Create a Virtualbox host if an existing host doesn't already exist. client := libmachine.NewClient(mcndirs.GetBaseDir()) existing, err := client.Load(DEFAULT_NAME) if err != nil { switch err.(type) { case mcnerror.ErrHostDoesNotExist: default: log.Fatal(err) } } if existing != nil && create && !force { return nil, errors.New("Host already exists.") } else if existing != nil && !create { log.Debug("Existing host found.") return &Host{ Host: existing, Client: client, }, nil } if create { driver := virtualbox.NewDriver(DEFAULT_NAME, mcndirs.GetBaseDir()) driver.CPU = DEFAULT_CPU driver.Memory = DEFAULT_MEMORY // Disable the '/Users' mount, we handle that ourselves via // `docker-unisync`. driver.NoShare = true data, err := json.Marshal(driver) if err != nil { log.Fatal(err) } pluginDriver, err := client.NewPluginDriver("virtualbox", data) if err != nil { log.Fatal(err) } h, err := client.NewHost(pluginDriver) if err != nil { log.Fatal(err) } if err := client.Create(h); err != nil { log.Fatal(err) } return &Host{ Host: h, Client: client, }, nil } return nil, errors.New(fmt.Sprintf("The %v host doesn't exist and create was not specified.", DEFAULT_NAME)) }
func WithApi(handler Handler, args map[string]string, form map[string][]string) func() (interface{}, error) { return func() (interface{}, error) { globalMutex.Lock() defer globalMutex.Unlock() api := libmachine.NewClient(mcndirs.GetBaseDir(), mcndirs.GetMachineCertDir()) defer api.Close() return handler.Handle(api, args, form) } }
func NewDockerMachine(config DockerMachineConfig) (DockerMachineAPI, error) { storePath := config.StorePath temp := false if storePath == "" { tempPath, err := ioutil.TempDir("", "") if err != nil { return nil, errors.Wrap(err, "failed to create temp dir") } storePath = tempPath temp = true } certsPath := filepath.Join(storePath, "certs") if _, err := os.Stat(certsPath); os.IsNotExist(err) { err := os.MkdirAll(certsPath, 0700) if err != nil { return nil, errors.WithMessage(err, "failed to create certs dir") } } if config.CaPath != "" { err := mcnutils.CopyFile(filepath.Join(config.CaPath, "ca.pem"), filepath.Join(certsPath, "ca.pem")) if err != nil { return nil, errors.Wrap(err, "failed to copy ca file") } err = mcnutils.CopyFile(filepath.Join(config.CaPath, "ca-key.pem"), filepath.Join(certsPath, "ca-key.pem")) if err != nil { return nil, errors.Wrap(err, "failed to copy ca key file") } } if config.OutWriter != nil { log.SetOutWriter(config.OutWriter) } else { log.SetOutWriter(ioutil.Discard) } if config.ErrWriter != nil { log.SetOutWriter(config.ErrWriter) } else { log.SetOutWriter(ioutil.Discard) } log.SetDebug(config.IsDebug) client := libmachine.NewClient(storePath, certsPath) client.IsDebug = config.IsDebug if _, err := os.Stat(client.GetMachinesDir()); os.IsNotExist(err) { err := os.MkdirAll(client.GetMachinesDir(), 0700) if err != nil { return nil, errors.WithMessage(err, "failed to create machines dir") } } return &DockerMachine{ StorePath: storePath, CertsPath: certsPath, client: client, temp: temp, }, nil }
func main() { log.IsDebug = true log.SetOutWriter(os.Stdout) log.SetErrWriter(os.Stderr) client := libmachine.NewClient("/tmp/automatic") hostName := "myfunhost" // Set some options on the provider... driver := virtualbox.NewDriver(hostName, "/tmp/automatic") driver.CPU = 2 driver.Memory = 2048 data, err := json.Marshal(driver) if err != nil { log.Fatal(err) } pluginDriver, err := client.NewPluginDriver("virtualbox", data) if err != nil { log.Fatal(err) } h, err := client.NewHost(pluginDriver) if err != nil { log.Fatal(err) } h.HostOptions.EngineOptions.StorageDriver = "overlay" if err := client.Create(h); err != nil { log.Fatal(err) } out, err := h.RunSSHCommand("df -h") if err != nil { log.Fatal(err) } fmt.Printf("Results of your disk space query:\n%s\n", out) fmt.Println("Powering down machine now...") if err := h.Stop(); err != nil { log.Fatal(err) } }
func main() { log.SetDebug(true) client := libmachine.NewClient("/tmp/automatic", "/tmp/automatic/certs") defer client.Close() hostName := "myfunhost" // Set some options on the provider... driver := virtualbox.NewDriver(hostName, "/tmp/automatic") driver.CPU = 2 driver.Memory = 2048 data, err := json.Marshal(driver) if err != nil { log.Error(err) return } h, err := client.NewHost("virtualbox", data) if err != nil { log.Error(err) return } h.HostOptions.EngineOptions.StorageDriver = "overlay" if err := client.Create(h); err != nil { log.Error(err) return } out, err := h.RunSSHCommand("df -h") if err != nil { log.Error(err) return } fmt.Printf("Results of your disk space query:\n%s\n", out) fmt.Println("Powering down machine now...") if err := h.Stop(); err != nil { log.Error(err) return } }
// findIP finds the IP address of a Docker Machine host given its name. func findIP(name string) (net.IP, error) { log.Println("Looking for virtualbox machine", name) api := libmachine.NewClient(mcndirs.GetBaseDir(), mcndirs.GetMachineCertDir()) defer api.Close() machine, err := api.Load(name) if err != nil { return nil, err } driver := machine.Driver.DriverName() ip, err := machine.Driver.GetIP() if err != nil { return nil, err } log.Printf("Found %s(%s) with IP %s\n", name, driver, ip) return net.ParseIP(ip), nil }
func runCommand(command func(commandLine CommandLine, api libmachine.API) error) func(context *cli.Context) { return func(context *cli.Context) { api := libmachine.NewClient(mcndirs.GetBaseDir(), mcndirs.GetMachineCertDir()) defer api.Close() if context.GlobalBool("native-ssh") { api.SSHClientType = ssh.Native } api.GithubAPIToken = context.GlobalString("github-api-token") api.Filestore.Path = context.GlobalString("storage-path") // TODO (nathanleclaire): These should ultimately be accessed // through the libmachine client by the rest of the code and // not through their respective modules. For now, however, // they are also being set the way that they originally were // set to preserve backwards compatibility. mcndirs.BaseDir = api.Filestore.Path mcnutils.GithubAPIToken = api.GithubAPIToken ssh.SetDefaultClient(api.SSHClientType) if err := command(&contextCommandLine{context}, api); err != nil { log.Error(err) if crashErr, ok := err.(crashreport.CrashError); ok { crashReporter := crashreport.NewCrashReporter(mcndirs.GetBaseDir(), context.GlobalString("bugsnag-api-token")) crashReporter.Send(crashErr) if _, ok := crashErr.Cause.(mcnerror.ErrDuringPreCreate); ok { osExit(3) return } } osExit(1) return } } }
func (d *DockerMachineFsNotify) NotifyVm(event FsEvent) error { api := libmachine.NewClient(mcndirs.GetBaseDir(), mcndirs.GetMachineCertDir()) host, err := api.Load(d.DockerMachineName) if err != nil { return err } currentState, err := host.Driver.GetState() if err != nil { return err } if currentState != state.Running { return errors.New("Docker Machine " + host.Name + " is not running") } client, err := host.CreateSSHClient() if err != nil { return err } return client.Shell("touch -t " + event.ModTime.UTC().Format(touchTimeFormat) + " -m -c " + event.File) }
func runStart(cmd *cobra.Command, args []string) { fmt.Println("Starting local OpenShift cluster...") api := libmachine.NewClient(constants.Minipath, constants.MakeMiniPath("certs")) defer api.Close() config := cluster.MachineConfig{ MinikubeISO: viper.GetString(isoURL), Memory: viper.GetInt(memory), CPUs: viper.GetInt(cpus), DiskSize: calculateDiskSizeInMB(viper.GetString(humanReadableDiskSize)), VMDriver: viper.GetString(vmDriver), DockerEnv: dockerEnv, InsecureRegistry: insecureRegistry, RegistryMirror: registryMirror, HostOnlyCIDR: viper.GetString(hostOnlyCIDR), DeployRouter: viper.GetBool(deployRouter), DeployRegistry: viper.GetBool(deployRegistry), } var host *host.Host start := func() (err error) { host, err = cluster.StartHost(api, config) if err != nil { glog.Errorf("Error starting host: %s. Retrying.\n", err) } return err } err := util.Retry(3, start) if err != nil { glog.Errorln("Error starting host: ", err) os.Exit(1) } if err := cluster.UpdateCluster(host.Driver); err != nil { glog.Errorln("Error updating cluster: ", err) os.Exit(1) } kubeIP, err := host.Driver.GetIP() if err != nil { glog.Errorln("Error connecting to cluster: ", err) os.Exit(1) } if err := cluster.StartCluster(host, kubeIP, config); err != nil { glog.Errorln("Error starting cluster: ", err) os.Exit(1) } kubeHost, err := host.Driver.GetURL() if err != nil { glog.Errorln("Error connecting to cluster: ", err) os.Exit(1) } kubeHost = strings.Replace(kubeHost, "tcp://", "https://", -1) kubeHost = strings.Replace(kubeHost, ":2376", ":"+strconv.Itoa(constants.APIServerPort), -1) // setup kubeconfig certAuth, err := cluster.GetCA(host) if err != nil { glog.Errorln("Error setting up kubeconfig: ", err) os.Exit(1) } if err := setupKubeconfig(kubeHost, certAuth); err != nil { glog.Errorln("Error setting up kubeconfig: ", err) os.Exit(1) } }
// otherwise default to allcaps HTTP_PROXY if noProxyValue == "" { noProxyVar = "NO_PROXY" noProxyValue = os.Getenv("NO_PROXY") } return noProxyVar, noProxyValue } // envCmd represents the docker-env command var dockerEnvCmd = &cobra.Command{ Use: "docker-env", Short: "sets up docker env variables; similar to '$(docker-machine env)'", Long: `sets up docker env variables; similar to '$(docker-machine env)'`, Run: func(cmd *cobra.Command, args []string) { api := libmachine.NewClient(constants.Minipath, constants.MakeMiniPath("certs")) defer api.Close() var ( err error shellCfg *ShellConfig ) if unset { shellCfg, err = shellCfgUnset(api) if err != nil { glog.Errorln("Error setting machine env variable(s):", err) os.Exit(1) } } else { shellCfg, err = shellCfgSet(api)
func runStart(cmd *cobra.Command, args []string) { fmt.Println("Starting local Kubernetes cluster...") api := libmachine.NewClient(constants.Minipath, constants.MakeMiniPath("certs")) defer api.Close() config := cluster.MachineConfig{ MinikubeISO: viper.GetString(isoURL), Memory: viper.GetInt(memory), CPUs: viper.GetInt(cpus), DiskSize: calculateDiskSizeInMB(viper.GetString(humanReadableDiskSize)), VMDriver: viper.GetString(vmDriver), DockerEnv: dockerEnv, InsecureRegistry: insecureRegistry, RegistryMirror: registryMirror, HostOnlyCIDR: viper.GetString(hostOnlyCIDR), } var host *host.Host start := func() (err error) { host, err = cluster.StartHost(api, config) if err != nil { glog.Errorf("Error starting host: %s. Retrying.\n", err) } return err } err := util.Retry(3, start) if err != nil { glog.Errorln("Error starting host: ", err) util.MaybeReportErrorAndExit(err) } ip, err := host.Driver.GetIP() if err != nil { glog.Errorln("Error starting host: ", err) util.MaybeReportErrorAndExit(err) } kubernetesConfig := cluster.KubernetesConfig{ KubernetesVersion: viper.GetString(kubernetesVersion), NodeIP: ip, ContainerRuntime: viper.GetString(containerRuntime), NetworkPlugin: viper.GetString(networkPlugin), } if err := cluster.UpdateCluster(host, host.Driver, kubernetesConfig); err != nil { glog.Errorln("Error updating cluster: ", err) util.MaybeReportErrorAndExit(err) } if err := cluster.SetupCerts(host.Driver); err != nil { glog.Errorln("Error configuring authentication: ", err) util.MaybeReportErrorAndExit(err) } if err := cluster.StartCluster(host, kubernetesConfig); err != nil { glog.Errorln("Error starting cluster: ", err) util.MaybeReportErrorAndExit(err) } kubeHost, err := host.Driver.GetURL() if err != nil { glog.Errorln("Error connecting to cluster: ", err) } kubeHost = strings.Replace(kubeHost, "tcp://", "https://", -1) kubeHost = strings.Replace(kubeHost, ":2376", ":"+strconv.Itoa(constants.APIServerPort), -1) // setup kubeconfig name := constants.MinikubeContext certAuth := constants.MakeMiniPath("ca.crt") clientCert := constants.MakeMiniPath("apiserver.crt") clientKey := constants.MakeMiniPath("apiserver.key") if err := setupKubeconfig(name, kubeHost, certAuth, clientCert, clientKey); err != nil { glog.Errorln("Error setting up kubeconfig: ", err) util.MaybeReportErrorAndExit(err) } fmt.Println("Kubectl is now configured to use the cluster.") }
// Streaming the output of an SSH session in virtualbox. func streaming() { log.SetDebug(true) client := libmachine.NewClient("/tmp/automatic", "/tmp/automatic/certs") defer client.Close() hostName := "myfunhost" // Set some options on the provider... driver := virtualbox.NewDriver(hostName, "/tmp/automatic") data, err := json.Marshal(driver) if err != nil { log.Error(err) return } h, err := client.NewHost("virtualbox", data) if err != nil { log.Error(err) return } if err := client.Create(h); err != nil { log.Error(err) return } h.HostOptions.EngineOptions.StorageDriver = "overlay" sshClient, err := h.CreateSSHClient() if err != nil { log.Error(err) return } stdout, stderr, err := sshClient.Start("yes | head -n 10000") if err != nil { log.Error(err) return } defer func() { _ = stdout.Close() _ = stderr.Close() }() scanner := bufio.NewScanner(stdout) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Error(err) } if err := sshClient.Wait(); err != nil { log.Error(err) } fmt.Println("Powering down machine now...") if err := h.Stop(); err != nil { log.Error(err) return } }