aboutsummaryrefslogtreecommitdiff
path: root/libpod/in_memory_state.go
blob: 9285589b1f9e159ab484de69670b6a5ad9ca976f (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
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
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
package libpod

import (
	"strings"

	"github.com/containers/podman/v2/libpod/define"
	"github.com/containers/podman/v2/pkg/registrar"
	"github.com/containers/storage/pkg/truncindex"
	"github.com/pkg/errors"
)

// TODO: Maybe separate idIndex for pod/containers
// As of right now, partial IDs used in Lookup... need to be unique as well
// This may be undesirable?

// An InMemoryState is a purely in-memory state store
type InMemoryState struct {
	// Maps pod ID to pod struct.
	pods map[string]*Pod
	// Maps container ID to container struct.
	containers map[string]*Container
	// Maps volume ID to volume struct
	volumes map[string]*Volume
	// Maps exec session ID to ID of associated container
	execSessions map[string]string
	// Maps container ID to a list of IDs of dependencies.
	ctrDepends map[string][]string
	// Maps volume ID to IDs of dependencies
	volumeDepends map[string][]string
	// Maps container ID to IDs of associated exec sessions.
	ctrExecSessions map[string][]string
	// Maps pod ID to a map of container ID to container struct.
	podContainers map[string]map[string]*Container
	ctrNetworks   map[string][]string
	// Maps container ID to network name to list of aliases.
	ctrNetworkAliases map[string]map[string][]string
	// Global name registry - ensures name uniqueness and performs lookups.
	nameIndex *registrar.Registrar
	// Global ID registry - ensures ID uniqueness and performs lookups.
	idIndex *truncindex.TruncIndex
	// Namespace the state is joined to.
	namespace string
	// Maps namespace name to local ID and name registries for looking up
	// pods and containers in a specific namespace.
	namespaceIndexes map[string]*namespaceIndex
}

// namespaceIndex contains name and ID registries for a specific namespace.
// This is used for namespaces lookup operations.
type namespaceIndex struct {
	nameIndex *registrar.Registrar
	idIndex   *truncindex.TruncIndex
}

// NewInMemoryState initializes a new, empty in-memory state
func NewInMemoryState() (State, error) {
	state := new(InMemoryState)

	state.pods = make(map[string]*Pod)
	state.containers = make(map[string]*Container)
	state.volumes = make(map[string]*Volume)
	state.execSessions = make(map[string]string)

	state.ctrDepends = make(map[string][]string)
	state.volumeDepends = make(map[string][]string)

	state.ctrExecSessions = make(map[string][]string)

	state.podContainers = make(map[string]map[string]*Container)

	state.ctrNetworks = make(map[string][]string)
	state.ctrNetworkAliases = make(map[string]map[string][]string)

	state.nameIndex = registrar.NewRegistrar()
	state.idIndex = truncindex.NewTruncIndex([]string{})

	state.namespace = ""

	state.namespaceIndexes = make(map[string]*namespaceIndex)

	return state, nil
}

// Close the state before shutdown
// This is a no-op as we have no backing disk
func (s *InMemoryState) Close() error {
	return nil
}

// Refresh clears container and pod stats after a reboot
// In-memory state won't survive a reboot so this is a no-op
func (s *InMemoryState) Refresh() error {
	return nil
}

// GetDBConfig is not implemented for in-memory state.
// As we do not store a config, return an empty one.
func (s *InMemoryState) GetDBConfig() (*DBConfig, error) {
	return &DBConfig{}, nil
}

// ValidateDBConfig is not implemented for the in-memory state.
// Since we do nothing just return no error.
func (s *InMemoryState) ValidateDBConfig(runtime *Runtime) error {
	return nil
}

// SetNamespace sets the namespace for container and pod retrieval.
func (s *InMemoryState) SetNamespace(ns string) error {
	s.namespace = ns

	return nil
}

// GetName retrieves the name associated with a given ID.
// Works with both Container and Pod IDs.
func (s *InMemoryState) GetName(id string) (string, error) {
	if id == "" {
		return "", define.ErrEmptyID
	}

	var idIndex *truncindex.TruncIndex
	if s.namespace != "" {
		nsIndex, ok := s.namespaceIndexes[s.namespace]
		if !ok {
			// We have no containers in the namespace
			// Return false
			return "", define.ErrNoSuchCtr
		}
		idIndex = nsIndex.idIndex
	} else {
		idIndex = s.idIndex
	}

	fullID, err := idIndex.Get(id)
	if err != nil {
		if err == truncindex.ErrNotExist {
			return "", define.ErrNoSuchCtr
		}
		return "", errors.Wrapf(err, "error performing truncindex lookup for ID %s", id)
	}
	return fullID, nil
}

// Container retrieves a container from its full ID
func (s *InMemoryState) Container(id string) (*Container, error) {
	if id == "" {
		return nil, define.ErrEmptyID
	}

	ctr, ok := s.containers[id]
	if !ok {
		return nil, errors.Wrapf(define.ErrNoSuchCtr, "no container with ID %s found", id)
	}

	if err := s.checkNSMatch(ctr.ID(), ctr.Namespace()); err != nil {
		return nil, err
	}

	return ctr, nil
}

// lookupID retrieves a container or pod ID by full ID, unique partial ID, or
// name
func (s *InMemoryState) lookupID(idOrName string) (string, error) {
	var (
		nameIndex *registrar.Registrar
		idIndex   *truncindex.TruncIndex
	)

	if idOrName == "" {
		return "", define.ErrEmptyID
	}

	if s.namespace != "" {
		nsIndex, ok := s.namespaceIndexes[s.namespace]
		if !ok {
			// We have no containers in the namespace
			// Return false
			return "", define.ErrNoSuchCtr
		}
		nameIndex = nsIndex.nameIndex
		idIndex = nsIndex.idIndex
	} else {
		nameIndex = s.nameIndex
		idIndex = s.idIndex
	}

	fullID, err := nameIndex.Get(idOrName)
	if err != nil {
		if err == registrar.ErrNameNotReserved {
			// What was passed is not a name, assume it's an ID
			fullID, err = idIndex.Get(idOrName)
			if err != nil {
				if err == truncindex.ErrNotExist {
					return "", define.ErrNoSuchCtr
				}
				return "", errors.Wrapf(err, "error performing truncindex lookup for ID %s", idOrName)
			}
		} else {
			return "", errors.Wrapf(err, "error performing registry lookup for ID %s", idOrName)
		}
	}

	return fullID, nil
}

// LookupContainerID retrieves a container ID by full ID, unique partial ID, or
// name
func (s *InMemoryState) LookupContainerID(idOrName string) (string, error) {
	fullID, err := s.lookupID(idOrName)

	switch err {
	case nil:
		_, ok := s.containers[fullID]
		if !ok {
			// It's a pod, not a container
			return "", errors.Wrapf(define.ErrNoSuchCtr, "name or ID %s is a pod, not a container", idOrName)
		}

	case define.ErrNoSuchCtr:
		return "", errors.Wrapf(define.ErrNoSuchCtr, "no container found with name or ID %s", idOrName)

	default:
		return "", err
	}

	return fullID, nil
}

// LookupContainer retrieves a container by full ID, unique partial ID, or name
func (s *InMemoryState) LookupContainer(idOrName string) (*Container, error) {
	fullID, err := s.lookupID(idOrName)

	switch err {
	case nil:

	case define.ErrNoSuchCtr:
		return nil, errors.Wrapf(define.ErrNoSuchCtr, "no container found with name or ID %s", idOrName)

	default:
		return nil, err
	}

	ctr, ok := s.containers[fullID]
	if !ok {
		// It's a pod, not a container
		return nil, errors.Wrapf(define.ErrNoSuchCtr, "name or ID %s is a pod, not a container", idOrName)
	}

	return ctr, nil
}

// HasContainer checks if a container with the given ID is present in the state
func (s *InMemoryState) HasContainer(id string) (bool, error) {
	if id == "" {
		return false, define.ErrEmptyID
	}

	ctr, ok := s.containers[id]
	if !ok || (s.namespace != "" && s.namespace != ctr.config.Namespace) {
		return false, nil
	}

	return true, nil
}

// AddContainer adds a container to the state
// Containers in a pod cannot be added to the state
func (s *InMemoryState) AddContainer(ctr *Container) error {
	if !ctr.valid {
		return errors.Wrapf(define.ErrCtrRemoved, "container with ID %s is not valid", ctr.ID())
	}

	if _, ok := s.containers[ctr.ID()]; ok {
		return errors.Wrapf(define.ErrCtrExists, "container with ID %s already exists in state", ctr.ID())
	}

	if ctr.config.Pod != "" {
		return errors.Wrapf(define.ErrInvalidArg, "cannot add a container that is in a pod with AddContainer, use AddContainerToPod")
	}

	if err := s.checkNSMatch(ctr.ID(), ctr.Namespace()); err != nil {
		return err
	}

	// Check networks
	for _, net := range ctr.config.Networks {
		if net == "" {
			return errors.Wrapf(define.ErrInvalidArg, "network names cannot be empty")
		}
	}

	// Check network aliases
	for network := range ctr.config.NetworkAliases {
		inNet := false
		for _, net := range ctr.config.Networks {
			if net == network {
				inNet = true
				break
			}
		}
		if !inNet {
			return errors.Wrapf(define.ErrInvalidArg, "container %s has network aliases for network %q but is not joined to network", ctr.ID(), network)
		}
	}

	// There are potential race conditions with this
	// But in-memory state is intended purely for testing and not production
	// use, so this should be fine.
	depCtrs := ctr.Dependencies()
	for _, depID := range depCtrs {
		depCtr, ok := s.containers[depID]
		if !ok {
			return errors.Wrapf(define.ErrNoSuchCtr, "cannot depend on nonexistent container %s", depID)
		} else if depCtr.config.Pod != "" {
			return errors.Wrapf(define.ErrInvalidArg, "cannot depend on container in a pod if not part of same pod")
		}
		if depCtr.config.Namespace != ctr.config.Namespace {
			return errors.Wrapf(define.ErrNSMismatch, "container %s is in namespace %s and cannot depend on container %s in namespace %s", ctr.ID(), ctr.config.Namespace, depID, depCtr.config.Namespace)
		}
	}

	if err := s.nameIndex.Reserve(ctr.Name(), ctr.ID()); err != nil {
		return errors.Wrapf(err, "error registering container name %s", ctr.Name())
	}

	if err := s.idIndex.Add(ctr.ID()); err != nil {
		s.nameIndex.Release(ctr.Name())
		return errors.Wrapf(err, "error registering container ID %s", ctr.ID())
	}

	s.containers[ctr.ID()] = ctr

	// If we're in a namespace, add us to that namespace's indexes
	if ctr.config.Namespace != "" {
		var nsIndex *namespaceIndex
		nsIndex, ok := s.namespaceIndexes[ctr.config.Namespace]
		if !ok {
			nsIndex = new(namespaceIndex)
			nsIndex.nameIndex = registrar.NewRegistrar()
			nsIndex.idIndex = truncindex.NewTruncIndex([]string{})
			s.namespaceIndexes[ctr.config.Namespace] = nsIndex
		}
		// Should be no errors here, the previous index adds should have caught that
		if err := nsIndex.nameIndex.Reserve(ctr.Name(), ctr.ID()); err != nil {
			return errors.Wrapf(err, "error registering container name %s", ctr.Name())
		}
		if err := nsIndex.idIndex.Add(ctr.ID()); err != nil {
			return errors.Wrapf(err, "error registering container ID %s", ctr.ID())
		}
	}

	// Add containers this container depends on
	for _, depCtr := range depCtrs {
		s.addCtrToDependsMap(ctr.ID(), depCtr)
	}

	// Add container to volume dependencies
	for _, vol := range ctr.config.NamedVolumes {
		s.addCtrToVolDependsMap(ctr.ID(), vol.Name)
	}

	// Add networks
	newNets := make([]string, 0, len(ctr.config.Networks))
	for _, net := range ctr.config.Networks {
		if net == "" {
			return define.ErrInvalidArg
		}
		newNets = append(newNets, net)
	}
	s.ctrNetworks[ctr.ID()] = newNets

	// Add network aliases
	s.ctrNetworkAliases[ctr.ID()] = ctr.config.NetworkAliases

	return nil
}

// RemoveContainer removes a container from the state
// The container will only be removed from the state, not from the pod the container belongs to
func (s *InMemoryState) RemoveContainer(ctr *Container) error {
	// Almost no validity checks are performed, to ensure we can kick
	// misbehaving containers out of the state

	if err := s.checkNSMatch(ctr.ID(), ctr.Namespace()); err != nil {
		return err
	}

	// Ensure we don't remove a container which other containers depend on
	deps, ok := s.ctrDepends[ctr.ID()]
	if ok && len(deps) != 0 {
		depsStr := strings.Join(deps, ", ")
		return errors.Wrapf(define.ErrCtrExists, "the following containers depend on container %s: %s", ctr.ID(), depsStr)
	}

	// Ensure we don't have active exec sessions
	ctrSessions := s.ctrExecSessions[ctr.ID()]
	if len(ctrSessions) > 0 {
		sessStr := strings.Join(ctrSessions, ", ")
		return errors.Wrapf(define.ErrCtrExists, "the following exec sessions are running for container %s: %s", ctr.ID(), sessStr)
	}

	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return errors.Wrapf(define.ErrNoSuchCtr, "no container exists in state with ID %s", ctr.ID())
	}

	if err := s.idIndex.Delete(ctr.ID()); err != nil {
		return errors.Wrapf(err, "error removing container ID from index")
	}
	delete(s.containers, ctr.ID())
	s.nameIndex.Release(ctr.Name())

	delete(s.ctrDepends, ctr.ID())

	if ctr.config.Namespace != "" {
		nsIndex, ok := s.namespaceIndexes[ctr.config.Namespace]
		if !ok {
			return errors.Wrapf(define.ErrInternal, "error retrieving index for namespace %q", ctr.config.Namespace)
		}
		if err := nsIndex.idIndex.Delete(ctr.ID()); err != nil {
			return errors.Wrapf(err, "error removing container %s from namespace ID index", ctr.ID())
		}
		nsIndex.nameIndex.Release(ctr.Name())
	}

	// Remove us from container dependencies
	depCtrs := ctr.Dependencies()
	for _, depCtr := range depCtrs {
		s.removeCtrFromDependsMap(ctr.ID(), depCtr)
	}

	// Remove this container from volume dependencies
	for _, vol := range ctr.config.NamedVolumes {
		s.removeCtrFromVolDependsMap(ctr.ID(), vol.Name)
	}

	// Remove our network aliases
	delete(s.ctrNetworkAliases, ctr.ID())
	delete(s.ctrNetworks, ctr.ID())

	return nil
}

