occlum.go 14.3 KB
Newer Older
S
stormgbs 已提交
1 2 3 4
package occlum

import (
	"context"
5
	"encoding/json"
S
stormgbs 已提交
6 7 8 9 10 11
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
12
	"syscall"
S
stormgbs 已提交
13 14
	"time"

15 16 17 18 19 20 21
	"github.com/BurntSushi/toml"
	shim_config "github.com/alibaba/inclavare-containers/shim/config"
	"github.com/alibaba/inclavare-containers/shim/runtime/carrier"
	carr_const "github.com/alibaba/inclavare-containers/shim/runtime/carrier/constants"
	"github.com/alibaba/inclavare-containers/shim/runtime/config"
	"github.com/alibaba/inclavare-containers/shim/runtime/utils"
	"github.com/alibaba/inclavare-containers/shim/runtime/v2/rune/constants"
S
stormgbs 已提交
22 23
	"github.com/containerd/containerd"
	"github.com/containerd/containerd/cio"
24
	"github.com/containerd/containerd/cmd/ctr/commands"
S
stormgbs 已提交
25 26 27 28 29 30 31 32
	"github.com/containerd/containerd/namespaces"
	"github.com/containerd/containerd/oci"
	"github.com/containerd/containerd/runtime/v2/task"
	"github.com/opencontainers/runtime-spec/specs-go"
	"github.com/sirupsen/logrus"
)

const (
33 34 35 36 37 38
	defaultNamespace         = "k8s.io"
	replaceOcclumImageScript = "replace_occlum_image.sh"
	carrierScriptFileName    = "carrier.sh"
	startScriptFileName      = "start.sh"
	rootfsDirName            = "rootfs"
	enclaveDataDir           = "data"
S
stormgbs 已提交
39 40 41 42
)

var _ carrier.Carrier = &occlum{}

43 44 45 46 47 48
type occlumBuildTask struct {
	client    *containerd.Client
	container *containerd.Container
	task      *containerd.Task
}

S
stormgbs 已提交
49 50 51 52 53 54
type occlum struct {
	context       context.Context
	bundle        string
	workDirectory string
	entryPoints   []string
	configPath    string
55
	task          *occlumBuildTask
S
stormgbs 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
	spec          *specs.Spec
	shimConfig    *shim_config.Config
}

// NewOcclumCarrier returns an carrier instance of occlum.
func NewOcclumCarrier(ctx context.Context, bundle string) (carrier.Carrier, error) {
	var cfg shim_config.Config
	if _, err := toml.DecodeFile(constants.ConfigurationPath, &cfg); err != nil {
		return nil, err
	}

	setLogLevel(cfg.LogLevel)

	return &occlum{
		context:    ctx,
		bundle:     bundle,
		shimConfig: &cfg,
73
		task:       &occlumBuildTask{},
S
stormgbs 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
	}, nil
}

// Name impl Carrier.
func (c *occlum) Name() string {
	return "occlum"
}

