作者:lucmichalsk
项目:rexra
func loadAsset(path, defaultValue string) string {
devPath := fmt.Sprintf(
"%s/src/github.com/emccode/rexray/daemon/module/admin/html/%s",
os.Getenv("GOPATH"),
path)
if gotil.FileExists(devPath) {
v, _ := ioutil.ReadFile(devPath)
log.Printf("Loaded %s from %s\n", path, devPath)
return string(v)
}
exeDir, _, _ := gotil.GetThisPathParts()
relPath := fmt.Sprintf(
"%s/html/%s",
exeDir,
path)
if gotil.FileExists(relPath) {
v, _ := ioutil.ReadFile(devPath)
log.Printf("Loaded %s from %s\n", path, relPath)
return string(v)
}
return defaultValue
}
作者:codenrhode
项目:rexra
func (c *CLI) initUsageTemplates() {
var ut string
utPath := fmt.Sprintf("%s/.rexray/usage.template", gotil.HomeDir())
log.WithField("path", utPath).Debug("usage template path")
if gotil.FileExists(utPath) {
dat, err := ioutil.ReadFile(utPath)
if err != nil {
panic(err)
}
log.WithField("source", utPath).Debug("loaded usage template")
ut = string(dat)
} else {
log.WithField("source", "UsageTemplate").Debug("loaded usage template")
ut = usageTemplate
}
c.c.SetUsageTemplate(ut)
c.c.SetHelpTemplate(ut)
cobra.AddTemplateFuncs(template.FuncMap{
"af": c.additionalFlags,
"afs": c.additionalFlagSets,
"hf": hasFlags,
"lf": c.localFlags,
"gf": c.globalFlags,
"df": c.driverFlags,
"ihf": isHelpFlag,
"ivf": isVerboseFlag,
"saf": c.sansAdditionalFlags,
"cmds": commands,
"rtrim": rtrim,
})
}
作者:akut
项目:rexra
// ValidateConfig validates a provided configuration file.
func ValidateConfig(path string) {
if !gotil.FileExists(path) {
return
}
buf, err := ioutil.ReadFile(path)
if err != nil {
fmt.Fprintf(
os.Stderr, "rexray: error reading config: %s\n%v\n", path, err)
os.Exit(1)
}
s := string(buf)
if _, err := gofigCore.ValidateYAMLString(s); err != nil {
fmt.Fprintf(
os.Stderr,
"rexray: invalid config: %s\n\n %v\n\n", path, err)
fmt.Fprint(
os.Stderr,
"paste the contents between ---BEGIN--- and ---END---\n")
fmt.Fprint(
os.Stderr,
"into http://www.yamllint.com/ to discover the issue\n\n")
fmt.Fprintln(os.Stderr, "---BEGIN---")
fmt.Fprintln(os.Stderr, s)
fmt.Fprintln(os.Stderr, "---END---")
os.Exit(1)
}
}
作者:lucmichalsk
项目:rexra
func (c *CLI) status() {
if !gotil.FileExists(util.PidFilePath()) {
fmt.Println("REX-Ray is stopped")
return
}
pid, _ := util.ReadPidFile()
fmt.Printf("REX-Ray is running at pid %d\n", pid)
}
作者:emccod
项目:libstorag
func (d *driver) getVolumeByID(volumeID string) (*types.Volume, error) {
volJSONPath := d.getVolPath(volumeID)
if !gotil.FileExists(volJSONPath) {
return nil, utils.NewNotFoundError(volumeID)
}
return readVolume(volJSONPath)
}
作者:emccod
项目:libstorag
func (d *driver) getSnapshotByID(snapshotID string) (*types.Snapshot, error) {
snapJSONPath := d.getSnapPath(snapshotID)
if !gotil.FileExists(snapJSONPath) {
return nil, utils.NewNotFoundError(snapshotID)
}
return readSnapshot(snapJSONPath)
}
作者:lucmichalsk
项目:rexra
func (c *CLI) restart() {
checkOpPerms("restarted")
if gotil.FileExists(util.PidFilePath()) {
stop()
}
c.start()
}
作者:luk
项目:rexra
func (c *CLI) preRun(cmd *cobra.Command, args []string) {
if c.cfgFile != "" && gotil.FileExists(c.cfgFile) {
if err := c.r.Config.ReadConfigFile(c.cfgFile); err != nil {
panic(err)
}
cmd.Flags().Parse(os.Args[1:])
}
c.updateLogLevel()
c.r.Config = c.r.Config.Scope("rexray.modules.default-docker")
if isHelpFlag(cmd) {
cmd.Help()
panic(&helpFlagPanic{})
}
if permErr := c.checkCmdPermRequirements(cmd); permErr != nil {
if term.IsTerminal() {
printColorizedError(permErr)
} else {
printNonColorizedError(permErr)
}
fmt.Println()
cmd.Help()
panic(&printedErrorPanic{})
}
if c.isInitDriverManagersCmd(cmd) {
if err := c.r.InitDrivers(); err != nil {
if term.IsTerminal() {
printColorizedError(err)
} else {
printNonColorizedError(err)
}
fmt.Println()
helpCmd := cmd
if cmd == c.volumeCmd {
helpCmd = c.volumeGetCmd
} else if cmd == c.snapshotCmd {
helpCmd = c.snapshotGetCmd
} else if cmd == c.deviceCmd {
helpCmd = c.deviceGetCmd
} else if cmd == c.adapterCmd {
helpCmd = c.adapterGetTypesCmd
}
helpCmd.Help()
panic(&printedErrorPanic{})
}
}
}
作者:emccod
项目:libstorag
// LocalDevices returns a map of the system's local devices.
func (d *driver) LocalDevices(
ctx types.Context,
opts *types.LocalDevicesOpts) (*types.LocalDevices, error) {
ctx.WithFields(log.Fields{
"vfs.root": d.rootDir,
"dev.path": d.devFilePath,
}).Debug("config info")
var devFileRWL *sync.RWMutex
func() {
devFileLocksRWL.RLock()
defer devFileLocksRWL.RUnlock()
devFileRWL = devFileLocks[d.devFilePath]
}()
devFileRWL.Lock()
defer devFileRWL.Unlock()
if !gotil.FileExists(d.devFilePath) {
return nil, goof.New("device file missing")
}
f, err := os.Open(d.devFilePath)
if err != nil {
return nil, err
}
defer f.Close()
localDevs := map[string]string{}
scn := bufio.NewScanner(f)
for {
if !scn.Scan() {
break
}
m := devRX.FindSubmatch(scn.Bytes())
if len(m) == 0 {
continue
}
dev := m[1]
var mountPoint []byte
if len(m) > 2 {
mountPoint = m[2]
}
localDevs[string(dev)] = string(mountPoint)
}
return &types.LocalDevices{Driver: vfs.Name, DeviceMap: localDevs}, nil
}
作者:emccod
项目:libstorag
func (d *driver) VolumeRemove(
ctx types.Context,
volumeID string,
opts types.Store) error {
context.MustSession(ctx)
volJSONPath := d.getVolPath(volumeID)
if !gotil.FileExists(volJSONPath) {
return utils.NewNotFoundError(volumeID)
}
os.Remove(volJSONPath)
return nil
}
作者:emccod
项目:libstorag
func (d *driver) SnapshotRemove(
ctx types.Context,
snapshotID string,
opts types.Store) error {
context.MustSession(ctx)
snapJSONPath := d.getSnapPath(snapshotID)
if !gotil.FileExists(snapJSONPath) {
return utils.NewNotFoundError(snapshotID)
}
os.Remove(snapJSONPath)
return nil
}
作者:akut
项目:gofi
func newConfigWithOptions(
loadGlobalConfig, loadUserConfig bool,
configName, configType string) *config {
c := newConfigObj()
log.Debug("initializing configuration")
c.v.SetTypeByDefaultValue(false)
c.v.SetConfigName(configName)
c.v.SetConfigType(configType)
c.processRegistrations()
cfgFile := fmt.Sprintf("%s.%s", configName, configType)
etcConfigFile := fmt.Sprintf("%s/%s", etcDirPath, cfgFile)
usrConfigFile := fmt.Sprintf("%s/%s", usrDirPath, cfgFile)
if loadGlobalConfig && gotil.FileExists(etcConfigFile) {
log.WithField("path", etcConfigFile).Debug("loading global config file")
if err := c.ReadConfigFile(etcConfigFile); err != nil {
log.WithField("path", etcConfigFile).WithError(err).Debug(
"error reading global config file")
}
}
if loadUserConfig && gotil.FileExists(usrConfigFile) {
log.WithField("path", usrConfigFile).Debug("loading user config file")
if err := c.ReadConfigFile(usrConfigFile); err != nil {
log.WithField("path", usrConfigFile).WithError(err).Debug(
"error reading user config file")
}
}
return c
}
作者:emccod
项目:libstorag
func checkPerms(k fileKey, mustPerm bool) bool {
if k > maxDirKey {
return true
}
p := k.get()
fields := log.Fields{
"path": p,
"perms": k.perms(),
"mustPerm": mustPerm,
}
if gotil.FileExists(p) {
if log.GetLevel() == log.DebugLevel {
log.WithField("path", p).Debug("file exists")
}
} else {
if Debug {
log.WithFields(fields).Info("making libStorage directory")
}
noPermMkdirErr := fmt.Sprintf("mkdir %s: permission denied", p)
if err := os.MkdirAll(p, k.perms()); err != nil {
if err.Error() == noPermMkdirErr {
if mustPerm {
log.WithFields(fields).Panic(noPermMkdirErr)
}
return false
}
}
}
touchFilePath := path.Join(p, fmt.Sprintf(".touch-%v", time.Now().Unix()))
defer os.RemoveAll(touchFilePath)
noPermTouchErr := fmt.Sprintf("open %s: permission denied", touchFilePath)
if _, err := os.Create(touchFilePath); err != nil {
if err.Error() == noPermTouchErr {
if mustPerm {
log.WithFields(fields).Panic(noPermTouchErr)
}
return false
}
}
return true
}
作者:emccod
项目:libstorag
func (d *driver) Init(ctx types.Context, config gofig.Config) error {
d.config = config
d.rootDir = vfs.RootDir(config)
d.devFilePath = vfs.DeviceFilePath(config)
if !gotil.FileExists(d.devFilePath) {
err := ioutil.WriteFile(d.devFilePath, initialDeviceFile, 0644)
if err != nil {
return err
}
}
devFileLocksRWL.Lock()
defer devFileLocksRWL.Unlock()
devFileLocks[d.devFilePath] = &sync.RWMutex{}
return nil
}
作者:lucmichalsk
项目:rexra
func stop() {
checkOpPerms("stopped")
if !gotil.FileExists(util.PidFilePath()) {
fmt.Println("REX-Ray is already stopped")
panic(1)
}
fmt.Print("Shutting down REX-Ray...")
pid, pidErr := util.ReadPidFile()
failOnError(pidErr)
proc, procErr := os.FindProcess(pid)
failOnError(procErr)
killErr := proc.Signal(syscall.SIGHUP)
failOnError(killErr)
fmt.Println("SUCCESS!")
}
作者:emccod
项目:libstorag
// NextDevice returns the next available device.
func (d *driver) NextDevice(
ctx types.Context,
opts types.Store) (string, error) {
var devFileRWL *sync.RWMutex
func() {
devFileLocksRWL.RLock()
defer devFileLocksRWL.RUnlock()
devFileRWL = devFileLocks[d.devFilePath]
}()
devFileRWL.Lock()
defer devFileRWL.Unlock()
if !gotil.FileExists(d.devFilePath) {
return "", goof.New("device file missing")
}
f, err := os.Open(d.devFilePath)
if err != nil {
return "", err
}
defer f.Close()
scn := bufio.NewScanner(f)
for {
if !scn.Scan() {
break
}
m := avaiDevRX.FindSubmatch(scn.Bytes())
if len(m) == 0 {
continue
}
return string(m[1]), nil
}
return "", goof.New("no available devices")
}
作者:lucmichalsk
项目:rexra
func (c *CLI) start() {
checkOpPerms("started")
log.WithField("os.Args", os.Args).Debug("invoking service start")
pidFile := util.PidFilePath()
if gotil.FileExists(pidFile) {
pid, pidErr := util.ReadPidFile()
if pidErr != nil {
fmt.Printf("Error reading REX-Ray PID file at %s\n", pidFile)
} else {
fmt.Printf("REX-Ray already running at PID %d\n", pid)
}
panic(1)
}
if c.fg || c.client != "" {
c.startDaemon()
} else {
c.tryToStartDaemon()
}
}
作者:neuji
项目:rexra
func (c *CLI) start() {
checkOpPerms("started")
log.WithField("os.Args", os.Args).Debug("invoking service start")
pidFile := util.PidFilePath()
if gotil.FileExists(pidFile) {
pid, pidErr := util.ReadPidFile()
if pidErr != nil {
fmt.Printf("Error reading REX-Ray PID file at %s\n", pidFile)
panic(1)
}
rrproc, err := findProcess(pid)
if err != nil {
fmt.Printf("Error finding process for PID %d", pid)
panic(1)
}
if rrproc != nil {
fmt.Printf("REX-Ray already running at PID %d\n", pid)
panic(1)
}
if err := os.RemoveAll(pidFile); err != nil {
fmt.Println("Error removing REX-Ray PID file")
panic(1)
}
}
if c.fg || c.client != "" {
c.startDaemon()
} else {
c.tryToStartDaemon()
}
}
作者:emccod
项目:libstorag
// ParseTLSConfig returns a new TLS configuration.
func ParseTLSConfig(
config gofig.Config,
fields log.Fields,
roots ...string) (*tls.Config, error) {
f := func(k string, v interface{}) {
if fields == nil {
return
}
fields[k] = v
}
if !isSet(config, types.ConfigTLS, roots...) {
return nil, nil
}
if isSet(config, types.ConfigTLSDisabled, roots...) {
tlsDisabled := getBool(config, types.ConfigTLSDisabled, roots...)
if tlsDisabled {
f(types.ConfigTLSDisabled, true)
return nil, nil
}
}
if !isSet(config, types.ConfigTLSKeyFile, roots...) {
return nil, goof.New("keyFile required")
}
keyFile := getString(config, types.ConfigTLSKeyFile, roots...)
if !gotil.FileExists(keyFile) {
return nil, goof.WithField("path", keyFile, "invalid key file")
}
f(types.ConfigTLSKeyFile, keyFile)
if !isSet(config, types.ConfigTLSCertFile, roots...) {
return nil, goof.New("certFile required")
}
certFile := getString(config, types.ConfigTLSCertFile, roots...)
if !gotil.FileExists(certFile) {
return nil, goof.WithField("path", certFile, "invalid cert file")
}
f(types.ConfigTLSCertFile, certFile)
cer, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{Certificates: []tls.Certificate{cer}}
if isSet(config, types.ConfigTLSServerName, roots...) {
serverName := getString(config, types.ConfigTLSServerName, roots...)
tlsConfig.ServerName = serverName
f(types.ConfigTLSServerName, serverName)
}
if isSet(config, types.ConfigTLSClientCertRequired, roots...) {
clientCertRequired := getBool(
config, types.ConfigTLSClientCertRequired, roots...)
if clientCertRequired {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
f(types.ConfigTLSClientCertRequired, clientCertRequired)
}
if isSet(config, types.ConfigTLSTrustedCertsFile, roots...) {
trustedCertsFile := getString(
config, types.ConfigTLSTrustedCertsFile, roots...)
if !gotil.FileExists(trustedCertsFile) {
return nil, goof.WithField(
"path", trustedCertsFile, "invalid trust file")
}
f(types.ConfigTLSTrustedCertsFile, trustedCertsFile)
buf, err := func() ([]byte, error) {
f, err := os.Open(trustedCertsFile)
if err != nil {
return nil, err
}
defer f.Close()
buf, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return buf, nil
}()
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(buf)
tlsConfig.RootCAs = certPool
tlsConfig.ClientCAs = certPool
}
return tlsConfig, nil
}
作者:akut
项目:rexra
func (c *CLI) preRun(cmd *cobra.Command, args []string) {
if c.cfgFile != "" && gotil.FileExists(c.cfgFile) {
util.ValidateConfig(c.cfgFile)
if err := c.config.ReadConfigFile(c.cfgFile); err != nil {
panic(err)
}
os.Setenv("REXRAY_CONFIG_FILE", c.cfgFile)
cmd.Flags().Parse(os.Args[1:])
}
c.updateLogLevel()
// disable path caching for the CLI
c.config.Set(apitypes.ConfigIgVolOpsPathCacheEnabled, false)
if v := c.rrHost(); v != "" {
c.config.Set(apitypes.ConfigHost, v)
}
if v := c.rrService(); v != "" {
c.config.Set(apitypes.ConfigService, v)
}
if isHelpFlag(cmd) {
cmd.Help()
panic(&helpFlagPanic{})
}
if permErr := c.checkCmdPermRequirements(cmd); permErr != nil {
if term.IsTerminal() {
printColorizedError(permErr)
} else {
printNonColorizedError(permErr)
}
fmt.Println()
cmd.Help()
panic(&printedErrorPanic{})
}
c.ctx.WithField("val", os.Args).Debug("os.args")
if c.activateLibStorage {
if c.runAsync {
c.ctx = c.ctx.WithValue("async", true)
}
c.ctx.WithField("cmd", cmd.Name()).Debug("activating libStorage")
var err error
c.ctx, c.config, c.rsErrs, err = util.ActivateLibStorage(
c.ctx, c.config)
if err == nil {
c.ctx.WithField("cmd", cmd.Name()).Debug(
"creating libStorage client")
c.r, err = util.NewClient(c.ctx, c.config)
}
if err != nil {
if term.IsTerminal() {
printColorizedError(err)
} else {
printNonColorizedError(err)
}
fmt.Println()
cmd.Help()
panic(&printedErrorPanic{})
}
}
}