// UpdateContainer updates a container's state
// As all state is in-memory, no update will be required
// As such this is a no-op
func (s *InMemoryState) UpdateContainer(ctr *Container) error {
	// If the container is invalid, return error
	if !ctr.valid {
		return errors.Wrapf(define.ErrCtrRemoved, "container with ID %s is not valid", ctr.ID())
	}

	// If the container does not exist, return error
	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return errors.Wrapf(define.ErrNoSuchCtr, "container with ID %s not found in state", ctr.ID())
	}

	return s.checkNSMatch(ctr.ID(), ctr.Namespace())
}

// SaveContainer saves a container's state
// As all state is in-memory, any changes are always reflected as soon as they
// are made
// As such this is a no-op
func (s *InMemoryState) SaveContainer(ctr *Container) error {
	// If the container is invalid, return error
	if !ctr.valid {
		return errors.Wrapf(define.ErrCtrRemoved, "container with ID %s is not valid", ctr.ID())
	}

	// If the container does not exist, return error
	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return errors.Wrapf(define.ErrNoSuchCtr, "container with ID %s not found in state", ctr.ID())
	}

	return s.checkNSMatch(ctr.ID(), ctr.Namespace())
}

// ContainerInUse checks if the given container is being used by other containers
func (s *InMemoryState) ContainerInUse(ctr *Container) ([]string, error) {
	if !ctr.valid {
		return nil, define.ErrCtrRemoved
	}

	// If the container does not exist, return error
	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return nil, errors.Wrapf(define.ErrNoSuchCtr, "container with ID %s not found in state", ctr.ID())
	}

	if err := s.checkNSMatch(ctr.ID(), ctr.Namespace()); err != nil {
		return nil, err
	}

	arr, ok := s.ctrDepends[ctr.ID()]
	if !ok {
		return []string{}, nil
	}

	return arr, nil
}

