/
instance_manager.cc
830 lines (707 loc) · 27.8 KB
/
instance_manager.cc
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
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
#include "oper/instance_manager.h"
#include <boost/bind.hpp>
#include <boost/functional/hash.hpp>
#include <boost/filesystem.hpp>
#include <boost/tokenizer.hpp>
#include <sys/wait.h>
#include "cmn/agent.h"
#include "db/db.h"
#include "io/event_manager.h"
#include "oper/instance_task.h"
#include "oper/loadbalancer.h"
#include "oper/loadbalancer_config.h"
#include "oper/loadbalancer_properties.h"
#include "oper/operdb_init.h"
#include "oper/service_instance.h"
#include "oper/vm.h"
#include "oper/docker_instance_adapter.h"
#include "oper/netns_instance_adapter.h"
#ifdef WITH_LIBVIRT
#include "oper/libvirt_instance_adapter.h"
#endif
#include "base/util.h"
using boost::uuids::uuid;
static const char loadbalancer_config_path_default[] =
"/var/lib/contrail/loadbalancer/";
static const char namespace_store_path_default[] =
"/var/run/netns";
static const char namespace_prefix[] = "vrouter-";
class InstanceManager::NamespaceStaleCleaner {
public:
NamespaceStaleCleaner(Agent *agent, InstanceManager *manager)
: agent_(agent), manager_(manager) {
}
void CleanStaleEntries() {
namespace fs = boost::filesystem;
//Read all the Namepaces in the system
fs::path ns(manager_->namespace_store_path_);
if ( !fs::exists(ns) || !fs::is_directory(ns)) {
return;
}
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> slash_sep("/");
boost::char_separator<char> colon_sep(":");
fs::directory_iterator end_iter;
for(fs::directory_iterator iter(ns); iter != end_iter; iter++) {
// Get to the name of namespace by removing complete path
tokenizer tokens(iter->path().string(), slash_sep);
std::string ns_name;
for(tokenizer::iterator it=tokens.begin(); it!=tokens.end(); it++){
ns_name = *it;
}
//We are interested only in namespaces starting with a given
//prefix
std::size_t vrouter_found;
vrouter_found = ns_name.find(namespace_prefix);
if (vrouter_found == std::string::npos) {
continue;
}
//Remove the standard prefix
ns_name.replace(vrouter_found, strlen(namespace_prefix), "");
//Namespace might have a ":". Extract both left and right of
//":" Left of ":" is the VM uuid. If not found in Agent's VM
//DB, it can be deleted
tokenizer tok(ns_name, colon_sep);
boost::uuids::uuid vm_uuid = StringToUuid(*tok.begin());
VmKey key(vm_uuid);
if (agent_->vm_table()->Find(&key, true)) {
continue;
}
ServiceInstance::Properties prop;
prop.instance_id = vm_uuid;
prop.service_type = ServiceInstance::SourceNAT;
tokenizer::iterator next_tok = ++(tok.begin());
//Loadbalancer namespace
if (next_tok != tok.end()) {
prop.pool_id = StringToUuid(*next_tok);
prop.service_type = ServiceInstance::LoadBalancer;
}
//Delete Namespace
manager_->StopStaleNetNS(prop);
//If Loadbalncer, delete the config files as well
if (prop.service_type == ServiceInstance::LoadBalancer) {
std::stringstream pathgen;
std::stringstream conf_path, json_path, sock_path, crt_path;
pathgen << manager_->loadbalancer_config_path_ << prop.pool_id;
conf_path << pathgen.str() << ".haproxy.conf";
json_path << pathgen.str() << ".conf.json";
sock_path << pathgen.str() << ".haproxy.sock";
crt_path << pathgen.str() << ".crtbundle.pem";
boost::system::error_code error;
if (fs::exists(conf_path.str())) {
fs::remove_all(conf_path.str(), error);
if (error) {
LOG(ERROR, "Stale loadbalancer conf fle delete error"
<< error.message());
}
}
if (fs::exists(sock_path.str())) {
fs::remove_all(sock_path.str(), error);
if (error) {
LOG(ERROR, "Stale loadbalancer sock fle delete error"
<< error.message());
}
}
if (fs::exists(json_path.str())) {
fs::remove_all(json_path.str(), error);
if (error) {
LOG(ERROR, "Stale loadbalancer json file delete error"
<< error.message());
}
}
if (fs::exists(crt_path.str())) {
fs::remove_all(crt_path.str(), error);
if (error) {
LOG(ERROR, "Stale loadbalancer certificate file delete error"
<< error.message());
}
}
}
}
}
private:
Agent *agent_;
InstanceManager *manager_;
};
InstanceManager::~InstanceManager() {
TimerManager::DeleteTimer(stale_timer_);
STLDeleteValues(&adapters_);
}
InstanceManager::InstanceManager(Agent *agent)
: si_listener_(DBTableBase::kInvalidId),
lb_listener_(DBTableBase::kInvalidId),
netns_timeout_(-1),
work_queue_(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0,
boost::bind(&InstanceManager::DequeueEvent, this, _1)),
loadbalancer_config_path_(loadbalancer_config_path_default),
namespace_store_path_(namespace_store_path_default),
stale_timer_interval_(5 * 60 * 1000),
lb_config_(new LoadbalancerConfig(agent)),
stale_timer_(TimerManager::CreateTimer(*(agent->event_manager()->io_service()),
"NameSpaceStaleTimer", TaskScheduler::GetInstance()->
GetTaskId("db::DBTable"), 0)), agent_(agent) {
work_queue_.set_name("Instance Manager");
}
void InstanceManager::Initialize(DB *database, const std::string &netns_cmd,
const std::string &docker_cmd,
const int netns_workers,
const int netns_timeout) {
DBTableBase *lb_table = agent_->loadbalancer_table();
assert(lb_table);
lb_listener_ = lb_table->Register(
boost::bind(&InstanceManager::LoadbalancerObserver, this, _1, _2));
DBTableBase *si_table = agent_->service_instance_table();
assert(si_table);
si_listener_ = si_table->Register(
boost::bind(&InstanceManager::EventObserver, this, _1, _2));
netns_cmd_ = netns_cmd;
if (netns_cmd_.length() == 0) {
LOG(ERROR, "NetNS path for network namespace command not specified "
"in the config file, the namespaces won't be started");
}
if (docker_cmd.length() == 0) {
LOG(ERROR, "Path for Docker starter command not specified "
"in the config file, the Docker instances won't be started");
}
adapters_.push_back(new DockerInstanceAdapter(docker_cmd, agent_));
adapters_.push_back(new NetNSInstanceAdapter(netns_cmd,
loadbalancer_config_path_, agent_));
#ifdef WITH_LIBVIRT
adapters_.push_back(new LibvirtInstanceAdapter(agent_,
"qemu:///system"));
#endif
netns_timeout_ = kTimeoutDefault;
if (netns_timeout >= 1) {
netns_timeout_ = netns_timeout;
}
int workers = kWorkersDefault;
if (netns_workers > 0) {
workers = netns_workers;
}
task_queues_.resize(workers);
for (std::vector<InstanceTaskQueue *>::iterator iter = task_queues_.begin();
iter != task_queues_.end(); ++iter) {
InstanceTaskQueue *task_queue =
new InstanceTaskQueue(agent_->event_manager());
assert(task_queue);
task_queue->set_on_timeout_cb(
boost::bind(&InstanceManager::OnTaskTimeout,
this, _1));
*iter = task_queue;
}
stale_timer_->Start(StaleTimerInterval(),
boost::bind(&InstanceManager::StaleTimeout, this));
}
void InstanceManager::SetStaleTimerInterval(int minutes) {
stale_timer_interval_ = minutes * 60 * 1000;
}
void InstanceManager::OnTaskTimeout(InstanceTaskQueue *task_queue) {
InstanceManagerChildEvent event;
event.type = OnTaskTimeoutEvent;
event.task_queue = task_queue;
work_queue_.Enqueue(event);
}
void InstanceManager::OnTaskTimeoutEventHandler(InstanceManagerChildEvent event) {
ScheduleNextTask(event.task_queue);
}
void InstanceManager::OnErrorEventHandler(InstanceManagerChildEvent event) {
ServiceInstance *svc_instance = GetSvcInstance(event.task);
if (!svc_instance) {
return;
}
InstanceState *state = GetState(svc_instance);
if (state != NULL) {
state->set_errors(event.errors);
}
}
void InstanceManager::OnExitEventHandler(InstanceManagerChildEvent event) {
ServiceInstance *svc_instance = GetSvcInstance(event.task);
if (!svc_instance) {
return;
}
UpdateStateStatusType(event);
for (std::vector<InstanceTaskQueue *>::iterator iter =
task_queues_.begin();
iter != task_queues_.end(); ++iter) {
InstanceTaskQueue *task_queue = *iter;
if (!task_queue->Empty()) {
if (task_queue->Front() == event.task) {
task_queue->Pop();
delete event.task;
task_queue->StopTimer();
DeleteState(svc_instance);
ScheduleNextTask(task_queue);
return;
}
}
}
}
bool InstanceManager::DequeueEvent(InstanceManagerChildEvent event) {
if (event.type == OnErrorEvent) {
OnErrorEventHandler(event);
} else if (event.type == OnTaskTimeoutEvent) {
OnTaskTimeoutEventHandler(event);
} else if (event.type == OnExitEvent) {
OnExitEventHandler(event);
}
return true;
}
void InstanceManager::UpdateStateStatusType(InstanceManagerChildEvent event) {
ServiceInstance* svc_instance = UnregisterSvcInstance(event.task);
if (svc_instance) {
InstanceState *state = GetState(svc_instance);
// The below code might not really capture the errors that
// occured in the child process. As we are relying on the pipe
// status to identify child exit, even if child process ends up
// in error state, pipe might return "success" because pipe is
// closed without erros. But what we want to reflect is the
// error of child process. If there is any error in the pipe
// status, we show that as is. If not, if there is any error string
// in error_, we mark the error status as -1.
// pipe returning boost::system::errc::no_such_file_or_directory
// error is considered as no pipe errors
if (state != NULL) {
int error_status = event.error_val;
if (error_status ==
boost::system::errc::no_such_file_or_directory) {
error_status = 0;
}
if (!state->errors().empty()) {
if (error_status == 0) {
error_status = -1;
}
}
state->set_status(error_status);
LOG(DEBUG, "NetNS update status for uuid: "
<< svc_instance->ToString()
<< " " << error_status);
if (error_status != 0) {
if (state->status_type() != InstanceState::Timeout) {
state->set_status_type(InstanceState::Error);
}
} else if (state->status_type() == InstanceState::Starting) {
state->set_status_type(InstanceState::Started);
} else if (state->status_type() == InstanceState::Stopping) {
state->set_status_type(InstanceState::Stopped);
}
}
}
}
InstanceState *InstanceManager::GetState(ServiceInstance *svc_instance) const {
return static_cast<InstanceState *>(
svc_instance->GetState(agent_->service_instance_table(),
si_listener_));
}
InstanceState *InstanceManager::GetState(InstanceTask* task) const {
ServiceInstance* svc_instance = GetSvcInstance(task);
if (svc_instance) {
InstanceState *state = GetState(svc_instance);
return state;
}
return NULL;
}
void InstanceManager::SetState(ServiceInstance *svc_instance,
InstanceState *state) {
svc_instance->SetState(agent_->service_instance_table(),
si_listener_,state);
}
void InstanceManager::ClearState(ServiceInstance *svc_instance) {
svc_instance->ClearState(agent_->service_instance_table(), si_listener_);
}
bool InstanceManager::DeleteState(ServiceInstance *svc_instance) {
if (!svc_instance || !svc_instance->IsDeleted()) {
return false;
}
InstanceState *state = GetState(svc_instance);
if (state && !state->tasks_running()) {
ClearState(svc_instance);
delete state;
ClearLastCmdType(svc_instance);
return true;
}
return false;
}
void InstanceManager::StateClear() {
DBTablePartition *partition = static_cast<DBTablePartition *>(
agent_->service_instance_table()->GetTablePartition(0));
DBEntryBase *next = NULL;
for (DBEntryBase *entry = partition->GetFirst(); entry; entry = next) {
DBState *state =
entry->GetState(agent_->service_instance_table(), si_listener_);
if (state != NULL) {
entry->ClearState(agent_->service_instance_table(), si_listener_);
delete state;
ClearLastCmdType(static_cast<ServiceInstance *>(entry));
}
next = partition->GetNext(entry);
}
}
void InstanceManager::Terminate() {
StateClear();
agent_->loadbalancer_table()->Unregister(lb_listener_);
agent_->loadbalancer_table()->Clear();
agent_->service_instance_table()->Unregister(si_listener_);
agent_->service_instance_table()->Clear();
InstanceTaskQueue *task_queue;
for (std::vector<InstanceTaskQueue *>::iterator iter = task_queues_.begin();
iter != task_queues_.end(); ++iter) {
if ((task_queue = *iter) == NULL) {
continue;
}
task_queue->Clear();
delete task_queue;
}
work_queue_.Shutdown();
}
void InstanceManager::Enqueue(InstanceTask *task,
const boost::uuids::uuid &uuid) {
std::stringstream ss;
ss << uuid;
InstanceTaskQueue *task_queue = GetTaskQueue(ss.str());
task_queue->Push(task);
ScheduleNextTask(task_queue);
}
InstanceTaskQueue *InstanceManager::GetTaskQueue(const std::string &str) {
boost::hash<std::string> hash;
int index = hash(str) % task_queues_.size();
return task_queues_[index];
}
bool InstanceManager::StartTask(InstanceTaskQueue *task_queue,
InstanceTask *task) {
InstanceState *state = GetState(task);
if (state) {
state->reset_errors();
}
pid_t pid;
if (task->Run())
pid = task->pid();
else
return false;
if (state != NULL) {
state->set_pid(pid);
state->set_cmd(task->cmd());
if (task->cmd_type() == Start) {
state->set_status_type(InstanceState::Starting);
} else {
state->set_status_type(InstanceState::Stopping);
}
}
if (pid > 0) {
task_queue->StartTimer(netns_timeout_ * 1000);
return true;
}
task_queue->Pop();
UnregisterSvcInstance(task);
delete task;
return false;
}
void InstanceManager::ScheduleNextTask(InstanceTaskQueue *task_queue) {
while (!task_queue->Empty()) {
InstanceTask *task = task_queue->Front();
if (!task->is_running()) {
bool starting = StartTask(task_queue, task);
if (starting) {
return;
}
} else {
int delay = time(NULL) - task->start_time();
if (delay < netns_timeout_) {
return;
}
InstanceState *state = GetState(task);
if (state) {
state->set_status_type(InstanceState::Timeout);
}
LOG(ERROR, "NetNS error timeout " << delay << " > " <<
netns_timeout_ << ", " << task->cmd());
if (delay > (netns_timeout_ * 2)) {
task->Terminate();
task_queue->StopTimer();
task_queue->Pop();
ServiceInstance* svc_instance = GetSvcInstance(task);
if (state && svc_instance)
state->decr_tasks_running();
task_svc_instances_.erase(task);
DeleteState(svc_instance);
delete task;
} else {
task->Stop();
return;
}
}
}
}
ServiceInstance *InstanceManager::GetSvcInstance(InstanceTask *task) const {
TaskSvcMap::const_iterator iter =
task_svc_instances_.find(task);
if (iter != task_svc_instances_.end()) {
return iter->second;
}
return NULL;
}
void InstanceManager::RegisterSvcInstance(InstanceTask *task,
ServiceInstance *svc_instance) {
pair<TaskSvcMap::iterator, bool> result =
task_svc_instances_.insert(std::make_pair(task, svc_instance));
assert(result.second);
InstanceState *state = GetState(svc_instance);
assert(state);
state->incr_tasks_running();
}
ServiceInstance *InstanceManager::UnregisterSvcInstance(InstanceTask *task) {
for (TaskSvcMap::iterator iter =
task_svc_instances_.begin();
iter != task_svc_instances_.end(); ++iter) {
if (task == iter->first) {
ServiceInstance *svc_instance = iter->second;
InstanceState *state = GetState(svc_instance);
assert(state);
state->decr_tasks_running();
task_svc_instances_.erase(iter);
return svc_instance;
}
}
return NULL;
}
void InstanceManager::UnregisterSvcInstance(ServiceInstance *svc_instance) {
InstanceState *state = GetState(svc_instance);
assert(state);
TaskSvcMap::iterator iter = task_svc_instances_.begin();
while(iter != task_svc_instances_.end()) {
if (svc_instance == iter->second) {
task_svc_instances_.erase(iter++);
state->decr_tasks_running();
} else {
++iter;
}
}
}
InstanceManagerAdapter* InstanceManager::FindApplicableAdapter(const ServiceInstance::Properties &props) {
for (std::vector<InstanceManagerAdapter *>::iterator iter = adapters_.begin();
iter != adapters_.end(); ++iter) {
InstanceManagerAdapter *adapter = *iter;
if (adapter != NULL && adapter->isApplicable(props)) {
return adapter;
}
}
return NULL;
}
void InstanceManager::StartServiceInstance(ServiceInstance *svc_instance,
InstanceState *state, bool update) {
const ServiceInstance::Properties &props = svc_instance->properties();
InstanceManagerAdapter *adapter = this->FindApplicableAdapter(props);
if (adapter != NULL) {
InstanceTask *task = adapter->CreateStartTask(props, update);
if (task != NULL) {
task->set_on_error_cb(boost::bind(&InstanceManager::OnError,
this, _1, _2));
task->set_on_exit_cb(boost::bind(&InstanceManager::OnExit,
this, _1, _2));
state->set_properties(props);
RegisterSvcInstance(task, svc_instance);
std::stringstream info;
info << "Service run command queued: " << task->cmd();
Enqueue(task, props.instance_id);
LOG(DEBUG, info.str().c_str());
} else {
LOG(ERROR, "Error creating task!");
}
} else {
LOG(ERROR, "Unknown virtualization type: " << props.virtualization_type);
}
}
void InstanceManager::StopServiceInstance(ServiceInstance *svc_instance,
InstanceState *state) {
const ServiceInstance::Properties &props = state->properties();
InstanceManagerAdapter *adapter = this->FindApplicableAdapter(props);
if (adapter != NULL) {
InstanceTask *task = adapter->CreateStopTask(props);
if (task != NULL) {
task->set_on_error_cb(boost::bind(&InstanceManager::OnError,
this, _1, _2));
task->set_on_exit_cb(boost::bind(&InstanceManager::OnExit,
this, _1, _2));
RegisterSvcInstance(task, svc_instance);
std::stringstream info;
info << "Service stop command queued: " << task->cmd();
Enqueue(task, props.instance_id);
LOG(DEBUG, info.str().c_str());
} else {
LOG(ERROR, "Error creating task!");
}
} else {
LOG(ERROR, "Unknown virtualization type: " << props.virtualization_type);
}
}
void InstanceManager::OnError(InstanceTask *task,
const std::string errors) {
InstanceManagerChildEvent event;
event.type = OnErrorEvent;
event.task = task;
event.errors = errors;
work_queue_.Enqueue(event);
}
void InstanceManager::OnExit(InstanceTask *task,
const boost::system::error_code &ec) {
InstanceManagerChildEvent event;
event.type = OnExitEvent;
event.task = task;
event.error_val = ec.value();
work_queue_.Enqueue(event);
}
void InstanceManager::StopStaleNetNS(ServiceInstance::Properties &props) {
std::stringstream cmd_str;
if (netns_cmd_.length() == 0) {
return;
}
cmd_str << netns_cmd_ << " destroy";
cmd_str << " " << props.ServiceTypeString();
cmd_str << " " << UuidToString(props.instance_id);
cmd_str << " " << UuidToString(boost::uuids::nil_uuid());
cmd_str << " " << UuidToString(boost::uuids::nil_uuid());
if (props.service_type == ServiceInstance::LoadBalancer) {
cmd_str << " --cfg-file " << loadbalancer_config_path_default <<
props.pool_id << ".conf.json";
cmd_str << " --pool-id " << props.pool_id;
}
InstanceTask *task = new InstanceTaskExecvp(cmd_str.str(), Stop,
agent_->event_manager());
std::stringstream info;
info << "NetNS stale run command queued: " << task->cmd();
Enqueue(task, props.instance_id);
LOG(DEBUG, info.str().c_str());
}
void InstanceManager::SetLastCmdType(ServiceInstance *svc_instance,
int last_cmd_type) {
std::string uuid = UuidToString(svc_instance->uuid());
std::map<std::string, int>::iterator iter =
last_cmd_types_.find(uuid);
if (iter != last_cmd_types_.end()) {
iter->second = last_cmd_type;
} else {
last_cmd_types_.insert(std::make_pair(uuid, last_cmd_type));
}
}
int InstanceManager::GetLastCmdType(ServiceInstance *svc_instance) const {
std::string uuid = UuidToString(svc_instance->uuid());
std::map<std::string, int>::const_iterator iter =
last_cmd_types_.find(uuid);
if (iter != last_cmd_types_.end()) {
return iter->second;
}
return 0;
}
void InstanceManager::ClearLastCmdType(ServiceInstance *svc_instance) {
std::string uuid = UuidToString(svc_instance->uuid());
std::map<std::string, int>::iterator iter =
last_cmd_types_.find(uuid);
if (iter != last_cmd_types_.end()) {
last_cmd_types_.erase(iter);
}
}
void InstanceManager::EventObserver(
DBTablePartBase *db_part, DBEntryBase *entry) {
ServiceInstance *svc_instance = static_cast<ServiceInstance *>(entry);
InstanceState *state = GetState(svc_instance);
if (svc_instance->IsDeleted()) {
if (state) {
if (GetLastCmdType(svc_instance) == Start) {
StopServiceInstance(svc_instance, state);
SetLastCmdType(svc_instance, Stop);
}
if (DeleteState(svc_instance)) {
return;
}
}
ClearLastCmdType(svc_instance);
} else {
if (state == NULL) {
state = new InstanceState();
SetState(svc_instance, state);
}
bool usable = svc_instance->IsUsable();
LOG(DEBUG, "NetNS event notification for uuid: " << svc_instance->ToString()
<< (usable ? " usable" : " not usable"));
if (!usable && GetLastCmdType(svc_instance) == Start) {
LOG(DEBUG, "Stopping service instance!");
StopServiceInstance(svc_instance, state);
SetLastCmdType(svc_instance, Stop);
} else if (usable) {
if (GetLastCmdType(svc_instance) == Start && state->properties().CompareTo(
svc_instance->properties()) != 0) {
StartServiceInstance(svc_instance, state, true);
} else if (GetLastCmdType(svc_instance) != Start) {
StartServiceInstance(svc_instance, state, false);
SetLastCmdType(svc_instance, Start);
}
}
}
}
void InstanceManager::LoadbalancerObserver(
DBTablePartBase *db_part, DBEntryBase *entry) {
Loadbalancer *loadbalancer = static_cast<Loadbalancer *>(entry);
std::stringstream pathgen;
pathgen << loadbalancer_config_path_ << loadbalancer->uuid();
boost::system::error_code error;
if (!loadbalancer->IsDeleted() && loadbalancer->properties() != NULL) {
boost::filesystem::path dir(loadbalancer_config_path_);
if (!boost::filesystem::exists(dir, error)) {
boost::filesystem::create_directories(dir, error);
if (error) {
LOG(ERROR, error.message());
return;
}
}
pathgen << ".conf.json";
lb_config_->GenerateConfig(pathgen.str(), loadbalancer->uuid(),
*loadbalancer->properties());
} else {
std::stringstream conf_path, json_path, sock_path, crt_path;
conf_path << pathgen.str() << ".haproxy.conf";
json_path << pathgen.str() << ".conf.json";
sock_path << pathgen.str() << ".haproxy.sock";
crt_path << pathgen.str() << ".crtbundle.pem";
boost::filesystem::path conf_file(conf_path.str());
if (boost::filesystem::exists(conf_file, error)) {
boost::filesystem::remove_all(conf_path.str(), error);
}
boost::filesystem::path sock_file(sock_path.str());
if (boost::filesystem::exists(sock_file, error)) {
boost::filesystem::remove_all(sock_path.str(), error);
}
boost::filesystem::path json_file(json_path.str());
if (boost::filesystem::exists(json_file, error)) {
boost::filesystem::remove_all(json_path.str(), error);
}
boost::filesystem::path crt_file(crt_path.str());
if (boost::filesystem::exists(crt_file, error)) {
boost::filesystem::remove_all(crt_path.str(), error);
}
}
}
bool InstanceManager::StaleTimeout() {
if (stale_cleaner_.get())
return false;
stale_cleaner_.reset(new NamespaceStaleCleaner(agent_, this));
stale_cleaner_->CleanStaleEntries();
stale_cleaner_.reset(NULL);
return false;
}
void InstanceManager::SetNamespaceStorePath(std::string path) {
namespace_store_path_ = path;
}
/*
* InstanceState class
*/
InstanceState::InstanceState() : DBState(),
pid_(0), status_(0), status_type_(0), tasks_running_(0) {
}
void InstanceState::Clear() {
pid_ = 0;
status_ = 0;
errors_.empty();
cmd_.empty();
}