Repository navigation
Expand file tree
/
Copy pathDobbyManager.cpp
More file actions
3800 lines (3350 loc) · 133 KB
/
Copy pathDobbyManager.cpp
File metadata and controls
3800 lines (3350 loc) · 133 KB
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
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2016 Sky UK
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.
*/
/*
* File: DobbyManager.cpp
*
*/
#include "DobbyManager.h"
#include "DobbyContainer.h"
#include "DobbyEnv.h"
#include "DobbyLegacyPluginManager.h"
#include "DobbyRdkPluginManager.h"
#include "DobbyRunC.h"
#include "DobbyRootfs.h"
#include "DobbyBundleConfig.h"
#include "DobbyBundle.h"
#include "DobbyStartState.h"
#include "DobbyStream.h"
#include "DobbyStats.h"
#include "DobbyFileAccessFixer.h"
#include "DobbyAsync.h"
#include "DobbyHibernate.h"
#if defined(LEGACY_COMPONENTS)
# include "DobbySpecConfig.h"
#endif // defined(LEGACY_COMPONENTS)
#include <DobbyProtocol.h>
#include <Logging.h>
#include <Tracing.h>
#include <rt_dobby_schema.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <fstream>
#include <unordered_map>
#include <chrono>
#include <thread>
#include <sys/syscall.h>
#ifdef USE_OPEN_TREE_FOR_DYNAMIC_MOUNTS
# include <linux/mount.h>
#endif
#include <linux/types.h>
#if defined(USE_SYSTEMD)
#include <systemd/sd-daemon.h>
#endif
// The following are supported by all sky kernels, but some toolchains (ST)
// aren't built against the correct kernel headers, hence need to define these
#ifndef PR_SET_CHILD_SUBREAPER
# define PR_SET_CHILD_SUBREAPER 36
#endif
#ifndef PR_GET_CHILD_SUBREAPER
# define PR_GET_CHILD_SUBREAPER 37
#endif
// Can override the plugin path at build time by setting -DPLUGIN_PATH=/path/to/plugins/
#ifndef PLUGIN_PATH
#define PLUGIN_PATH "/usr/lib/plugins/dobby"
#endif
DobbyManager::DobbyManager(const std::shared_ptr<IDobbyEnv> &env,
const std::shared_ptr<IDobbyUtils> &utils,
const std::shared_ptr<IDobbyIPCUtils> &ipcUtils,
const std::shared_ptr<const IDobbySettings> &settings,
const ContainerStartedFunc &containerStartedCb,
const ContainerStoppedFunc &containerStoppedCb,
const ContainerHibernatedFunc& containerHibernatedCb,
const ContainerHibernatedFunc& containerAwokenCb)
: mContainerStartedCb(containerStartedCb)
, mContainerStoppedCb(containerStoppedCb)
, mContainerHibernatedCb(containerHibernatedCb)
, mContainerAwokenCb(containerAwokenCb)
, mEnvironment(env)
, mUtilities(utils)
, mIPCUtilities(ipcUtils)
, mSettings(settings)
, mLogger(std::make_unique<DobbyLogger>(settings))
, mRunc(std::make_unique<DobbyRunC>(utils, settings))
, mRuncMonitorTerminate(false)
, mCleanupTaskTimerId(0)
#if defined(LEGACY_COMPONENTS)
, mLegacyPlugins(new DobbyLegacyPluginManager(env, utils))
#endif // defined(LEGACY_COMPONENTS)
{
AI_LOG_FN_ENTRY();
setupSystem();
setupWorkspace(env);
cleanupContainers();
startRuncMonitorThread();
AI_LOG_FN_EXIT();
}
DobbyManager::~DobbyManager()
{
// Intentially stop monitoring for container termination before cleaning up
// so we can force container cleanup to be synchronous and deterministic
stopRuncMonitorThread();
cleanupContainersShutdown();
if (mCleanupTaskTimerId > 0)
{
mUtilities->cancelTimer(mCleanupTaskTimerId);
}
}
// -----------------------------------------------------------------------------
/**
* @brief Configures the linux system for enabling features needed for runc
*
* This method is equivalent to performing the following on the cmdline
*
* ulimit -c unlimited
*
* echo "1" > /proc/sys/net/ipv4/ip_forward
*
*
* See the comments in the code for why each step is needed
*/
void DobbyManager::setupSystem()
{
AI_LOG_FN_ENTRY();
// make us a subreaper SUBREAPER!! which means we get the SIGCHLD signal
// for the fork/exec descendants (i.e. runc cmdline tool) we've spawned
if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0)
{
AI_LOG_SYS_ERROR(errno, "failed to set PR_SET_CHILD_SUBREAPER");
}
// set the core dump ulimit to un-limited, this is needed to get core
// dumps from apps within containers ... and for if this daemon dies.
// note that is can be overridden by the 'rlimits' field in the OCI
// json spec file
struct rlimit coreLimit;
coreLimit.rlim_cur = coreLimit.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &coreLimit) != 0)
{
AI_LOG_SYS_ERROR(errno, "failed to set RLIMIT_CORE");
}
// globally enable ipv4 forwarding, this is what libvirt does and it
// seems selectively enabling forwarding on only the interfaces we
// control doesn't seem to work (intermittently)
if (!mUtilities->writeTextFile("/proc/sys/net/ipv4/ip_forward", "1\n",
O_TRUNC | O_WRONLY, 0))
{
AI_LOG_FATAL("failed to write to ip_forward file, you may have issues"
" with container networking");
}
// finally cisco, in their infinite hardening wisdom, keep monkeying around
// with access permissions, so here we reset everything to sensible values
DobbyFileAccessFixer fileFixer;
fileFixer.fixIt();
AI_LOG_FN_EXIT();
}
// -----------------------------------------------------------------------------
/**
* @brief Configures the workspace directory
*
* The supplied path will be created if it doesn't exist. It should be on
* writable mount point with an adequate amount of space available.
*
* The workspace is where bundle directories are created for each container
* and also where various temporary files are created. However the runc
* tool doesn't use it and log files are written to /var/log/...
*
* TODO: show tree of workspace layout
*
* @param[in] path The absolute path to the workspace
*/
void DobbyManager::setupWorkspace(const std::shared_ptr<IDobbyEnv> &env)
{
AI_LOG_FN_ENTRY();
// the workspace path in the environment is the top level tmpfs mount, we
// want to create a subdirectory under that for all dobby stuff
std::string path = env->workspaceMountPath();
path += "/dobby";
if ((mkdir(path.c_str(), 0755) != 0) && (errno != EEXIST))
{
AI_LOG_SYS_FATAL_EXIT(errno, "failed to create workspace dir '%s'",
path.c_str());
return;
}
else if (chmod(path.c_str(), 0755) != 0)
{
AI_LOG_SYS_WARN(errno, "failed to set the workspace mode to 0755");
}
// create a directory for the bundles
path += "/bundles";
if ((mkdir(path.c_str(), 0755) != 0) && (errno != EEXIST))
{
AI_LOG_SYS_ERROR(errno, "failed to make '%s' directory", path.c_str());
}
else if (chmod(path.c_str(), 0755) != 0)
{
AI_LOG_SYS_WARN(errno, "failed to set 0755 mode on '%s' dir",
path.c_str());
}
AI_LOG_FN_EXIT();
}
/**
* @brief Cleans up a container that is in an unknown state - used at Dobby startup to ensure the box
* is in a clean state with no leftover containers
*
* @param[in] container Container info returned by crun list command
*/
bool DobbyManager::cleanupContainer(const DobbyRunC::ContainerListItem &container)
{
DobbyRunC::ContainerStatus status = container.status;
if (status == DobbyRunC::ContainerStatus::Paused ||
status == DobbyRunC::ContainerStatus::Pausing ||
status == DobbyRunC::ContainerStatus::Running)
{
/*
There have been scenarios where SIGKILL doesn't work. Retry killing the container a
few times. If the container is still running, then we can't attempt to destroy
it (destroy will just hang forever)
Seems to occur when a process gets stuck in an uninterruptible sleep
*/
const int maxRetry = 4;
int retryCount = 1;
auto retryTime = std::chrono::milliseconds(50);
while (retryCount <= maxRetry)
{
AI_LOG_INFO("attempting to kill old container '%s' (attempt %d/%d)", container.id.c_str(), retryCount, maxRetry);
mRunc->killCont(container.id, SIGKILL, true);
// Did we actually kill it? Give it some time, then check the status
std::this_thread::sleep_for(retryTime * retryCount);
DobbyRunC::ContainerStatus state = mRunc->state(container.id);
if (state != DobbyRunC::ContainerStatus::Running)
{
// Managed to kill the container, mark it as stopped so we destroy it next
AI_LOG_INFO("Successfully killed old container '%s", container.id.c_str());
status = DobbyRunC::ContainerStatus::Stopped;
// Quit the retry loop
break;
}
AI_LOG_WARN("Failed to kill container '%s' (attempt %d/%d)", container.id.c_str(), retryCount, maxRetry);
if (retryCount >= maxRetry)
{
// We can't kill the container. This will leave dobby in a potentially bad state since there is a container
// running that is stuck somewhere between life and death. However this is better than the whole daemon
// locking up completely (and being killed by watchdog repeatedly)
return false;
}
retryCount++;
}
}
if (status == DobbyRunC::ContainerStatus::Created ||
status == DobbyRunC::ContainerStatus::Stopped ||
status == DobbyRunC::ContainerStatus::Unknown)
{
// Attempt to run the postHalt hook to clean up anything done by the container plugins
// Since the bundle may not exist, load the config file from the crun copy
char configPath[PATH_MAX];
snprintf(configPath, sizeof(configPath), "%s/%s/config.json", mRunc->getWorkingDir().c_str(), container.id.c_str());
parser_error err = nullptr;
auto containerConfig = std::shared_ptr<rt_dobby_schema>(rt_dobby_schema_parse_file(configPath, nullptr, &err), free_rt_dobby_schema);
if (containerConfig.get() == nullptr || err)
{
AI_LOG_WARN("Couldn't load container confirm from %s, cannot run postHalt hook for %s", configPath, container.id.c_str());
if (err)
{
free(err);
err = nullptr;
}
}
else
{
// Got a good config
// Work out the rootfs path (if it exists)
std::string rootfsDirPath;
if (containerConfig->root->path[0] == '/')
{
rootfsDirPath = std::string(containerConfig->root->path) + "/";
}
else
{
// relative path to rootfs
rootfsDirPath = std::string(container.bundlePath) + "/" + containerConfig->root->path + "/";
}
if (access(rootfsDirPath.c_str(), R_OK) != 0)
{
AI_LOG_WARN("Cannot access container rootfs @ '%s' - postHalt hooks may fail", rootfsDirPath.c_str());
}
auto rdkPluginUtils = std::make_shared<DobbyRdkPluginUtils>(containerConfig, container.id.str());
auto rdkPluginManager = std::make_shared<DobbyRdkPluginManager>(containerConfig, rootfsDirPath.c_str(), PLUGIN_PATH, rdkPluginUtils);
// Attempt to run the postHalt hook for the container
if (!rdkPluginManager->runPlugins(IDobbyRdkPlugin::HintFlags::PostHaltFlag, 4000))
{
AI_LOG_ERROR("Failure in postHalt hook");
}
}
// Now attempt to actually delete the container
std::shared_ptr<DobbyBufferStream> buffer = std::make_shared<DobbyBufferStream>();
AI_LOG_INFO("attempting to destroy old container '%s'", container.id.c_str());
// Dobby will try a normal delete, then a force delete
// Force delete may hang on old crun versions if process in uninterruptible sleep: https://github.com/containers/crun/issues/868
if (!mRunc->destroy(container.id, buffer))
{
AI_LOG_ERROR_EXIT("Could not destroy container %s with error %s", container.id.c_str(), buffer->getBuffer().data());
return false;
}
else
{
AI_LOG_INFO("Successfully destroyed old container '%s", container.id.c_str());
}
}
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Gets a list of running containers and tries to kill and delete them.
*
* Will run the postHalt hook for the container where possible (some hooks might
* fail as the container bundle cannot be guaranteed to exist at this time)
*
* Designed as a crash-recovery mechanism as we should clean up all our containers
* if the daemon shut down gracefully
*
*/
void DobbyManager::cleanupContainers()
{
AI_LOG_FN_ENTRY();
// Do a manual check for leftover containers ourselves to improve startup performance
// For consistency, we should really call out to crun list here, but in some scenarios
// that can fail. Since we're only interested in finding out if the container is running
// or stopped, do it ourselves
const std::string workDir = mRunc->getWorkingDir();
DIR *d = opendir(workDir.c_str());
if (!d)
{
AI_LOG_SYS_WARN(errno, "Could not access %s dir", workDir.c_str());
}
int count = 0;
struct dirent *entry = {};
while ((entry = readdir(d)) != nullptr)
{
// Skip "." and ".." dirs
if ((entry->d_name[0] == '.') && ((entry->d_name[1] == '\0') ||
((entry->d_name[1] == '.') && (entry->d_name[2] == '\0'))))
{
continue;
}
if (entry->d_type == DT_DIR)
{
count++;
}
}
closedir(d);
// No old containers - return
if (count == 0)
{
return;
}
AI_LOG_INFO("%d old containers found - attempting to clean up", count);
/* We've got some old containers, try to clean them up
There are a few important caveats here since we are likely recovering from a crash situation at this point.
The main consideration is that we can't guarantee the container bundle will actually still exist on disk. We'll
attempt to run the postHalt and postStop plugins, but they might throw errors if they try to do
anything with the rootfs. */
int stuckContainerCount = 0;
const std::list<DobbyRunC::ContainerListItem> containers = mRunc->list();
for (const auto &container : containers)
{
#if defined(USE_SYSTEMD)
// Wag the watchdog each time we go round here, since we haven't started the watchdog wagging thread
// yet and if we have many containers this could take some time...
sd_notify(0, "WATCHDOG=1");
#endif
AI_LOG_WARN("found old container '%s' with pid %d in state %d, cleaning it up",
container.id.c_str(), container.pid, int(container.status));
bool cleanupSuccess = cleanupContainer(container);
// If the container is stuck (i.e. we can't kill or destroy it), then
// add it in the Unknown state so we can't attempt to start a container with
// the same ID again
if (!cleanupSuccess)
{
AI_LOG_FATAL("Failed to clean up container '%s'. We may be unable to launch app until next reboot!", container.id.c_str());
// Track the container so we can't start a container with the same name again
// A background thread will handle cleaning it up if/when it eventually dies
stuckContainerCount++;
std::unique_ptr<DobbyContainer> dobbyContainer(new DobbyContainer(nullptr, nullptr, nullptr));
dobbyContainer->state = DobbyContainer::State::Unknown;
dobbyContainer->containerPid = container.pid;
mContainers.emplace(container.id, std::move(dobbyContainer));
}
}
if (stuckContainerCount > 0)
{
// Try to clean up the container later so the user can restart the app again
AI_LOG_INFO("%d containers are stuck and can't be destroyed. Starting regular cleanup job", stuckContainerCount);
mCleanupTaskTimerId = mUtilities->startTimer(std::chrono::seconds(10),
false,
std::bind(&DobbyManager::invalidContainerCleanupTask, this));
}
AI_LOG_FN_EXIT();
}
/**
* @brief Gracefully stops and cleans up any running containers. Will emit the container stop
* event when a container stops.
*
* Designed to be called when the daemon is going down (e.g. SIGTERM)
*
*/
void DobbyManager::cleanupContainersShutdown()
{
AI_LOG_FN_ENTRY();
std::unique_lock<std::mutex> locker(mLock);
AI_LOG_INFO("Dobby shutting down - stopping %lu containers", mContainers.size());
auto it = mContainers.begin();
while (it != mContainers.end())
{
if ((it->second->state == DobbyContainer::State::Running) || \
(it->second->state == DobbyContainer::State::Paused) || \
(it->second->state == DobbyContainer::State::Hibernating) || \
(it->second->state == DobbyContainer::State::Hibernated) || \
(it->second->state == DobbyContainer::State::Awakening))
{
ContainerId id = it->first;
int32_t descriptor = it->second->descriptor;
AI_LOG_INFO("Stopping container %s", id.c_str());
++it;
locker.unlock();
// By calling the "proper" stop method here, any listening services will be
// notified of the container stop event
bool stopSuccess = stopContainer(descriptor, false);
locker.lock();
auto eraseIt = mContainers.find(id);
if (eraseIt == mContainers.end())
continue;
if (!stopSuccess)
{
// As DobbyRunC::killCont already handles problem of masked SIGTERM in
// case we failed to stop it means that it tried to SIGKILL too, so
// container must be in uninterrable sleep and we cannot do anything
// Remove it container from the list (even though it wasn't clean up)
// to avoid repeating indefinitely. It will be cleaned on boot-up
mContainers.erase(eraseIt);
AI_LOG_ERROR("Failed to stop container %s. Will attempt to clean up at daemon restart", id.c_str());
}
else
{
// This would normally be done async by the runc monitor thread, but we're
// shutting down so we want to run synchronously
handleContainerTerminate(eraseIt->first, eraseIt->second, 0);
mContainers.erase(eraseIt);
}
}
else
{
++it;
}
}
AI_LOG_FN_EXIT();
}
/**
* @brief Get the instance of the logging plugin for the current container (if
* one is loaded)
*
*/
std::shared_ptr<IDobbyRdkLoggingPlugin> DobbyManager::GetContainerLogger(const std::unique_ptr<DobbyContainer> &container)
{
if (container->rdkPluginManager)
{
auto loggingPlugin = container->rdkPluginManager->getContainerLogger();
if (!loggingPlugin)
{
AI_LOG_WARN("No logging plugin is specified in the container config"
" - container logs will not be handled");
}
return loggingPlugin;
}
return nullptr;
}
/**
* @brief Create and start a container. Set up and capture logs from all
* container hooks if an RDK logging plugin is loaded.
*
* If container->customConfigFilePath is set, the container will use that
* config.json file instead of the onein the bundle
*
* @param[in] id id of the container
* @param[in] container The object that wraps up the container details.
* @param[in] files List of fds to preserve inside the container
*/
bool DobbyManager::createAndStart(const ContainerId &id,
const std::unique_ptr<DobbyContainer> &container,
const std::list<int> &files)
{
AI_LOG_FN_ENTRY();
// Create the container, but don't start it yet
auto loggingPlugin = GetContainerLogger(container);
std::shared_ptr<DobbyBufferStream> createBuffer = std::make_shared<DobbyBufferStream>();
auto pids = mRunc->create(id,
container->bundle,
createBuffer,
files,
container->customConfigFilePath);
// First PID = crun
// Second PID = DobbyInit (same as container.pid)
if (pids.second < 0)
{
AI_LOG_ERROR("Failed to create container - see crun log for more details");
// Dump the runtime output to a new file even if the container failed to start
if (loggingPlugin)
{
mLogger->DumpBuffer(createBuffer->getMemFd(), -1, std::move(loggingPlugin));
}
container->containerPid = -1;
return false;
}
container->containerPid = pids.second;
#if defined(LEGACY_COMPONENTS)
// Run the legacy Dobby PreStart hooks (to be removed once RDK plugin work is complete)
if (!onPreStartHook(id, container))
{
AI_LOG_ERROR("failure in one of the PreStart hooks");
return false;
}
#endif //defined(LEGACY_COMPONENTS)
// if we've survived to this point then the container is pretty much
// already to go, so move it's state to Running
container->state = DobbyContainer::State::Running;
// Attempt to start the container
std::shared_ptr<DobbyBufferStream> startBuffer = std::make_shared<DobbyBufferStream>();
bool started = mRunc->start(id, startBuffer);
if (!started)
{
AI_LOG_ERROR("Failed to start container '%s'", id.c_str());
}
// Dump the hook logs and start the main logging thread if started. Have to wait until
// now since the startContainer logs are tied to the create process
if (loggingPlugin)
{
// Dump the contents of the buffers even if the container didn't start
mLogger->DumpBuffer(createBuffer->getMemFd(), container->containerPid, loggingPlugin);
mLogger->DumpBuffer(startBuffer->getMemFd(), container->containerPid, loggingPlugin);
if (started)
{
mLogger->StartContainerLogging(id.str(), pids.first, pids.second, std::move(loggingPlugin));
}
}
AI_LOG_FN_EXIT();
return started;
}
/**
* @brief Updates the container config with custom options provided by the start
* command
*
* @param[in] command The custom command to run instead of the args in the
* config file
* @param[in] displaySocket Path to a westeros socket to mount into the container
* @param[in] envVars Custom env vars to add to the container
*
* @return true if modifications were made, false if no changes made
*/
bool DobbyManager::customiseConfig(const std::shared_ptr<DobbyConfig> &config,
const std::string &command,
const std::string &displaySocket,
const std::vector<std::string>& envVars)
{
AI_LOG_FN_ENTRY();
bool changesMade = false;
// If we've been given a custom command, replace args[] with the custom command
if (!command.empty())
{
config->changeProcessArgs(command);
changesMade = true;
}
// If we've been given a displaySocket, then add the mount it into the container
// Will always be mounted to /tmp/westeros in container
if (!displaySocket.empty())
{
config->addWesterosMount(displaySocket);
changesMade = true;
}
// Add any extra environment variables
if (envVars.size() > 0)
{
for (const auto &var : envVars)
{
config->addEnvironmentVar(var);
}
changesMade = true;
}
if (shouldEnableSTrace(config))
{
// Start container with strace.
// It should be done in customiseConfig so that change in strace params
// would not require to reinstall container bundle.
config->enableSTrace(mSettings->straceSettings().logsDir);
changesMade = true;
}
AI_LOG_FN_EXIT();
return changesMade;
}
// -----------------------------------------------------------------------------
/**
* @brief Creates and attempts to start the container.
*
*
* @param[in] id The id string for the container.
* @param[in] container The object that wraps up the container details.
* @param[in] startState The start state object of the files.
* @param[in] command The custom command to run instead of the args in the
* config file
*
* @return true on success, false on failure.
*/
bool DobbyManager::createAndStartContainer(const ContainerId &id,
const std::unique_ptr<DobbyContainer> &container,
const std::list<int> &files)
{
AI_LOG_FN_ENTRY();
if (createAndStart(id, container, files))
{
AI_LOG_INFO("container '%s' started, controller process pid %d",
id.c_str(), container->containerPid);
#if defined(LEGACY_COMPONENTS)
// call the postStart hook, don't care about the return code
// for now
onPostStartHook(id, container);
#endif //defined(LEGACY_COMPONENTS)
// signal that the container has started
if (mContainerStartedCb)
{
mContainerStartedCb(container->descriptor, id);
}
AI_LOG_FN_EXIT();
return true;
}
// If the PID is < 0, something went wrong during container creation and
// start was never attempted
if (container->containerPid < 0)
{
AI_LOG_WARN("Something went wrong when creating '%s'", id.c_str());
}
else
{
// PID > 0 so container was created but failed to start
AI_LOG_WARN("Something went wrong when starting '%s', cleaning up", id.c_str());
// Something went wrong during container start, clean up everything
// kill the container created
if (!mRunc->killCont(id, SIGKILL))
{
AI_LOG_ERROR("failed to kill (non-running) container for '%s'",
id.c_str());
}
// wait for the half-started container to terminate
if (waitpid(container->containerPid, nullptr, 0) < 0)
{
AI_LOG_SYS_ERROR(errno, "error waiting for the container '%s' to terminate",
id.c_str());
}
#if defined(LEGACY_COMPONENTS)
// either the container failed to start, or one of the preStart hooks
// failed, either way we want to call the postStop hook
onPostStopHook(id, container);
#endif //defined(LEGACY_COMPONENTS)
// once we're here we mark the container as Stopping, however the container
// object is not removed from the list until the crun parent process has
// actually terminated
container->state = DobbyContainer::State::Stopping;
// if we dropped out here it means something has gone wrong, but the
// container was created, so destroy it
std::shared_ptr<DobbyBufferStream> destroyBuffer = std::make_shared<DobbyBufferStream>();
if (!mRunc->destroy(id, destroyBuffer))
{
AI_LOG_ERROR("failed to destroy '%s'", id.c_str());
}
auto loggingPlugin = GetContainerLogger(container);
if (loggingPlugin)
{
mLogger->DumpBuffer(destroyBuffer->getMemFd(), container->containerPid, std::move(loggingPlugin));
}
// clear the pid now it's been killed
container->containerPid = -1;
}
// Call the postHalt hook to clean up from the creation (preCreation,
// createRuntime, createContainer) hooks
if (container->config->rdkPlugins().size() > 0)
{
onPostHaltHook(container);
}
AI_LOG_FN_EXIT();
return false;
}
#if defined(LEGACY_COMPONENTS)
// -----------------------------------------------------------------------------
/**
* @brief Where the magic begins .... attempts to create a container
* from a Dobby spec file.
*
* @param[in] id The id string for the container
* @param[in] jsonSpec The sky json spec with the container details
* @param[in] files A list of file descriptors to pass into the
* container, can be empty.
* @param[in] command The custom command to run instead of the args in the
* config file (optional)
*
* @return a container descriptor, which is just a unique number that
* identifies the container.
*/
int32_t DobbyManager::startContainerFromSpec(const ContainerId &id,
const std::string &jsonSpec,
const std::list<int> &files,
const std::string &command,
const std::string &displaySocket,
const std::vector<std::string>& envVars = std::vector<std::string>())
{
AI_LOG_FN_ENTRY();
std::lock_guard<std::mutex> locker(mLock);
// the first step is to check we don't already have a container with the
// given id
if (mContainers.count(id) > 0)
{
AI_LOG_ERROR_EXIT("trying to start a container for '%s' that is already running",
id.c_str());
return -1;
}
// create a bundle directory
std::shared_ptr<DobbyBundle> bundle =
std::make_shared<DobbyBundle>(mUtilities, mEnvironment, id);
if (!bundle || !bundle->isValid())
{
AI_LOG_ERROR_EXIT("failed to create bundle");
return -1;
}
// parse the json config
std::shared_ptr<DobbySpecConfig> config =
std::make_shared<DobbySpecConfig>(mUtilities, mSettings, id, bundle, jsonSpec);
if (!config || !config->isValid())
{
AI_LOG_ERROR_EXIT("failed to create config object from OCI bundle config");
return -1;
}
// create a (populated) rootfs directory within the bundle from the config
std::shared_ptr<DobbyRootfs> rootfs =
std::make_shared<DobbyRootfs>(mUtilities, bundle, config);
if (!rootfs || !rootfs->isValid())
{
AI_LOG_ERROR_EXIT("failed to create rootfs");
return -1;
}
// create a 'start state' object that wraps the file descriptors
std::shared_ptr<DobbyStartState> startState =
std::make_shared<DobbyStartState>(config, files);
if (!startState || !startState->isValid())
{
AI_LOG_ERROR_EXIT("failed to create 'start state' object");
return -1;
}
// Set Apparmor profile
if (mSettings->apparmorSettings().enabled)
{
config->setApparmorProfile(mSettings->apparmorSettings().profileName);
}
// Set pids limit
if (mSettings->pidsSettings().enabled)
{
config->setPidsLimit(mSettings->pidsSettings().limit);
}
// Load the RDK plugins from disk (if necessary)
std::map<std::string, Json::Value> rdkPlugins = config->rdkPlugins();
AI_LOG_DEBUG("There are %zd rdk plugins to run", rdkPlugins.size());
std::unique_ptr<DobbyContainer> container;
if (rdkPlugins.size() > 0)
{
const std::string rootfsPath = rootfs->path();
std::shared_ptr<rt_dobby_schema> containerConfig(config->config());
auto rdkPluginUtils = std::make_shared<DobbyRdkPluginUtils>(config->config(), startState, id.str());
auto rdkPluginManager = std::make_shared<DobbyRdkPluginManager>(containerConfig, rootfsPath, PLUGIN_PATH, rdkPluginUtils);
std::vector<std::string> loadedPlugins = rdkPluginManager->listLoadedPlugins();
AI_LOG_DEBUG("Loaded %zd RDK plugins\n", loadedPlugins.size());
// Create the container wrapper
std::unique_ptr<DobbyContainer> dobbyContainer(new DobbyContainer(bundle, config, rootfs, rdkPluginManager));
container = std::move(dobbyContainer);
}
else
{
// Create the container wrapper
std::unique_ptr<DobbyContainer> dobbyContainer(new DobbyContainer(bundle, config, rootfs));
container = std::move(dobbyContainer);
}
// If we have legacy plugins, run their postConstruction hooks before
// executing crun
bool pluginFailure = false;
if (!onPostConstructionHook(id, startState, container))
{
AI_LOG_ERROR("failure in one of the PostConstruction hooks");
pluginFailure = true;
}
// If we have RDK plugins, run their postInstallation hooks. Other
// hooks (excluding preCreate) will be run automatically by crun
if (!pluginFailure && rdkPlugins.size() > 0)
{
if (!onPostInstallationHook(container))
{
pluginFailure = true;
}
// Run any pre-creation hooks
// Note: running the hooks here allows these hooks to also modify the
// config. This is necessary to add envvars etc, but can cause issues
// when launching multiple containers from the same bundle where the plugin
// could add duplicate data to the config
if (!onPreCreationHook(container))
{
pluginFailure = true;
}
}
// Don't start if necessary plugins have failed
if (!pluginFailure)
{
// Customise the config if necessary
customiseConfig(config, command, displaySocket, envVars);
if (!config->writeConfigJson(bundle->path() + "/config.json"))
{
AI_LOG_ERROR("failed to create config.json file");
}
else
{
// if the respawn flag is set in the spec file then we need to store
// any file descriptors for use at respawn time
if (config->restartOnCrash())
{
container->setRestartOnCrash(startState->files());
}
// try and create and start the container
if (createAndStartContainer(id, container, startState->files()))
{
// get the descriptor of the container and return that to the
// caller (need to do this before we move into the map)
int32_t cd = container->descriptor;
// woo - she's off and running, so move the container object
// into the map and then we're done
mContainers.emplace(id, std::move(container));
AI_LOG_FN_EXIT();
return cd;
}
}
}
// not required, but tidy up the start state object so all the file
// descriptors will be released now
startState.reset();
// something went wrong, however we still want to call the preDestruction
// hook, in case a hook setup some stuff the post-construction phase above
onPreDestructionHook(id, container);
AI_LOG_FN_EXIT();
return -1;
}
#endif //defined(LEGACY_COMPONENTS)
// -----------------------------------------------------------------------------
/**
* @brief Where the magic begins ... attempts to create a container from