func init() {
	Describe("ReleaseApplySpec", func() {
		var (
			platform *fakeplatform.FakePlatform
			action   ReleaseApplySpecAction
		)

		BeforeEach(func() {
			platform = fakeplatform.NewFakePlatform()
			action = NewReleaseApplySpec(platform)
		})

		It("is synchronous", func() {
			Expect(action.IsAsynchronous()).To(BeFalse())
		})

		It("is not persistent", func() {
			Expect(action.IsPersistent()).To(BeFalse())
		})

		It("run", func() {
			err := platform.GetFs().WriteFileString("/var/vcap/micro/apply_spec.json", `{"json":["objects"]}`)
			Expect(err).ToNot(HaveOccurred())

			value, err := action.Run()
			Expect(err).ToNot(HaveOccurred())

			Expect(value).To(Equal(map[string]interface{}{"json": []interface{}{"objects"}}))
		})
	})
}
Exemplo n.º 2
0
func init() {
	Describe("Testing with Ginkgo", func() {
		var (
			vsphere  Infrastructure
			platform *fakeplatform.FakePlatform
		)

		BeforeEach(func() {
			platform = fakeplatform.NewFakePlatform()
		})

		JustBeforeEach(func() {
			vsphere = NewVsphereInfrastructure(platform)
		})

		It("vsphere get settings", func() {
			platform.GetFileContentsFromCDROMContents = []byte(`{"agent_id": "123"}`)

			settings, err := vsphere.GetSettings()
			Expect(err).NotTo(HaveOccurred())

			Expect(platform.GetFileContentsFromCDROMPath).To(Equal("env"))
			Expect(settings.AgentId).To(Equal("123"))
		})

		It("vsphere setup networking", func() {
			networks := boshsettings.Networks{"bosh": boshsettings.Network{}}

			vsphere.SetupNetworking(networks)

			Expect(platform.SetupManualNetworkingNetworks).To(Equal(networks))
		})

		It("vsphere get ephemeral disk path", func() {
			platform.NormalizeDiskPathRealPath = "/dev/sdb"
			platform.NormalizeDiskPathFound = true

			realPath, found := vsphere.GetEphemeralDiskPath("does not matter")
			Expect(found).To(Equal(true))

			Expect(realPath).To(Equal("/dev/sdb"))
			Expect(platform.NormalizeDiskPathPath).To(Equal("/dev/sdb"))
		})
	})
}
Exemplo n.º 3
0
func init() {
	Describe("Testing with Ginkgo", func() {
		var (
			logger   boshlog.Logger
			platform *fakeplatform.FakePlatform
		)

		BeforeEach(func() {
			platform = fakeplatform.NewFakePlatform()
			logger = boshlog.NewLogger(boshlog.LEVEL_NONE)
		})

		It("list disk should be synchronous", func() {
			settings := &fakesettings.FakeSettingsService{}
			action := NewListDisk(settings, platform, logger)
			Expect(action.IsAsynchronous()).To(BeFalse())
		})

		It("is not persistent", func() {
			settings := &fakesettings.FakeSettingsService{}
			action := NewListDisk(settings, platform, logger)
			Expect(action.IsPersistent()).To(BeFalse())
		})

		It("list disk run", func() {
			settings := &fakesettings.FakeSettingsService{
				Disks: boshsettings.Disks{
					Persistent: map[string]string{
						"volume-1": "/dev/sda",
						"volume-2": "/dev/sdb",
						"volume-3": "/dev/sdc",
					},
				},
			}
			platform.MountedDevicePaths = []string{"/dev/sdb", "/dev/sdc"}

			action := NewListDisk(settings, platform, logger)
			value, err := action.Run()
			Expect(err).ToNot(HaveOccurred())
			boshassert.MatchesJsonString(GinkgoT(), value, `["volume-2","volume-3"]`)
		})
	})
}
Exemplo n.º 4
0
func init() {
	Describe("ListDisk", func() {
		var (
			settingsService *fakesettings.FakeSettingsService
			platform        *fakeplatform.FakePlatform
			logger          boshlog.Logger
			action          ListDiskAction
		)

		BeforeEach(func() {
			settingsService = &fakesettings.FakeSettingsService{}
			platform = fakeplatform.NewFakePlatform()
			logger = boshlog.NewLogger(boshlog.LevelNone)
			action = NewListDisk(settingsService, platform, logger)
		})

		It("list disk should be synchronous", func() {
			Expect(action.IsAsynchronous()).To(BeFalse())
		})

		It("is not persistent", func() {
			Expect(action.IsPersistent()).To(BeFalse())
		})

		It("list disk run", func() {
			platform.MountedDevicePaths = []string{"/dev/sdb", "/dev/sdc"}

			settingsService.Settings.Disks = boshsettings.Disks{
				Persistent: map[string]string{
					"volume-1": "/dev/sda",
					"volume-2": "/dev/sdb",
					"volume-3": "/dev/sdc",
				},
			}

			value, err := action.Run()
			Expect(err).ToNot(HaveOccurred())
			boshassert.MatchesJSONString(GinkgoT(), value, `["volume-2","volume-3"]`)
		})
	})
}
Exemplo n.º 5
0
func init() {
	Describe("concreteV1Service", func() {
		var (
			fs       *fakesys.FakeFileSystem
			platform *fakeplatform.FakePlatform
			specPath = "/spec.json"
			service  V1Service
		)

		BeforeEach(func() {
			fs = fakesys.NewFakeFileSystem()
			platform = fakeplatform.NewFakePlatform()
			service = NewConcreteV1Service(fs, platform, specPath)
		})

		Describe("Get", func() {
			Context("when filesystem has a spec file", func() {
				BeforeEach(func() {
					fs.WriteFileString(specPath, `{"deployment":"fake-deployment-name"}`)
				})

				It("reads spec from filesystem", func() {
					spec, err := service.Get()
					Expect(err).ToNot(HaveOccurred())
					Expect(spec).To(Equal(V1ApplySpec{Deployment: "fake-deployment-name"}))
				})

				It("returns error if reading spec from filesystem errs", func() {
					fs.ReadFileError = errors.New("fake-read-error")

					spec, err := service.Get()
					Expect(err).To(HaveOccurred())
					Expect(err.Error()).To(ContainSubstring("fake-read-error"))
					Expect(spec).To(Equal(V1ApplySpec{}))
				})
			})

			Context("when filesystem does not have a spec file", func() {
				It("reads spec from filesystem", func() {
					spec, err := service.Get()
					Expect(err).ToNot(HaveOccurred())
					Expect(spec).To(Equal(V1ApplySpec{}))
				})
			})
		})

		Describe("Set", func() {
			newSpec := V1ApplySpec{Deployment: "fake-deployment-name"}

			It("writes spec to filesystem", func() {
				err := service.Set(newSpec)
				Expect(err).ToNot(HaveOccurred())

				specPathStats := fs.GetFileTestStat(specPath)
				Expect(specPathStats).ToNot(BeNil())
				boshassert.MatchesJSONBytes(GinkgoT(), newSpec, specPathStats.Content)
			})

			It("returns error if writing spec to filesystem errs", func() {
				fs.WriteToFileError = errors.New("fake-write-error")

				err := service.Set(newSpec)
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-write-error"))
			})
		})

		Describe("ResolveDynamicNetworks", func() {
			Context("when there is are no dynamic networks", func() {
				unresolvedSpec := V1ApplySpec{
					Deployment: "fake-deployment",
					NetworkSpecs: map[string]NetworkSpec{
						"fake-net": NetworkSpec{
							Fields: map[string]interface{}{"ip": "fake-net-ip"},
						},
					},
				}

				It("returns spec without modifying any networks", func() {
					spec, err := service.ResolveDynamicNetworks(unresolvedSpec)
					Expect(err).ToNot(HaveOccurred())
					Expect(spec).To(Equal(V1ApplySpec{
						Deployment: "fake-deployment",
						NetworkSpecs: map[string]NetworkSpec{
							"fake-net": NetworkSpec{
								Fields: map[string]interface{}{"ip": "fake-net-ip"},
							},
						},
					}))
				})
			})

			Context("when there is one dynamic network", func() {
				unresolvedSpec := V1ApplySpec{
					Deployment: "fake-deployment",
					NetworkSpecs: map[string]NetworkSpec{
						"fake-net1": NetworkSpec{
							Fields: map[string]interface{}{
								"ip":      "fake-net1-ip",
								"netmask": "fake-net1-netmask",
								"gateway": "fake-net1-gateway",
							},
						},
						"fake-net2": NetworkSpec{
							Fields: map[string]interface{}{
								"type":    NetworkSpecTypeDynamic,
								"ip":      "fake-net2-ip",
								"netmask": "fake-net2-netmask",
								"gateway": "fake-net2-gateway",
							},
						},
					},
				}

				Context("when default network can be retrieved", func() {
					BeforeEach(func() {
						platform.GetDefaultNetworkNetwork = boshsettings.Network{
							IP:      "fake-resolved-ip",
							Netmask: "fake-resolved-netmask",
							Gateway: "fake-resolved-gateway",
						}
					})

					It("returns spec with modified dynamic network and keeping everything else the same", func() {
						spec, err := service.ResolveDynamicNetworks(unresolvedSpec)
						Expect(err).ToNot(HaveOccurred())
						Expect(spec).To(Equal(V1ApplySpec{
							Deployment: "fake-deployment",
							NetworkSpecs: map[string]NetworkSpec{
								"fake-net1": NetworkSpec{
									Fields: map[string]interface{}{
										"ip":      "fake-net1-ip",
										"netmask": "fake-net1-netmask",
										"gateway": "fake-net1-gateway",
									},
								},
								"fake-net2": NetworkSpec{
									Fields: map[string]interface{}{
										"type":    NetworkSpecTypeDynamic,
										"ip":      "fake-resolved-ip",
										"netmask": "fake-resolved-netmask",
										"gateway": "fake-resolved-gateway",
									},
								},
							},
						}))
					})
				})

				Context("when default network fails to be retrieved", func() {
					BeforeEach(func() {
						platform.GetDefaultNetworkErr = errors.New("fake-get-default-network-err")
					})

					It("returns error", func() {
						spec, err := service.ResolveDynamicNetworks(unresolvedSpec)
						Expect(err).To(HaveOccurred())
						Expect(err.Error()).To(ContainSubstring("fake-get-default-network-err"))
						Expect(spec).To(Equal(V1ApplySpec{}))
					})
				})
			})

			Context("when there is are multiple dynamic networks", func() {
				unresolvedSpec := V1ApplySpec{
					NetworkSpecs: map[string]NetworkSpec{
						"fake-net1": NetworkSpec{
							Fields: map[string]interface{}{"type": NetworkSpecTypeDynamic},
						},
						"fake-net2": NetworkSpec{
							Fields: map[string]interface{}{"type": NetworkSpecTypeDynamic},
						},
					},
				}

				It("returns error because multiple dynamic networks are not supported", func() {
					spec, err := service.ResolveDynamicNetworks(unresolvedSpec)
					Expect(err).To(HaveOccurred())
					Expect(err.Error()).To(ContainSubstring("Multiple dynamic networks are not supported"))
					Expect(spec).To(Equal(V1ApplySpec{}))
				})
			})
		})
	})
}
Exemplo n.º 6
0
import (
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "bosh/infrastructure"
	boshdpresolv "bosh/infrastructure/devicepathresolver"
	boshlog "bosh/logger"
	fakeplatform "bosh/platform/fakes"
)

