Exemplo n.º 1
0
// Run starts the RPC instance in the foreground.
// This means: This method is a blocking method.
func (instance *RPC) Run() {
	defer panics.DefaultPanicHandler()
	container := restful.NewContainer()

	ws := new(restful.WebService)
	ws.Produces(restful.MIME_JSON)

	ws.Route(ws.GET("/config").To(instance.config))

	ws.Route(ws.GET("/control/config").To(instance.controlConfig))

	ws.Route(ws.GET("/services").To(instance.services))

	ws.Route(ws.GET("/service/{serviceName}").To(instance.service))
	ws.Route(ws.GET("/service/{serviceName}/config").To(instance.serviceConfig))
	ws.Route(ws.GET("/service/{serviceName}/state").To(instance.serviceStatus))
	ws.Route(ws.GET("/service/{serviceName}/pid").To(instance.servicePid))

	ws.Route(ws.POST("/service/{serviceName}/start").To(instance.serviceStart))
	ws.Route(ws.POST("/service/{serviceName}/restart").To(instance.serviceRestart))
	ws.Route(ws.POST("/service/{serviceName}/status").To(instance.serviceStart))
	ws.Route(ws.POST("/service/{serviceName}/stop").To(instance.serviceStop))
	ws.Route(ws.POST("/service/{serviceName}/kill").To(instance.serviceKill))
	ws.Route(ws.POST("/service/{serviceName}/signal").To(instance.serviceSignal))

	container.Add(ws)

	server := &http.Server{
		Handler:  container,
		ErrorLog: log.New(instance.logger.NewOutputStreamWrapperFor(logger.Debug), "", 0),
	}
	instance.logger.Log(logger.Debug, "Rpc will bind to %v...", instance.conf.Listen)
	listener, err := net.Listen(instance.conf.Listen.AsScheme(), instance.conf.Listen.AsAddress())
	if err != nil {
		log.Fatal(err)
	}
	sl, err2 := NewStoppableListener(listener)
	if err2 != nil {
		panics.New("Could not create listener.").CausedBy(err2).Throw()
	}
	defer func() {
		(*instance).listener = nil
	}()
	(*instance).listener = sl
	if err := server.Serve(instance.secure(sl)); err != nil {
		if _, ok := err.(ListenerStoppedError); !ok {
			panics.New("Could not listen.").CausedBy(err2).Throw()
		}
	}
}
Exemplo n.º 2
0
// GetMasterOrFail returns the master, if a master exists.
// Otherwise it will fail with a panic.
func (instance Services) GetMasterOrFail() *Service {
	master := instance.GetMaster()
	if master == nil {
		panics.New("There is no master service defined.").Throw()
	}
	return master
}
Exemplo n.º 3
0
func newSerialNumber() *big.Int {
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		panics.New("Could not generate serial number.").CausedBy(err).Throw()
	}
	return serialNumber
}
Exemplo n.º 4
0
func (i *Logger) write(level Level, message []byte) {
	i.lock.Lock()
	defer i.unlocker()
	if !i.IsOpen() {
		panics.New("The logger is not open.").Throw()
	}
	i.writeSynchronizer.Write(message, level.IsIndicatingProblem())
}
Exemplo n.º 5
0
// ExtractValueIDType extracts the value ID types from the given type.
func ExtractValueIDType(t Type) IDType {
	if idType, ok := t.(IDType); ok {
		return idType
	} else if arrayType, ok := t.(ArrayType); ok {
		return ExtractValueIDType(arrayType.Value)
	} else if pointerType, ok := t.(PointerType); ok {
		return ExtractValueIDType(pointerType.Value)
	} else if mapType, ok := t.(MapType); ok {
		return ExtractValueIDType(mapType.Value)
	}
	panic(panics.New("Unknown type %v.", reflect.TypeOf(t)))
}
Exemplo n.º 6
0
func serviceHandleUsersFor(service *Service, cmd *exec.Cmd) {
	config := (*service).config
	userName := config.User
	if !userName.IsTrimmedEmpty() {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
		uid, gid, err := lookupUser(userName.String())
		if err != nil {
			panics.New("Could not run as user '%v'.", userName).CausedBy(err).Throw()
		}
		cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}
	}
}
Exemplo n.º 7
0
// LogAdvanced logs a problem with the given pattern and level.
func (i *Logger) LogAdvanced(framesToSkip int, problem interface{}, level Level, pattern interface{}, args ...interface{}) {
	if level >= i.config.Level {
		now := time.Now()
		message := formatMessage(pattern, args...)
		entry := i.EntryFor(framesToSkip+1, problem, level, now, message)
		toLog, err := entry.Format(i.config.Pattern, framesToSkip+1)
		if err != nil {
			panics.New("Could not format log entry with given pattern '%v'. Got: %v", i.config.Pattern, err)
		}
		i.write(level, []byte(toLog))
	}
}
Exemplo n.º 8
0
// ExtractAllIDTypesFrom extracts all referenced ID types from the given type as an array.
func ExtractAllIDTypesFrom(t Type) []IDType {
	if idType, ok := t.(IDType); ok {
		return []IDType{idType}
	} else if arrayType, ok := t.(ArrayType); ok {
		return ExtractAllIDTypesFrom(arrayType.Value)
	} else if pointerType, ok := t.(PointerType); ok {
		return ExtractAllIDTypesFrom(pointerType.Value)
	} else if mapType, ok := t.(MapType); ok {
		result := []IDType{}
		result = append(result, ExtractAllIDTypesFrom(mapType.Key)...)
		result = append(result, ExtractAllIDTypesFrom(mapType.Value)...)
		return result
	}
	panic(panics.New("Unknown type %v.", reflect.TypeOf(t)))
}
Exemplo n.º 9
0
// EnrichFromEnvironment enriches the current Config instance with configuration from the environment
// variables.
func (instance Config) EnrichFromEnvironment() Config {
	result := &instance
	for _, plainEnviron := range os.Environ() {
		environ := strings.SplitN(plainEnviron, "=", 2)
		var err error
		if len(environ) > 1 {
			err = instance.handleUnknownEnv(plainEnviron, environ[0], environ[1])
		} else {
			err = instance.handleUnknownEnv(plainEnviron, environ[0], "")
		}
		if err != nil {
			panics.New("Could not handle environment variable '%s'. Got: %s", plainEnviron, err.Error()).CausedBy(err).Throw()
		}
	}
	return *result
}
Exemplo n.º 10
0
func (instance *RPC) secure(in net.Listener) net.Listener {
	out := in
	sec := instance.caretakerd.KeyStore()
	keyPair, err := tls.X509KeyPair(sec.PEM(), sec.PEM())
	if err != nil {
		panics.New("Could not load pem of caretakerd.").CausedBy(err).Throw()
	}

	rootCas := x509.NewCertPool()
	for _, cert := range sec.CA() {
		rootCas.AddCert(cert)
	}

	out = tls.NewListener(in, &tls.Config{
		NextProtos:   []string{"http/1.1"},
		Certificates: []tls.Certificate{keyPair},
		RootCAs:      rootCas,
		ClientCAs:    rootCas,
		ClientAuth:   tls.RequireAndVerifyClientCert,
	})

	return out
}
Exemplo n.º 11
0
// ParseDefinitions parses every Definitions from the given project and returns it.
// If there is any error it will be returned and the Definitions are nil.
func ParseDefinitions(project Project) (*Definitions, error) {
	et := &extractionTask{
		defaultImporter: importer.Default(),
		info: &types.Info{
			Types: make(map[ast.Expr]types.TypeAndValue),
			Defs:  make(map[*ast.Ident]types.Object),
			Uses:  make(map[*ast.Ident]types.Object),
		},
		packageNameToParsedPackage: make(map[string]*parsedPackage),
		project:                    project,
		context: &build.Context{
			GOARCH:   runtime.GOARCH,
			GOOS:     runtime.GOOS,
			GOROOT:   GOROOT,
			GOPATH:   GOPATH,
			Compiler: runtime.Compiler,
		},
		definitions: NewDefinitions(project),
		typesConfig: types.Config{
			FakeImportC:              true,
			DisableUnusedImportCheck: true,
			IgnoreFuncBodies:         true,
		},
	}
	et.typesConfig.Importer = et

	excludedPaths := []string{
		project.SrcRootPath + system.PathSeparator + "build",
		project.SrcRootPath + system.PathSeparator + "vendor",
		project.SrcRootPath + system.PathSeparator + "manual",
		project.SrcRootPath + system.PathSeparator + "gradle",
		project.SrcRootPath + system.PathSeparator + "target",
	}
	err := filepath.Walk(project.SrcRootPath, func(path string, info os.FileInfo, err error) error {
		if info != nil && info.IsDir() {
			if strings.HasPrefix(info.Name(), ".") {
				log.Log(logger.Debug, "Skipping dotted path: %v", path)
				return filepath.SkipDir
			} else if matchesPaths(path, excludedPaths) {
				log.Log(logger.Debug, "Skipping exluded path: %v", path)
				return filepath.SkipDir
			} else if path == project.SrcRootPath {
				return et.parsePackageToDefinitions(project.RootPackage, project.SrcRootPath)
			} else if strings.HasPrefix(path, project.GoSrcPath+system.PathSeparator) {
				subPath := path[len(project.GoSrcPath)+1:]
				targetPackage := strings.Replace(subPath, system.PathSeparator, "/", -1)
				err := et.parsePackageToDefinitions(targetPackage, path)
				if _, ok := err.(*build.NoGoError); ok {
					return nil
				}
				return err
			}
			panics.New("Unexpected path: %v", path).Throw()
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	return et.definitions, nil
}