// BuildUnsignedEnclave impl Carrier.
func (c *occlum) BuildUnsignedEnclave(req *task.CreateTaskRequest, args *carrier.BuildUnsignedEnclaveArgs) (
	unsignedEnclave string, err error) {

	// Initialize environment variables for occlum in config.json
	if err := c.initBundleConfig(); err != nil {
		return "", err
	}

	namespace, ok := namespaces.Namespace(c.context)
	if !ok {
		namespace = defaultNamespace
	}
	// Create a new client connected to the default socket path for containerd.
	client, err := containerd.New(c.shimConfig.Containerd.Socket)
	if err != nil {
		return "", fmt.Errorf("failed to create containerd client. error: %++v", err)
99 100
	} else {
		c.task.client = client
S
stormgbs 已提交
101 102 103 104
	}
	logrus.Debugf("BuildUnsignedEnclave: get containerd client successfully")

	if err = createNamespaceIfNotExist(client, namespace); err != nil {
105
		logrus.Errorf("BuildUnsignedEnclave: create namespace %s failed. error: %++v", namespace, err)
S
stormgbs 已提交
106 107 108
		return "", err
	}

109
	// pull the image that used to build enclave.
S
stormgbs 已提交
110
	occlumEnclaveBuilderImage := c.shimConfig.EnclaveRuntime.Occlum.BuildImage
111
	image, err := client.Pull(c.context, occlumEnclaveBuilderImage, containerd.WithPullUnpack)
S
stormgbs 已提交
112 113 114 115 116
	if err != nil {
		return "", fmt.Errorf("failed to pull image %s. error: %++v", occlumEnclaveBuilderImage, err)
	}
	logrus.Debugf("BuildUnsignedEnclave: pull image %s successfully", occlumEnclaveBuilderImage)

117
	// Generate the containerId and snapshotId.
118
	// FIXME The variables containerId and snapshotId should be generated by utils.GenerateID
S
stormgbs 已提交
119 120 121 122 123 124
	rand.Seed(time.Now().UnixNano())
	containerId := fmt.Sprintf("occlum-enclave-builder-%s", strconv.FormatInt(rand.Int63(), 16))
	snapshotId := fmt.Sprintf("occlum-enclave-builder-snapshot-%s", strconv.FormatInt(rand.Int63(), 16))

	logrus.Debugf("BuildUnsignedEnclave: containerId: %s, snapshotId: %s", containerId, snapshotId)

125
	if err := os.Mkdir(filepath.Join(req.Bundle, enclaveDataDir), 0755); err != nil {
S
stormgbs 已提交
126 127 128
		return "", err
	}

129 130
	replaceImagesScript := filepath.Join(req.Bundle, enclaveDataDir, replaceOcclumImageScript)
	if err := ioutil.WriteFile(replaceImagesScript, []byte(carr_const.ReplaceOcclumImageScript), os.ModePerm); err != nil {
S
stormgbs 已提交
131 132 133
		return "", err
	}

134 135 136 137 138 139 140
	carrierScript := filepath.Join(req.Bundle, enclaveDataDir, carrierScriptFileName)
	if err := ioutil.WriteFile(carrierScript, []byte(carr_const.CarrierScript), os.ModePerm); err != nil {
		return "", err
	}

	startScript := filepath.Join(req.Bundle, enclaveDataDir, startScriptFileName)
	if err := ioutil.WriteFile(startScript, []byte(carr_const.StartScript), os.ModePerm); err != nil {
S
stormgbs 已提交
141 142 143 144 145 146 147 148 149 150 151 152
		return "", err
	}

	// Create rootfs mount points.
	mounts := make([]specs.Mount, 0)
	rootfsMount := specs.Mount{
		Destination: filepath.Join("/", rootfsDirName),
		Type:        "bind",
		Source:      filepath.Join(req.Bundle, rootfsDirName),
		Options:     []string{"rbind", "rw"},
	}
	dataMount := specs.Mount{
153
		Destination: filepath.Join("/", enclaveDataDir),
S
stormgbs 已提交
154
		Type:        "bind",
155
		Source:      filepath.Join(req.Bundle, enclaveDataDir),
S
stormgbs 已提交
156 157 158 159 160 161 162 163 164
		Options:     []string{"rbind", "rw"},
	}

	logrus.Debugf("BuildUnsignedEnclave: rootfsMount source: %s, destination: %s",
		rootfsMount.Source, rootfsMount.Destination)

	mounts = append(mounts, rootfsMount, dataMount)
	// create a container
	container, err := client.NewContainer(
165
		c.context,
S
stormgbs 已提交
166 167 168 169
		containerId,
		containerd.WithImage(image),
		containerd.WithNewSnapshot(snapshotId, image),
		containerd.WithNewSpec(oci.WithImageConfig(image),
170
			oci.WithProcessArgs("/bin/bash", filepath.Join("/", enclaveDataDir, startScriptFileName)),
S
stormgbs 已提交
171 172 173 174 175 176 177
			oci.WithPrivileged,
			oci.WithMounts(mounts),
		),
	)
	if err != nil {
		return "", fmt.Errorf("failed to create container by image %s. error: %++v",
			occlumEnclaveBuilderImage, err)
178 179
	} else {
		c.task.container = &container
S
stormgbs 已提交
180 181 182
	}

	// Create a task from the container.
183
	t, err := container.NewTask(c.context, cio.NewCreator(cio.WithStdio))
S
stormgbs 已提交
184 185
	if err != nil {
		return "", err
186 187
	} else {
		c.task.task = &t
S
stormgbs 已提交
188 189 190
	}
	logrus.Debugf("BuildUnsignedEnclave: create task successfully")

191 192
	if err := t.Start(c.context); err != nil {
		logrus.Errorf("BuildUnsignedEnclave: start task failed. error: %++v", err)
S
stormgbs 已提交
193 194 195
		return "", err
	}

196 197 198 199 200 201
	cmd := []string{
		"/bin/bash", filepath.Join("/", enclaveDataDir, carrierScriptFileName),
		"--action", "buildUnsignedEnclave",
		"--entry_point", c.entryPoints[0],
		"--work_dir", c.workDirectory,
		"--rootfs", filepath.Join("/", rootfsDirName),
S
stormgbs 已提交
202
	}
203
	var occlumConfigPath string
204
	if c.configPath != "" {
205 206 207 208 209 210 211 212
		occlumConfigPath = filepath.Join("/", rootfsDirName, c.configPath)
	} else {
		c.configPath = "Occlum.json"
		occlumConfigPath = filepath.Join("/", enclaveDataDir, c.configPath)
		hostPath := filepath.Join(c.bundle, enclaveDataDir, c.configPath)
		if err := c.saveOcclumConfig(hostPath); err != nil {
			return "", err
		}
S
stormgbs 已提交
213
	}
214
	cmd = append(cmd, "--occlum_config_path", occlumConfigPath)
215 216 217 218 219 220
	logrus.Debugf("BuildUnsignedEnclave: command: %v", cmd)
	if err := c.execTask(cmd...); err != nil {
		logrus.Errorf("BuildUnsignedEnclave: exec failed. error: %++v", err)
		return "", err
	}
	enclavePath := filepath.Join("/", rootfsDirName, c.workDirectory, ".occlum/build/lib/libocclum-libos.so")
S
stormgbs 已提交
221 222 223 224 225 226
	return enclavePath, nil
}