var _ = Describe("Provider", func() {
	var (
		logger   boshlog.Logger
		platform *fakeplatform.FakePlatform
		provider Provider
	)

	BeforeEach(func() {
		platform = fakeplatform.NewFakePlatform()
		logger = boshlog.NewLogger(boshlog.LevelNone)
		provider = NewProvider(logger, platform)
	})

	Describe("Get", func() {
		It("returns aws infrastructure", func() {
			metadataService := NewConcreteMetadataService(
				"http://169.254.169.254",
				NewDigDNSResolver(logger),
			)
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	boshlog "bosh/logger"
	. "bosh/mbus"
	"bosh/micro"
	fakeplatform "bosh/platform/fakes"
	boshdir "bosh/settings/directories"
	fakesettings "bosh/settings/fakes"
)

var _ = Describe("MbusHandlerProvider", func() {
	var (
		settingsService *fakesettings.FakeSettingsService
		platform        *fakeplatform.FakePlatform
		dirProvider     boshdir.DirectoriesProvider
		logger          boshlog.Logger
		provider        MbusHandlerProvider
	)

	BeforeEach(func() {
		settingsService = &fakesettings.FakeSettingsService{}
		logger = boshlog.NewLogger(boshlog.LevelNone)
		platform = fakeplatform.NewFakePlatform()
		dirProvider = boshdir.NewDirectoriesProvider("/var/vcap")
		provider = NewHandlerProvider(settingsService, logger)
	})

	Describe("Get", func() {
		It("returns nats handler", func() {
			settingsService.Settings.Mbus = "nats://lol"
Exemplo n.º 8
0
func init() {
	Describe("bootstrap", func() {
		Describe("Run", func() {
			var (
				inf         *fakeinf.FakeInfrastructure
				platform    *fakeplatform.FakePlatform
				dirProvider boshdir.DirectoriesProvider

				settingsServiceProvider *fakesettings.FakeSettingsServiceProvider
				settingsService         *fakesettings.FakeSettingsService
			)

			BeforeEach(func() {
				inf = &fakeinf.FakeInfrastructure{
					GetEphemeralDiskPathFound:    true,
					GetEphemeralDiskPathRealPath: "/dev/sdz",
				}
				platform = fakeplatform.NewFakePlatform()
				dirProvider = boshdir.NewDirectoriesProvider("/var/vcap")

				settingsServiceProvider = fakesettings.NewServiceProvider()
				settingsService = settingsServiceProvider.NewServiceSettingsService
			})

			bootstrap := func() (boshsettings.Service, error) {
				logger := boshlog.NewLogger(boshlog.LevelNone)
				return New(inf, platform, dirProvider, settingsServiceProvider, logger).Run()
			}

			It("sets up runtime configuration", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.SetupRuntimeConfigurationWasInvoked).To(BeTrue())
			})

			It("sets up ssh", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(inf.SetupSshUsername).To(Equal("vcap"))
			})

			It("sets up hostname", func() {
				settingsService.Settings.AgentID = "foo-bar-baz-123"

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.SetupHostnameHostname).To(Equal("foo-bar-baz-123"))
			})

			It("returns the settings service", func() {
				settingsService, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(settingsService).To(Equal(settingsService))

				Expect(settingsServiceProvider.NewServiceFs).To(Equal(platform.GetFs()))
				Expect(settingsServiceProvider.NewServiceDir).To(Equal(dirProvider.BoshDir()))

				fetchedSettings, err := settingsServiceProvider.NewServiceFetcher()
				Expect(err).NotTo(HaveOccurred())
				Expect(fetchedSettings).To(Equal(inf.Settings))
			})

			It("fetches initial settings", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(settingsService.SettingsWereLoaded).To(BeTrue())
			})

			It("returns error from loading initial settings", func() {
				settingsService.LoadSettingsError = errors.New("fake-load-error")

				_, err := bootstrap()
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-load-error"))
			})

			It("sets up networking", func() {
				networks := boshsettings.Networks{
					"bosh": boshsettings.Network{},
				}
				settingsService.Settings.Networks = networks

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(inf.SetupNetworkingNetworks).To(Equal(networks))
			})

			It("sets up ephemeral disk", func() {
				settingsService.Disks = boshsettings.Disks{
					Ephemeral: "fake-ephemeral-disk-setting",
				}

				inf.GetEphemeralDiskPathRealPath = "/dev/sda"
				inf.GetEphemeralDiskPathFound = true

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.SetupEphemeralDiskWithPathDevicePath).To(Equal("/dev/sda"))
				Expect(inf.GetEphemeralDiskPathDevicePath).To(Equal("fake-ephemeral-disk-setting"))
			})

			It("returns error if setting ephemeral disk fails", func() {
				platform.SetupEphemeralDiskWithPathErr = errors.New("fake-setup-ephemeral-disk-err")
				_, err := bootstrap()
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-setup-ephemeral-disk-err"))
			})

			It("sets up data dir", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.SetupDataDirCalled).To(BeTrue())
			})

			It("returns error if set up of data dir fails", func() {
				platform.SetupDataDirErr = errors.New("fake-setup-data-dir-err")
				_, err := bootstrap()
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-setup-data-dir-err"))
			})

			It("sets up tmp dir", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.SetupTmpDirCalled).To(BeTrue())
			})

			It("returns error if set up of tmp dir fails", func() {
				platform.SetupTmpDirErr = errors.New("fake-setup-tmp-dir-err")
				_, err := bootstrap()
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-setup-tmp-dir-err"))
			})

			It("mounts persistent disk", func() {
				settingsService.Disks = boshsettings.Disks{
					Persistent: map[string]string{"vol-123": "/dev/sdb"},
				}

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.MountPersistentDiskDevicePath).To(Equal("/dev/sdb"))
				Expect(platform.MountPersistentDiskMountPoint).To(Equal(dirProvider.StoreDir()))
			})

			It("errors if there is more than one persistent disk", func() {
				settingsService.Disks = boshsettings.Disks{
					Persistent: map[string]string{
						"vol-123": "/dev/sdb",
						"vol-456": "/dev/sdc",
					},
				}

				_, err := bootstrap()
				Expect(err).To(HaveOccurred())
			})

			It("does not try to mount when no persistent disk", func() {
				settingsService.Disks = boshsettings.Disks{
					Persistent: map[string]string{},
				}

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.MountPersistentDiskDevicePath).To(Equal(""))
				Expect(platform.MountPersistentDiskMountPoint).To(Equal(""))
			})

			It("sets root and vcap passwords", func() {
				settingsService.Settings.Env.Bosh.Password = "******"

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(2).To(Equal(len(platform.UserPasswords)))
				Expect("some-encrypted-password").To(Equal(platform.UserPasswords["root"]))
				Expect("some-encrypted-password").To(Equal(platform.UserPasswords["vcap"]))
			})

			It("does not set password if not provided", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(0).To(Equal(len(platform.UserPasswords)))
			})

			It("sets ntp", func() {
				settingsService.Settings.Ntp = []string{
					"0.north-america.pool.ntp.org",
					"1.north-america.pool.ntp.org",
				}

				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(2).To(Equal(len(platform.SetTimeWithNtpServersServers)))
				Expect("0.north-america.pool.ntp.org").To(Equal(platform.SetTimeWithNtpServersServers[0]))
				Expect("1.north-america.pool.ntp.org").To(Equal(platform.SetTimeWithNtpServersServers[1]))
			})

			It("setups up monit user", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.SetupMonitUserSetup).To(BeTrue())
			})

			It("starts monit", func() {
				_, err := bootstrap()
				Expect(err).NotTo(HaveOccurred())
				Expect(platform.StartMonitStarted).To(BeTrue())
			})
		})
	})
}
func init() {
	Describe("concreteServiceProvider", func() {
		var (
			platform *fakeplatform.FakePlatform
		)

		Describe("NewService", func() {
			It("returns service with settings.json as its settings path", func() {
				// Cannot compare fetcher functions since function comparison is problematic
				fs := fakesys.NewFakeFileSystem()
				logger := boshlog.NewLogger(boshlog.LevelNone)
				service := NewServiceProvider().NewService(fs, "/setting/path", nil, platform, logger)
				Expect(service).To(Equal(NewService(fs, "/setting/path/settings.json", nil, platform, logger)))
			})
		})
	})

	Describe("concreteService", func() {
		var (
			fs       *fakesys.FakeFileSystem
			platform *fakeplatform.FakePlatform
		)

		BeforeEach(func() {
			fs = fakesys.NewFakeFileSystem()
			platform = fakeplatform.NewFakePlatform()
		})

		buildService := func(fetcher SettingsFetcher) (Service, *fakesys.FakeFileSystem) {
			logger := boshlog.NewLogger(boshlog.LevelNone)
			service := NewService(fs, "/setting/path", fetcher, platform, logger)
			return service, fs
		}

		Describe("LoadSettings", func() {
			var (
				fetchedSettings Settings
				fetcherFuncErr  error
				service         Service
			)

			BeforeEach(func() {
				fetchedSettings = Settings{}
				fetcherFuncErr = nil
			})

			JustBeforeEach(func() {
				fetcherFunc := func() (Settings, error) { return fetchedSettings, fetcherFuncErr }
				service, fs = buildService(fetcherFunc)
			})

			Context("when settings fetcher succeeds fetching settings", func() {
				BeforeEach(func() {
					fetchedSettings = Settings{AgentID: "some-new-agent-id"}
				})

				Context("when settings contain at most one dynamic network", func() {
					BeforeEach(func() {
						fetchedSettings.Networks = Networks{
							"fake-net-1": Network{Type: NetworkTypeDynamic},
						}
					})

					It("updates the service with settings from the fetcher", func() {
						err := service.LoadSettings()
						Expect(err).NotTo(HaveOccurred())
						Expect(service.GetSettings().AgentID).To(Equal("some-new-agent-id"))
					})

					It("persists settings to the settings file", func() {
						err := service.LoadSettings()
						Expect(err).NotTo(HaveOccurred())

						json, err := json.Marshal(fetchedSettings)
						Expect(err).NotTo(HaveOccurred())

						fileContent, err := fs.ReadFile("/setting/path")
						Expect(err).NotTo(HaveOccurred())
						Expect(fileContent).To(Equal(json))
					})

					It("returns any error from writing to the setting file", func() {
						fs.WriteToFileError = errors.New("fs-write-file-error")

						err := service.LoadSettings()
						Expect(err).To(HaveOccurred())
						Expect(err.Error()).To(ContainSubstring("fs-write-file-error"))
					})
				})

				Context("when settings contain multiple dynamic networks", func() {
					BeforeEach(func() {
						fetchedSettings.Networks = Networks{
							"fake-net-1": Network{Type: NetworkTypeDynamic},
							"fake-net-2": Network{Type: NetworkTypeDynamic},
						}
					})

					It("returns error because multiple dynamic networks are not supported", func() {
						err := service.LoadSettings()
						Expect(err).To(HaveOccurred())
						Expect(err.Error()).To(ContainSubstring("Multiple dynamic networks are not supported"))
					})
				})
			})

			Context("when settings fetcher fails fetching settings", func() {
				BeforeEach(func() {
					fetcherFuncErr = errors.New("fake-fetch-error")
				})

				Context("when a settings file exists", func() {
					Context("when settings contain at most one dynamic network", func() {
						BeforeEach(func() {
							fs.WriteFile("/setting/path", []byte(`{
								"agent_id":"some-agent-id",
								"networks": {"fake-net-1": {"type": "dynamic"}}
							}`))
						})

						It("returns settings from the settings file", func() {
							err := service.LoadSettings()
							Expect(err).ToNot(HaveOccurred())
							Expect(service.GetSettings()).To(Equal(Settings{
								AgentID: "some-agent-id",
								Networks: Networks{
									"fake-net-1": Network{Type: NetworkTypeDynamic},
								},
							}))
						})
					})

					Context("when settings contain multiple dynamic networks", func() {
						BeforeEach(func() {
							fs.WriteFile("/setting/path", []byte(`{
								"agent_id":"some-agent-id",
								"networks": {
									"fake-net-1": {"type": "dynamic"},
									"fake-net-2": {"type": "dynamic"}
								}
							}`))
						})

						It("returns error because multiple dynamic networks are not supported", func() {
							err := service.LoadSettings()
							Expect(err).To(HaveOccurred())
							Expect(err.Error()).To(ContainSubstring("Multiple dynamic networks are not supported"))
						})
					})
				})

				Context("when non-unmarshallable settings file exists", func() {
					It("returns any error from the fetcher", func() {
						fs.WriteFile("/setting/path", []byte(`$%^&*(`))

						err := service.LoadSettings()
						Expect(err).To(HaveOccurred())
						Expect(err.Error()).To(ContainSubstring("fake-fetch-error"))

						Expect(service.GetSettings()).To(Equal(Settings{}))
					})
				})

				Context("when no settings file exists", func() {
					It("returns any error from the fetcher", func() {
						err := service.LoadSettings()
						Expect(err).To(HaveOccurred())
						Expect(err.Error()).To(ContainSubstring("fake-fetch-error"))

						Expect(service.GetSettings()).To(Equal(Settings{}))
					})
				})
			})
		})

		Describe("InvalidateSettings", func() {
			It("removes the settings file", func() {
				service, fs := buildService(nil)

				fs.WriteFile("/setting/path", []byte(`{}`))

				err := service.InvalidateSettings()
				Expect(err).ToNot(HaveOccurred())

				Expect(fs.FileExists("/setting/path")).To(BeFalse())
			})

			It("returns err if removing settings file errored", func() {
				service, fs := buildService(nil)

				fs.RemoveAllError = errors.New("fs-remove-all-error")

				err := service.InvalidateSettings()
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fs-remove-all-error"))
			})
		})

		Describe("GetSettings", func() {
			var (
				loadedSettings Settings
				service        Service
			)

			BeforeEach(func() {
				loadedSettings = Settings{AgentID: "some-agent-id"}
			})

			JustBeforeEach(func() {
				service, _ = buildService(func() (Settings, error) { return loadedSettings, nil })
				err := service.LoadSettings()
				Expect(err).NotTo(HaveOccurred())
			})

			Context("when there is are no dynamic networks", func() {
				It("returns settings without modifying any networks", func() {
					Expect(service.GetSettings()).To(Equal(loadedSettings))
				})

				It("does not try to determine default network", func() {
					_ = service.GetSettings()
					Expect(platform.GetDefaultNetworkCalled).To(BeFalse())
				})
			})

			Context("when there is one dynamic network", func() {
				BeforeEach(func() {
					loadedSettings = Settings{
						Networks: map[string]Network{
							"fake-net1": Network{
								IP:      "fake-net1-ip",
								Netmask: "fake-net1-netmask",
								Gateway: "fake-net1-gateway",
							},
							"fake-net2": Network{
								Type:    "dynamic",
								IP:      "fake-net2-ip",
								Netmask: "fake-net2-netmask",
								Gateway: "fake-net2-gateway",
								DNS:     []string{"fake-net2-dns"},
							},
						},
					}
				})

				Context("when default network can be retrieved", func() {
					BeforeEach(func() {
						platform.GetDefaultNetworkNetwork = Network{
							IP:      "fake-resolved-ip",
							Netmask: "fake-resolved-netmask",
							Gateway: "fake-resolved-gateway",
						}
					})

					It("returns settings with resolved dynamic network ip, netmask, gateway and keeping everything else the same", func() {
						settings := service.GetSettings()
						Expect(settings).To(Equal(Settings{
							Networks: map[string]Network{
								"fake-net1": Network{
									IP:      "fake-net1-ip",
									Netmask: "fake-net1-netmask",
									Gateway: "fake-net1-gateway",
								},
								"fake-net2": Network{
									Type:    "dynamic",
									IP:      "fake-resolved-ip",
									Netmask: "fake-resolved-netmask",
									Gateway: "fake-resolved-gateway",
									DNS:     []string{"fake-net2-dns"},
								},
							},
						}))
					})
				})

				Context("when default network fails to be retrieved", func() {
					BeforeEach(func() {
						platform.GetDefaultNetworkErr = errors.New("fake-get-default-network-err")
					})

					It("returns error", func() {
						settings := service.GetSettings()
						Expect(settings).To(Equal(loadedSettings))
					})
				})
			})
		})
	})
}
Exemplo n.º 10
0
package blobstore_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "bosh/blobstore"
	fakeplatform "bosh/platform/fakes"
	boshsettings "bosh/settings"
	boshdir "bosh/settings/directories"
	boshuuid "bosh/uuid"
)

