func (r defaultNetworkResolver) GetDefaultNetwork() (boshsettings.Network, error) {
	network := boshsettings.Network{}

	routes, err := r.routesSearcher.SearchRoutes()
	if err != nil {
		return network, bosherr.WrapError(err, "Searching routes")
	}

	if len(routes) == 0 {
		return network, bosherr.New("No routes found")
	}

	for _, route := range routes {
		if !route.IsDefault() {
			continue
		}

		ip, err := r.ipResolver.GetPrimaryIPv4(route.InterfaceName)
		if err != nil {
			return network, bosherr.WrapError(
				err, "Getting primary IPv4 for interface '%s'", route.InterfaceName)
		}

		return boshsettings.Network{
			IP:      ip.IP.String(),
			Netmask: gonet.IP(ip.Mask).String(),
			Gateway: route.Gateway,
		}, nil

	}

	return network, bosherr.New("Failed to find default route")
}
Example #2
0
func (r ipResolver) GetPrimaryIPv4(interfaceName string) (*gonet.IPNet, error) {
	addrs, err := r.ifaceToAddrsFunc(interfaceName)
	if err != nil {
		return nil, bosherr.WrapError(err, "Looking up addresses for interface '%s'", interfaceName)
	}

	if len(addrs) == 0 {
		return nil, bosherr.New("No addresses found for interface '%s'", interfaceName)
	}

	for _, addr := range addrs {
		ip, ok := addr.(*gonet.IPNet)
		if !ok {
			continue
		}

		// ignore ipv6
		if ip.IP.To4() == nil {
			continue
		}

		return ip, nil
	}

	return nil, bosherr.New("Failed to find primary IPv4 address for interface '%s'", interfaceName)
}
Example #3
0
func (c Config) validate() error {
	if c.AssetsDir == "" {
		return bosherr.New("Must provide non-empty assets_dir")
	}

	if c.ReposDir == "" {
		return bosherr.New("Must provide non-empty repos_dir")
	}

	err := c.EventLog.Validate()
	if err != nil {
		return bosherr.WrapError(err, "Validating event_log configuration")
	}

	if c.Blobstore.Type != bpprov.BlobstoreConfigTypeLocal {
		return bosherr.New("Blobstore type must be local")
	}

	err = c.Blobstore.Validate()
	if err != nil {
		return bosherr.WrapError(err, "Validating blobstore configuration")
	}

	return nil
}
func (tc ConcreteTemplatesCompiler) buildJobReaders(job bpdep.Job) ([]jobReader, error) {
	var readers []jobReader

	for _, template := range job.Templates {
		rec, found, err := tc.tplToJobRepo.FindByTemplate(template)
		if err != nil {
			return readers, bosherr.WrapError(err, "Finding dep-template -> release-job record %s", template.Name)
		} else if !found {
			return readers, bosherr.New("Expected to find dep-template -> release-job record %s", template.Name)
		}

		jobRec, found, err := tc.jobsRepo.FindByReleaseJob(rec)
		if err != nil {
			return readers, bosherr.WrapError(err, "Finding job source blob %s", template.Name)
		} else if !found {
			return readers, bosherr.New("Expected to find job source blob %s -- %s", template.Name, rec)
		}

		jobURL := fmt.Sprintf("blobstore:///%s?fingerprint=%s", jobRec.BlobID, jobRec.SHA1)

		reader := jobReader{
			rec:       rec,
			tarReader: tc.jobReaderFactory.NewReader(jobURL),
		}

		readers = append(readers, reader)
	}

	return readers, nil
}
func (v SyntaxValidator) validateJob(job *Job) error {
	if job.Name == "" {
		return bosherr.New("Missing job name")
	}

	if job.Template != nil {
		return bosherr.New("'template' is deprecated in favor of 'templates'")
	}

	err := v.validateUpdate(&job.Update)
	if err != nil {
		return bosherr.WrapError(err, "Update")
	}

	props, err := bputil.NewStringKeyed().ConvertMap(job.PropertiesRaw)
	if err != nil {
		return bosherr.WrapError(err, "Properties")
	}

	job.Properties = props

	for i, na := range job.NetworkAssociations {
		err := v.validateNetworkAssociation(&job.NetworkAssociations[i])
		if err != nil {
			return bosherr.WrapError(err, "Network association %s (%d)", na.NetworkName, i)
		}
	}

	return nil
}
Example #6
0
func NewWatchTimeFromString(str string) (WatchTime, error) {
	var watchTime WatchTime

	parts := strings.Split(str, "-")
	if len(parts) != 2 {
		return watchTime, bosherr.New("Invalid watch time range %s", str)
	}

	min, err := strconv.Atoi(strings.Trim(parts[0], " "))
	if err != nil {
		return watchTime, bosherr.WrapError(
			err, "Non-positive number as watch time minimum %s", parts[0])
	}

	max, err := strconv.Atoi(strings.Trim(parts[1], " "))
	if err != nil {
		return watchTime, bosherr.WrapError(
			err, "Non-positive number as watch time maximum %s", parts[1])
	}

	if max < min {
		return watchTime, bosherr.New(
			"Watch time must have maximum greater than or equal minimum %s", str)
	}

	watchTime[0], watchTime[1] = min, max

	return watchTime, nil
}
func (v SyntaxValidator) Validate() error {
	if v.release.Name == "" {
		return bosherr.New("Missing release name")
	}

	if v.release.Version == "" {
		return bosherr.New("Missing release version")
	}

	if v.release.CommitHash == "" {
		return bosherr.New("Missing release commit_hash")
	}

	for i, job := range v.release.Jobs {
		err := v.validateJob(&v.release.Jobs[i])
		if err != nil {
			return bosherr.WrapError(err, "Job %s (%d)", job.Name, i)
		}
	}

	for i, pkg := range v.release.Packages {
		err := v.validatePkg(&v.release.Packages[i])
		if err != nil {
			return bosherr.WrapError(err, "Package %s (%d)", pkg.Name, i)
		}
	}

	return nil
}
func (v SemanticValidator) validateNetworkAssociation(na NetworkAssociation) error {
	if na.Network == nil {
		return bosherr.New("Missing associated network")
	}

	if na.MustHaveStaticIP && na.StaticIP == nil {
		return bosherr.New("Missing static IP assignment")
	}

	return nil
}
func (bc FileBundleCollection) Get(definition BundleDefinition) (Bundle, error) {
	if len(definition.BundleName()) == 0 {
		return nil, bosherr.New("Missing bundle name")
	}

	if len(definition.BundleVersion()) == 0 {
		return nil, bosherr.New("Missing bundle version")
	}

	installPath := filepath.Join(bc.installPath, bc.name, definition.BundleName(), definition.BundleVersion())
	enablePath := filepath.Join(bc.enablePath, bc.name, definition.BundleName())
	return NewFileBundle(installPath, enablePath, bc.fs, bc.logger), nil
}
func (v SyntaxValidator) validateNetworkType(networkType string) error {
	if networkType == "" {
		return bosherr.New("Missing network type")
	}

	for _, t := range NetworkTypes {
		if networkType == t {
			return nil
		}
	}

	return bosherr.New("Unknown network type %s", networkType)
}
func (v SyntaxValidator) validateRelease(release *Release) error {
	if release.Name == "" {
		return bosherr.New("Missing release name")
	}

	if release.Version == "" {
		return bosherr.New("Missing release version")
	}

	if release.URL == "" {
		return bosherr.New("Missing release URL")
	}

	return nil
}
Example #12
0
func (ri DBIndex) Find(key interface{}, value interface{}) error {
	rawKey, err := ri.structToMap(key)
	if err != nil {
		return err
	}

	rawKeyBytes, err := json.Marshal(rawKey)
	if err != nil {
		return err
	}

	rows, err := ri.adapter.Find(rawKeyBytes)
	if err != nil {
		return err
	}

	if rows == nil {
		return bosherr.New("Expected to find entries for key '%s'", rawKeyBytes)
	}

	if !rows.Next() {
		return bpindex.ErrNotFound
	}

	var rawEntryBytes []byte

	err = rows.Scan(&rawEntryBytes)
	if err != nil {
		return err
	}

	if rows.Next() {
		// todo should rows.Err() be called before returning
		return bosherr.New("Expected to not find more than 1 entry for key '%s'", rawKeyBytes)
	}

	err = rows.Err()
	if err != nil {
		return err
	}

	err = json.Unmarshal(rawEntryBytes, &value)
	if err != nil {
		return err
	}

	return nil
}
func (p RunitProvisioner) stopRunsv(name string, stopTimeout time.Duration) error {
	p.logger.Info(runitProvisionerLogTag, "Stopping runsv")

	// Potentially tried to deprovision before ever provisioning
	if !p.runner.CommandExists("sv") {
		return nil
	}

	downStdout, _, _, err := p.runner.RunCommand("sv", "down", name)
	if err != nil {
		p.logger.Error(runitProvisionerLogTag, "Ignoring down error %s", err)
	}

	// If runsv configuration does not exist, service was never started
	if strings.Contains(downStdout, "file does not exist") {
		return nil
	}

	var lastStatusStdout string
	var passedDuration time.Duration

	for ; passedDuration < stopTimeout; passedDuration += runitStopStepDuration {
		lastStatusStdout, _, _, _ = p.runner.RunCommand("sv", "status", name)

		if runitStatusDownRegex.MatchString(lastStatusStdout) {
			return nil
		}

		time.Sleep(runitStopStepDuration)
	}

	return bosherr.New("Failed to stop runsv for %s. Output: %s", name, lastStatusStdout)
}
func (v SemanticValidator) validateTemplate(template Template) error {
	if template.Release == nil {
		return bosherr.New("Missing associated release")
	}

	return nil
}
Example #15
0
func (a MountDiskAction) Run(diskCid string) (interface{}, error) {
	err := a.settingsService.LoadSettings()
	if err != nil {
		return nil, bosherr.WrapError(err, "Refreshing the settings")
	}

	settings := a.settingsService.GetSettings()

	devicePath, found := settings.Disks.Persistent[diskCid]
	if !found {
		return nil, bosherr.New("Persistent disk with volume id '%s' could not be found", diskCid)
	}

	mountPoint := a.dirProvider.StoreDir()

	isMountPoint, err := a.mountPoints.IsMountPoint(mountPoint)
	if err != nil {
		return nil, bosherr.WrapError(err, "Checking mount point")
	}
	if isMountPoint {
		mountPoint = a.dirProvider.StoreMigrationDir()
	}

	err = a.diskMounter.MountPersistentDisk(devicePath, mountPoint)
	if err != nil {
		return nil, bosherr.WrapError(err, "Mounting persistent disk")
	}

	return map[string]string{}, nil
}
Example #16
0
func (r WatcherRec) Validate() error {
	if len(r.RelSource) == 0 {
		return bosherr.New("Expected release source to be non-empty")
	}

	if len(r.MinVersionRaw) == 0 {
		return bosherr.New("Expected min version to be non-empty")
	}

	_, err := semiver.NewVersionFromString(r.MinVersionRaw)
	if err != nil {
		return bosherr.WrapError(err, "Expected min version to be a valid version")
	}

	return nil
}
func (v SemanticValidator) validateNetwork(network Network) error {
	if network.Type == NetworkTypeManual {
		return bosherr.New("Manual networking is not supported")
	}

	return nil
}
Example #18
0
func (ri DBIndex) Save(key interface{}, value interface{}) error {
	rawKey, err := ri.structToMap(key)
	if err != nil {
		return err
	}

	rawKeyBytes, err := json.Marshal(rawKey)
	if err != nil {
		return err
	}

	valueBytes, err := json.Marshal(value)
	if err != nil {
		return err
	}

	res, err := ri.adapter.Save(rawKeyBytes, valueBytes)
	if err != nil {
		return err
	}

	numRows, err := res.RowsAffected()
	if err != nil {
		return err
	}

	if numRows != 1 {
		return bosherr.New("Expected to update 1 entry for key '%s'; updated '%d'", rawKeyBytes, numRows)
	}

	return nil
}
Example #19
0
func (p Provider) Get(name string) (supervisor JobSupervisor, err error) {
	supervisor, found := p.supervisors[name]
	if !found {
		err = bosherr.New("JobSupervisor %s could not be found", name)
	}
	return
}
func (b retryableBlobstore) Validate() error {
	if b.maxTries < 1 {
		return bosherr.New("Max tries must be > 0")
	}

	return b.blobstore.Validate()
}
Example #21
0
func (p provider) Get(name string) (Platform, error) {
	plat, found := p.platforms[name]
	if !found {
		return nil, bosherror.New("Platform %s could not be found", name)
	}
	return plat, nil
}
func (v SemanticValidator) validateRelease(release Release) error {
	if release.Version == "latest" {
		return bosherr.New("Version 'latest' is not supported")
	}

	return nil
}
func (v SyntaxValidator) validateNetwork(network *Network) error {
	if network.Name == "" {
		return bosherr.New("Missing network name")
	}

	return v.validateNetworkType(network.Type)
}
func (b externalBlobstore) Validate() error {
	if !b.runner.CommandExists(b.executable()) {
		return bosherr.New("executable %s not found in PATH", b.executable())
	}

	return b.writeConfigFile()
}
func (c ReleaseWatchersController) WatchOrUnwatch(req *http.Request, r martrend.Render, params mart.Params) {
	action := req.FormValue("action")

	switch {
	case action == "watch":
		err := c.watchersRepo.Add(req.FormValue("relSource"), req.FormValue("minVersion"))
		if err != nil {
			r.HTML(500, c.errorTmpl, err)
			return
		}

	case action == "unwatch":
		err := c.watchersRepo.Remove(req.FormValue("relSource"))
		if err != nil {
			r.HTML(500, c.errorTmpl, err)
			return
		}

	default:
		r.HTML(500, c.errorTmpl, bosherr.New("Unknown action '%s'", action))
		return
	}

	r.Redirect("/release_watchers")
}
func (v SyntaxValidator) validateCompilation(compilation *Compilation) error {
	if compilation.NetworkName == "" {
		return bosherr.New("Missing network name")
	}

	return nil
}
Example #27
0
func (a UnmountDiskAction) Run(volumeID string) (value interface{}, err error) {
	settings := a.settingsService.GetSettings()

	devicePath, found := settings.Disks.Persistent[volumeID]
	if !found {
		err = bosherr.New("Persistent disk with volume id '%s' could not be found", volumeID)
		return
	}

	didUnmount, err := a.platform.UnmountPersistentDisk(devicePath)
	if err != nil {
		err = bosherr.WrapError(err, "Unmounting persistent disk")
		return
	}

	msg := fmt.Sprintf("Partition of %s is not mounted", devicePath)

	if didUnmount {
		msg = fmt.Sprintf("Unmounted partition of %s", devicePath)
	}

	type valueType struct {
		Message string `json:"message"`
	}

	value = valueType{Message: msg}
	return
}
Example #28
0
func (ac HTTPClient) makeQuickRequest(method reqMethod, args reqArgs) (responseEnvelope, error) {
	var responseBody responseEnvelope

	requestBody := requestEnvelope{
		Method:    method,
		Arguments: args,
		ReplyTo:   "n-a",
	}

	requestBytes, err := json.Marshal(requestBody)
	if err != nil {
		return responseBody, bosherr.WrapError(err, "Marshalling request body")
	}

	responseBytes, err := ac.makePlainRequest(string(requestBytes), "application/json")
	if err != nil {
		return responseBody, bosherr.WrapError(err, "Making plain request")
	}

	err = json.Unmarshal(responseBytes, &responseBody)
	if err != nil {
		return responseBody, bosherr.WrapError(err, "Unmarshalling response body")
	}

	if responseBody.HasException() {
		return responseBody, bosherr.New("Ended with exception %#v", responseBody.Exception)
	}

	return responseBody, nil
}
func (c JobsController) extractShowParams(req *http.Request, params mart.Params) (string, string, string, error) {
	relSource := req.URL.Query().Get("source")

	if len(relSource) == 0 {
		return "", "", "", bosherr.New("Param 'source' must be non-empty")
	}

	relVersion := req.URL.Query().Get("version")

	jobName := params["name"]

	if len(jobName) == 0 {
		return "", "", "", bosherr.New("Param 'name' must be non-empty")
	}

	return relSource, relVersion, jobName, nil
}
Example #30
0
func (a CancelTaskAction) Run(taskID string) (string, error) {
	task, found := a.taskService.FindTaskWithID(taskID)
	if !found {
		return "", bosherr.New("Task with id %s could not be found", taskID)
	}

	return "canceled", task.Cancel()
}