// AllContainers retrieves all containers from the state
func (s *InMemoryState) AllContainers() ([]*Container, error) {
	ctrs := make([]*Container, 0, len(s.containers))
	for _, ctr := range s.containers {
		if s.namespace == "" || ctr.config.Namespace == s.namespace {
			ctrs = append(ctrs, ctr)
		}
	}

	return ctrs, nil
}

// Get all networks this container is present in.
func (s *InMemoryState) GetNetworks(ctr *Container) ([]string, error) {
	if !ctr.valid {
		return nil, define.ErrCtrRemoved
	}

	ctr, ok := s.containers[ctr.ID()]
	if !ok {
		ctr.valid = false
		return nil, define.ErrNoSuchCtr
	}

	ctrNetworks, ok := s.ctrNetworks[ctr.ID()]
	if !ok {
		return nil, define.ErrNoSuchNetwork
	}

	return ctrNetworks, nil
}

// GetNetworkAliases returns network aliases for the given container in the
// given network.
func (s *InMemoryState) GetNetworkAliases(ctr *Container, network string) ([]string, error) {
	if !ctr.valid {
		return nil, define.ErrCtrRemoved
	}

	if network == "" {
		return nil, errors.Wrapf(define.ErrInvalidArg, "network names must not be empty")
	}

	ctr, ok := s.containers[ctr.ID()]
	if !ok {
		ctr.valid = false
		return nil, define.ErrNoSuchCtr
	}

	inNet := false
	for _, net := range ctr.config.Networks {
		if net == network {
			inNet = true
		}
	}
	if !inNet {
		return nil, define.ErrInvalidArg
	}

	ctrAliases, ok := s.ctrNetworkAliases[ctr.ID()]
	if !ok {
		return []string{}, nil
	}
	netAliases, ok := ctrAliases[network]
	if !ok {
		return []string{}, nil
	}

	return netAliases, nil
}

// GetAllNetworkAliases gets all network aliases for the given container.
func (s *InMemoryState) GetAllNetworkAliases(ctr *Container) (map[string][]string, error) {
	if !ctr.valid {
		return nil, define.ErrCtrRemoved
	}

	ctr, ok := s.containers[ctr.ID()]
	if !ok {
		ctr.valid = false
		return nil, define.ErrNoSuchCtr
	}

	ctrAliases, ok := s.ctrNetworkAliases[ctr.ID()]
	if !ok {
		return map[string][]string{}, nil
	}

	return ctrAliases, nil
}