// GenerateSigningMaterial impl Carrier.
func (c *occlum) GenerateSigningMaterial(req *task.CreateTaskRequest, args *carrier.CommonArgs) (
	signingMaterial string, err error) {
227 228 229 230 231 232 233 234
	signingMaterial = filepath.Join("/", rootfsDirName, c.workDirectory, "enclave_sig.dat")
	args.Config = filepath.Join("/", rootfsDirName, c.workDirectory, "Enclave.xml")
	cmd := []string{
		"/bin/bash", filepath.Join("/", enclaveDataDir, carrierScriptFileName),
		"--action", "generateSigningMaterial",
		"--enclave_config_path", args.Config,
		"--unsigned_encalve_path", args.Enclave,
		"--unsigned_material_path", signingMaterial,
S
stormgbs 已提交
235
	}
236 237 238 239
	logrus.Debugf("GenerateSigningMaterial: sgx_sign gendata command: %v", cmd)
	if err := c.execTask(cmd...); err != nil {
		logrus.Errorf("GenerateSigningMaterial: sgx_sign gendata failed. error: %++v", err)
		return "", err
S
stormgbs 已提交
240
	}
241
	logrus.Debugf("GenerateSigningMaterial: sgx_sign gendata successfully")
S
stormgbs 已提交
242 243 244 245 246 247
	return signingMaterial, nil
}

