forked from PelionIoT/maestro
/
processMgmt.go
2085 lines (1870 loc) · 64.8 KB
/
processMgmt.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 processes
// Copyright (c) 2018, Arm Limited and affiliates.
// SPDX-License-Identifier: Apache-2.0
//
// 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.
/*
#cgo amd64 LDFLAGS: -L/usr/lib/x86_64-linux-gnu
#cgo LDFLAGS: -L${SRCDIR}/../vendor/github.com/armPelionEdge/greasego/deps/lib
#cgo LDFLAGS: -lgrease -luv -lTW -lstdc++ -lm -ltcmalloc_minimal -lm
#cgo CFLAGS: -I${SRCDIR}/../vendor/github.com/armPelionEdge/greasego/deps/include -DDEBUG_BINDINGS -I${SRCDIR}/processes
#define GREASE_IS_LOCAL 1
#include <stdio.h>
#include <stdlib.h>
#include "process_utils.h"
#include "grease_lib.h"
*/
import "C"
import (
"bytes"
"encoding/json"
"fmt"
"github.com/armPelionEdge/greasego"
"github.com/armPelionEdge/hashmap" // thread-safe, fast hashmaps
"github.com/armPelionEdge/maestro/configMgr"
"github.com/armPelionEdge/maestro/configs"
"github.com/armPelionEdge/maestro/debugging"
"github.com/armPelionEdge/maestro/storage"
"github.com/armPelionEdge/maestroSpecs"
"github.com/kardianos/osext" // not needed in go1.8 - see their README
"golang.org/x/sys/unix"
"os"
"regexp"
"strconv"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
)
type ProcessStatsConfig interface {
GetInterval() uint32
GetConfig_CheckMem() (uint32, bool)
}
const (
STDIN_CLOSE = iota
STDIN_TO_MANAGER = iota
)
const (
STDOUT_CLOSE = iota
STDOUT_TO_LOGGER = iota
STDOUT_TO_MANAGER = iota
)
const (
STDERR_CLOSE = iota
STDERR_TO_LOGGER = iota
STDERR_TO_MANAGER = iota
)
const (
PROCESS_STARTED = 0x1
PROCESS_READY = 0x2
PROCESS_DIED = 0x4
)
var PROCESS_STATES = map[uint32]string{
0: "unknown",
PROCESS_STARTED: "started",
PROCESS_READY: "ready",
PROCESS_DIED: "died",
}
type ExecFileOpts struct {
jobName string
compId string
// stdoutDirection int
// stderrDirection int
// stdinDirection int
internal C.childOpts
}
// The magic message sent from a process
// which is following the maestro startup procedures.
// when it writes this to stdout, the process is finished
// with startup.
const process_OK_message = maestroSpecs.JOB_OK_STRING
func NewExecFileOpts(jobname string, compid string) (opts *ExecFileOpts) {
opts = new(ExecFileOpts)
opts.jobName = "[no job name]"
if len(jobname) > 0 {
opts.jobName = jobname
}
opts.compId = "[no composite id]"
if len(compid) > 0 {
opts.compId = compid
}
opts.internal.pgid = 0
opts.internal.flags = 0
opts.internal.chroot = nil
opts.internal.message = nil
opts.internal.ok_string = 0
opts.internal.jobname = nil
opts.internal.stdout_fd = 0
opts.internal.stderr_fd = 0
opts.internal.die_on_parent_sig = 0
opts.internal.env_GREASE_ORIGIN_ID = 0
return
}
func (opts *ExecFileOpts) SetNewPgid() {
opts.internal.flags &= ^C.uint32_t(C.PROCESS_USE_PGID)
}
func (opts *ExecFileOpts) SetUsePgid(pid int) {
opts.internal.flags |= C.uint32_t(C.PROCESS_USE_PGID)
opts.internal.pgid = C.pid_t(pid)
}
func (opts *ExecFileOpts) SetJobName(name string) {
if len(name) > 0 {
opts.internal.jobname = C.CString(name)
} else {
opts.internal.jobname = nil
}
}
func (opts *ExecFileOpts) GetOriginLabelId() uint32 {
return uint32(opts.internal.originLabel)
}
func (opts *ExecFileOpts) SetNewSid() {
opts.internal.flags |= C.uint32_t(C.PROCESS_NEW_SID)
}
func (opts *ExecFileOpts) SetMessageString(msg string) {
if len(msg) > 0 {
opts.internal.message = C.CString(msg)
} else {
opts.internal.message = nil
}
}
func (opts *ExecFileOpts) SetOkString(ok bool) {
if ok {
opts.internal.ok_string = 1
} else {
opts.internal.ok_string = 0
}
}
func (opts *ExecFileOpts) GetStdoutFd() (ret int) {
ret = int(opts.internal.stdout_fd)
return
}
func (opts *ExecFileOpts) GetStderrFd() (ret int) {
ret = int(opts.internal.stderr_fd)
return
}
// a record of start and/or stop operation. basically a
// single life of a process (not a Job)
type ProcessRecord struct {
Pid int
// the Path to start the process executable
Path string
// serves as a generic identifier for a particular job
// jobs maybe restarted, etc. A Job should be a unique name to the
// instance of maestro on this gateway
Job string
CompId string
Started time.Time
Stopped time.Time
State uint32 // see PROCESS_STATES
ExitValue int
// cgroup
// pgid
}
// returns a ProcessRecord by its PID (process ID)
func GetTrackedProcessByPid(pid int) (ret *ProcessRecord, ok bool) {
var val unsafe.Pointer
val, ok = processIndexByPid.GetHashedKey(uintptr(pid))
if ok {
ret = (*ProcessRecord)(val)
}
// ret, ok = processIndexByPid[pid]
return
}
// creates a new ProcessRecord, stores it in the tracking map, and returns this new one
// the old one - if for some rare reason a process with the same PID was already there
func TrackNewProcessByPid(pid int) (ret *ProcessRecord, old *ProcessRecord) {
oldval, ok := processIndexByPid.GetHashedKey(uintptr(pid))
if ok {
old = (*ProcessRecord)(oldval)
}
ret = new(ProcessRecord)
ret.Pid = pid
ret.Path = ""
processIndexByPid.SetHashedKey(uintptr(pid), unsafe.Pointer(ret))
// old = processIndexByPid[pid]
// processIndexByPid[pid] = ret
return
}
func RemoveTrackedProcessByPid(pid int) (ret *ProcessRecord) {
// var ok bool
// ret, ok = processIndexByPid[pid]
oldval, ok := processIndexByPid.GetHashedKey(uintptr(pid))
if ok {
ret = (*ProcessRecord)(oldval)
processIndexByPid.DelHashedKey(uintptr(pid))
// delete(processIndexByPid,pid)
}
return
}
func ForEachTrackedProcess(cb func(int, *ProcessRecord)) {
for keyval := range processIndexByPid.Iter() {
key, ok := keyval.Key.(uintptr)
if ok {
cb(int(key), (*ProcessRecord)(keyval.Value))
}
}
// for pid, record := range processIndexByPid {
// cb(pid, record)
// }
}
func NumberOfTrackedProcesses() int {
// return len(processIndexByPid)
return processIndexByPid.Len()
}
//var processIndexByPid map[int]*ProcessRecord
var processIndexByPid *hashmap.HashMap
// composite processes by their compositeId
var compositeProcessesById *hashmap.HashMap
// enum JOB_STATUS
const (
// JOB_STATUS_UNSET = iota // zero should be the unset
NEVER_RAN = iota
RUNNING = iota
STOPPED = iota
WAITING_FOR_DEPS = iota
STARTING = iota
STOPPING = iota
RESTARTING = iota
FAILED = iota
)
var stringOfStatus map[int]string
type processStatus struct {
// the original JobDefinition which create this process. This is 'nil' if this process
// is a master process
job maestroSpecs.JobDefinition
// at some point, the Job is initially started.
// We keep this around so we can reference on restarts, etc.
originatingEvent *processEvent
// for jobs which are waiting on the OK start screen, used if we get a partial messages
startMessageBuf []rune
status int // JOB_STATUS
restarts uint32
pid int
errno int // last error if tried to exec() and failed
// composite data, formed from template & job start request
execPath string
execArgs []string
execEnv []string
usesOKString bool
deferRunningStatus uint32
originLabelId uint32 // used by greasego to identify this process to the logger
// If this process is part of a composite process this is set
// See masterComposite for more.
compositeId string
// attempt to make this process die if maestro dies
dieOnParentDeath bool
// The following keys are for Composite Processes only:
//
// masterComposite & compositeId
// A composite ID allows grouping of multiple 'jobs' together under a single process
// If masterComposite is true, then this process is a master 'holding' process for one or more
// Jobs (and their processStatus records)
// This should always hold true: masterComposite == true && len(compositeID) > 0
// for a master composite process
masterComposite bool
// all the 'GetDependsOn()' of all Jobs which this composite process holds
// as a map
combinedDeps map[string]bool
// if true, we bundle up all the job data as JSON and send to the process
// once started to it's standard input
send_composite_jobs_to_stdin bool
// make a GREASE_ORIGIN_ID env var, and then when execvpe the new process, attach this env var
// which will have the generated origin ID for the process. Useful for deviceJS
send_GREASE_ORIGIN_ID bool
// string of Job Names this composite process holds
childNames map[string]int // int is JOB_STATUS
mutex sync.Mutex
compositeContainerTemplate string
}
func (this *processStatus) lock() {
this.mutex.Lock()
}
func (this *processStatus) unlock() {
this.mutex.Unlock()
}
// locks the mutex - returns .status
func (this *processStatus) lockingGetStatus() (ret int) {
this.mutex.Lock()
ret = this.status
this.mutex.Unlock()
return
}
// locks the mutex - returns .status
func (this *processStatus) lockingSetStatus(v int) {
this.mutex.Lock()
this.status = v
this.mutex.Unlock()
}
// sets the status on jobs referenced in the childNames slice
func (this *processStatus) setAllChildJobStatus(status int) {
this.mutex.Lock()
for child, _ := range this.childNames {
this.childNames[child] = status
val, ok := jobsByName.GetStringKey(child)
if ok {
child_proc := (*processStatus)(val)
child_proc.status = status
// child_proc.setAllChildJobStatus(status)
} else {
debugging.DEBUG_OUT("WARNING - could not find child referenced in .childNames in the jobsByName map!\n")
}
}
this.mutex.Unlock()
}
// sends an event for all child processes - NOTE: needs a lock on processStatus first
func (status *processStatus) sendEventAndSetStatusForCompProcess(statuscode int, evcode int) {
for child, _ := range status.childNames {
status.childNames[child] = statuscode
val, ok := jobsByName.GetStringKey(child)
if ok {
child_proc := (*processStatus)(val)
child_proc.status = statuscode
jname := child_proc.job.GetJobName()
internalEv := newProcessEvent(jname, evcode)
controlChan <- internalEv
} else {
debugging.DEBUG_OUT("WARNING - could not find child referenced in .childNames in the jobsByName map!\n")
}
}
status.status = statuscode
}
type containerStatus struct {
uses int
container maestroSpecs.ContainerTemplate
}
type JobError struct {
JobName string
Code int
Aux string
}
type ContainerError struct {
ContainerName string
Code int
Aux string
}
const (
CONTAINERERROR_UNKNOWN = iota
CONTAINERERROR_DUPLICATE = iota
)
const (
JOBERROR_UNKNOWN = iota
JOBERROR_NOT_FOUND = iota // don't have a job by that name
JOBERROR_DUPLICATE_JOB = iota
JOBERROR_MISSING_DEPENDENCY = iota
JOBERROR_DEPENDENCY_FAILURE = iota
JOBERROR_MISSING_CONTAINER_TEMPLATE = iota
JOBERROR_INVALID_CONFIG = iota // config options don't make sense
JOBERROR_INTERNAL_ERROR = iota // catch all for things which should just not happen
)
var job_error_map = map[int]string{
0: "unknown",
JOBERROR_NOT_FOUND: "JOBERROR_NOT_FOUND",
JOBERROR_MISSING_CONTAINER_TEMPLATE: "JOBERROR_MISSING_CONTAINER_TEMPLATE",
}
var container_error_map = map[int]string{
0: "unknown",
CONTAINERERROR_DUPLICATE: "CONTAINERERROR_DUPLICATE",
}
func (this *JobError) Error() string {
s := job_error_map[this.Code]
return "JobError: " + this.JobName + ":" + s + " (" + strconv.Itoa(this.Code) + ") " + this.Aux
}
func (this *ContainerError) Error() string {
s := container_error_map[this.Code]
return "JobError: " + this.ContainerName + ":" + s + " (" + strconv.Itoa(this.Code) + ") " + this.Aux
}
const (
internalEvent_unknown = iota // not set!
internalEvent_shutdown = iota // shutdown the processEventWork thread
internalEvent_start_job = iota // start a process
internalEvent_stop_job = iota // tell loop to stop a process
internalEvent_job_starting = iota // event happens when the process is 'starting'
internalEvent_job_running = iota // event happens when the process is 'running'
internalEvent_job_stopped = iota // event happens when the process stopped
internalEvent_job_died = iota // an external event cause a process to die (we did not stop it)
internalEvent_job_controlledExit = iota // event happens when the process exited normally or killed explicitly
internalEvent_job_failed = iota // a job failed to start
)
// the internal event structure
// Note: not to be confused with ProcessEvent which is the external
// event, which is in processEvents.go
type processEvent struct {
code int // codes above ^
errno int
// these interface pointers used as needed:
jobname string
request maestroSpecs.JobDefinition
}
// new internal process Event
func newProcessEvent(jobname string, code int) (ret *processEvent) {
//ret := new(processEvent)
ret = &processEvent{code, 0, jobname, nil}
return
}
func newProcessEventFromExisting(ev *processEvent, code int) (ret *processEvent) {
//ret := new(processEvent)
ret = &processEvent{code, 0, ev.jobname, ev.request}
return
}
func newShutdownEvent() (ret *processEvent) {
ret = &processEvent{internalEvent_shutdown, 0, "", nil}
return
}
// var containerTemplatesByName map[string]*ContainerTemplate
// var jobsByName map[string]*processStatus
var containerTemplatesByName *hashmap.HashMap
var jobsByName *hashmap.HashMap
var controlChan chan *processEvent
var internalTicker *time.Ticker
var statsConfig ProcessStatsConfig
var monitorWorkerRunning int32
var globalDepGraph dependencyGraph // defined in depGraph.go
var graphValidated = bool(true) // the graph is empty to begin with, which is validated
const (
worker_stopped = iota
worker_started = iota
)
var re_this_dir *regexp.Regexp // {{thisdir}}
var re_cwd *regexp.Regexp // {{cwd}}
var THIS_DIR string
var CWD string
func updateMacroVars() {
cwd, err := os.Getwd()
if err == nil {
CWD = cwd
}
}
const (
EPOLLET = 1 << 31
MaxEpollEvents = 32
)
type epollListener struct {
shutdown_messageListener int // 1 == shutdown, atomic
wakeup_fd_messageListener *WakeupFd
epfd int // the epoll() fd
// event syscall.EpollEvent
events [MaxEpollEvents]syscall.EpollEvent
fdToJob *hashmap.HashMap
}
var mainEpollListener *epollListener
func newEpollListener() (ret *epollListener, e error) {
if epfd, e := syscall.EpollCreate1(0); e == nil {
ret = new(epollListener)
ret.epfd = epfd
ret.fdToJob = hashmap.New(10)
} else {
debugging.DEBUG_OUT("!!!!!!!!!!! Error creating epoll FD: %s\n", e.Error())
}
return
}
const listener_shutdown_magic_num = 99
// this worker deals specifically with listening for processes
// which are using the process_OK_message feedback for maestro.
//
func (this *epollListener) listener() {
var event syscall.EpollEvent
ok_message_len := len(process_OK_message)
ok_first_char := []rune(process_OK_message)[0]
// var local_buf [ok_message_len*4]byte
var local_buf = make([]byte, ok_message_len*4, ok_message_len*4)
wakeup_fd, err := NewWakeupFd()
if err != nil {
// bad news!
//
debugging.DEBUG_OUT("CRITICAL - could not create a FD for wakingup processMessageListener() thread. FAILING\n")
return
}
this.wakeup_fd_messageListener = wakeup_fd
// add in our wakeup FD
event.Events = syscall.EPOLLIN
event.Fd = int32(wakeup_fd.fd_read)
debugging.DEBUG_OUT("add FD from event_fd %d to epoll FD %d\n", wakeup_fd.fd_read, this.epfd)
if e := syscall.EpollCtl(this.epfd, syscall.EPOLL_CTL_ADD, this.wakeup_fd_messageListener.fd_read, &event); e != nil {
debugging.DEBUG_OUT("CRITICAL - could not add FD for waking up epoll - epoll_ctl: %+v\n", e)
return
}
// loop forever waiting for stuff
debugging.DEBUG_OUT("epollListener FD %d - listener() loop starting\n", this.epfd)
for {
nevents, e := syscall.EpollWait(this.epfd, this.events[:], -1)
if e != nil {
debugging.DEBUG_OUT("ERROR - epoll_wait: %+v\n", e)
}
if this.shutdown_messageListener > 0 {
break
}
for ev := 0; ev < nevents; ev++ {
if int(this.events[ev].Fd) == this.wakeup_fd_messageListener.fd_read {
val, err2 := this.wakeup_fd_messageListener.ReadWakeup() // clear the wakeup
if err2 == nil {
if val == listener_shutdown_magic_num {
debugging.DEBUG_OUT("epollListener listener() got shutdown magic num\n")
this.shutdown_messageListener = 1
} else {
debugging.DEBUG_OUT("epollListener listener() got wakeup\n")
}
} else {
debugging.DEBUG_OUT("ERROR on WakeupFd ReadWakeup() %s\n", err2.Error())
}
} else {
// it must be a process we are waiting for it's OK string
val, ok := this.fdToJob.GetHashedKey(uintptr(this.events[ev].Fd))
if ok {
process_ready := false
job := (*processStatus)(val)
var _p0 unsafe.Pointer
currlen := len(job.startMessageBuf)
remain := ok_message_len - currlen
_p0 = unsafe.Pointer(&local_buf[0])
r0, _, e1 := syscall.RawSyscall(syscall.SYS_READ, uintptr(this.events[ev].Fd), uintptr(_p0), uintptr(remain))
n := int(r0)
if e1 != 0 {
// errno = e1
} else {
if n > 0 {
offset := -1
stringified := string(local_buf[:n])
// fast path:
if currlen == 0 && len(stringified) >= remain {
if stringified[:ok_message_len] == process_OK_message {
process_ready = true
}
} else {
// longer path
a := []rune(stringified) // convert to array of codepoints
if currlen == 0 {
for i, c := range a {
if c == ok_first_char {
offset = i
break
}
}
if offset == -1 {
// nothing, the output had no 'process_OK_message'
continue
}
} else {
offset = 0
}
take := len(a)
if take > remain {
take = remain
}
job.startMessageBuf = append(job.startMessageBuf, a[offset:take]...)
if (len(job.startMessageBuf) == ok_message_len) && (string(job.startMessageBuf) == process_OK_message) {
process_ready = true
}
}
if process_ready {
this.removeProcessFDListen(int(this.events[ev].Fd))
// switch it over to stdout log capture and report ready:
var originid uint32
if job.originLabelId > 0 {
originid = job.originLabelId
} else {
originid = greasego.GetUnusedOriginId()
}
greasego.AddFDForStdout(int(this.events[ev].Fd), originid)
greasego.AddOriginLabel(job.originLabelId, job.job.GetJobName())
job.status = RUNNING
// submit an event that process is RUNNING
debugging.DEBUG_OUT("Got process_ready (OK string) for %s\n", job.job.GetJobName())
controlChan <- newProcessEvent(job.job.GetJobName(), internalEvent_job_running)
//
}
}
}
} // if ok
}
}
} // big for{}
}
func (this *epollListener) removeProcessFDListen(fd int) (e error) {
var event syscall.EpollEvent
event.Events = syscall.EPOLLIN
event.Fd = int32(fd)
this.fdToJob.DelHashedKey(uintptr(fd))
if e = syscall.EpollCtl(this.epfd, syscall.EPOLL_CTL_DEL, fd, &event); e != nil {
debugging.DEBUG_OUT("ERROR: epoll_ctl DEL: %+v\n", e)
}
// wakeup listener
this.wakeup_fd_messageListener.Wakeup(1)
return
}
func (this *epollListener) addProcessFDListen(fd int, job *processStatus) (e error) {
var event syscall.EpollEvent
event.Events = syscall.EPOLLIN
event.Fd = int32(fd)
job.startMessageBuf = make([]rune, 0, len(process_OK_message))
this.fdToJob.SetHashedKey(uintptr(fd), unsafe.Pointer(job))
if e = syscall.EpollCtl(this.epfd, syscall.EPOLL_CTL_ADD, fd, &event); e != nil {
debugging.DEBUG_OUT("ERROR: epoll_ctl: %+v\n", e)
}
// wakeup listener
this.wakeup_fd_messageListener.Wakeup(1)
return
}
func (this *epollListener) shutdownListener() {
// wakeup listener
this.wakeup_fd_messageListener.Wakeup(listener_shutdown_magic_num)
}
func init() {
processIndexByPid = hashmap.New(10)
compositeProcessesById = hashmap.New(10)
atomic.StoreInt32(&monitorWorkerRunning, worker_stopped)
containerTemplatesByName = hashmap.New(10)
jobsByName = hashmap.New(10)
controlChan = make(chan *processEvent, 100) // buffer up to 100 events
re_this_dir = regexp.MustCompile(`\{\{thisdir\}\}`)
re_cwd = regexp.MustCompile(`\{\{cwd\}\}`)
folderPath, err2 := osext.ExecutableFolder()
if err2 == nil {
THIS_DIR = folderPath
} else {
fmt.Printf("ERROR - could not get maestro executable folder. {{thisdir}} macro will fail.")
}
updateMacroVars()
// NEVER_RAN = iota
// RUNNING = iota
// STOPPED = iota
// WAITING_FOR_DEPS = iota
// STARTING = iota
// STOPPING = iota
// RESTARTING = iota
// FAILED = iota
stringOfStatus = map[int]string{
NEVER_RAN: "NEVER_RAN",
RUNNING: "RUNNING",
STARTING: "STARTING",
STOPPING: "STOPPING",
STOPPED: "STOPPED",
WAITING_FOR_DEPS: "WAITING_FOR_DEPS",
RESTARTING: "RESTARTING",
FAILED: "FAILED",
}
}
// Should be called when a job successfully starts, named jobstarted
// to see if any other jobs were waiting on it as a dependency
// If there are jobs - then it sends events to start those.
func startStartableJobs(jobstarted string) {
debugging.DEBUG_OUT2("startStartableJobs()--->\n")
for job := range jobsByName.Iter() {
val := job.Value
debugging.DEBUG_OUT("ITER %+v\n", val)
if val != nil {
j := (*processStatus)(val)
debugging.DEBUG_OUT2("ITER processStatus %+v\n", j)
if j.status == WAITING_FOR_DEPS {
StartJob(j.job.GetJobName())
}
}
}
}
func _internalStartProcess(proc_status *processStatus, orig_event *processEvent, sendthis []byte, procIdentifier string) { //ev *processEvent,
var opts *ExecFileOpts
var originatingJob maestroSpecs.JobDefinition
// FIXME / TODO - note, this entire merging of options between container, job and composite ID / process
// is a bit of a mess. We need to have a more organized approach here.
originatingJob = proc_status.job
procName := procIdentifier
if originatingJob == nil {
debugging.DEBUG_OUT("NOTE: don't have originating job\n")
if orig_event != nil {
originatingJob = orig_event.request
} else {
procLogErrorf("Malformed process in _internalStartProcess() - be advised. Don't have an originating Job.\n")
}
} else {
procName = originatingJob.GetJobName()
}
// }
if len(proc_status.compositeId) > 0 {
opts = NewExecFileOpts("", proc_status.compositeId)
} else {
opts = NewExecFileOpts(procName, "")
}
debugging.DEBUG_OUT2("_internalStartProcess 1.1\n")
if originatingJob == nil {
opts.SetNewSid()
} else {
if originatingJob.IsDaemonize() {
opts.SetNewSid()
} else {
debugging.DEBUG_OUT2("_internalStartProcess 2\n")
if originatingJob.GetPgid() < 1 {
opts.SetNewPgid()
} else {
opts.SetUsePgid(originatingJob.GetPgid())
}
}
}
if (proc_status.job != nil && proc_status.job.IsDieOnParentDeath()) || proc_status.dieOnParentDeath {
proc_status.dieOnParentDeath = true
opts.internal.die_on_parent_sig = 1
}
if proc_status.send_GREASE_ORIGIN_ID {
opts.internal.env_GREASE_ORIGIN_ID = 1
}
env := proc_status.execEnv
if originatingJob != nil && originatingJob.IsInheritEnv() {
env = append(env, os.Environ()...)
}
debugging.DEBUG_OUT("_internalStartProcess 3\n")
var errno int
var pid int
args := proc_status.execArgs
path := proc_status.execPath
// there can not be both a message and the sendthis data.
// sendthis is usually used for a composite process, and sending its configuration.
// If this happens, then we will use sendthis, but throw a warning that message was set
//
// setup stdin message if one is provided (otherwise just set to NULL)
var msg string
if originatingJob != nil {
msg = originatingJob.GetMessageForProcess()
if len(msg) > 0 {
if len(sendthis) > 0 {
procLogWarnf("NOTE: the .message option was configured for Job %s - but this Job is part of a composite process. The config object will take precendence.\n", proc_status.job.GetJobName())
} else {
opts.SetMessageString(msg)
}
}
}
if len(sendthis) > 0 {
opts.SetMessageString(string(sendthis))
}
// if it is a composite Job, use the composite Job ID, otherwise use the JobName
if len(proc_status.compositeId) > 0 {
opts.SetJobName(proc_status.compositeId)
} else {
opts.SetJobName(procName)
}
opts.SetOkString(proc_status.usesOKString)
if len(args) > 0 {
pid, errno = ExecFile(path, args, env, opts)
} else {
pid, errno = ExecFile(path, nil, env, opts)
}
proc_status.originLabelId = opts.GetOriginLabelId()
if errno != 0 {
proc_status.status = FAILED
proc_status.setAllChildJobStatus(FAILED)
next_ev := newProcessEventFromExisting(orig_event, internalEvent_job_failed)
controlChan <- next_ev
} else {
// status RUNNING or
proc_status.pid = pid
if proc_status.usesOKString {
// if there was a message to send, then we are waiting on an "!!OK!!"
// from the process
debugging.DEBUG_OUT(" Job: %s is STARTING\n", procName)
// TODO add listener to mainEpollListener
stdoutfd := opts.GetStdoutFd()
if stdoutfd == 0 {
debugging.DEBUG_OUT("CRITICAL - stdout FD for new process is zero!\n")
} else {
mainEpollListener.addProcessFDListen(stdoutfd, proc_status)
}
proc_status.status = STARTING
proc_status.setAllChildJobStatus(STARTING)
ev := new(ProcessEvent)
ev.Name = "job_started"
ev.Pid = pid
ev.When = time.Now().UnixNano()
if proc_status.job != nil {
ev.Job = proc_status.job.GetJobName()
}
// TODO make Job name for master process
SubmitEvent(ev)
} else {
if proc_status.deferRunningStatus > 0 {
debugging.DEBUG_OUT("Deferring RUNNING status change for %s\n", procName)
procLogDebugf("Deferring RUNNING status change for %s for %d ms\n", procName, proc_status.deferRunningStatus)
go func(jobname string, pid int, proc_status *processStatus) {
time.Sleep(time.Millisecond * time.Duration(proc_status.deferRunningStatus))
_setJobToRunning(jobname, pid, proc_status)
procLogDebugf("Now setting RUNNING status change for %s for %d ms\n", procName, proc_status.deferRunningStatus)
proc_status.setAllChildJobStatus(RUNNING)
controlChan <- newProcessEvent(procName, internalEvent_job_running)
}(procName, pid, proc_status)
} else {
_setJobToRunning(procName, pid, proc_status)
}
}
}
}
func _setJobToRunning(jobname string, pid int, proc_status *processStatus) {
proc_status.lockingSetStatus(RUNNING)
debugging.DEBUG_OUT(" Job: %s is RUNNING\n", jobname)
proc_status.setAllChildJobStatus(RUNNING)
ev := new(ProcessEvent)
ev.Name = "job_running"
ev.Pid = pid
if proc_status.job != nil {
ev.Job = proc_status.job.GetJobName()
}
ev.When = time.Now().UnixNano()
// ProcessEvents.Push(ev)
SubmitEvent(ev)
if proc_status.job != nil {
startStartableJobs(proc_status.job.GetJobName())
} else {
startStartableJobs("") // FIXME - this works for now
}
}
func _startCompositeProcessJobs(proc *processStatus, ev *processEvent) (err error) {
templName := proc.job.GetContainerTemplate()
var templStatus *containerStatus
var masterP *processStatus
childList := []*processStatus{}
_innerStart := func() (err error) {
configOut := []byte{}
config := configMgr.NewCompositeProcessConfigPayload()
if masterP.send_composite_jobs_to_stdin {
for _, child := range childList {
config.Moduleconfigs[child.job.GetJobName()] = child.job
}
config.ProcessConfig = templStatus.container.GetCompositeConfig()
configOut, err = json.Marshal(config)
if err != nil {
return
}
}
if templStatus.container.IsDieOnParentDeath() {
masterP.dieOnParentDeath = true
}
_internalStartProcess(masterP, ev, configOut, proc.compositeId)
return
// if send_composite_jobs_to_stdin, then JSON-ify and ready string
//
// start process
// emit start event for all Jobs it has
}
if len(templName) > 0 {
val, ok := containerTemplatesByName.GetStringKey(templName)
if ok {
templStatus = (*containerStatus)(val)
} else {
joberr := new(JobError)
joberr.Code = JOBERROR_MISSING_CONTAINER_TEMPLATE
joberr.JobName = proc.job.GetJobName()
joberr.Aux = "_startCompositeProcessJobs can't find container template: " + templName
err = joberr
}
// see if the master process is already running...
unsafep, ok := compositeProcessesById.GetStringKey(proc.compositeId)
if ok {
masterP = (*processStatus)(unsafep)
if masterP.compositeContainerTemplate != templName {
joberr := new(JobError)
joberr.Code = JOBERROR_INVALID_CONFIG
joberr.JobName = proc.job.GetJobName()
joberr.Aux = "_startCompositeProcessJobs attempting to start jobs with differing container templates"
err = joberr
}
// find all jobs which use this composite ID
for el := range jobsByName.Iter() {
if el.Value != nil {
child := (*processStatus)(el.Value)
if child.compositeId == proc.compositeId {
childList = append(childList, child)
}
}
}