// NetworkConnect connects to the given network
func (s *InMemoryState) NetworkConnect(ctr *Container, network string, aliases []string) error {
	if !ctr.valid {
		return define.ErrCtrRemoved
	}

	if network == "" {
		return errors.Wrapf(define.ErrInvalidArg, "network names must not be empty")
	}

	ctr, ok := s.containers[ctr.ID()]
	if !ok {
		ctr.valid = false
		return define.ErrNoSuchCtr
	}

	inNet := false
	ctrNetworks, ok := s.ctrNetworks[ctr.ID()]
	if !ok {
		return define.ErrNoSuchNetwork
	}
	for _, net := range ctrNetworks {
		if net == network {
			inNet = true
		}
	}
	if inNet {
		return define.ErrNoSuchNetwork
	}
	s.ctrNetworks[ctr.ID()] = append(ctrNetworks, network)

	ctrAliases, ok := s.ctrNetworkAliases[ctr.ID()]
	if !ok {
		ctrAliases = make(map[string][]string)
		s.ctrNetworkAliases[ctr.ID()] = ctrAliases
	}
	ctrAliases[network] = aliases

	return nil
}

// Disconnect from the given network and remove all aliases in it.
func (s *InMemoryState) NetworkDisconnect(ctr *Container, network string) error {
	if !ctr.valid {
		return define.ErrCtrRemoved
	}

	if network == "" {
		return errors.Wrapf(define.ErrInvalidArg, "network names must not be empty")
	}

	ctr, ok := s.containers[ctr.ID()]
	if !ok {
		ctr.valid = false
		return define.ErrNoSuchCtr
	}

	ctrNetworks, ok := s.ctrNetworks[ctr.ID()]
	if !ok {
		return define.ErrNoSuchNetwork
	}
	inNet := false
	remainingNets := make([]string, 0, len(ctrNetworks))
	for _, net := range ctrNetworks {
		if net == network {
			inNet = true
			break
		} else {
			remainingNets = append(remainingNets, net)
		}
	}
	if !inNet {
		return define.ErrNoSuchNetwork
	}
	s.ctrNetworks[ctr.ID()] = remainingNets

	ctrAliases, ok := s.ctrNetworkAliases[ctr.ID()]
	if !ok {
		ctrAliases = make(map[string][]string)
		s.ctrNetworkAliases[ctr.ID()] = ctrAliases
	}
	delete(ctrAliases, network)

	return nil
}

// GetContainerConfig returns a container config from the database by full ID
func (s *InMemoryState) GetContainerConfig(id string) (*ContainerConfig, error) {
	ctr, err := s.LookupContainer(id)
	if err != nil {
		return nil, err
	}

	return ctr.Config(), nil
}

// Add an exec session to the database
func (s *InMemoryState) AddExecSession(ctr *Container, session *ExecSession) error {
	if !ctr.valid {
		return define.ErrCtrRemoved
	}
	if session.ContainerID() != ctr.ID() {
		return errors.Wrapf(define.ErrInvalidArg, "container ID and exec session ID must match")
	}
	if _, ok := s.containers[ctr.ID()]; !ok {
		return define.ErrNoSuchCtr
	}

	if _, ok := s.execSessions[session.ID()]; ok {
		return define.ErrExecSessionExists
	}

	s.execSessions[session.ID()] = ctr.ID()

	ctrSessions, ok := s.ctrExecSessions[ctr.ID()]
	if !ok {
		ctrSessions = []string{}
	}

	ctrSessions = append(ctrSessions, session.ID())
	s.ctrExecSessions[ctr.ID()] = ctrSessions

	return nil
}

// Get an exec session from the database by full or partial ID.
func (s *InMemoryState) GetExecSession(id string) (string, error) {
	if id == "" {
		return "", define.ErrEmptyID
	}

	session, ok := s.execSessions[id]
	if !ok {
		return "", define.ErrNoSuchExecSession
	}

	return session, nil
}

// RemoveExecSession removes an exec session from the database.
func (s *InMemoryState) RemoveExecSession(session *ExecSession) error {
	if _, ok := s.execSessions[session.ID()]; !ok {
		return define.ErrNoSuchExecSession
	}

	ctrSessions, ok := s.ctrExecSessions[session.ContainerID()]
	// If !ok - internal state seems inconsistent, but the thing we wanted
	// to remove is gone. Continue.
	if ok {
		newSessions := []string{}
		for _, sess := range ctrSessions {
			if sess != session.ID() {
				newSessions = append(newSessions, sess)
			}
		}
		s.ctrExecSessions[session.ContainerID()] = newSessions
	}

	delete(s.execSessions, session.ID())

	return nil
}

// GetContainerExecSessions retrieves all exec sessions for the given container.
func (s *InMemoryState) GetContainerExecSessions(ctr *Container) ([]string, error) {
	if !ctr.valid {
		return nil, define.ErrCtrRemoved
	}
	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return nil, define.ErrNoSuchCtr
	}

	ctrSessions := s.ctrExecSessions[ctr.ID()]

	return ctrSessions, nil
}

// RemoveContainerExecSessions removes all exec sessions for the given
// container.
func (s *InMemoryState) RemoveContainerExecSessions(ctr *Container) error {
	if !ctr.valid {
		return define.ErrCtrRemoved
	}
	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return define.ErrNoSuchCtr
	}

	ctrSessions, ok := s.ctrExecSessions[ctr.ID()]
	if !ok {
		return nil
	}

	for _, sess := range ctrSessions {
		if _, ok := s.execSessions[sess]; !ok {
			// We have an internal state inconsistency
			// Error out
			return errors.Wrapf(define.ErrInternal, "inconsistent database state: exec session %s is missing", sess)
		}
		delete(s.execSessions, sess)
	}
	delete(s.ctrExecSessions, ctr.ID())

	return nil
}

// RewriteContainerConfig rewrites a container's configuration.
// This function is DANGEROUS, even with an in-memory state.
// Please read the full comment on it in state.go before using it.
func (s *InMemoryState) RewriteContainerConfig(ctr *Container, newCfg *ContainerConfig) error {
	if !ctr.valid {
		return define.ErrCtrRemoved
	}

	// If the container does not exist, return error
	stateCtr, ok := s.containers[ctr.ID()]
	if !ok {
		ctr.valid = false
		return errors.Wrapf(define.ErrNoSuchCtr, "container with ID %s not found in state", ctr.ID())
	}

	stateCtr.config = newCfg

	return nil
}

