app.go 1.68 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Package app holds application-global state to make it accessible
// by other packages in the application.
//
// This package differs from config in that the things in app aren't
// really related to server configuration.
package app

import (
	"errors"
	"runtime"
	"strconv"
	"strings"
	"sync"

	"github.com/mholt/caddy/server"
)

const (
Zac Bergquist's avatar
Zac Bergquist committed
19
	// Name is the program name
20 21
	Name = "Caddy"

Zac Bergquist's avatar
Zac Bergquist committed
22
	// Version is the program version
Matthew Holt's avatar
Matthew Holt committed
23
	Version = "0.7.6"
24 25 26 27 28 29
)

var (
	// Servers is a list of all the currently-listening servers
	Servers []*server.Server

Zac Bergquist's avatar
Zac Bergquist committed
30
	// ServersMutex protects the Servers slice during changes
31 32
	ServersMutex sync.Mutex

Zac Bergquist's avatar
Zac Bergquist committed
33
	// Wg is used to wait for all servers to shut down
34 35
	Wg sync.WaitGroup

36 37
	// HTTP2 indicates whether HTTP2 is enabled or not
	HTTP2 bool // TODO: temporary flag until http2 is standard
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

	// Quiet mode hides non-error initialization output
	Quiet bool
)

// SetCPU parses string cpu and sets GOMAXPROCS
// according to its value. It accepts either
// a number (e.g. 3) or a percent (e.g. 50%).
func SetCPU(cpu string) error {
	var numCPU int

	availCPU := runtime.NumCPU()

	if strings.HasSuffix(cpu, "%") {
		// Percent
		var percent float32
		pctStr := cpu[:len(cpu)-1]
		pctInt, err := strconv.Atoi(pctStr)
		if err != nil || pctInt < 1 || pctInt > 100 {
57
			return errors.New("invalid CPU value: percentage must be between 1-100")
58 59 60 61 62 63 64
		}
		percent = float32(pctInt) / 100
		numCPU = int(float32(availCPU) * percent)
	} else {
		// Number
		num, err := strconv.Atoi(cpu)
		if err != nil || num < 1 {
65
			return errors.New("invalid CPU value: provide a number or percent greater than 0")
66 67 68 69 70 71 72 73 74 75 76
		}
		numCPU = num
	}

	if numCPU > availCPU {
		numCPU = availCPU
	}

	runtime.GOMAXPROCS(numCPU)
	return nil
}