/
sqlite_state.go
2204 lines (1807 loc) · 59.8 KB
/
sqlite_state.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
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
package libpod
import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
goruntime "runtime"
"strings"
"time"
"github.com/containers/common/libnetwork/types"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/rootless"
"github.com/containers/storage"
"github.com/sirupsen/logrus"
// SQLite backend for database/sql
_ "github.com/mattn/go-sqlite3"
)
const schemaVersion = 1
// SQLiteState is a state implementation backed by a SQLite database
type SQLiteState struct {
valid bool
conn *sql.DB
runtime *Runtime
}
const (
// Deal with timezone automatically.
sqliteOptionLocation = "_loc=auto"
// Set the journal mode (https://www.sqlite.org/pragma.html#pragma_journal_mode).
sqliteOptionJournal = "&_journal=WAL"
// Force WAL mode to fsync after each transaction (https://www.sqlite.org/pragma.html#pragma_synchronous).
sqliteOptionSynchronous = "&_sync=FULL"
// Allow foreign keys (https://www.sqlite.org/pragma.html#pragma_foreign_keys).
sqliteOptionForeignKeys = "&_foreign_keys=1"
// Enable cache sharing for threads within a process
sqliteOptionSharedCache = "&cache=shared"
// Make sure that transactions happen exclusively.
sqliteOptionTXLock = "&_txlock=exclusive"
// Assembled sqlite options used when opening the database.
sqliteOptions = "db.sql?" +
sqliteOptionLocation +
sqliteOptionJournal +
sqliteOptionSynchronous +
sqliteOptionForeignKeys +
sqliteOptionSharedCache +
sqliteOptionTXLock
)
// NewSqliteState creates a new SQLite-backed state database.
func NewSqliteState(runtime *Runtime) (_ State, defErr error) {
state := new(SQLiteState)
basePath := runtime.storageConfig.GraphRoot
if runtime.storageConfig.TransientStore {
basePath = runtime.storageConfig.RunRoot
}
// c/storage is set up *after* the DB - so even though we use the c/s
// root (or, for transient, runroot) dir, we need to make the dir
// ourselves.
if err := os.MkdirAll(basePath, 0700); err != nil {
return nil, fmt.Errorf("creating root directory: %w", err)
}
conn, err := sql.Open("sqlite3", filepath.Join(basePath, sqliteOptions))
if err != nil {
return nil, fmt.Errorf("initializing sqlite database: %w", err)
}
defer func() {
if defErr != nil {
if err := conn.Close(); err != nil {
logrus.Errorf("Error closing SQLite DB connection: %v", err)
}
}
}()
// Necessary to avoid database locked errors.
conn.SetMaxOpenConns(1)
state.conn = conn
if err := state.conn.Ping(); err != nil {
return nil, fmt.Errorf("cannot connect to database: %w", err)
}
// Migrate schema (if necessary)
if err := state.migrateSchemaIfNecessary(); err != nil {
return nil, err
}
// Set up tables
if err := sqliteInitTables(state.conn); err != nil {
return nil, fmt.Errorf("creating tables: %w", err)
}
state.valid = true
state.runtime = runtime
return state, nil
}
// Close closes the state and prevents further use
func (s *SQLiteState) Close() error {
if err := s.conn.Close(); err != nil {
return err
}
s.valid = false
return nil
}
// Refresh clears container and pod states after a reboot
func (s *SQLiteState) Refresh() (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
// Retrieve all containers, pods, and volumes.
// Maps are indexed by ID (or volume name) so we know which goes where,
// and store the marshalled state JSON
ctrStates := make(map[string]string)
podStates := make(map[string]string)
volumeStates := make(map[string]string)
ctrRows, err := s.conn.Query("SELECT ID, JSON FROM ContainerState;")
if err != nil {
return fmt.Errorf("querying for container states: %w", err)
}
defer ctrRows.Close()
for ctrRows.Next() {
var (
id, stateJSON string
)
if err := ctrRows.Scan(&id, &stateJSON); err != nil {
return fmt.Errorf("scanning container state row: %w", err)
}
ctrState := new(ContainerState)
if err := json.Unmarshal([]byte(stateJSON), ctrState); err != nil {
return fmt.Errorf("unmarshalling container state json: %w", err)
}
// Refresh the state
resetContainerState(ctrState)
newJSON, err := json.Marshal(ctrState)
if err != nil {
return fmt.Errorf("marshalling container state json: %w", err)
}
ctrStates[id] = string(newJSON)
}
podRows, err := s.conn.Query("SELECT ID, JSON FROM PodState;")
if err != nil {
return fmt.Errorf("querying for pod states: %w", err)
}
defer podRows.Close()
for podRows.Next() {
var (
id, stateJSON string
)
if err := podRows.Scan(&id, &stateJSON); err != nil {
return fmt.Errorf("scanning pod state row: %w", err)
}
podState := new(podState)
if err := json.Unmarshal([]byte(stateJSON), podState); err != nil {
return fmt.Errorf("unmarshalling pod state json: %w", err)
}
// Refresh the state
resetPodState(podState)
newJSON, err := json.Marshal(podState)
if err != nil {
return fmt.Errorf("marshalling pod state json: %w", err)
}
podStates[id] = string(newJSON)
}
volRows, err := s.conn.Query("SELECT Name, JSON FROM VolumeState;")
if err != nil {
return fmt.Errorf("querying for volume states: %w", err)
}
defer volRows.Close()
for volRows.Next() {
var (
name, stateJSON string
)
if err := volRows.Scan(&name, &stateJSON); err != nil {
return fmt.Errorf("scanning volume state row: %w", err)
}
volState := new(VolumeState)
if err := json.Unmarshal([]byte(stateJSON), volState); err != nil {
return fmt.Errorf("unmarshalling volume state json: %w", err)
}
// Refresh the state
resetVolumeState(volState)
newJSON, err := json.Marshal(volState)
if err != nil {
return fmt.Errorf("marshalling volume state json: %w", err)
}
volumeStates[name] = string(newJSON)
}
// Write updated states back to DB, and perform additional maintenance
// (Remove exit codes and exec sessions)
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning refresh transaction: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to refresh database state: %v", err)
}
}
}()
for id, json := range ctrStates {
if _, err := tx.Exec("UPDATE ContainerState SET JSON=? WHERE ID=?;", json, id); err != nil {
return fmt.Errorf("updating container state: %w", err)
}
}
for id, json := range podStates {
if _, err := tx.Exec("UPDATE PodState SET JSON=? WHERE ID=?;", json, id); err != nil {
return fmt.Errorf("updating pod state: %w", err)
}
}
for name, json := range volumeStates {
if _, err := tx.Exec("UPDATE VolumeState SET JSON=? WHERE Name=?;", json, name); err != nil {
return fmt.Errorf("updating volume state: %w", err)
}
}
if _, err := tx.Exec("DELETE FROM ContainerExitCode;"); err != nil {
return fmt.Errorf("removing container exit codes: %w", err)
}
if _, err := tx.Exec("DELETE FROM ContainerExecSession;"); err != nil {
return fmt.Errorf("removing container exec sessions: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction: %w", err)
}
return nil
}
// GetDBConfig retrieves runtime configuration fields that were created when
// the database was first initialized
func (s *SQLiteState) GetDBConfig() (*DBConfig, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
cfg := new(DBConfig)
var staticDir, tmpDir, graphRoot, runRoot, graphDriver, volumeDir string
row := s.conn.QueryRow("SELECT StaticDir, TmpDir, GraphRoot, RunRoot, GraphDriver, VolumeDir FROM DBConfig;")
if err := row.Scan(&staticDir, &tmpDir, &graphRoot, &runRoot, &graphDriver, &volumeDir); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return cfg, nil
}
return nil, fmt.Errorf("retrieving DB config: %w", err)
}
cfg.LibpodRoot = staticDir
cfg.LibpodTmp = tmpDir
cfg.StorageRoot = graphRoot
cfg.StorageTmp = runRoot
cfg.GraphDriver = graphDriver
cfg.VolumePath = volumeDir
return cfg, nil
}
// ValidateDBConfig validates paths in the given runtime against the database
func (s *SQLiteState) ValidateDBConfig(runtime *Runtime) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
storeOpts, err := storage.DefaultStoreOptions(rootless.IsRootless(), rootless.GetRootlessUID())
if err != nil {
return err
}
const createRow = `
INSERT INTO DBconfig VALUES (
?, ?, ?,
?, ?, ?,
?, ?, ?
);`
var (
os, staticDir, tmpDir, graphRoot, runRoot, graphDriver, volumePath string
runtimeOS = goruntime.GOOS
runtimeStaticDir = filepath.Clean(s.runtime.config.Engine.StaticDir)
runtimeTmpDir = filepath.Clean(s.runtime.config.Engine.TmpDir)
runtimeGraphRoot = filepath.Clean(s.runtime.StorageConfig().GraphRoot)
runtimeRunRoot = filepath.Clean(s.runtime.StorageConfig().RunRoot)
runtimeGraphDriver = s.runtime.StorageConfig().GraphDriverName
runtimeVolumePath = filepath.Clean(s.runtime.config.Engine.VolumePath)
)
// Some fields may be empty, indicating they are set to the default.
// If so, grab the default from c/storage for them.
if runtimeGraphRoot == "" {
runtimeGraphRoot = storeOpts.GraphRoot
}
if runtimeRunRoot == "" {
runtimeRunRoot = storeOpts.RunRoot
}
if runtimeGraphDriver == "" {
runtimeGraphDriver = storeOpts.GraphDriverName
}
row := s.conn.QueryRow("SELECT Os, StaticDir, TmpDir, GraphRoot, RunRoot, GraphDriver, VolumeDir FROM DBConfig;")
if err := row.Scan(&os, &staticDir, &tmpDir, &graphRoot, &runRoot, &graphDriver, &volumePath); err != nil {
if errors.Is(err, sql.ErrNoRows) {
// Need to create runtime config info in DB
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning DB config transaction: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to create DB config: %v", err)
}
}
}()
if _, err := tx.Exec(createRow, 1, schemaVersion, runtimeOS,
runtimeStaticDir, runtimeTmpDir, runtimeGraphRoot,
runtimeRunRoot, runtimeGraphDriver, runtimeVolumePath); err != nil {
return fmt.Errorf("adding DB config row: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing DB config transaction: %w", err)
}
return nil
}
return fmt.Errorf("retrieving DB config: %w", err)
}
checkField := func(fieldName, dbVal, ourVal string) error {
if dbVal != ourVal {
return fmt.Errorf("database %s %q does not match our %s %q: %w", fieldName, dbVal, fieldName, ourVal, define.ErrDBBadConfig)
}
return nil
}
if err := checkField("os", os, runtimeOS); err != nil {
return err
}
if err := checkField("static dir", staticDir, runtimeStaticDir); err != nil {
return err
}
if err := checkField("tmp dir", tmpDir, runtimeTmpDir); err != nil {
return err
}
if err := checkField("graph root", graphRoot, runtimeGraphRoot); err != nil {
return err
}
if err := checkField("run root", runRoot, runtimeRunRoot); err != nil {
return err
}
if err := checkField("graph driver", graphDriver, runtimeGraphDriver); err != nil {
return err
}
if err := checkField("volume path", volumePath, runtimeVolumePath); err != nil {
return err
}
return nil
}
// GetContainerName returns the name of the container associated with a given
// ID. Returns ErrNoSuchCtr if the ID does not exist.
func (s *SQLiteState) GetContainerName(id string) (string, error) {
if id == "" {
return "", define.ErrEmptyID
}
if !s.valid {
return "", define.ErrDBClosed
}
var name string
row := s.conn.QueryRow("SELECT Name FROM ContainerConfig WHERE ID=?;", id)
if err := row.Scan(&name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", define.ErrNoSuchCtr
}
return "", fmt.Errorf("looking up container %s name: %w", id, err)
}
return name, nil
}
// GetPodName returns the name of the pod associated with a given ID.
// Returns ErrNoSuchPod if the ID does not exist.
func (s *SQLiteState) GetPodName(id string) (string, error) {
if id == "" {
return "", define.ErrEmptyID
}
if !s.valid {
return "", define.ErrDBClosed
}
var name string
row := s.conn.QueryRow("SELECT Name FROM PodConfig WHERE ID=?;", id)
if err := row.Scan(&name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", define.ErrNoSuchPod
}
return "", fmt.Errorf("looking up pod %s name: %w", id, err)
}
return name, nil
}
// Container retrieves a single container from the state by its full ID
func (s *SQLiteState) Container(id string) (*Container, error) {
if id == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
ctrConfig, err := s.getCtrConfig(id)
if err != nil {
return nil, err
}
ctr := new(Container)
ctr.config = ctrConfig
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
return ctr, nil
}
// LookupContainerID retrieves a container ID from the state by full or unique
// partial ID or name
func (s *SQLiteState) LookupContainerID(idOrName string) (string, error) {
if idOrName == "" {
return "", define.ErrEmptyID
}
if !s.valid {
return "", define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT ID FROM ContainerConfig WHERE ContainerConfig.Name=? OR (ContainerConfig.ID LIKE ?);", idOrName, idOrName+"%")
if err != nil {
return "", fmt.Errorf("looking up container %q in database: %w", idOrName, err)
}
defer rows.Close()
var id string
foundResult := false
for rows.Next() {
if foundResult {
return "", fmt.Errorf("more than one result for container %q: %w", idOrName, define.ErrCtrExists)
}
if err := rows.Scan(&id); err != nil {
return "", fmt.Errorf("retrieving container %q ID from database: %w", idOrName, err)
}
foundResult = true
}
if !foundResult {
return "", define.ErrNoSuchCtr
}
return id, nil
}
// LookupContainer retrieves a container from the state by full or unique
// partial ID or name
func (s *SQLiteState) LookupContainer(idOrName string) (*Container, error) {
if idOrName == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT JSON FROM ContainerConfig WHERE ContainerConfig.Name=? OR (ContainerConfig.ID LIKE ?);", idOrName, idOrName+"%")
if err != nil {
return nil, fmt.Errorf("looking up container %q in database: %w", idOrName, err)
}
defer rows.Close()
var rawJSON string
foundResult := false
for rows.Next() {
if foundResult {
return nil, fmt.Errorf("more than one result for container %q: %w", idOrName, define.ErrCtrExists)
}
if err := rows.Scan(&rawJSON); err != nil {
return nil, fmt.Errorf("retrieving container %q ID from database: %w", idOrName, err)
}
foundResult = true
}
if !foundResult {
return nil, fmt.Errorf("no container with name or ID %q found: %w", idOrName, define.ErrNoSuchCtr)
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(rawJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config JSON: %w", err)
}
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
return ctr, nil
}
// HasContainer checks if a container is present in the state
func (s *SQLiteState) HasContainer(id string) (bool, error) {
if id == "" {
return false, define.ErrEmptyID
}
if !s.valid {
return false, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT 1 FROM ContainerConfig WHERE ID=?;", id)
var check int
if err := row.Scan(&check); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, fmt.Errorf("looking up container %s in database: %w", id, err)
} else if check != 1 {
return false, fmt.Errorf("check digit for container %s lookup incorrect: %w", id, define.ErrInternal)
}
return true, nil
}
// AddContainer adds a container to the state
// The container being added cannot belong to a pod
func (s *SQLiteState) AddContainer(ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
if ctr.config.Pod != "" {
return fmt.Errorf("cannot add a container that belongs to a pod with AddContainer - use AddContainerToPod: %w", define.ErrInvalidArg)
}
return s.addContainer(ctr)
}
// RemoveContainer removes a container from the state
// Only removes containers not in pods - for containers that are a member of a
// pod, use RemoveContainerFromPod
func (s *SQLiteState) RemoveContainer(ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if ctr.config.Pod != "" {
return fmt.Errorf("container %s is part of a pod, use RemoveContainerFromPod instead: %w", ctr.ID(), define.ErrPodExists)
}
return s.removeContainer(ctr)
}
// UpdateContainer updates a container's state from the database
func (s *SQLiteState) UpdateContainer(ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
row := s.conn.QueryRow("SELECT JSON FROM ContainerState WHERE ID=?;", ctr.ID())
var rawJSON string
if err := row.Scan(&rawJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
// Container was removed
ctr.valid = false
return fmt.Errorf("no container with ID %s found in database: %w", ctr.ID(), define.ErrNoSuchCtr)
}
}
newState := new(ContainerState)
if err := json.Unmarshal([]byte(rawJSON), newState); err != nil {
return fmt.Errorf("unmarshalling container %s state JSON: %w", ctr.ID(), err)
}
ctr.state = newState
return nil
}
// SaveContainer saves a container's current state in the database
func (s *SQLiteState) SaveContainer(ctr *Container) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
stateJSON, err := json.Marshal(ctr.state)
if err != nil {
return fmt.Errorf("marshalling container %s state JSON: %w", ctr.ID(), err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning container %s save transaction: %w", ctr.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to save container %s state: %v", ctr.ID(), err)
}
}
}()
result, err := tx.Exec("UPDATE ContainerState SET JSON=? WHERE ID=?;", stateJSON, ctr.ID())
if err != nil {
return fmt.Errorf("writing container %s state: %w", ctr.ID(), err)
}
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving container %s save rows affected: %w", ctr.ID(), err)
}
if rows == 0 {
ctr.valid = false
return define.ErrNoSuchCtr
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing container %s state: %w", ctr.ID(), err)
}
return nil
}
// ContainerInUse checks if other containers depend on the given container
// It returns a slice of the IDs of the containers depending on the given
// container. If the slice is empty, no containers depend on the given container
func (s *SQLiteState) ContainerInUse(ctr *Container) ([]string, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !ctr.valid {
return nil, define.ErrCtrRemoved
}
rows, err := s.conn.Query("SELECT ID FROM ContainerDependency WHERE DependencyID=?;", ctr.ID())
if err != nil {
return nil, fmt.Errorf("retrieving containers that depend on container %s: %w", ctr.ID(), err)
}
defer rows.Close()
deps := []string{}
for rows.Next() {
var dep string
if err := rows.Scan(&dep); err != nil {
return nil, fmt.Errorf("reading containers that depend on %s: %w", ctr.ID(), err)
}
deps = append(deps, dep)
}
return deps, nil
}
// AllContainers retrieves all the containers in the database
// If `loadState` is set, the containers' state will be loaded as well.
func (s *SQLiteState) AllContainers(loadState bool) ([]*Container, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
ctrs := []*Container{}
if loadState {
rows, err := s.conn.Query("SELECT ContainerConfig.JSON, ContainerState.JSON AS StateJSON FROM ContainerConfig INNER JOIN ContainerState ON ContainerConfig.ID = ContainerState.ID;")
if err != nil {
return nil, fmt.Errorf("retrieving all containers from database: %w", err)
}
defer rows.Close()
for rows.Next() {
var configJSON, stateJSON string
if err := rows.Scan(&configJSON, &stateJSON); err != nil {
return nil, fmt.Errorf("scanning container from database: %w", err)
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(configJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config: %w", err)
}
if err := json.Unmarshal([]byte(stateJSON), ctr.state); err != nil {
return nil, fmt.Errorf("unmarshalling container %s state: %w", ctr.ID(), err)
}
ctrs = append(ctrs, ctr)
}
} else {
rows, err := s.conn.Query("SELECT JSON FROM ContainerConfig;")
if err != nil {
return nil, fmt.Errorf("retrieving all containers from database: %w", err)
}
defer rows.Close()
for rows.Next() {
var rawJSON string
if err := rows.Scan(&rawJSON); err != nil {
return nil, fmt.Errorf("scanning container from database: %w", err)
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(rawJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config: %w", err)
}
ctrs = append(ctrs, ctr)
}
}
for _, ctr := range ctrs {
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
}
return ctrs, nil
}
// GetNetworks returns the networks this container is a part of.
func (s *SQLiteState) GetNetworks(ctr *Container) (map[string]types.PerNetworkOptions, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !ctr.valid {
return nil, define.ErrCtrRemoved
}
// if the network mode is not bridge return no networks
if !ctr.config.NetMode.IsBridge() {
return nil, nil
}
cfg, err := s.getCtrConfig(ctr.ID())
if err != nil {
if errors.Is(err, define.ErrNoSuchCtr) {
ctr.valid = false
}
return nil, err
}
return cfg.Networks, nil
}
// NetworkConnect adds the given container to the given network. If aliases are
// specified, those will be added to the given network.
func (s *SQLiteState) NetworkConnect(ctr *Container, network string, opts types.PerNetworkOptions) error {
return s.networkModify(ctr, network, opts, true, false)
}
// NetworkModify will allow you to set new options on an existing connected network
func (s *SQLiteState) NetworkModify(ctr *Container, network string, opts types.PerNetworkOptions) error {
return s.networkModify(ctr, network, opts, false, false)
}
// NetworkDisconnect disconnects the container from the given network, also
// removing any aliases in the network.
func (s *SQLiteState) NetworkDisconnect(ctr *Container, network string) error {
return s.networkModify(ctr, network, types.PerNetworkOptions{}, false, true)
}
// GetContainerConfig returns a container config from the database by full ID
func (s *SQLiteState) GetContainerConfig(id string) (*ContainerConfig, error) {
if len(id) == 0 {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
return s.getCtrConfig(id)
}
// AddContainerExitCode adds the exit code for the specified container to the database.
func (s *SQLiteState) AddContainerExitCode(id string, exitCode int32) (defErr error) {
if len(id) == 0 {
return define.ErrEmptyID
}
if !s.valid {
return define.ErrDBClosed
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to add exit code: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to add exit code: %v", err)
}
}
}()
if _, err := tx.Exec("INSERT OR REPLACE INTO ContainerExitCode VALUES (?, ?, ?);", id, time.Now().Unix(), exitCode); err != nil {
return fmt.Errorf("adding container %s exit code %d: %w", id, exitCode, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to add exit code: %w", err)
}
return nil
}
// GetContainerExitCode returns the exit code for the specified container.
func (s *SQLiteState) GetContainerExitCode(id string) (int32, error) {
if len(id) == 0 {
return -1, define.ErrEmptyID
}
if !s.valid {
return -1, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT ExitCode FROM ContainerExitCode WHERE ID=?;", id)
var exitCode int32
if err := row.Scan(&exitCode); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return -1, fmt.Errorf("getting exit code of container %s from DB: %w", id, define.ErrNoSuchExitCode)
}
return -1, fmt.Errorf("scanning exit code of container %s: %w", id, err)
}
return exitCode, nil
}
// GetContainerExitCodeTimeStamp returns the time stamp when the exit code of
// the specified container was added to the database.
func (s *SQLiteState) GetContainerExitCodeTimeStamp(id string) (*time.Time, error) {
if len(id) == 0 {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT Timestamp FROM ContainerExitCode WHERE ID=?;", id)
var timestamp int64
if err := row.Scan(×tamp); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("getting timestamp for exit code of container %s from DB: %w", id, define.ErrNoSuchExitCode)
}
return nil, fmt.Errorf("scanning exit timestamp of container %s: %w", id, err)
}
result := time.Unix(timestamp, 0)
return &result, nil
}
// PruneExitCodes removes exit codes older than 5 minutes.
func (s *SQLiteState) PruneContainerExitCodes() (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
fiveMinsAgo := time.Now().Add(-5 * time.Minute).Unix()
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to remove old timestamps: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove old timestamps: %v", err)
}
}
}()
if _, err := tx.Exec("DELETE FROM ContainerExitCode WHERE (Timestamp <= ?);", fiveMinsAgo); err != nil {
return fmt.Errorf("removing exit codes with timestamps older than 5 minutes: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to remove old timestamps: %w", err)
}
return nil
}
// AddExecSession adds an exec session to the state.
func (s *SQLiteState) AddExecSession(ctr *Container, session *ExecSession) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning container %s exec session %s add transaction: %w", ctr.ID(), session.Id, err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to add container %s exec session %s: %v", ctr.ID(), session.Id, err)
}
}
}()
if _, err := tx.Exec("INSERT INTO ContainerExecSession VALUES (?, ?);", session.Id, ctr.ID()); err != nil {
return fmt.Errorf("adding container %s exec session %s to database: %w", ctr.ID(), session.Id, err)
}