// RewritePodConfig rewrites a pod's configuration.
// This function is DANGEROUS, even with in-memory state.
// Please read the full comment on it in state.go before using it.
func (s *InMemoryState) RewritePodConfig(pod *Pod, newCfg *PodConfig) error {
	if !pod.valid {
		return define.ErrPodRemoved
	}

	// If the pod does not exist, return error
	statePod, ok := s.pods[pod.ID()]
	if !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrNoSuchPod, "pod with ID %s not found in state", pod.ID())
	}

	statePod.config = newCfg

	return nil
}

// RewriteVolumeConfig rewrites a volume's configuration.
// This function is DANGEROUS, even with in-memory state.
// Please read the full comment in state.go before using it.
func (s *InMemoryState) RewriteVolumeConfig(volume *Volume, newCfg *VolumeConfig) error {
	if !volume.valid {
		return define.ErrVolumeRemoved
	}

	// If the volume does not exist, return error
	stateVol, ok := s.volumes[volume.Name()]
	if !ok {
		volume.valid = false
		return errors.Wrapf(define.ErrNoSuchVolume, "volume with name %q not found in state", volume.Name())
	}

	stateVol.config = newCfg

	return nil
}

// Volume retrieves a volume from its full name
func (s *InMemoryState) Volume(name string) (*Volume, error) {
	if name == "" {
		return nil, define.ErrEmptyID
	}

	vol, ok := s.volumes[name]
	if !ok {
		return nil, errors.Wrapf(define.ErrNoSuchCtr, "no volume with name %s found", name)
	}

	return vol, nil
}

// LookupVolume finds a volume from an unambiguous partial ID.
func (s *InMemoryState) LookupVolume(name string) (*Volume, error) {
	if name == "" {
		return nil, define.ErrEmptyID
	}

	vol, ok := s.volumes[name]
	if ok {
		return vol, nil
	}

	// Alright, we've failed to find by full name. Now comes the expensive
	// part.
	// Loop through all volumes and look for matches.
	var (
		foundMatch bool
		candidate  *Volume
	)
	for volName, vol := range s.volumes {
		if strings.HasPrefix(volName, name) {
			if foundMatch {
				return nil, errors.Wrapf(define.ErrVolumeExists, "more than one result for volume name %q", name)
			}
			candidate = vol
			foundMatch = true
		}
	}

	if !foundMatch {
		return nil, errors.Wrapf(define.ErrNoSuchVolume, "no volume with name %q found", name)
	}

	return candidate, nil
}

// HasVolume checks if a volume with the given name is present in the state
func (s *InMemoryState) HasVolume(name string) (bool, error) {
	if name == "" {
		return false, define.ErrEmptyID
	}

	_, ok := s.volumes[name]
	if !ok {
		return false, nil
	}

	return true, nil
}

// AddVolume adds a volume to the state
func (s *InMemoryState) AddVolume(volume *Volume) error {
	if !volume.valid {
		return errors.Wrapf(define.ErrVolumeRemoved, "volume with name %s is not valid", volume.Name())
	}

	if _, ok := s.volumes[volume.Name()]; ok {
		return errors.Wrapf(define.ErrVolumeExists, "volume with name %s already exists in state", volume.Name())
	}

	s.volumes[volume.Name()] = volume

	return nil
}

// RemoveVolume removes a volume from the state
func (s *InMemoryState) RemoveVolume(volume *Volume) error {
	// Ensure we don't remove a volume which containers depend on
	deps, ok := s.volumeDepends[volume.Name()]
	if ok && len(deps) != 0 {
		depsStr := strings.Join(deps, ", ")
		return errors.Wrapf(define.ErrVolumeExists, "the following containers depend on volume %s: %s", volume.Name(), depsStr)
	}

	if _, ok := s.volumes[volume.Name()]; !ok {
		volume.valid = false
		return errors.Wrapf(define.ErrVolumeRemoved, "no volume exists in state with name %s", volume.Name())
	}

	delete(s.volumes, volume.Name())

	return nil
}

// UpdateVolume updates a volume from the database.
// For the in-memory state, this is a no-op.
func (s *InMemoryState) UpdateVolume(volume *Volume) error {
	if !volume.valid {
		return define.ErrVolumeRemoved
	}

	if _, ok := s.volumes[volume.Name()]; !ok {
		volume.valid = false
		return errors.Wrapf(define.ErrNoSuchVolume, "volume with name %q not found in state", volume.Name())
	}

	return nil
}

// SaveVolume saves a volume's state to the database.
// For the in-memory state, this is a no-op.
func (s *InMemoryState) SaveVolume(volume *Volume) error {
	if !volume.valid {
		return define.ErrVolumeRemoved
	}

	if _, ok := s.volumes[volume.Name()]; !ok {
		volume.valid = false
		return errors.Wrapf(define.ErrNoSuchVolume, "volume with name %q not found in state", volume.Name())
	}

	return nil
}

// VolumeInUse checks if the given volume is being used by at least one container
func (s *InMemoryState) VolumeInUse(volume *Volume) ([]string, error) {
	if !volume.valid {
		return nil, define.ErrVolumeRemoved
	}

	// If the volume does not exist, return error
	if _, ok := s.volumes[volume.Name()]; !ok {
		volume.valid = false
		return nil, errors.Wrapf(define.ErrNoSuchVolume, "volume with name %s not found in state", volume.Name())
	}

	arr, ok := s.volumeDepends[volume.Name()]
	if !ok {
		return []string{}, nil
	}

	return arr, nil
}

// AllVolumes returns all volumes that exist in the state
func (s *InMemoryState) AllVolumes() ([]*Volume, error) {
	allVols := make([]*Volume, 0, len(s.volumes))
	for _, v := range s.volumes {
		allVols = append(allVols, v)
	}

	return allVols, nil
}

// Pod retrieves a pod from the state from its full ID
func (s *InMemoryState) Pod(id string) (*Pod, error) {
	if id == "" {
		return nil, define.ErrEmptyID
	}

	pod, ok := s.pods[id]
	if !ok {
		return nil, errors.Wrapf(define.ErrNoSuchPod, "no pod with id %s found", id)
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return nil, err
	}

	return pod, nil
}

// LookupPod retrieves a pod from the state from a full or unique partial ID or
// a full name
func (s *InMemoryState) LookupPod(idOrName string) (*Pod, error) {
	fullID, err := s.lookupID(idOrName)

	switch err {
	case nil:

	case define.ErrNoSuchCtr, define.ErrNoSuchPod:
		return nil, errors.Wrapf(define.ErrNoSuchPod, "no pod found with name or ID %s", idOrName)

	default:
		return nil, err
	}

	pod, ok := s.pods[fullID]
	if !ok {
		// It's a container not a pod
		return nil, errors.Wrapf(define.ErrNoSuchPod, "id or name %s is a container, not a pod", idOrName)
	}

	return pod, nil
}