var _ = Describe("Provider", func() {
	var (
		platform *fakeplatform.FakePlatform
		provider Provider
	)

	BeforeEach(func() {
		platform = fakeplatform.NewFakePlatform()
		dirProvider := boshdir.NewDirectoriesProvider("/var/vcap")
		provider = NewProvider(platform, dirProvider)
	})

	Describe("Get", func() {
		It("get dummy", func() {
			blobstore, err := provider.Get(boshsettings.Blobstore{
				Type: boshsettings.BlobstoreTypeDummy,
			})
			Expect(err).ToNot(HaveOccurred())
			Expect(blobstore).ToNot(BeNil())
import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "bosh/infrastructure"
	fakedpresolv "bosh/infrastructure/devicepathresolver/fakes"
	boshlog "bosh/logger"
	fakeplatform "bosh/platform/fakes"
	boshsettings "bosh/settings"
)

var _ = Describe("vSphere Infrastructure", func() {
	var (
		logger             boshlog.Logger
		vsphere            Infrastructure
		platform           *fakeplatform.FakePlatform
		devicePathResolver *fakedpresolv.FakeDevicePathResolver
	)

	BeforeEach(func() {
		platform = fakeplatform.NewFakePlatform()
		devicePathResolver = fakedpresolv.NewFakeDevicePathResolver()
		logger = boshlog.NewLogger(boshlog.LevelNone)
	})

	JustBeforeEach(func() {
		vsphere = NewVsphereInfrastructure(platform, devicePathResolver, logger)
	})

	Describe("GetSettings", func() {
		It("vsphere get settings", func() {
	fakejobsuper "bosh/jobsupervisor/fakes"
	boshlog "bosh/logger"
	fakenotif "bosh/notification/fakes"
	fakeplatform "bosh/platform/fakes"
	boshntp "bosh/platform/ntp"
	fakesettings "bosh/settings/fakes"
)

var _ = Describe("concreteFactory", func() {
	var (
		settingsService     *fakesettings.FakeSettingsService
		platform            *fakeplatform.FakePlatform
		blobstore           *fakeblobstore.FakeBlobstore
		taskService         *faketask.FakeService
		notifier            *fakenotif.FakeNotifier
		applier             *fakeappl.FakeApplier
		compiler            *fakecomp.FakeCompiler
		jobSupervisor       *fakejobsuper.FakeJobSupervisor
		specService         *fakeas.FakeV1Service
		drainScriptProvider boshdrain.DrainScriptProvider
		factory             Factory
		logger              boshlog.Logger
	)

	BeforeEach(func() {
		settingsService = &fakesettings.FakeSettingsService{}
		platform = fakeplatform.NewFakePlatform()
		blobstore = &fakeblobstore.FakeBlobstore{}
		taskService = &faketask.FakeService{}
		notifier = fakenotif.NewFakeNotifier()
		applier = fakeappl.NewFakeApplier()
		compiler = fakecomp.NewFakeCompiler()
import (
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "bosh/agent/action"
	fakeplatform "bosh/platform/fakes"
	fakesettings "bosh/settings/fakes"
)

var _ = Describe("prepareConfigureNetworks", func() {
	var (
		action          PrepareConfigureNetworksAction
		platform        *fakeplatform.FakePlatform
		settingsService *fakesettings.FakeSettingsService
	)

	BeforeEach(func() {
		platform = fakeplatform.NewFakePlatform()
		settingsService = &fakesettings.FakeSettingsService{}
		action = NewPrepareConfigureNetworks(platform, settingsService)
	})

	It("is synchronous", func() {
		Expect(action.IsAsynchronous()).To(BeFalse())
	})

	It("is not persistent", func() {
		Expect(action.IsPersistent()).To(BeFalse())
Exemplo n.º 14
0
func init() {
	var (
		platform               *fakeplatform.FakePlatform
		fakeDevicePathResolver *fakedpresolv.FakeDevicePathResolver
	)

	BeforeEach(func() {
		platform = fakeplatform.NewFakePlatform()
		fakeDevicePathResolver = fakedpresolv.NewFakeDevicePathResolver(
			1*time.Millisecond,
			platform.GetFs(),
		)
	})

	Describe("AWS Infrastructure", func() {
		Describe("SetupSsh", func() {
			var (
				ts  *httptest.Server
				aws Infrastructure
			)

			const expectedKey = "some public key"

			BeforeEach(func() {
				handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					Expect(r.Method).To(Equal("GET"))
					Expect(r.URL.Path).To(Equal("/latest/meta-data/public-keys/0/openssh-key"))
					w.Write([]byte(expectedKey))
				})
				ts = httptest.NewServer(handler)
			})

			AfterEach(func() {
				ts.Close()
			})

			It("gets the public key and sets up ssh via the platform", func() {
				aws = NewAwsInfrastructure(ts.URL, &FakeDNSResolver{}, platform, fakeDevicePathResolver)
				err := aws.SetupSsh("vcap")
				Expect(err).NotTo(HaveOccurred())

				Expect(platform.SetupSshPublicKey).To(Equal(expectedKey))
				Expect(platform.SetupSshUsername).To(Equal("vcap"))
			})
		})

		Describe("GetSettings", func() {
			var (
				settingsJSON     string
				expectedSettings boshsettings.Settings
			)

			BeforeEach(func() {
				settingsJSON = `{
					"agent_id": "my-agent-id",
					"blobstore": {
						"options": {
							"bucket_name": "george",
							"encryption_key": "optional encryption key",
							"access_key_id": "optional access key id",
							"secret_access_key": "optional secret access key"
						},
						"provider": "s3"
					},
					"disks": {
						"ephemeral": "/dev/sdb",
						"persistent": {
							"vol-xxxxxx": "/dev/sdf"
						},
						"system": "/dev/sda1"
					},
					"env": {
						"bosh": {
							"password": "******"
						}
					},
					"networks": {
						"netA": {
							"default": ["dns", "gateway"],
							"ip": "ww.ww.ww.ww",
							"dns": [
								"xx.xx.xx.xx",
								"yy.yy.yy.yy"
							]
						},
						"netB": {
							"dns": [
								"zz.zz.zz.zz"
							]
						}
					},
					"mbus": "https://*****:*****@0.0.0.0:6868",
					"ntp": [
						"0.north-america.pool.ntp.org",
						"1.north-america.pool.ntp.org"
					],
					"vm": {
						"name": "vm-abc-def"
					}
				}`
				settingsJSON = strings.Replace(settingsJSON, `"`, `\"`, -1)
				settingsJSON = strings.Replace(settingsJSON, "\n", "", -1)
				settingsJSON = strings.Replace(settingsJSON, "\t", "", -1)

				settingsJSON = fmt.Sprintf(`{"settings": "%s"}`, settingsJSON)

				expectedSettings = boshsettings.Settings{
					AgentID: "my-agent-id",
					Blobstore: boshsettings.Blobstore{
						Options: map[string]string{
							"bucket_name":       "george",
							"encryption_key":    "optional encryption key",
							"access_key_id":     "optional access key id",
							"secret_access_key": "optional secret access key",
						},
						Type: "s3",
					},
					Disks: boshsettings.Disks{
						Ephemeral:  "/dev/sdb",
						Persistent: map[string]string{"vol-xxxxxx": "/dev/sdf"},
						System:     "/dev/sda1",
					},
					Env: boshsettings.Env{
						Bosh: boshsettings.BoshEnv{
							Password: "******",
						},
					},
					Networks: boshsettings.Networks{
						"netA": boshsettings.Network{
							Default: []string{"dns", "gateway"},
							IP:      "ww.ww.ww.ww",
							DNS:     []string{"xx.xx.xx.xx", "yy.yy.yy.yy"},
						},
						"netB": boshsettings.Network{
							DNS: []string{"zz.zz.zz.zz"},
						},
					},
					Mbus: "https://*****:*****@0.0.0.0:6868",
					Ntp: []string{
						"0.north-america.pool.ntp.org",
						"1.north-america.pool.ntp.org",
					},
					VM: boshsettings.VM{
						Name: "vm-abc-def",
					},
				}
			})

			Context("when a dns is not provided", func() {
				It("aws get settings", func() {
					boshRegistryHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
						Expect(r.Method).To(Equal("GET"))
						Expect(r.URL.Path).To(Equal("/instances/123-456-789/settings"))
						w.Write([]byte(settingsJSON))
					})

					registryTs := httptest.NewServer(boshRegistryHandler)
					defer registryTs.Close()

					expectedUserData := fmt.Sprintf(`{"registry":{"endpoint":"%s"}}`, registryTs.URL)

					instanceID := "123-456-789"

					awsMetaDataHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
						Expect(r.Method).To(Equal("GET"))

						switch r.URL.Path {
						case "/latest/user-data":
							w.Write([]byte(expectedUserData))
						case "/latest/meta-data/instance-id":
							w.Write([]byte(instanceID))
						}
					})

					metadataTs := httptest.NewServer(awsMetaDataHandler)
					defer metadataTs.Close()

					platform := fakeplatform.NewFakePlatform()

					aws := NewAwsInfrastructure(metadataTs.URL, &FakeDNSResolver{}, platform, fakeDevicePathResolver)

					settings, err := aws.GetSettings()
					Expect(err).NotTo(HaveOccurred())
					Expect(settings).To(Equal(expectedSettings))
				})
			})

			Context("when dns servers are provided", func() {
				It("aws get settings", func() {
					fakeDNSResolver := &FakeDNSResolver{
						LookupHostIP: "127.0.0.1",
					}

					registryHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
						Expect(r.Method).To(Equal("GET"))
						Expect(r.URL.Path).To(Equal("/instances/123-456-789/settings"))
						w.Write([]byte(settingsJSON))
					})

					registryTs := httptest.NewServer(registryHandler)

					registryURL, err := url.Parse(registryTs.URL)
					Expect(err).NotTo(HaveOccurred())
					registryTsPort := strings.Split(registryURL.Host, ":")[1]
					defer registryTs.Close()

					expectedUserData := fmt.Sprintf(`
						{
							"registry":{
								"endpoint":"http://the.registry.name:%s"
							},
							"dns":{
								"nameserver": ["8.8.8.8", "9.9.9.9"]
							}
						}`, registryTsPort)

					instanceID := "123-456-789"

					awsMetaDataHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
						Expect(r.Method).To(Equal("GET"))

						switch r.URL.Path {
						case "/latest/user-data":
							w.Write([]byte(expectedUserData))
						case "/latest/meta-data/instance-id":
							w.Write([]byte(instanceID))
						}
					})

					metadataTs := httptest.NewServer(awsMetaDataHandler)
					defer metadataTs.Close()

					platform := fakeplatform.NewFakePlatform()

					aws := NewAwsInfrastructure(metadataTs.URL, fakeDNSResolver, platform, fakeDevicePathResolver)

					settings, err := aws.GetSettings()
					Expect(err).NotTo(HaveOccurred())
					Expect(settings).To(Equal(expectedSettings))
					Expect(fakeDNSResolver.LookupHostHost).To(Equal("the.registry.name"))
					Expect(fakeDNSResolver.LookupHostDNSServers).To(Equal([]string{"8.8.8.8", "9.9.9.9"}))
				})
			})
		})

		Describe("SetupNetworking", func() {
			It("sets up DHCP on the platform", func() {
				fakeDNSResolver := &FakeDNSResolver{}
				platform := fakeplatform.NewFakePlatform()
				aws := NewAwsInfrastructure("", fakeDNSResolver, platform, fakeDevicePathResolver)
				networks := boshsettings.Networks{"bosh": boshsettings.Network{}}

				aws.SetupNetworking(networks)

				Expect(platform.SetupDhcpNetworks).To(Equal(networks))
			})
		})

		Describe("GetEphemeralDiskPath", func() {
			It("returns the real disk path given an AWS EBS hint", func() {
				fakeDNSResolver := &FakeDNSResolver{}
				platform := fakeplatform.NewFakePlatform()
				aws := NewAwsInfrastructure("", fakeDNSResolver, platform, fakeDevicePathResolver)

				platform.NormalizeDiskPathRealPath = "/dev/xvdb"
				platform.NormalizeDiskPathFound = true

				realPath, found := aws.GetEphemeralDiskPath("/dev/sdb")

				Expect(found).To(Equal(true))
				Expect(realPath).To(Equal("/dev/xvdb"))
				Expect(platform.NormalizeDiskPathPath).To(Equal("/dev/sdb"))
			})
		})

		Describe("MountPersistentDisk", func() {
			It("mounts the persistent disk", func() {
				fakePlatform := fakeplatform.NewFakePlatform()

				fakeFormatter := fakePlatform.FakeDiskManager.FakeFormatter
				fakePartitioner := fakePlatform.FakeDiskManager.FakePartitioner
				fakeMounter := fakePlatform.FakeDiskManager.FakeMounter

				fakePlatform.GetFs().WriteFile("/dev/vdf", []byte{})

				fakeDNSResolver := &FakeDNSResolver{}
				aws := NewAwsInfrastructure("", fakeDNSResolver, fakePlatform, fakeDevicePathResolver)

				fakeDevicePathResolver.RealDevicePath = "/dev/vdf"
				err := aws.MountPersistentDisk("/dev/sdf", "/mnt/point")
				Expect(err).NotTo(HaveOccurred())

				mountPoint := fakePlatform.Fs.GetFileTestStat("/mnt/point")
				Expect(mountPoint.FileType).To(Equal(fakesys.FakeFileTypeDir))
				Expect(mountPoint.FileMode).To(Equal(os.FileMode(0700)))

				partition := fakePartitioner.PartitionPartitions[0]
				Expect(fakePartitioner.PartitionDevicePath).To(Equal("/dev/vdf"))
				Expect(len(fakePartitioner.PartitionPartitions)).To(Equal(1))
				Expect(partition.Type).To(Equal(boshdisk.PartitionTypeLinux))

				Expect(len(fakeFormatter.FormatPartitionPaths)).To(Equal(1))
				Expect(fakeFormatter.FormatPartitionPaths[0]).To(Equal("/dev/vdf1"))

				Expect(len(fakeFormatter.FormatFsTypes)).To(Equal(1))
				Expect(fakeFormatter.FormatFsTypes[0]).To(Equal(boshdisk.FileSystemExt4))

				Expect(len(fakeMounter.MountMountPoints)).To(Equal(1))
				Expect(fakeMounter.MountMountPoints[0]).To(Equal("/mnt/point"))
				Expect(len(fakeMounter.MountPartitionPaths)).To(Equal(1))
				Expect(fakeMounter.MountPartitionPaths[0]).To(Equal("/dev/vdf1"))
			})
		})
	})
}
Exemplo n.º 15
0
func init() {
	Describe("vSphere Infrastructure", func() {
		var (
			logger                 boshlog.Logger
			vsphere                Infrastructure
			platform               *fakeplatform.FakePlatform
			fakeDevicePathResolver *fakedpresolv.FakeDevicePathResolver
		)

		BeforeEach(func() {
			platform = fakeplatform.NewFakePlatform()
			fakeDevicePathResolver = fakedpresolv.NewFakeDevicePathResolver(1*time.Millisecond, platform.GetFs())
			logger = boshlog.NewLogger(boshlog.LevelNone)
		})

		JustBeforeEach(func() {
			vsphere = NewVsphereInfrastructure(platform, fakeDevicePathResolver, logger)
		})

		Describe("GetSettings", func() {
			It("vsphere get settings", func() {
				platform.GetFileContentsFromCDROMContents = []byte(`{"agent_id": "123"}`)

				settings, err := vsphere.GetSettings()
				Expect(err).NotTo(HaveOccurred())

				Expect(platform.GetFileContentsFromCDROMPath).To(Equal("env"))
				Expect(settings.AgentID).To(Equal("123"))
			})
		})

		Describe("SetupNetworking", func() {
			It("vsphere setup networking", func() {
				networks := boshsettings.Networks{"bosh": boshsettings.Network{}}

				vsphere.SetupNetworking(networks)

				Expect(platform.SetupManualNetworkingNetworks).To(Equal(networks))
			})
		})

		Describe("GetEphemeralDiskPath", func() {
			It("vsphere get ephemeral disk path", func() {
				realPath, found := vsphere.GetEphemeralDiskPath("does not matter")
				Expect(found).To(Equal(true))

				Expect(realPath).To(Equal("/dev/sdb"))
			})
		})

		Describe("MountPersistentDisk", func() {
			BeforeEach(func() {
				fakeDevicePathResolver.RealDevicePath = "fake-real-device-path"
			})

			It("creates the mount directory with the correct permissions", func() {
				vsphere.MountPersistentDisk("fake-volume-id", "/mnt/point")

				mountPoint := platform.Fs.GetFileTestStat("/mnt/point")
				Expect(mountPoint.FileType).To(Equal(fakesys.FakeFileTypeDir))
				Expect(mountPoint.FileMode).To(Equal(os.FileMode(0700)))
			})

			It("partitions the disk", func() {
				vsphere.MountPersistentDisk("fake-volume-id", "/mnt/point")

				Expect(platform.FakeDiskManager.FakePartitioner.PartitionDevicePath).To(Equal("fake-real-device-path"))
				partitions := []boshdisk.Partition{
					{Type: boshdisk.PartitionTypeLinux},
				}
				Expect(platform.FakeDiskManager.FakePartitioner.PartitionPartitions).To(Equal(partitions))
			})

			It("formats the disk", func() {
				vsphere.MountPersistentDisk("fake-volume-id", "/mnt/point")

				Expect(platform.FakeDiskManager.FakeFormatter.FormatPartitionPaths).To(Equal([]string{"fake-real-device-path1"}))
				Expect(platform.FakeDiskManager.FakeFormatter.FormatFsTypes).To(Equal([]boshdisk.FileSystemType{boshdisk.FileSystemExt4}))
			})

			It("mounts the disk", func() {
				vsphere.MountPersistentDisk("fake-volume-id", "/mnt/point")

				Expect(platform.FakeDiskManager.FakeMounter.MountPartitionPaths).To(Equal([]string{"fake-real-device-path1"}))
				Expect(platform.FakeDiskManager.FakeMounter.MountMountPoints).To(Equal([]string{"/mnt/point"}))

			})
		})
	})
}
Exemplo n.º 16
0
func init() {
	Describe("concreteFactory", func() {
		var (
			settings            *fakesettings.FakeSettingsService
			platform            *fakeplatform.FakePlatform
			infrastructure      *fakeinfrastructure.FakeInfrastructure
			blobstore           *fakeblobstore.FakeBlobstore
			taskService         *faketask.FakeService
			notifier            *fakenotif.FakeNotifier
			applier             *fakeappl.FakeApplier
			compiler            *fakecomp.FakeCompiler
			jobSupervisor       *fakejobsuper.FakeJobSupervisor
			specService         *fakeas.FakeV1Service
			drainScriptProvider boshdrain.DrainScriptProvider
			factory             Factory
			logger              boshlog.Logger
		)

		BeforeEach(func() {
			settings = &fakesettings.FakeSettingsService{}
			platform = fakeplatform.NewFakePlatform()
			infrastructure = fakeinfrastructure.NewFakeInfrastructure()
			blobstore = &fakeblobstore.FakeBlobstore{}
			taskService = &faketask.FakeService{}
			notifier = fakenotif.NewFakeNotifier()
			applier = fakeappl.NewFakeApplier()
			compiler = fakecomp.NewFakeCompiler()
			jobSupervisor = fakejobsuper.NewFakeJobSupervisor()
			specService = fakeas.NewFakeV1Service()
			drainScriptProvider = boshdrain.NewConcreteDrainScriptProvider(nil, nil, platform.GetDirProvider())
			logger = boshlog.NewLogger(boshlog.LEVEL_NONE)
		})

		JustBeforeEach(func() {
			factory = NewFactory(
				settings,
				platform,
				infrastructure,
				blobstore,
				taskService,
				notifier,
				applier,
				compiler,
				jobSupervisor,
				specService,
				drainScriptProvider,
				logger,
			)
		})

		It("new factory", func() {
			actions := []string{
				"apply",
				"drain",
				"fetch_logs",
				"get_task",
				"get_state",
				"list_disk",
				"migrate_disk",
				"mount_disk",
				"ping",
				"prepare_network_change",
				"ssh",
				"start",
				"stop",
				"unmount_disk",
				"compile_package",
				"release_apply_spec",
			}

			for _, actionName := range actions {
				action, err := factory.Create(actionName)
				Expect(err).NotTo(HaveOccurred())
				Expect(action).ToNot(BeNil())
			}

			action, err := factory.Create("gobberish")
			Expect(err).To(HaveOccurred())
			Expect(action).To(BeNil())
		})

		It("apply", func() {
			action, err := factory.Create("apply")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewApply(applier, specService)).To(Equal(action))
		})

		It("drain", func() {
			action, err := factory.Create("drain")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewDrain(notifier, specService, drainScriptProvider, jobSupervisor)).To(Equal(action))
		})

		It("fetch_logs", func() {
			action, err := factory.Create("fetch_logs")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewLogs(platform.GetCompressor(), platform.GetCopier(), blobstore, platform.GetDirProvider())).To(Equal(action))
		})

		It("get_task", func() {
			action, err := factory.Create("get_task")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewGetTask(taskService)).To(Equal(action))
		})

		It("get_state", func() {
			ntpService := boshntp.NewConcreteService(platform.GetFs(), platform.GetDirProvider())
			action, err := factory.Create("get_state")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewGetState(settings, specService, jobSupervisor, platform.GetVitalsService(), ntpService)).To(Equal(action))
		})

		It("list_disk", func() {
			action, err := factory.Create("list_disk")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewListDisk(settings, platform, logger)).To(Equal(action))
		})

		It("migrate_disk", func() {
			action, err := factory.Create("migrate_disk")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewMigrateDisk(platform, platform.GetDirProvider())).To(Equal(action))
		})

		It("mount_disk", func() {
			action, err := factory.Create("mount_disk")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewMountDisk(settings, infrastructure, platform, platform.GetDirProvider())).To(Equal(action))
		})

		It("prepare_network_change", func() {
			action, err := factory.Create("prepare_network_change")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewPrepareNetworkChange(platform.GetFs(), settings)).To(Equal(action))
		})

		It("prepare_configure_networks", func() {
			action, err := factory.Create("prepare_configure_networks")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewPrepareConfigureNetworks(platform.GetFs(), settings)).To(Equal(action))
		})

		It("configure_networks", func() {
			action, err := factory.Create("configure_networks")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewConfigureNetworks()).To(Equal(action))
		})

		It("ssh", func() {
			action, err := factory.Create("ssh")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewSsh(settings, platform, platform.GetDirProvider())).To(Equal(action))
		})

		It("start", func() {
			action, err := factory.Create("start")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewStart(jobSupervisor)).To(Equal(action))
		})

		It("unmount_disk", func() {
			action, err := factory.Create("unmount_disk")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewUnmountDisk(settings, platform)).To(Equal(action))
		})

		It("compile_package", func() {
			action, err := factory.Create("compile_package")
			Expect(err).NotTo(HaveOccurred())
			Expect(action).ToNot(BeNil())
			Expect(NewCompilePackage(compiler)).To(Equal(action))
		})
	})
}
Exemplo n.º 17
0
import (
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "bosh/agent/action"
	fakeplatform "bosh/platform/fakes"
	boshdirs "bosh/settings/directories"
	fakesettings "bosh/settings/fakes"
)