// CascadeEnclaveSignature impl Carrier.
func (c *occlum) CascadeEnclaveSignature(req *task.CreateTaskRequest, args *carrier.CascadeEnclaveSignatureArgs) (
	signedEnclave string, err error) {
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	var bufferSize int64 = 1024 * 4
	signedEnclave = filepath.Join("/", rootfsDirName, c.workDirectory, ".occlum/build/lib/libocclum-libos.signed.so")
	publicKey := filepath.Join("/", enclaveDataDir, "public_key.pem")
	signature := filepath.Join("/", enclaveDataDir, "signature.dat")
	if err := utils.CopyFile(args.Key, filepath.Join(req.Bundle, publicKey), bufferSize); err != nil {
		logrus.Errorf("CascadeEnclaveSignature copy file %s to %s failed. err: %++v", args.Key, publicKey, err)
		return "", err
	}
	if err := utils.CopyFile(args.Signature, filepath.Join(req.Bundle, signature), bufferSize); err != nil {
		logrus.Errorf("CascadeEnclaveSignature copy file %s to %s failed. err: %++v", args.Signature, signature, err)
		return "", err
	}
	cmd := []string{
		"/bin/bash", filepath.Join("/", enclaveDataDir, carrierScriptFileName),
		"--action", "cascadeEnclaveSignature",
		"--enclave_config_path", args.Config,
		"--unsigned_encalve_path", args.Enclave,
		"--unsigned_material_path", args.SigningMaterial,
		"--signed_enclave_path", signedEnclave,
		"--public_key_path", publicKey,
		"--signature_path", signature,
S
stormgbs 已提交
269
	}
270 271 272 273 274 275
	logrus.Debugf("CascadeEnclaveSignature: sgx_sign catsig command: %v", cmd)
	if err := c.execTask(cmd...); err != nil {
		logrus.Errorf("CascadeEnclaveSignature: sgx_sign catsig failed. error: %++v", err)
		return "", err
	}
	logrus.Debugf("CascadeEnclaveSignature: sgx_sign catsig successfully")
S
stormgbs 已提交
276 277 278 279 280
	return signedEnclave, nil
}

// Cleanup impl Carrier.
func (c *occlum) Cleanup() error {
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	defer func() {
		if c.task.client != nil {
			c.task.client.Close()
		}
	}()
	defer func() {
		if c.task.container != nil {
			container := *c.task.container
			if err := container.Delete(c.context, containerd.WithSnapshotCleanup); err != nil {
				logrus.Errorf("Cleanup: delete container %s failed. err: %++v", container.ID(), err)
			}
			logrus.Debugf("Cleanup: delete container %s successfully.", container.ID())
		}
	}()

	if c.task.task == nil {
		return nil
	}
299

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	t := *c.task.task
	if err := t.Kill(c.context, syscall.SIGTERM); err != nil {
		logrus.Errorf("Cleanup: kill task %s failed. err: %++v", t.ID(), err)
		return err
	}
	for {
		status, err := t.Status(c.context)
		if err != nil {
			logrus.Errorf("Cleanup: get task %s status failed. error: %++v", t.ID(), err)
			return err
		}
		if status.ExitStatus != 0 {
			logrus.Errorf("Cleanup: task %s exit abnormally. exit code: %d, task status: %s", t.ID(),
				status.ExitStatus, status.Status)
			return fmt.Errorf("task  %s exit abnormally. exit code: %d, task status: %s",
				t.ID(), status.ExitStatus, status.Status)
		}
		if status.Status != containerd.Stopped {
			logrus.Debugf("Cleanup: task %s status: %s", t.ID(), status.Status)
			time.Sleep(time.Second)
			continue
		}
		break
	}
	if _, err := t.Delete(c.context); err != nil {
		logrus.Errorf("Cleanup: delete task %s failed. error: %++v", t.ID(), err)
		return err
	}
	logrus.Debugf("Cleanup: clean occlum container and task successfully")
S
stormgbs 已提交
329 330 331 332 333 334 335 336 337 338 339
	return nil
}