// HasPod checks if a pod with the given ID is present in the state
func (s *InMemoryState) HasPod(id string) (bool, error) {
	if id == "" {
		return false, define.ErrEmptyID
	}

	pod, ok := s.pods[id]
	if !ok || (s.namespace != "" && s.namespace != pod.config.Namespace) {
		return false, nil
	}

	return true, nil
}

// PodHasContainer checks if the given pod has a container with the given ID
func (s *InMemoryState) PodHasContainer(pod *Pod, ctrID string) (bool, error) {
	if !pod.valid {
		return false, errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid", pod.ID())
	}

	if ctrID == "" {
		return false, define.ErrEmptyID
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return false, err
	}

	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return false, errors.Wrapf(define.ErrNoSuchPod, "no pod with ID %s found in state", pod.ID())
	}

	_, ok = podCtrs[ctrID]
	return ok, nil
}

// PodContainersByID returns the IDs of all containers in the given pod
func (s *InMemoryState) PodContainersByID(pod *Pod) ([]string, error) {
	if !pod.valid {
		return nil, errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid", pod.ID())
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return nil, err
	}

	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return nil, errors.Wrapf(define.ErrNoSuchPod, "no pod with ID %s found in state", pod.ID())
	}

	length := len(podCtrs)
	if length == 0 {
		return []string{}, nil
	}

	ctrs := make([]string, 0, length)
	for _, ctr := range podCtrs {
		ctrs = append(ctrs, ctr.ID())
	}

	return ctrs, nil
}

// PodContainers retrieves the containers from a pod
func (s *InMemoryState) PodContainers(pod *Pod) ([]*Container, error) {
	if !pod.valid {
		return nil, errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid", pod.ID())
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return nil, err
	}

	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return nil, errors.Wrapf(define.ErrNoSuchPod, "no pod with ID %s found in state", pod.ID())
	}

	length := len(podCtrs)
	if length == 0 {
		return []*Container{}, nil
	}

	ctrs := make([]*Container, 0, length)
	for _, ctr := range podCtrs {
		ctrs = append(ctrs, ctr)
	}

	return ctrs, nil
}

// AddPod adds a given pod to the state
func (s *InMemoryState) AddPod(pod *Pod) error {
	if !pod.valid {
		return errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid and cannot be added", pod.ID())
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return err
	}

	if _, ok := s.pods[pod.ID()]; ok {
		return errors.Wrapf(define.ErrPodExists, "pod with ID %s already exists in state", pod.ID())
	}

	if _, ok := s.podContainers[pod.ID()]; ok {
		return errors.Wrapf(define.ErrPodExists, "pod with ID %s already exists in state", pod.ID())
	}

	if err := s.nameIndex.Reserve(pod.Name(), pod.ID()); err != nil {
		return errors.Wrapf(err, "error registering pod name %s", pod.Name())
	}

	if err := s.idIndex.Add(pod.ID()); err != nil {
		s.nameIndex.Release(pod.Name())
		return errors.Wrapf(err, "error registering pod ID %s", pod.ID())
	}

	s.pods[pod.ID()] = pod

	s.podContainers[pod.ID()] = make(map[string]*Container)

	// If we're in a namespace, add us to that namespace's indexes
	if pod.config.Namespace != "" {
		var nsIndex *namespaceIndex
		nsIndex, ok := s.namespaceIndexes[pod.config.Namespace]
		if !ok {
			nsIndex = new(namespaceIndex)
			nsIndex.nameIndex = registrar.NewRegistrar()
			nsIndex.idIndex = truncindex.NewTruncIndex([]string{})
			s.namespaceIndexes[pod.config.Namespace] = nsIndex
		}
		// Should be no errors here, the previous index adds should have caught that
		if err := nsIndex.nameIndex.Reserve(pod.Name(), pod.ID()); err != nil {
			return errors.Wrapf(err, "error registering container name %s", pod.Name())
		}
		if err := nsIndex.idIndex.Add(pod.ID()); err != nil {
			return errors.Wrapf(err, "error registering container ID %s", pod.ID())
		}
	}

	return nil
}

// RemovePod removes a given pod from the state
// Only empty pods can be removed
func (s *InMemoryState) RemovePod(pod *Pod) error {
	// Don't make many validity checks to ensure we can kick badly formed
	// pods out of the state

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return err
	}

	if _, ok := s.pods[pod.ID()]; !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrNoSuchPod, "no pod exists in state with ID %s", pod.ID())
	}
	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrNoSuchPod, "no pod exists in state with ID %s", pod.ID())
	}
	if len(podCtrs) != 0 {
		return errors.Wrapf(define.ErrCtrExists, "pod %s is not empty and cannot be removed", pod.ID())
	}

	if err := s.idIndex.Delete(pod.ID()); err != nil {
		return errors.Wrapf(err, "error removing pod ID %s from index", pod.ID())
	}
	delete(s.pods, pod.ID())
	delete(s.podContainers, pod.ID())
	s.nameIndex.Release(pod.Name())

	if pod.config.Namespace != "" {
		nsIndex, ok := s.namespaceIndexes[pod.config.Namespace]
		if !ok {
			return errors.Wrapf(define.ErrInternal, "error retrieving index for namespace %q", pod.config.Namespace)
		}
		if err := nsIndex.idIndex.Delete(pod.ID()); err != nil {
			return errors.Wrapf(err, "error removing container %s from namespace ID index", pod.ID())
		}
		nsIndex.nameIndex.Release(pod.Name())
	}

	return nil
}

