state.go 1.95 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package oci

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/opencontainers/runtime-spec/specs-go"
)

// State stores an OCI container state. This includes the spec path and the environment
type State specs.State

// LoadContainerState loads the container state from the specified filename. If the filename is empty or '-' the state is loaded from STDIN
func LoadContainerState(filename string) (*State, error) {
	if filename == "" || filename == "-" {
		return ReadContainerState(os.Stdin)
	}

	inputFile, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to open file: %v", err)
	}
	defer inputFile.Close()

	return ReadContainerState(inputFile)
}

// ReadContainerState reads the container state from the specified reader
func ReadContainerState(reader io.Reader) (*State, error) {
	var s State

	d := json.NewDecoder(reader)
	if err := d.Decode(&s); err != nil {
		return nil, fmt.Errorf("failed to decode container state: %v", err)
	}

	return &s, nil
}

// LoadSpec loads the OCI spec associated with the container state
func (s *State) LoadSpec() (*specs.Spec, error) {
	specFilePath := GetSpecFilePath(s.Bundle)
	specFile, err := os.Open(specFilePath)
	if err != nil {
		return nil, fmt.Errorf("failed to open OCI spec file: %v", err)
	}
	defer specFile.Close()

	spec, err := LoadFrom(specFile)
	if err != nil {
		return nil, fmt.Errorf("failed to load OCI spec: %v", err)
	}
	return spec, nil
}

// GetContainerRoot returns the root for the container from the associated spec. If the spec is not yet loaded, it is
// loaded and cached.
func (s *State) GetContainerRoot() (string, error) {
	spec, err := s.LoadSpec()
	if err != nil {
		return "", err
	}

	var containerRoot string
	if spec.Root != nil {
		containerRoot = spec.Root.Path
	}

	if filepath.IsAbs(containerRoot) {
		return containerRoot, nil
	}

	return filepath.Join(s.Bundle, containerRoot), nil
}