var _ = Describe("MountDiskAction", func() {
	var (
		settingsService *fakesettings.FakeSettingsService
		platform        *fakeplatform.FakePlatform
		action          MountDiskAction
	)

	BeforeEach(func() {
		settingsService = &fakesettings.FakeSettingsService{}
		platform = fakeplatform.NewFakePlatform()
		dirProvider := boshdirs.NewDirectoriesProvider("/fake-base-dir")
		action = NewMountDisk(settingsService, platform, platform, dirProvider)
	})

	It("is asynchronous", func() {
		Expect(action.IsAsynchronous()).To(BeTrue())
	})

	It("is not persistent", func() {
func init() {
	Describe("awsInfrastructure", func() {
		var (
			metadataService    *fakeinf.FakeMetadataService
			registry           *fakeinf.FakeRegistry
			platform           *fakeplatform.FakePlatform
			devicePathResolver *fakedpresolv.FakeDevicePathResolver
			aws                Infrastructure
		)

		BeforeEach(func() {
			metadataService = &fakeinf.FakeMetadataService{}
			registry = &fakeinf.FakeRegistry{}
			platform = fakeplatform.NewFakePlatform()
			devicePathResolver = fakedpresolv.NewFakeDevicePathResolver()
			logger := boshlog.NewLogger(boshlog.LevelNone)
			aws = NewAwsInfrastructure(metadataService, registry, platform, devicePathResolver, logger)
		})

		Describe("SetupSSH", func() {
			It("gets the public key and sets up ssh via the platform", func() {
				metadataService.PublicKey = "fake-public-key"

				err := aws.SetupSSH("vcap")
				Expect(err).NotTo(HaveOccurred())

				Expect(platform.SetupSSHPublicKey).To(Equal("fake-public-key"))
				Expect(platform.SetupSSHUsername).To(Equal("vcap"))
			})

			It("returns error without configuring ssh on the platform if getting public key fails", func() {
				metadataService.GetPublicKeyErr = errors.New("fake-get-public-key-err")

				err := aws.SetupSSH("vcap")
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-get-public-key-err"))

				Expect(platform.SetupSSHCalled).To(BeFalse())
			})

			It("returns error if configuring ssh on the platform fails", func() {
				platform.SetupSSHErr = errors.New("fake-setup-ssh-err")

				err := aws.SetupSSH("vcap")
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-setup-ssh-err"))
			})
		})

		Describe("GetSettings", func() {
			It("gets settings", func() {
				settings := boshsettings.Settings{AgentID: "fake-agent-id"}
				registry.Settings = settings

				settings, err := aws.GetSettings()
				Expect(err).ToNot(HaveOccurred())

				Expect(settings).To(Equal(settings))
			})

			It("returns an error when registry fails to get settings", func() {
				registry.GetSettingsErr = errors.New("fake-get-settings-err")

				settings, err := aws.GetSettings()
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-get-settings-err"))

				Expect(settings).To(Equal(boshsettings.Settings{}))
			})
		})

		Describe("SetupNetworking", func() {
			It("sets up DHCP on the platform", func() {
				networks := boshsettings.Networks{"bosh": boshsettings.Network{}}

				err := aws.SetupNetworking(networks)
				Expect(err).ToNot(HaveOccurred())

				Expect(platform.SetupDhcpNetworks).To(Equal(networks))
			})

			It("returns error if configuring DHCP fails", func() {
				platform.SetupDhcpErr = errors.New("fake-setup-dhcp-err")

				err := aws.SetupNetworking(boshsettings.Networks{})
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("fake-setup-dhcp-err"))
			})
		})

		Describe("GetEphemeralDiskPath", func() {
			It("returns the real disk path given an AWS EBS hint", func() {
				platform.NormalizeDiskPathRealPath = "/dev/xvdb"
				platform.NormalizeDiskPathFound = true

				realPath, found := aws.GetEphemeralDiskPath("/dev/sdb")
				Expect(found).To(Equal(true))
				Expect(realPath).To(Equal("/dev/xvdb"))

				Expect(platform.NormalizeDiskPathPath).To(Equal("/dev/sdb"))
			})

			It("returns false if path cannot be normalized", func() {
				platform.NormalizeDiskPathRealPath = ""
				platform.NormalizeDiskPathFound = false

				realPath, found := aws.GetEphemeralDiskPath("/dev/sdb")
				Expect(found).To(BeFalse())
				Expect(realPath).To(Equal(""))

				Expect(platform.NormalizeDiskPathPath).To(Equal("/dev/sdb"))
			})

			It("returns false if device path is empty because ephemeral storage should not be on root partition", func() {
				realPath, found := aws.GetEphemeralDiskPath("")
				Expect(found).To(BeFalse())
				Expect(realPath).To(BeEmpty())

				Expect(platform.NormalizeDiskPathCalled).To(BeFalse())
			})
		})
	})
}
Exemplo n.º 19
0
import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "bosh/blobstore"
	boshlog "bosh/logger"
	fakeplatform "bosh/platform/fakes"
	boshsettings "bosh/settings"
	boshdir "bosh/settings/directories"
	boshuuid "bosh/uuid"
)

var _ = Describe("Provider", func() {
	var (
		platform *fakeplatform.FakePlatform
		logger   boshlog.Logger
		provider Provider
	)

	BeforeEach(func() {
		platform = fakeplatform.NewFakePlatform()
		dirProvider := boshdir.NewDirectoriesProvider("/var/vcap")
		logger = boshlog.NewLogger(boshlog.LevelNone)
		provider = NewProvider(platform, dirProvider, logger)
	})

	Describe("Get", func() {
		It("get dummy", func() {
			blobstore, err := provider.Get(boshsettings.Blobstore{
				Type: boshsettings.BlobstoreTypeDummy,
			})