// RemovePodContainers removes all containers from a pod
// This is used to simultaneously remove a number of containers with
// many interdependencies
// Will only remove containers if no dependencies outside of the pod are present
func (s *InMemoryState) RemovePodContainers(pod *Pod) error {
	if !pod.valid {
		return errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid", pod.ID())
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return err
	}

	// Get pod containers
	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrNoSuchPod, "no pod exists in state with ID %s", pod.ID())
	}

	// Go through container dependencies. Check to see if any are outside the pod.
	for ctr := range podCtrs {
		ctrDeps, ok := s.ctrDepends[ctr]
		if ok {
			for _, dep := range ctrDeps {
				if _, ok := podCtrs[dep]; !ok {
					return errors.Wrapf(define.ErrCtrExists, "container %s has dependency %s outside of pod %s", ctr, dep, pod.ID())
				}
			}
		}
	}

	// All dependencies are OK to remove
	// Remove all containers
	s.podContainers[pod.ID()] = make(map[string]*Container)
	for _, ctr := range podCtrs {
		if err := s.idIndex.Delete(ctr.ID()); err != nil {
			return errors.Wrapf(err, "error removing container ID from index")
		}
		s.nameIndex.Release(ctr.Name())

		delete(s.containers, ctr.ID())
		delete(s.ctrDepends, ctr.ID())
	}

	return nil
}

// AddContainerToPod adds a container to the given pod, also adding it to the
// state
func (s *InMemoryState) AddContainerToPod(pod *Pod, ctr *Container) error {
	if !pod.valid {
		return errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid", pod.ID())
	}
	if !ctr.valid {
		return errors.Wrapf(define.ErrCtrRemoved, "container %s is not valid", ctr.ID())
	}

	if ctr.config.Pod != pod.ID() {
		return errors.Wrapf(define.ErrInvalidArg, "container %s is not in pod %s", ctr.ID(), pod.ID())
	}

	if ctr.config.Namespace != pod.config.Namespace {
		return errors.Wrapf(define.ErrNSMismatch, "container %s is in namespace %s and pod %s is in namespace %s",
			ctr.ID(), ctr.config.Namespace, pod.ID(), pod.config.Namespace)
	}

	if err := s.checkNSMatch(ctr.ID(), ctr.Namespace()); err != nil {
		return err
	}

	// Check networks
	for _, net := range ctr.config.Networks {
		if net == "" {
			return errors.Wrapf(define.ErrInvalidArg, "network names cannot be empty")
		}
	}

	// Check network aliases
	for network := range ctr.config.NetworkAliases {
		inNet := false
		for _, net := range ctr.config.Networks {
			if net == network {
				inNet = true
				break
			}
		}
		if !inNet {
			return errors.Wrapf(define.ErrInvalidArg, "container %s has network aliases for network %q but is not joined to network", ctr.ID(), network)
		}
	}

	// Retrieve pod containers list
	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrPodRemoved, "pod %s not found in state", pod.ID())
	}

	// Is the container already in the pod?
	if _, ok = podCtrs[ctr.ID()]; ok {
		return errors.Wrapf(define.ErrCtrExists, "container with ID %s already exists in pod %s", ctr.ID(), pod.ID())
	}

	// There are potential race conditions with this
	// But in-memory state is intended purely for testing and not production
	// use, so this should be fine.
	depCtrs := ctr.Dependencies()
	for _, depCtr := range depCtrs {
		if _, ok = s.containers[depCtr]; !ok {
			return errors.Wrapf(define.ErrNoSuchCtr, "cannot depend on nonexistent container %s", depCtr)
		}
		depCtrStruct, ok := podCtrs[depCtr]
		if !ok {
			return errors.Wrapf(define.ErrInvalidArg, "cannot depend on container %s as it is not in pod %s", depCtr, pod.ID())
		}
		if depCtrStruct.config.Namespace != ctr.config.Namespace {
			return errors.Wrapf(define.ErrNSMismatch, "container %s is in namespace %s and cannot depend on container %s in namespace %s", ctr.ID(), ctr.config.Namespace, depCtr, depCtrStruct.config.Namespace)
		}
	}

	// Add container to state
	if _, ok = s.containers[ctr.ID()]; ok {
		return errors.Wrapf(define.ErrCtrExists, "container with ID %s already exists in state", ctr.ID())
	}

	if err := s.nameIndex.Reserve(ctr.Name(), ctr.ID()); err != nil {
		return errors.Wrapf(err, "error reserving container name %s", ctr.Name())
	}

	if err := s.idIndex.Add(ctr.ID()); err != nil {
		s.nameIndex.Release(ctr.Name())
		return errors.Wrapf(err, "error releasing container ID %s", ctr.ID())
	}

	s.containers[ctr.ID()] = ctr

	// Add container to pod containers
	podCtrs[ctr.ID()] = ctr

	// If we're in a namespace, add us to that namespace's indexes
	if ctr.config.Namespace != "" {
		var nsIndex *namespaceIndex
		nsIndex, ok := s.namespaceIndexes[ctr.config.Namespace]
		if !ok {
			nsIndex = new(namespaceIndex)
			nsIndex.nameIndex = registrar.NewRegistrar()
			nsIndex.idIndex = truncindex.NewTruncIndex([]string{})
			s.namespaceIndexes[ctr.config.Namespace] = nsIndex
		}
		// Should be no errors here, the previous index adds should have caught that
		if err := nsIndex.nameIndex.Reserve(ctr.Name(), ctr.ID()); err != nil {
			return errors.Wrapf(err, "error registering container name %s", ctr.Name())
		}
		if err := nsIndex.idIndex.Add(ctr.ID()); err != nil {
			return errors.Wrapf(err, "error registering container ID %s", ctr.ID())
		}
	}

	// Add containers this container depends on
	for _, depCtr := range depCtrs {
		s.addCtrToDependsMap(ctr.ID(), depCtr)
	}

	// Add container to volume dependencies
	for _, vol := range ctr.config.NamedVolumes {
		s.addCtrToVolDependsMap(ctr.ID(), vol.Name)
	}

	// Add networks
	newNets := make([]string, 0, len(ctr.config.Networks))
	for _, net := range ctr.config.Networks {
		if net == "" {
			return define.ErrInvalidArg
		}
		newNets = append(newNets, net)
	}
	s.ctrNetworks[ctr.ID()] = newNets

	// Add network aliases
	s.ctrNetworkAliases[ctr.ID()] = ctr.config.NetworkAliases

	return nil
}

