package isolation import ( "bufio" "encoding/json" "errors" "fmt" "io" "math" "net/http" "os" "path/filepath" "regexp" "strconv" "strings" "sync" "time" ) type trafficCursor struct { Month string `json:"month"` FileID uint64 `json:"fileId"` Offset int64 `json:"offset"` Bytes uint64 `json:"bytes"` } type trafficState struct { Version int `json:"version"` Domains map[string]trafficCursor `json:"domains"` } var ( trafficStateMu sync.Mutex nginxBytesPattern = regexp.MustCompile(`"\s+[0-9]{3}\s+([0-9]+|-)\s`) nginxDatePattern = regexp.MustCompile(`\[([0-9]{2})/([A-Za-z]{3})/([0-9]{4}):`) ) func (a Agent) resourceUsage(w http.ResponseWriter, r *http.Request) { var spec ResourceUsageSpec decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !validUsageSpec(spec) || len(spec.Domains) > 100 { http.Error(w, "invalid request", http.StatusBadRequest) return } projectRoot, err := a.projectPath(spec.Project) if err != nil || requirePhysicalDirectory(projectRoot) != nil { http.Error(w, "project root unavailable", http.StatusPreconditionFailed) return } storage, err := measureProjectStorage(projectRoot) if err != nil { http.Error(w, "cannot measure project storage", http.StatusInternalServerError) return } processes, err := countIdentityProcesses(spec.Project.HostName) if err != nil { http.Error(w, "cannot count isolated processes", http.StatusInternalServerError) return } bandwidth, err := a.measureBandwidth(spec.Domains, time.Now()) if err != nil { http.Error(w, "cannot measure site bandwidth", http.StatusInternalServerError) return } ftpBytes, err := a.measureFTPBandwidth(spec.Project.HostName, time.Now()) if err != nil || ftpBytes > math.MaxUint64-bandwidth { http.Error(w, "cannot measure FTP bandwidth", 500) return } bandwidth += ftpBytes memory, ticks, err := identityMetrics(spec.Project.HostName) if err != nil { http.Error(w, "cannot read process metrics", 412) return } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(ResourceUsage{StorageBytes: storage, BandwidthBytes: bandwidth, ProcessCount: processes, MemoryBytes: memory, CPUTicks: ticks}) } // measureProjectStorage runs only in the root isolation agent. The API service // deliberately cannot traverse private runtime directories owned by a host // identity, so measuring there would let a tenant make quota refresh fail with // chmod(000). WalkDir does not follow symlinks; only logical entry sizes below // the already validated physical project root are counted. func measureProjectStorage(projectRoot string) (uint64, error) { if err := requirePhysicalDirectory(projectRoot); err != nil { return 0, err } var total uint64 err := filepath.WalkDir(projectRoot, func(_ string, entry os.DirEntry, walkErr error) error { if walkErr != nil { return walkErr } if entry.IsDir() { return nil } info, err := entry.Info() if err != nil { return err } size := info.Size() if size < 0 || uint64(size) > math.MaxUint64-total { return errors.New("storage usage overflow") } total += uint64(size) return nil }) if err != nil { return 0, err } return total, nil } func (a Agent) terminateProcesses(w http.ResponseWriter, r *http.Request) { spec, ok := a.decode(w, r) if !ok { return } projectRoot, err := a.projectPath(spec) if err != nil || requirePhysicalDirectory(projectRoot) != nil { http.Error(w, "project root unavailable", http.StatusPreconditionFailed) return } if err = terminateIdentityProcesses(r.Context(), spec.HostName); err != nil { http.Error(w, "cannot terminate isolated processes", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func (a Agent) terminateRuntime(w http.ResponseWriter, r *http.Request) { var input RuntimeProcessSpec decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) || input.Project.TenantID == 0 || input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 { http.Error(w, "invalid request", http.StatusBadRequest) return } projectRoot, err := a.projectPath(input.Project) if err != nil { http.Error(w, "invalid path", http.StatusBadRequest) return } runtimeRoot, err := physicalRunDirectory(projectRoot, input.Project.RunPath) if err != nil { http.Error(w, "unsafe runtime directory", http.StatusPreconditionFailed) return } if err = terminateRuntimeDirectoryProcesses(r.Context(), input.Project.HostName, runtimeRoot); err != nil { http.Error(w, "cannot terminate isolated runtime processes", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func validUsageSpec(spec ResourceUsageSpec) bool { if !safeName.MatchString(spec.Project.HostName) || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 || !validProjectRunPath(spec.Project.RunPath) { return false } seen := make(map[string]bool, len(spec.Domains)) for index, domain := range spec.Domains { domain = strings.ToLower(strings.TrimSpace(domain)) if !webDomainPattern.MatchString(domain) || seen[domain] { return false } seen[domain] = true spec.Domains[index] = domain } return true } func (a Agent) measureBandwidth(domains []string, now time.Time) (uint64, error) { trafficStateMu.Lock() defer trafficStateMu.Unlock() statePath := a.UsageStatePath if statePath == "" { statePath = "/var/lib/sea-vhost-agent/traffic.json" } logRoot := a.NginxLogRoot if logRoot == "" { logRoot = "/www/wwwlogs" } state, err := loadTrafficState(statePath) if err != nil { return 0, err } month := now.Format("2006-01") var total uint64 for _, rawDomain := range domains { domain := strings.ToLower(strings.TrimSpace(rawDomain)) cursor := state.Domains[domain] if cursor.Month != month { cursor.Month = month cursor.Bytes = 0 } cursor, err = measureDomainLog(filepath.Join(logRoot, domain+".log"), cursor, month) if err != nil { return 0, fmt.Errorf("measure %s: %w", domain, err) } state.Domains[domain] = cursor if cursor.Bytes > math.MaxUint64-total { return 0, errors.New("bandwidth usage overflow") } total += cursor.Bytes } if err = saveTrafficState(statePath, state); err != nil { return 0, err } return total, nil } func loadTrafficState(path string) (trafficState, error) { state := trafficState{Version: 1, Domains: map[string]trafficCursor{}} data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return state, nil } if err != nil { return state, err } if err = json.Unmarshal(data, &state); err != nil || state.Version != 1 || state.Domains == nil { return trafficState{}, errors.New("invalid traffic state") } return state, nil } func saveTrafficState(path string, state trafficState) error { if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { return err } data, err := json.Marshal(state) if err != nil { return err } temporary, err := os.CreateTemp(filepath.Dir(path), ".traffic-*.tmp") if err != nil { return err } temporaryPath := temporary.Name() defer os.Remove(temporaryPath) if err = temporary.Chmod(0600); err == nil { _, err = temporary.Write(append(data, '\n')) } if closeErr := temporary.Close(); err == nil { err = closeErr } if err != nil { return err } return os.Rename(temporaryPath, path) } func measureDomainLog(path string, cursor trafficCursor, month string) (trafficCursor, error) { return measureTransferLog(path, cursor, month, nil) } func measureTransferLog(path string, cursor trafficCursor, month string, parse func(string) (uint64, bool)) (trafficCursor, error) { info, err := os.Stat(path) if errors.Is(err, os.ErrNotExist) { return cursor, nil } if err != nil || !info.Mode().IsRegular() { return cursor, errors.New("site log is not a regular file") } currentID := fileIdentity(info) if cursor.FileID != 0 && cursor.FileID != currentID { rotated := path + ".1" if rotatedInfo, statErr := os.Stat(rotated); statErr == nil && rotatedInfo.Mode().IsRegular() && fileIdentity(rotatedInfo) == cursor.FileID { if err = accumulateTransferLog(rotated, cursor.Offset, month, &cursor, parse); err != nil { return cursor, err } } cursor.Offset = 0 } if cursor.FileID == currentID && info.Size() < cursor.Offset { cursor.Offset = 0 // copytruncate rotation } cursor.FileID = currentID if err = accumulateTransferLog(path, cursor.Offset, month, &cursor, parse); err != nil { return cursor, err } return cursor, nil } func accumulateLog(path string, offset int64, month string, cursor *trafficCursor) error { return accumulateTransferLog(path, offset, month, cursor, nil) } func accumulateTransferLog(path string, offset int64, month string, cursor *trafficCursor, parse func(string) (uint64, bool)) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() if _, err = file.Seek(offset, io.SeekStart); err != nil { return err } reader := bufio.NewReaderSize(file, 64<<10) for { line, readErr := reader.ReadString('\n') if errors.Is(readErr, io.EOF) && len(line) > 0 && !strings.HasSuffix(line, "\n") { // Nginx may still be writing this record. Re-read it from the same // offset next cycle instead of permanently skipping a partial line. return nil } if len(line) > 0 { cursor.Offset += int64(len(line)) if parse != nil { if value, ok := parse(line); ok { if value > math.MaxUint64-cursor.Bytes { return errors.New("FTP bandwidth usage overflow") } cursor.Bytes += value } } else if lineMonth(line) == month { match := nginxBytesPattern.FindStringSubmatch(line) if match != nil && match[1] != "-" { value, parseErr := strconv.ParseUint(match[1], 10, 64) if parseErr != nil || value > math.MaxUint64-cursor.Bytes { return errors.New("bandwidth usage overflow") } cursor.Bytes += value } } } if errors.Is(readErr, io.EOF) { return nil } if readErr != nil { return readErr } } } func lineMonth(line string) string { match := nginxDatePattern.FindStringSubmatch(line) if match == nil { return "" } months := map[string]string{"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"} return match[3] + "-" + months[match[2]] }