func (c *occlum) initBundleConfig() error {
	configPath := filepath.Join(c.bundle, "config.json")
	spec, err := config.LoadSpec(configPath)
	if err != nil {
		return err
	}
	c.workDirectory = spec.Process.Cwd
	c.entryPoints = spec.Process.Args
340 341 342 343
	enclaveRuntimePath := c.shimConfig.EnclaveRuntime.Occlum.EnclaveRuntimePath
	if enclaveRuntimePath == "" {
		enclaveRuntimePath = fmt.Sprintf("%s/liberpal-occlum.so", c.workDirectory)
	}
S
stormgbs 已提交
344 345 346 347 348 349 350 351 352 353 354 355
	envs := map[string]string{
		carr_const.EnclaveRuntimePathKeyName: enclaveRuntimePath,
		carr_const.EnclaveTypeKeyName:        string(carr_const.IntelSGX),
		carr_const.EnclaveRuntimeArgsKeyName: carr_const.DefaultEnclaveRuntimeArgs,
	}
	c.spec = spec
	if err := config.UpdateEnvs(spec, envs, false); err != nil {
		return err
	}
	return config.SaveSpec(configPath, spec)
}

356 357 358 359 360 361
func (o *occlum) saveOcclumConfig(path string) error {
	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return err
	}
	cfg := GetDefaultOcclumConfig()
	cfg.ApplyEnvs(o.spec.Process.Env)
362
	cfg.ApplyEntrypoints([]string{o.entryPoints[0]})
363 364 365 366 367 368 369
	bytes, err := json.Marshal(cfg)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(path, bytes, 0644)
}

S
stormgbs 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
func createNamespaceIfNotExist(client *containerd.Client, namespace string) error {
	svc := client.NamespaceService()

	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, time.Second*60)
	defer cancel()
	nses, err := svc.List(ctx)
	if err != nil {
		return err
	}
	for _, ns := range nses {
		if ns == namespace {
			return nil
		}
	}

	return svc.Create(ctx, namespace, nil)
}

func setLogLevel(level string) {
	switch level {
	case "debug":
		logrus.SetLevel(logrus.DebugLevel)
	case "info":
		logrus.SetLevel(logrus.InfoLevel)
	case "warn":
		logrus.SetLevel(logrus.WarnLevel)
	case "error":
		logrus.SetLevel(logrus.ErrorLevel)
	default:
		logrus.SetLevel(logrus.InfoLevel)
	}
}
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

func (c *occlum) execTask(args ...string) error {
	container := *c.task.container
	t := *c.task.task
	if container == nil || t == nil {
		return fmt.Errorf("task is not exist")
	}
	spec, err := container.Spec(c.context)
	if err != nil {
		logrus.Errorf("execTask: get container spec failed. error: %++v", err)
		return err
	}
	pspec := spec.Process
	pspec.Terminal = false
	pspec.Args = args

	cioOpts := []cio.Opt{cio.WithStdio, cio.WithFIFODir("/run/containerd/fifo")}
	ioCreator := cio.NewCreator(cioOpts...)
	process, err := t.Exec(c.context, utils.GenerateID(), pspec, ioCreator)
	if err != nil {
		logrus.Errorf("execTask: exec process in task failed. error: %++v", err)
		return err
	}
	defer process.Delete(c.context)
	statusC, err := process.Wait(c.context)
	if err != nil {
		return err
	}
	sigc := commands.ForwardAllSignals(c.context, process)
	defer commands.StopCatch(sigc)

	if err := process.Start(c.context); err != nil {
		logrus.Errorf("execTask: start process failed. error: %++v", err)
		return err
	}
	status := <-statusC
	code, _, err := status.Result()
	if err != nil {
		logrus.Errorf("execTask: exec process failed. error: %++v", err)
		return err
	}
	if code != 0 {
		return fmt.Errorf("process exit abnormaly. exitCode: %d, error: %++v", code, status.Error())
	}
	logrus.Debugf("execTask: exec successfully.")
	return nil
}