// RemoveContainerFromPod removes the given container from the given pod
// The container is also removed from the state
func (s *InMemoryState) RemoveContainerFromPod(pod *Pod, ctr *Container) error {
	if !pod.valid {
		return errors.Wrapf(define.ErrPodRemoved, "pod %s is not valid and containers cannot be removed", pod.ID())
	}
	if !ctr.valid {
		return errors.Wrapf(define.ErrCtrRemoved, "container %s is not valid and cannot be removed from the pod", ctr.ID())
	}

	if err := s.checkNSMatch(ctr.ID(), ctr.Namespace()); err != nil {
		return err
	}

	// Ensure we don't remove a container which other containers depend on
	deps, ok := s.ctrDepends[ctr.ID()]
	if ok && len(deps) != 0 {
		depsStr := strings.Join(deps, ", ")
		return errors.Wrapf(define.ErrCtrExists, "the following containers depend on container %s: %s", ctr.ID(), depsStr)
	}

	// Ensure we don't have active exec sessions
	ctrSessions := s.ctrExecSessions[ctr.ID()]
	if len(ctrSessions) > 0 {
		sessStr := strings.Join(ctrSessions, ", ")
		return errors.Wrapf(define.ErrCtrExists, "the following exec sessions are running for container %s: %s", ctr.ID(), sessStr)
	}

	// Retrieve pod containers
	podCtrs, ok := s.podContainers[pod.ID()]
	if !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrPodRemoved, "pod %s has been removed", pod.ID())
	}

	// Does the container exist?
	if _, ok := s.containers[ctr.ID()]; !ok {
		ctr.valid = false
		return errors.Wrapf(define.ErrNoSuchCtr, "container %s does not exist in state", ctr.ID())
	}

	// Is the container in the pod?
	if _, ok := podCtrs[ctr.ID()]; !ok {
		return errors.Wrapf(define.ErrNoSuchCtr, "container with ID %s not found in pod %s", ctr.ID(), pod.ID())
	}

	// Remove container from state
	if _, ok := s.containers[ctr.ID()]; !ok {
		return errors.Wrapf(define.ErrNoSuchCtr, "no container exists in state with ID %s", ctr.ID())
	}

	if err := s.idIndex.Delete(ctr.ID()); err != nil {
		return errors.Wrapf(err, "error removing container ID from index")
	}
	delete(s.containers, ctr.ID())
	s.nameIndex.Release(ctr.Name())

	// Remove the container from the pod
	delete(podCtrs, ctr.ID())

	if ctr.config.Namespace != "" {
		nsIndex, ok := s.namespaceIndexes[ctr.config.Namespace]
		if !ok {
			return errors.Wrapf(define.ErrInternal, "error retrieving index for namespace %q", ctr.config.Namespace)
		}
		if err := nsIndex.idIndex.Delete(ctr.ID()); err != nil {
			return errors.Wrapf(err, "error removing container %s from namespace ID index", ctr.ID())
		}
		nsIndex.nameIndex.Release(ctr.Name())
	}

	// Remove us from container dependencies
	depCtrs := ctr.Dependencies()
	for _, depCtr := range depCtrs {
		s.removeCtrFromDependsMap(ctr.ID(), depCtr)
	}

	// Remove our network aliases
	delete(s.ctrNetworkAliases, ctr.ID())
	delete(s.ctrNetworks, ctr.ID())

	return nil
}

// UpdatePod updates a pod in the state
// This is a no-op as there is no backing store
func (s *InMemoryState) UpdatePod(pod *Pod) error {
	if !pod.valid {
		return define.ErrPodRemoved
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return err
	}

	if _, ok := s.pods[pod.ID()]; !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrNoSuchPod, "no pod exists in state with ID %s", pod.ID())
	}

	return nil
}

// SavePod updates a pod in the state
// This is a no-op at there is no backing store
func (s *InMemoryState) SavePod(pod *Pod) error {
	if !pod.valid {
		return define.ErrPodRemoved
	}

	if err := s.checkNSMatch(pod.ID(), pod.Namespace()); err != nil {
		return err
	}

	if _, ok := s.pods[pod.ID()]; !ok {
		pod.valid = false
		return errors.Wrapf(define.ErrNoSuchPod, "no pod exists in state with ID %s", pod.ID())
	}

	return nil
}

// AllPods retrieves all pods currently in the state
func (s *InMemoryState) AllPods() ([]*Pod, error) {
	pods := make([]*Pod, 0, len(s.pods))
	for _, pod := range s.pods {
		if s.namespace != "" {
			if s.namespace == pod.config.Namespace {
				pods = append(pods, pod)
			}
		} else {
			pods = append(pods, pod)
		}
	}

	return pods, nil
}

// Internal Functions

// Add a container to the dependency mappings
func (s *InMemoryState) addCtrToDependsMap(ctrID, dependsID string) {
	if dependsID != "" {
		arr, ok := s.ctrDepends[dependsID]
		if !ok {
			// Do not have a mapping for that container yet
			s.ctrDepends[dependsID] = []string{ctrID}
		} else {
			// Have a mapping for the container
			arr = append(arr, ctrID)
			s.ctrDepends[dependsID] = arr
		}
	}
}

// Remove a container from dependency mappings
func (s *InMemoryState) removeCtrFromDependsMap(ctrID, dependsID string) {
	if dependsID != "" {
		arr, ok := s.ctrDepends[dependsID]
		if !ok {
			// Internal state seems inconsistent
			// But the dependency is definitely gone
			// So just return
			return
		}

		newArr := make([]string, 0, len(arr))

		for _, id := range arr {
			if id != ctrID {
				newArr = append(newArr, id)
			}
		}

		s.ctrDepends[dependsID] = newArr
	}
}

// Add a container to the dependency mappings for the volume
func (s *InMemoryState) addCtrToVolDependsMap(depCtrID, volName string) {
	if volName != "" {
		arr, ok := s.volumeDepends[volName]
		if !ok {
			// Do not have a mapping for that volume yet
			s.volumeDepends[volName] = []string{depCtrID}
		} else {
			// Have a mapping for the volume
			arr = append(arr, depCtrID)
			s.volumeDepends[volName] = arr
		}
	}
}

// Remove a container from the dependency mappings for the volume
func (s *InMemoryState) removeCtrFromVolDependsMap(depCtrID, volName string) {
	if volName != "" {
		arr, ok := s.volumeDepends[volName]
		if !ok {
			// Internal state seems inconsistent
			// But the dependency is definitely gone
			// So just return
			return
		}

		newArr := make([]string, 0, len(arr))

		for _, id := range arr {
			if id != depCtrID {
				newArr = append(newArr, id)
			}
		}

		s.volumeDepends[volName] = newArr
	}
}

// Check if we can access a pod or container, or if that is blocked by
// namespaces.
func (s *InMemoryState) checkNSMatch(id, ns string) error {
	if s.namespace != "" && s.namespace != ns {
		return errors.Wrapf(define.ErrNSMismatch, "cannot access %s as it is in namespace %q and we are in namespace %q",
			id, ns, s.namespace)
	}
	return nil
}