Exemple #1
0
// dev
func dev(ccmd *cobra.Command, args []string) {

	// PreRun: boot

	// don't rebuild
	if !nobuild {

		// if the vm has no been created or deployed, the rebuild flag, or the VM has
		// recently been reloaded do a deploy
		if Vagrant.Status() == "not created" || !config.VMfile.HasDeployed() || rebuild || config.VMfile.HasReloaded() {

			fmt.Printf(stylish.Bullet("Deploying codebase..."))

			// remount the engine file at ~/.nanobox/apps/<app>/<engine> so any new scripts
			// will be used during the deploy
			if err := engineutil.RemountLocal(); err != nil {
				config.Debug("No engine mounted (not found locally).")
			}

			// run a deploy
			if err := server.Deploy(""); err != nil {
				server.Fatal("[commands/dev] server.Deploy() failed", err.Error())
			}

			// stream log output
			go Mist.Stream([]string{"log", "deploy"}, Mist.PrintLogStream)

			// listen for status updates
			errch := make(chan error)
			go func() {
				errch <- Mist.Listen([]string{"job", "deploy"}, Mist.DeployUpdates)
			}()

			// wait for a status update (blocking)
			err := <-errch

			//
			if err != nil {
				fmt.Printf(err.Error())
				return
			}
		}
	}

	//
	if err := server.Exec("develop", ""); err != nil {
		server.Error("[commands/dev] Server.Exec failed", err.Error())
	}

	// PostRun: halt
}
Exemple #2
0
// deploy
func deploy(ccmd *cobra.Command, args []string) {

	// PreRun: boot

	fmt.Printf(stylish.Bullet("Deploying codebase..."))

	// stream deploy output
	go mistutil.Stream([]string{"log", "deploy"}, mistutil.PrintLogStream)

	// listen for status updates
	errch := make(chan error)
	go func() {
		errch <- mistutil.Listen([]string{"job", "deploy"}, mistutil.DeployUpdates)
	}()

	v := url.Values{}
	v.Add("reset", strconv.FormatBool(config.Force))
	v.Add("run", strconv.FormatBool(install))

	// remount the engine file at ~/.nanobox/apps/<app>/<engine> so any new scripts
	// will be used during the deploy
	if err := engineutil.RemountLocal(); err != nil {
		config.Debug("No engine mounted (not found locally).")
	}

	// run a deploy
	if err := server.Deploy(v.Encode()); err != nil {
		server.Fatal("[commands/deploy] server.Deploy() failed", err.Error())
	}

	// wait for a status update (blocking)
	err := <-errch

	//
	if err != nil {
		fmt.Printf(err.Error())
		return
	}

	// reset "reloaded" to false after a successful deploy so as NOT to deploy on
	// subsequent runnings of "nanobox dev"
	config.VMfile.ReloadedIs(false)

	// PostRun: halt
}
Exemple #3
0
// build
func build(ccmd *cobra.Command, args []string) {

	// PreRun: boot

	fmt.Printf(stylish.Bullet("Building codebase..."))

	// stream build output
	go mistutil.Stream([]string{"log", "deploy"}, mistutil.PrintLogStream)

	// listen for status updates
	errch := make(chan error)
	go func() {
		errch <- mistutil.Listen([]string{"job", "build"}, mistutil.BuildUpdates)
	}()

	// remount the engine file at ~/.nanobox/apps/<app>/<engine> so any new scripts
	// are used during the build
	if err := engineutil.RemountLocal(); err != nil {
		config.Debug("No engine mounted (not found locally).")
	}

	// run a build
	if err := server.Build(""); err != nil {
		server.Fatal("[commands/build] server.Build() failed", err.Error())
	}

	// wait for a status update (blocking)
	err := <-errch

	//
	if err != nil {
		fmt.Printf(err.Error())
		return
	}

	// PostRun: halt
}
Exemple #4
0
// run
func run(ccmd *cobra.Command, args []string) {

	// PreRun: boot

	fmt.Printf(stylish.Bullet("Deploying codebase..."))

	// stream deploy output
	go mistutil.Stream([]string{"log", "deploy"}, mistutil.PrintLogStream)

	// listen for status updates
	errch := make(chan error)
	go func() {
		errch <- mistutil.Listen([]string{"job", "deploy"}, mistutil.DeployUpdates)
	}()

	// remount the engine file at ~/.nanobox/apps/<app>/<engine> so any new scripts
	// will be used during the deploy
	if err := engineutil.RemountLocal(); err != nil {
		config.Debug("No engine mounted (not found locally).")
	}

	// run a deploy
	if err := server.Deploy("run=true"); err != nil {
		server.Fatal("[commands/run] server.Deploy() failed", err.Error())
	}

	// wait for a status update (blocking)
	err := <-errch

	//
	if err != nil {
		fmt.Printf(err.Error())
		return
	}

	fmt.Printf(`
--------------------------------------------------------------------------------
[√] APP SUCCESSFULLY BUILT   ///   DEV URL : %v
--------------------------------------------------------------------------------
`, config.Nanofile.Domain)

	// if in background mode just exist w/o streaming logs or watching files
	if config.VMfile.IsBackground() {
		fmt.Println(`
To stream logs and watch files while in 'background mode' you can use
'nanobox log' and 'nanobox watch'
`)
		return
	}

	// if not in background mode begin streaming logs and watching files
	fmt.Printf(`
++> STREAMING LOGS (ctrl-c to exit) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
`)

	// stream app output
	go mistutil.Stream([]string{"log", "app"}, mistutil.ProcessLogStream)

	// begin watching for file changes (blocking)
	if err := notify.Watch(config.CWDir, server.NotifyRebuild); err != nil {
		fmt.Printf(err.Error())
	}

	// PostRun: halt
}
Exemple #5
0
// Init
func Init() {

	// create Vagrantfile
	vagrantfile, err := os.Create(config.AppDir + "/Vagrantfile")
	if err != nil {
		config.Fatal("[util/vagrant/init] ioutil.WriteFile() failed", err.Error())
	}
	defer vagrantfile.Close()

	//
	// create synced folders

	// mount code directory (mounted as nfs by default)
	synced_folders := fmt.Sprintf(`nanobox.vm.synced_folder "%s", "/vagrant/code/%s"`, config.CWDir, config.Nanofile.Name)

	// mount code directory as NFS unless configured otherwise; if not mounted in
	// this way Vagrant will just decide what it thinks is best
	if config.Nanofile.MountNFS {
		synced_folders += `,
      type: "nfs",
      mount_options: ["nfsvers=3", "proto=tcp"]`
	}

	// "mount" the engine file locally at ~/.nanobox/apps/<app>/<engine>
	name, path, err := engineutil.MountLocal()
	if err != nil {
		config.Debug("No engine mounted (not found locally).")
	}

	// "mount" the engine into the VM (if there is one)
	if name != "" && path != "" {
		synced_folders += fmt.Sprintf(`
    nanobox.vm.synced_folder "%s", "/vagrant/engines/%s"`, path, name)

		// mount engine directory as NFS unless configured otherwise; if not mounted in
		// this way Vagrant will just decide what it thinks is best
		if config.Nanofile.MountNFS {
			synced_folders += `,
      type: "nfs",
      mount_options: ["nfsvers=3", "proto=tcp"]`
		}
	}

	//
	// nanofile config

	// create nanobox private network and unique forward port
	network := fmt.Sprintf("nanobox.vm.network \"private_network\", ip: \"%s\"", config.Nanofile.IP)
	sshport := fmt.Sprintf("nanobox.vm.network :forwarded_port, guest: 22, host: %v, id: 'ssh'", util.StringToPort(config.Nanofile.Name))

	//
	provider := fmt.Sprintf(`# VirtualBox
    nanobox.vm.provider "virtualbox" do |p|
      p.name = "%v"

      p.customize ["modifyvm", :id, "--natdnshostresolver1", "%+v"]
      p.customize ["modifyvm", :id, "--cpuexecutioncap", "%v"]
      p.cpus = %v
      p.memory = %v
    end`, config.Nanofile.Name, config.Nanofile.HostDNS, config.Nanofile.CPUCap, config.Nanofile.CPUs, config.Nanofile.RAM)

	//
	// insert a provision script that will indicate to nanobox-server to boot into
	// 'devmode'
	var devmode string
	if config.Devmode {
		fmt.Printf(stylish.Bullet("Configuring vm to run in 'devmode'"))

		devmode = `# added because --dev was detected; boots the server into 'devmode'
    config.vm.provision "shell", inline: <<-DEVMODE
      echo "Starting VM in dev mode..."
      mkdir -p /mnt/sda/var/nanobox
      touch /mnt/sda/var/nanobox/DEV
    DEVMODE`
	}

	//
	// write to Vagrantfile
	vagrantfile.Write([]byte(fmt.Sprintf(`
################################################################################
##                                                                            ##
##                                   ***                                      ##
##                                *********                                   ##
##                           *******************                              ##
##                       ***************************                          ##
##                           *******************                              ##
##                       ...      *********      ...                          ##
##                           ...     ***     ...                              ##
##                       +++      ...   ...      +++                          ##
##                           +++     ...     +++                              ##
##                       \\\      +++   +++      ///                          ##
##                           \\\     +++     ///                              ##
##                                \\     //                                   ##
##                                   \//                                      ##
##                                                                            ##
##                    _  _ ____ _  _ ____ ___  ____ _  _                      ##
##                    |\ | |__| |\ | |  | |__) |  |  \/                       ##
##                    | \| |  | | \| |__| |__) |__| _/\_                      ##
##                                                                            ##
## This file was generated by nanobox. Any modifications to it may cause your ##
## nanobox VM to fail! To regenerate this file, delete it and run             ##
## 'nanobox init'                                                             ##
##                                                                            ##
################################################################################

# -*- mode: ruby -*-
# vi: set ft=ruby :

#
Vagrant.configure(2) do |config|

  # add the boot2docker user credentials to allow nanobox to freely ssh into the vm
  # w/o requiring a password
  config.ssh.shell = "bash"
  config.ssh.username = "******"
  config.ssh.password = "******"

  config.vm.define :'%s' do |nanobox|

    ## Set the hostname of the vm to the app domain
    nanobox.vm.provision "shell", inline: <<-SCRIPT
      sudo hostname %s
    SCRIPT

    ## Wait for nanobox-server to be ready before vagrant exits
    nanobox.vm.provision "shell", inline: <<-WAIT
      echo "Waiting for nanobox server..."
      while ! nc -z 127.0.0.1 1757; do sleep 1; done;
    WAIT

    ## box
    nanobox.vm.box     = "nanobox/boot2docker"


    ## network

    # add custom private network and ip and custom ssh port forward
    %s
    %s


    ## shared folders

    # disable default /vagrant share (overridden below)
    nanobox.vm.synced_folder ".", "/vagrant", disabled: true

    # add nanobox shared folders
    nanobox.vm.synced_folder "~/.ssh", "/mnt/ssh"
    %s


    ## provider configs
    %s

    ## wait for the dhcp service to come online
    nanobox.vm.provision "shell", inline: <<-WAIT
      attempts=0
      while [[ ! -f /var/run/udhcpc.eth1.pid && $attempts -lt 30 ]]; do
        let attempts++
        sleep 1
      done
    WAIT

    # kill the eth1 dhcp server so that it doesn't override the assigned ip when
    # the lease is up
    nanobox.vm.provision "shell", inline: <<-KILL
      if [ -f /var/run/udhcpc.eth1.pid ]; then
        echo "Killing eth1 dhcp..."
        kill -9 $(cat /var/run/udhcpc.eth1.pid)
      fi
    KILL

    %s

  end
end`, config.Nanofile.Name, config.Nanofile.Domain, network, sshport, synced_folders, provider, devmode)))
}
Exemple #6
0
// dev
func dev(ccmd *cobra.Command, args []string) {

	// PreRun: boot

	// check to see if the devconfig option is one of our predetermined values. If
	// not indicate as much and return
	switch devconfig {
	case "mount", "copy", "none":
		break
	default:
		fmt.Printf("--dev-config option '%s' is not accepted. Please choose either 'mount', 'copy', or 'none'\n", devconfig)
		os.Exit(1)
	}

	// stream log output; this is done here because there might be output from hooks
	// that needs to be streamed to the client. This will also capture any output
	// that would come from a deploy (if one is run).
	mist, err := Mist.Connect([]string{"log", "deploy"}, Mist.PrintLogStream)
	if err != nil {
		config.Fatal("[commands/dev] mist.Connect() failed", err.Error())
	}

	// don't rebuild
	if !nobuild {

		// if the vm has no been created or deployed, the rebuild flag, or the VM has
		// recently been reloaded do a deploy
		if Vagrant.Status() == "not created" || !config.VMfile.HasDeployed() || rebuild || config.VMfile.HasReloaded() {

			fmt.Printf(stylish.Bullet("Deploying codebase..."))

			// remount the engine file at ~/.nanobox/apps/<app>/<engine> so any new scripts
			// will be used during the deploy
			if err := engineutil.RemountLocal(); err != nil {
				config.Debug("No engine mounted (not found locally).")
			}

			// run a deploy
			if err := server.Deploy(""); err != nil {
				server.Fatal("[commands/dev] server.Deploy() failed", err.Error())
			}

			// listen for status updates
			errch := make(chan error)
			go func() {
				errch <- Mist.Listen([]string{"job", "deploy"}, Mist.DeployUpdates)
			}()

			// wait for a status update (blocking)
			err := <-errch

			//
			if err != nil {
				fmt.Printf(err.Error())
				return
			}
		}
	}

	//
	v := url.Values{}
	v.Add("dev_config", devconfig)

	//
	if err := server.Develop(v.Encode(), mist); err != nil {
		server.Error("[commands/dev] Server.Develop failed", err.Error())
	}

	// PostRun: halt
}
Exemple #7
0
// Init
func Init() {

	// create Vagrantfile
	vagrantfile, err := os.Create(config.AppDir + "/Vagrantfile")
	if err != nil {
		config.Fatal("[util/vagrant/init] ioutil.WriteFile() failed", err.Error())
	}
	defer vagrantfile.Close()

	//
	// create synced folders

	var sshMount, engineMount, codeMount string

	//
	// default path to ssh dir (assumes Unix)
	sshPath := filepath.Join(config.Home, ".ssh")

	// default path to ssh (windows)
	if config.OS == "windows" {
		sshPath = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") + `\.ssh`
	}

	// if an sshPath is provided in the nanofile override the default
	if config.Nanofile.SshPath != "" {
		sshPath = config.Nanofile.SshPath
	}

	// ensure the ssh location is a valid place; if the ssh dir is found, mount it
	sshDir, err := os.Stat(sshPath)
	if err == nil && sshDir.IsDir() {
		sshMount = fmt.Sprintf(`nanobox.vm.synced_folder '%s', "/mnt/ssh"`, sshPath)

		// if not found print this friendly warning
	} else {
		fmt.Printf(`
WARNING: Nanobox was unable to mount your .ssh folder into the VM because it was
unable to detect the location of an .ssh directory at:
%s

While nanobox is still usable for local development, this may result in failures
to fetch dependancies that require the use of those credentials`, sshPath)
	}

	//
	// mount code directory (mounted as nfs by default)
	codeMount = fmt.Sprintf(`nanobox.vm.synced_folder '%s', '/vagrant/code/%s'`, config.CWDir, config.Nanofile.Name)

	// mount code directory as NFS unless configured otherwise; if not mounted in
	// this way Vagrant will just decide what it thinks is best
	if config.Nanofile.MountNFS {
		codeMount += `,
      type: "nfs", mount_options: ["nfsvers=3", "proto=tcp"]`
	}

	//
	// "mount" the engine file locally at ~/.nanobox/apps/<app>/<engine>; this is
	// done when a local engine is detected so that the engine can be developed
	// and changed are reflected in the VM
	name, path, err := engineutil.MountLocal()
	if err != nil {
		config.Debug("No engine mounted (not found locally).")
	}

	// "mount" the engine into the VM (if there is one)
	if name != "" && path != "" {
		engineMount = fmt.Sprintf(`nanobox.vm.synced_folder '%s', "/vagrant/engines/%s"`, path, name)

		// mount engine directory as NFS unless configured otherwise; if not mounted
		// in this way Vagrant will just decide what it thinks is best
		if config.Nanofile.MountNFS {
			engineMount += `,
      type: "nfs", mount_options: ["nfsvers=3", "proto=tcp"]`
		}
	}

	//
	// nanofile config

	// create nanobox private network and unique forward port
	network := fmt.Sprintf("nanobox.vm.network \"private_network\", ip: \"%s\"", config.Nanofile.IP)
	sshport := fmt.Sprintf("nanobox.vm.network :forwarded_port, guest: 22, host: %v, id: 'ssh'", appNameToPort(config.Nanofile.Name))

	//
	provider := fmt.Sprintf(`# VirtualBox
    nanobox.vm.provider "virtualbox" do |p|
      p.name = "%v"

      p.customize ["modifyvm", :id, "--natdnshostresolver1", "%+v"]
      p.customize ["modifyvm", :id, "--cpuexecutioncap", "%v"]
      p.cpus = %v
      p.memory = %v
    end`, config.Nanofile.Name, config.Nanofile.HostDNS, config.Nanofile.CPUCap, config.Nanofile.CPUs, config.Nanofile.RAM)

	//
	// insert a provision script that will indicate to nanobox-server to boot into
	// 'devmode'
	var devmode string
	if config.Devmode {
		fmt.Printf(stylish.Bullet("Configuring vm to run in 'devmode'"))

		devmode = `# added because --dev was detected; boots the server into 'devmode'
    nanobox.vm.provision "shell", inline: <<-DEVMODE
      echo "Starting VM in dev mode..."
      mkdir -p /mnt/sda/var/nanobox
      touch /mnt/sda/var/nanobox/DEV
    DEVMODE`
	}

	//
	// insert a provision script that will allow utilization of system proxy vars
	var proxy string

	if config.Nanofile.UseProxy {
		fmt.Printf(stylish.Bullet("Configuring vm to use 'proxy' vars"))

		proxy = `# added because env 'use_proxy' was set; configures vm to use proxy
    nanobox.vm.provision "shell" do |s|
      s.inline = <<-PROXY
        echo "Configuring VM for proxy..."
        cat > /var/lib/boot2docker/profile <<-EOF
export http_proxy="$1"
export https_proxy="$2"
export https_user="******"
export https_pass="******"
EOF
        sudo /usr/local/etc/init.d/docker restart
        sudo /etc/init.d/services/nanoboxd stop && sudo /etc/init.d/services/nanoboxd start
      PROXY
      s.args = "'#{ENV['http_proxy']}' '#{ENV['https_proxy']}' '#{ENV['https_user']}' '#{ENV['https_pass']}'"
    end`
	}

	//
	// write to Vagrantfile
	vagrantfile.Write([]byte(fmt.Sprintf(`
################################################################################
##                                                                            ##
##                                   ***                                      ##
##                                *********                                   ##
##                           *******************                              ##
##                       ***************************                          ##
##                           *******************                              ##
##                       ...      *********      ...                          ##
##                           ...     ***     ...                              ##
##                       +++      ...   ...      +++                          ##
##                           +++     ...     +++                              ##
##                       \\\      +++   +++      ///                          ##
##                           \\\     +++     ///                              ##
##                                \\     //                                   ##
##                                   \//                                      ##
##                                                                            ##
##                    _  _ ____ _  _ ____ ___  ____ _  _                      ##
##                    |\ | |__| |\ | |  | |__) |  |  \/                       ##
##                    | \| |  | | \| |__| |__) |__| _/\_                      ##
##                                                                            ##
## This file was generated by nanobox. Any modifications to it may cause your ##
## nanobox VM to fail! To regenerate this file, delete it and run             ##
## 'nanobox init'                                                             ##
##                                                                            ##
################################################################################

# -*- mode: ruby -*-
# vi: set ft=ruby :

#
Vagrant.configure(2) do |config|

  # add the boot2docker user credentials to allow nanobox to freely ssh into the vm
  # w/o requiring a password
  config.ssh.shell = "bash"
  config.ssh.username = "******"
  config.ssh.password = "******"

  config.vm.define :'%s' do |nanobox|

    ## Set the hostname of the vm to the app domain
    nanobox.vm.provision "shell", inline: <<-SCRIPT
      sudo hostname %s
    SCRIPT

    ## Wait for nanobox-server to be ready before vagrant exits
    nanobox.vm.provision "shell", inline: <<-WAIT
      echo "Waiting for nanobox server..."
      while ! nc -z 127.0.0.1 1757; do sleep 1; done;
    WAIT

    ## box
    nanobox.vm.box = "nanobox/boot2docker"


    ## network

    # add custom private network and ip and custom ssh port forward
    `+network+`
    `+sshport+`


    ## shared folders

    # disable default /vagrant share (overridden below)
    nanobox.vm.synced_folder ".", "/vagrant", disabled: true

    # add nanobox shared folders
    `+sshMount+`
    `+codeMount+`
    `+engineMount+`

    ## provider configs
    `+provider+`

    ## wait for the dhcp service to come online
    nanobox.vm.provision "shell", inline: <<-WAIT
      attempts=0
      while [[ ! -f /var/run/udhcpc.eth1.pid && $attempts -lt 30 ]]; do
        let attempts++
        sleep 1
      done
    WAIT

    # kill the eth1 dhcp server so that it doesn't override the assigned ip when
    # the lease is up
    nanobox.vm.provision "shell", inline: <<-KILL
      if [ -f /var/run/udhcpc.eth1.pid ]; then
        echo "Killing eth1 dhcp..."
        kill -9 $(cat /var/run/udhcpc.eth1.pid)
      fi
    KILL

    %s

    %s

  end
end`, config.Nanofile.Name, config.Nanofile.Domain, devmode, proxy)))
}