forked from aws/amazon-ecs-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
81 lines (71 loc) · 2.57 KB
/
json.go
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 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package dockerstate
import (
"encoding/json"
"errors"
"github.com/aws/amazon-ecs-agent/agent/api"
)
// These bits of information should be enough to reconstruct the entire
// DockerTaskEngine state
type savedState struct {
Tasks []*api.Task
IdToContainer map[string]*api.DockerContainer // DockerId -> api.DockerContainer
IdToTask map[string]string // DockerId -> taskarn
}
func (state *DockerTaskEngineState) MarshalJSON() ([]byte, error) {
var toSave savedState
state.lock.RLock()
defer state.lock.RUnlock()
toSave = savedState{
Tasks: state.AllTasks(),
IdToContainer: state.idToContainer,
IdToTask: state.idToTask,
}
return json.Marshal(toSave)
}
func (state *DockerTaskEngineState) UnmarshalJSON(data []byte) error {
var saved savedState
err := json.Unmarshal(data, &saved)
if err != nil {
return err
}
// reset it by just creating a new one and swapping shortly.
// This also means we don't have to lock for the remainder of this function
// because we are the only ones with a reference to clean
clean := NewDockerTaskEngineState()
for _, task := range saved.Tasks {
clean.AddOrUpdateTask(task)
}
for id, container := range saved.IdToContainer {
taskArn, ok := saved.IdToTask[id]
if !ok {
return errors.New("Could not unmarshal state; incomplete save. There was no task for docker id " + id)
}
task, ok := clean.TaskByArn(taskArn)
if !ok {
return errors.New("Could not unmarshal state; incomplete save. There was no task for arn " + taskArn)
}
// The container.Container pointers *must* match the task's container
// pointers for things to operate correctly; update them here
taskContainer, ok := task.ContainerByName(container.Container.Name)
if !ok {
return errors.New("Could not resolve a container into a task based on name: " + task.String() + " -- " + container.String())
}
container.Container = taskContainer
//pointer matching now; everyone happy
clean.AddContainer(container, task)
}
*state = *clean
return nil
}