func (m linuxMounter) shouldMount(partitionPath, mountPoint string) (shouldMount bool, err error) { isMounted, err := m.searchMounts(func(mountedPartitionPath, mountedMountPoint string) (found bool, err error) { switch { case mountedPartitionPath == partitionPath && mountedMountPoint == mountPoint: found = true return case mountedPartitionPath == partitionPath && mountedMountPoint != mountPoint: err = bosherr.New("Device %s is already mounted to %s, can't mount to %s", mountedPartitionPath, mountedMountPoint, mountPoint) return case mountedMountPoint == mountPoint: err = bosherr.New("Device %s is already mounted to %s, can't mount %s", mountedPartitionPath, mountedMountPoint, partitionPath) return } return }) if err != nil { err = bosherr.WrapError(err, "Searching mounts") return } shouldMount = !isMounted return }
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 (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") }
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 (r concreteRunner) Run(action Action, payloadBytes []byte) (value interface{}, err error) { payloadArgs, err := r.extractJsonArguments(payloadBytes) if err != nil { err = bosherr.WrapError(err, "Extracting json arguments") return } actionValue := reflect.ValueOf(action) runMethodValue := actionValue.MethodByName("Run") if runMethodValue.Kind() != reflect.Func { err = bosherr.New("Run method not found") return } runMethodType := runMethodValue.Type() if r.invalidReturnTypes(runMethodType) { err = bosherr.New("Run method should return a value and an error") return } methodArgs, err := r.extractMethodArgs(runMethodType, payloadArgs) if err != nil { err = bosherr.WrapError(err, "Extracting method arguments from payload") return } values := runMethodValue.Call(methodArgs) return r.extractReturns(values) }
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) }
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 }
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.NewTarReader(jobURL), } readers = append(readers, reader) } return readers, nil }
func (a DrainAction) Run(drainType DrainType, newSpecs ...boshas.V1ApplySpec) (int, error) { currentSpec, err := a.specService.Get() if err != nil { return 0, bosherr.WrapError(err, "Getting current spec") } if len(currentSpec.JobSpec.Template) == 0 { if drainType == DrainTypeStatus { return 0, bosherr.New("Check Status on Drain action requires job spec") } else { return 0, nil } } err = a.jobSupervisor.Unmonitor() if err != nil { return 0, bosherr.WrapError(err, "Unmonitoring services") } drainScript := a.drainScriptProvider.NewDrainScript(currentSpec.JobSpec.Template) var params boshdrain.DrainScriptParams switch drainType { case DrainTypeUpdate: if len(newSpecs) == 0 { return 0, bosherr.New("Drain update requires new spec") } params = boshdrain.NewUpdateDrainParams(currentSpec, newSpecs[0]) case DrainTypeShutdown: err = a.notifier.NotifyShutdown() if err != nil { return 0, bosherr.WrapError(err, "Notifying shutdown") } params = boshdrain.NewShutdownDrainParams() case DrainTypeStatus: params = boshdrain.NewStatusDrainParams() } if !drainScript.Exists() { if drainType == DrainTypeStatus { return 0, bosherr.New("Check Status on Drain action requires a valid drain script") } else { return 0, nil } } value, err := drainScript.Run(params) if err != nil { return 0, bosherr.WrapError(err, "Running Drain Script") } return value, nil }
func (s *FileBundleCollection) checkBundle(bundle Bundle) error { if len(bundle.BundleName()) == 0 { return bosherr.New("missing bundle name") } if len(bundle.BundleVersion()) == 0 { return bosherr.New("missing bundle version") } return nil }
func (s *FileBundleCollection) checkBundle(bundle Bundle) (err error) { if len(bundle.BundleName()) == 0 { err = bosherr.New("missing bundle name") return } if len(bundle.BundleVersion()) == 0 { err = bosherr.New("missing bundle version") return } return }
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 (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 (blobstore local) Validate() error { path, found := blobstore.options["blobstore_path"] if !found { return bosherr.New("missing blobstore_path") } _, ok := path.(string) if !ok { return bosherr.New("blobstore_path must be a string") } 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 (p diskParams) GetDevicePath() (devicePath string, err error) { if len(p.payload.Arguments) != 1 { err = bosherr.New("Invalid payload missing volume id.") return } volumeId := p.payload.Arguments[0] disks := p.settings.GetDisks() devicePath, found := disks.Persistent[volumeId] if !found { err = bosherr.New("Invalid payload volume id does not match") } return }
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 }
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") } for _, route := range routes { if !route.IsDefault() { continue } addrs, err := r.ifaceToAddrsFunc(route.InterfaceName) if err != nil { return network, bosherr.WrapError(err, "Looking addrs for interface %s", route.InterfaceName) } if len(addrs) == 0 { return network, bosherr.New("No addresses") } for _, addr := range addrs { ip, ok := addr.(*gonet.IPNet) if !ok { continue } if ip.IP.To4() == nil { // filter out ipv6 continue } return boshsettings.Network{ IP: ip.IP.String(), Netmask: gonet.IP(ip.Mask).String(), Gateway: route.Gateway, }, nil } return network, bosherr.New("Failed to find IPv4 address") } return network, bosherr.New("Failed to find default route") }
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 (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 (v SyntaxValidator) validateNetwork(network *Network) error { if network.Name == "" { return bosherr.New("Missing network name") } return v.validateNetworkType(network.Type) }
func (a UnmountDiskAction) Run(volumeID string) (value interface{}, err error) { disksSettings := a.settings.GetDisks() devicePath, found := disksSettings.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 }
func (v SyntaxValidator) validateCompilation(compilation *Compilation) error { if compilation.NetworkName == "" { return bosherr.New("Missing network name") } return nil }
func (p RunitProvisioner) stopRunsv(name string, stopTimeout time.Duration) error { p.logger.Info(runitProvisionerLogTag, "Stopping runsv") downStdout, _, _, err := p.runner.RunCommand("sv", "down", name) if err != nil { p.logger.Error(runitProvisionerLogTag, "Ignoring down error %s", err.Error()) } // 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) }
// Symlinked from {{ enablePath }}/{{ name }}/{{ bundle.BundleName }} to installed path func (s *FileBundleCollection) Enable(bundle Bundle) (err error) { err = s.checkBundle(bundle) if err != nil { return } installPath := s.buildInstallPath(bundle) if !s.fs.FileExists(installPath) { err = bosherr.New("bundle must be installed") return } enablePath := s.buildEnablePath(bundle) err = s.fs.MkdirAll(filepath.Dir(enablePath), os.FileMode(0755)) if err != nil { err = bosherr.WrapError(err, "failed to create enable dir") return } err = s.fs.Symlink(installPath, enablePath) if err != nil { err = bosherr.WrapError(err, "failed to enable") return } return }
func (p MbusHandlerProvider) Get( platform boshplatform.Platform, dirProvider boshdir.DirectoriesProvider, ) (handler boshhandler.Handler, err error) { if p.handler != nil { handler = p.handler return } mbusURL, err := url.Parse(p.settings.GetMbusURL()) if err != nil { err = bosherr.WrapError(err, "Parsing handler URL") return } switch mbusURL.Scheme { case "nats": handler = NewNatsHandler(p.settings, p.logger, yagnats.NewClient()) case "https": handler = micro.NewHTTPSHandler(mbusURL, p.logger, platform.GetFs(), dirProvider) default: err = bosherr.New("Message Bus Handler with scheme %s could not be found", mbusURL.Scheme) } p.handler = handler return }
func (m monitJobSupervisor) Reload() (err error) { oldIncarnation, err := m.getIncarnation() if err != nil { err = bosherr.WrapError(err, "Getting monit incarnation") return err } // Exit code or output cannot be trusted m.runner.RunCommand("monit", "reload") for attempt := 1; attempt < 60; attempt++ { err = nil currentIncarnation, err := m.getIncarnation() if err != nil { err = bosherr.WrapError(err, "Getting monit incarnation") return err } if oldIncarnation < currentIncarnation { return nil } time.Sleep(m.delayBetweenReloadCheckRetries) } err = bosherr.New("Failed to reload monit") return }
func (blobstore external) Validate() error { if !blobstore.runner.CommandExists(blobstore.executable()) { return bosherr.New("executable %s not found in PATH", blobstore.executable()) } return blobstore.writeConfigFile() }
func (a mountDiskAction) Run(volumeId string) (value interface{}, err error) { err = a.settings.Refresh() if err != nil { err = bosherr.WrapError(err, "Refreshing the settings") return } disksSettings := a.settings.GetDisks() devicePath, found := disksSettings.Persistent[volumeId] if !found { err = bosherr.New("Persistent disk with volume id '%s' could not be found", volumeId) return } mountPoint := a.dirProvider.StoreDir() isMountPoint, err := a.platform.IsMountPoint(mountPoint) if err != nil { err = bosherr.WrapError(err, "Checking mount point") return } if isMountPoint { mountPoint = a.dirProvider.StoreMigrationDir() } err = a.platform.MountPersistentDisk(devicePath, mountPoint) if err != nil { err = bosherr.WrapError(err, "Mounting persistent disk") return } value = make(map[string]string) return }
func (self FileBundleCollection) Get(definition BundleDefinition) (bundle Bundle, err error) { if len(definition.BundleName()) == 0 { err = bosherr.New("missing bundle name") return } if len(definition.BundleVersion()) == 0 { err = bosherr.New("missing bundle version") return } installPath := filepath.Join(self.installPath, self.name, definition.BundleName(), definition.BundleVersion()) enablePath := filepath.Join(self.enablePath, self.name, definition.BundleName()) bundle = NewFileBundle(installPath, enablePath, self.fs) return }