File: tty.go

package info (click to toggle)
golang-github-mesos-mesos-go 0.0.6%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 11,724 kB
  • sloc: makefile: 163
file content (217 lines) | stat: -rw-r--r-- 5,076 bytes parent folder | download
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
package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"

	"github.com/mesos/mesos-go/api/v1/lib"
)

// #include <stdio.h>
// #include <stdlib.h>
// #include <termios.h>
// #include <unistd.h>
// #include <fcntl.h>
// #include <sys/ioctl.h>
//
// /* because golang doesn't like the ... param of ioctl */
// int ioctl_winsize(int d, unsigned long request, void *buf) {
//   return ioctl(d, request, buf);
// }
//
import "C"
import "unsafe"

type cleanups struct {
	ops  []func()
	once sync.Once
}

func (c *cleanups) unwind() {
	c.once.Do(func() {
		for _, f := range c.ops {
			defer f()
		}
	})
}

func (c *cleanups) push(f func()) {
	if f != nil {
		c.ops = append(c.ops, f)
	}
}

type ttyDevice struct {
	fd               int
	cancel           chan struct{}
	winch            chan mesos.TTYInfo_WindowSize
	cleanups         *cleanups
	original_winsize C.struct_winsize
}

func (t *ttyDevice) Done() <-chan struct{} { return t.cancel }
func (t *ttyDevice) Close()                { t.cleanups.unwind() }

func initTTY() (_ *ttyDevice, err error) {
	return newTTY(
		ttyConsoleAttach(&os.Stdin, &os.Stdout, &os.Stderr),
		ttyWinch,
		ttyTermReset,
	)
}

func newTTY(opts ...ttyOption) (_ *ttyDevice, err error) {
	tty := ttyDevice{
		cancel:   make(chan struct{}),
		cleanups: new(cleanups),
	}
	tty.cleanups.push(func() { close(tty.cancel) })
	defer func() {
		if err != nil {
			tty.Close()
		}
	}()

	ttyname := C.ctermid((*C.char)(unsafe.Pointer(nil)))
	if p := (*C.char)(unsafe.Pointer(ttyname)); p == nil {
		err = fmt.Errorf("failed to get tty name")
		return
	}

	tty.fd, _ = syscall.Open(C.GoString(ttyname), syscall.O_RDWR, 0)
	if tty.fd < 0 {
		err = fmt.Errorf("failed to open tty device: %d", tty.fd)
		return
	}
	tty.cleanups.push(func() { syscall.Close(tty.fd) })

	var original_termios C.struct_termios
	result := C.tcgetattr(C.int(tty.fd), &original_termios)
	if result < 0 {
		err = fmt.Errorf("failed getting termios: %d", result)
		return
	}

	new_termios := original_termios
	C.cfmakeraw(&new_termios)
	result = C.tcsetattr(C.int(tty.fd), C.TCSANOW, &new_termios)
	if result < 0 {
		err = fmt.Errorf("failed setting termios: %d", result)
		return
	}
	tty.cleanups.push(func() {
		r := C.tcsetattr(C.int(tty.fd), C.TCSANOW, &original_termios)
		if r < 0 {
			log.Printf("failed to set original termios: %d", r)
		}
	})

	// use this local var instead of tty.original_winsize to avoid cgo complaints about double-pointers
	var original_winsize C.struct_winsize
	result = C.ioctl_winsize(0, C.TIOCGWINSZ, unsafe.Pointer(&original_winsize))
	if result < 0 {
		err = fmt.Errorf("failed to get winsize: %d", result)
		return
	}
	tty.original_winsize = original_winsize
	tty.cleanups.push(func() {
		r := C.ioctl_winsize(0, C.TIOCSWINSZ, unsafe.Pointer(&original_winsize))
		if r < 0 {
			log.Printf("failed to set winsize: %d", r)
		}
	})

	log.Printf("original window size is %d x %d\n", tty.original_winsize.ws_col, tty.original_winsize.ws_row)

	for _, f := range opts {
		if f != nil {
			f(&tty)
		}
	}

	return &tty, nil
}

type ttyOption func(*ttyDevice)

func ttyConsoleAttach(stdin, stdout, stderr **os.File) ttyOption {
	swapfd := func(newfd uintptr, name string, target **os.File) func() {
		f := os.NewFile(newfd, name)
		if f == nil {
			panic(fmt.Sprintf("failed to swap fd for %q", name))
		}
		old := *target
		*target = f
		return func() {
			*target = old
		}
	}
	return func(tty *ttyDevice) {
		tty.cleanups.push(swapfd(uintptr(tty.fd), "tty", stdout))
		tty.cleanups.push(swapfd(uintptr(tty.fd), "tty", stderr))
		tty.cleanups.push(swapfd(uintptr(tty.fd), "tty", stdin))
	}
}

func ttyWinch(tty *ttyDevice) {
	// translate window-size signals into chan events
	c := make(chan os.Signal, 1)
	tty.winch = make(chan mesos.TTYInfo_WindowSize, 1)
	tty.winch <- mesos.TTYInfo_WindowSize{
		Rows:    uint32(tty.original_winsize.ws_row),
		Columns: uint32(tty.original_winsize.ws_col),
	}
	go func() {
		defer signal.Reset(os.Signal(syscall.SIGWINCH))
		for {
			select {
			case <-c:
				signal.Ignore(os.Signal(syscall.SIGWINCH))
				var temp_winsize C.struct_winsize
				r := C.ioctl_winsize(0, C.TIOCGWINSZ, unsafe.Pointer(&temp_winsize))
				if r < 0 {
					panic(fmt.Sprintf("failed to get winsize: %d", r))
				}
				ws := mesos.TTYInfo_WindowSize{
					Rows:    uint32(temp_winsize.ws_row),
					Columns: uint32(temp_winsize.ws_col),
				}
				select {
				case <-tty.Done():
					return
				case tty.winch <- ws:
					signal.Notify(c, os.Signal(syscall.SIGWINCH))
				}
			case <-tty.Done():
				return
			}
		}
	}()
	signal.Notify(c, os.Signal(syscall.SIGWINCH))
}

func ttyTermReset(tty *ttyDevice) {
	var (
		// cleanup properly upon SIGTERM
		term = make(chan os.Signal, 1)
		done = make(chan struct{})
	)
	go func() {
		select {
		case <-term:
			tty.cleanups.unwind()
			os.Exit(0)
		case <-done:
			//println("stop waiting for SIGTERM")
		}
	}()
	tty.cleanups.push(func() {
		signal.Reset(os.Signal(syscall.SIGTERM))
		close(done) // stop waiting for a signal
	})
	signal.Notify(term, os.Signal(syscall.SIGTERM))
}