YkLib 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (125) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +11 -0
  3. data/.rspec +3 -0
  4. data/.travis.yml +6 -0
  5. data/CODE_OF_CONDUCT.md +74 -0
  6. data/Gemfile +7 -0
  7. data/Gemfile.lock +34 -0
  8. data/LICENSE.txt +21 -0
  9. data/README.md +44 -0
  10. data/Rakefile +6 -0
  11. data/YkLib.gemspec +29 -0
  12. data/bin/console +14 -0
  13. data/bin/setup +8 -0
  14. data/lib/YkLib/Yk/__advance__.rb +151 -0
  15. data/lib/YkLib/Yk/__defun__.rb +44 -0
  16. data/lib/YkLib/Yk/__hook__.rb +244 -0
  17. data/lib/YkLib/Yk/__minmax__.rb +123 -0
  18. data/lib/YkLib/Yk/__stdlog.rb +329 -0
  19. data/lib/YkLib/Yk/adhocLiterals/email.rb +119 -0
  20. data/lib/YkLib/Yk/adhocLiterals/path.rb +402 -0
  21. data/lib/YkLib/Yk/adhocLiterals/tag.rb +19 -0
  22. data/lib/YkLib/Yk/adhocLiterals/url.rb +36 -0
  23. data/lib/YkLib/Yk/adhocLiterals.rb +199 -0
  24. data/lib/YkLib/Yk/auto_escseq.rb +5 -0
  25. data/lib/YkLib/Yk/auto_pstore.rb +179 -0
  26. data/lib/YkLib/Yk/bsearch.rb +120 -0
  27. data/lib/YkLib/Yk/clambda.rb +309 -0
  28. data/lib/YkLib/Yk/confLine.rb +423 -0
  29. data/lib/YkLib/Yk/create_tty_width_available.rb +24 -0
  30. data/lib/YkLib/Yk/crypt.rb +26 -0
  31. data/lib/YkLib/Yk/debug2 +1 -0
  32. data/lib/YkLib/Yk/debug2.rb +473 -0
  33. data/lib/YkLib/Yk/debugout.rb +139 -0
  34. data/lib/YkLib/Yk/email_tz.rb +533 -0
  35. data/lib/YkLib/Yk/enum_expect.rb +170 -0
  36. data/lib/YkLib/Yk/errlog.rb +5 -0
  37. data/lib/YkLib/Yk/escseq.rb +59 -0
  38. data/lib/YkLib/Yk/eval_alt.rb +281 -0
  39. data/lib/YkLib/Yk/expector.rb +93 -0
  40. data/lib/YkLib/Yk/fetch.rb +556 -0
  41. data/lib/YkLib/Yk/fetch_old.rb +290 -0
  42. data/lib/YkLib/Yk/fib.rb +158 -0
  43. data/lib/YkLib/Yk/file_aux.rb +843 -0
  44. data/lib/YkLib/Yk/file_aux2.rb +919 -0
  45. data/lib/YkLib/Yk/file_aux_old.rb +160 -0
  46. data/lib/YkLib/Yk/filemod.rb +19 -0
  47. data/lib/YkLib/Yk/force_escseq.rb +3 -0
  48. data/lib/YkLib/Yk/generator__.rb +144 -0
  49. data/lib/YkLib/Yk/generator__.rb.org +139 -0
  50. data/lib/YkLib/Yk/indenter/argless_case.rb +46 -0
  51. data/lib/YkLib/Yk/indenter/each_token.rb +671 -0
  52. data/lib/YkLib/Yk/indenter/free_case.rb +313 -0
  53. data/lib/YkLib/Yk/indenter/if_less.rb +53 -0
  54. data/lib/YkLib/Yk/indenter/independent_ensure.rb +23 -0
  55. data/lib/YkLib/Yk/indenter/independent_rescue.rb +23 -0
  56. data/lib/YkLib/Yk/indenter/operand_circumflex.rb +0 -0
  57. data/lib/YkLib/Yk/indenter/operand_period.rb +16 -0
  58. data/lib/YkLib/Yk/indenter/parenless_and.rb +37 -0
  59. data/lib/YkLib/Yk/indenter/post_test.rb +48 -0
  60. data/lib/YkLib/Yk/indenter/token.rb +1525 -0
  61. data/lib/YkLib/Yk/indenter.rb +1382 -0
  62. data/lib/YkLib/Yk/inot.rb +265 -0
  63. data/lib/YkLib/Yk/intf.rb +815 -0
  64. data/lib/YkLib/Yk/io_aux.rb +1332 -0
  65. data/lib/YkLib/Yk/ioctl.rb +60 -0
  66. data/lib/YkLib/Yk/ipcc.rb +87 -0
  67. data/lib/YkLib/Yk/ipcountry.rb +207 -0
  68. data/lib/YkLib/Yk/ipv4adr.rb +318 -0
  69. data/lib/YkLib/Yk/localmail.rb +276 -0
  70. data/lib/YkLib/Yk/method_chain.rb +359 -0
  71. data/lib/YkLib/Yk/misc_tz.rb +1716 -0
  72. data/lib/YkLib/Yk/missing_method.rb +50 -0
  73. data/lib/YkLib/Yk/mojiConv.rb +257 -0
  74. data/lib/YkLib/Yk/nostdlog.rb +4 -0
  75. data/lib/YkLib/Yk/on_marshal.rb +20 -0
  76. data/lib/YkLib/Yk/overrider.rb +47 -0
  77. data/lib/YkLib/Yk/path.rb +293 -0
  78. data/lib/YkLib/Yk/path_aux.rb +883 -0
  79. data/lib/YkLib/Yk/path_aux_alt.rb +0 -0
  80. data/lib/YkLib/Yk/path_rep.rb +1267 -0
  81. data/lib/YkLib/Yk/pg_setup.rb +917 -0
  82. data/lib/YkLib/Yk/procinfo.rb +314 -0
  83. data/lib/YkLib/Yk/proclist.rb +492 -0
  84. data/lib/YkLib/Yk/property.rb +863 -0
  85. data/lib/YkLib/Yk/ranger.rb +606 -0
  86. data/lib/YkLib/Yk/resolv_tz.rb +88 -0
  87. data/lib/YkLib/Yk/rlprompt.rb +73 -0
  88. data/lib/YkLib/Yk/rootexec.rb +48 -0
  89. data/lib/YkLib/Yk/rpm-packageproxy.rb +784 -0
  90. data/lib/YkLib/Yk/rpm-packageproxy2.rb +1430 -0
  91. data/lib/YkLib/Yk/rwhen.rb +21 -0
  92. data/lib/YkLib/Yk/selector.rb +124 -0
  93. data/lib/YkLib/Yk/set.rb +170 -0
  94. data/lib/YkLib/Yk/shellquote.rb +300 -0
  95. data/lib/YkLib/Yk/sio.rb +1001 -0
  96. data/lib/YkLib/Yk/sio0.rb +835 -0
  97. data/lib/YkLib/Yk/sio_aux.rb +1524 -0
  98. data/lib/YkLib/Yk/sio_inot.rb +86 -0
  99. data/lib/YkLib/Yk/sock_aux.rb +42 -0
  100. data/lib/YkLib/Yk/spipe.rb +843 -0
  101. data/lib/YkLib/Yk/sql_table.rb +565 -0
  102. data/lib/YkLib/Yk/stdlog.rb +4 -0
  103. data/lib/YkLib/Yk/syscommand.rb +173 -0
  104. data/lib/YkLib/Yk/sysinit.rb +75 -0
  105. data/lib/YkLib/Yk/ttyFontWidth.rb +46113 -0
  106. data/lib/YkLib/Yk/tty_char.dump +0 -0
  107. data/lib/YkLib/Yk/tty_char.rb +47 -0
  108. data/lib/YkLib/Yk/tty_char_create.rb +437031 -0
  109. data/lib/YkLib/Yk/tty_char_static.rb +437016 -0
  110. data/lib/YkLib/Yk/tty_rewrite.rb +142 -0
  111. data/lib/YkLib/Yk/tty_str.rb +461 -0
  112. data/lib/YkLib/Yk/tty_width.dat.rb +114 -0
  113. data/lib/YkLib/Yk/tty_width.rb +180 -0
  114. data/lib/YkLib/Yk/tty_width_available +569 -0
  115. data/lib/YkLib/Yk/tty_width_list +0 -0
  116. data/lib/YkLib/Yk/tty_width_list.linux +280 -0
  117. data/lib/YkLib/Yk/tty_width_list.windows +324 -0
  118. data/lib/YkLib/Yk/tz_tty +0 -0
  119. data/lib/YkLib/Yk/tz_tty.rb +0 -0
  120. data/lib/YkLib/Yk/uprepos.rb +94 -0
  121. data/lib/YkLib/Yk/userinfo.rb +91 -0
  122. data/lib/YkLib/Yk/with.rb +109 -0
  123. data/lib/YkLib/version.rb +3 -0
  124. data/lib/YkLib.rb +6 -0
  125. metadata +170 -0
@@ -0,0 +1,917 @@
1
+ require 'Yk/path_aux'
2
+ require 'Yk/debug2'
3
+ require 'Yk/misc_tz'
4
+
5
+
6
+ p >> "./test.rb.debug"
7
+
8
+
9
+ require 'Yk/mojiConv'
10
+
11
+
12
+ require 'binding_of_caller'
13
+ require 'Yk/debug2'
14
+ require 'pg'
15
+ require "shellwords"
16
+
17
+ using Code
18
+
19
+
20
+ module PGSetup
21
+
22
+ module_function
23
+ def YkDBUserDir user = Etc::EUser.name
24
+ Etc::User.home(user) / ".yk_postgres"
25
+ end
26
+
27
+ def YkDBPassword user
28
+ (YkDBUserDir(user) / "password")._?[:_r?]&.read
29
+ end
30
+
31
+ def getPostgresPid
32
+ %W{ps ax --cols 10000}.read_each_line_p do |ln|
33
+ if Etc::User.uid("postgres") == "/proc/#{pid = ln.strip.split[0]}"._?[:_e?]&.stat&.uid && ln =~ /:\d\d\s+postgres\s+/
34
+ p ln.strip.split[0]
35
+ p pid
36
+ return pid
37
+ end
38
+ end
39
+ return nil
40
+ end
41
+
42
+ def setPostgresEnvParam
43
+ #起動中のpostgresポート
44
+ $pgdata, $pgport = nil
45
+ analparam = ->{
46
+ p _1
47
+ _1.each_cons 2 do |a, b|
48
+ a.gsub! /[\'\"]/, ""
49
+ b.gsub! /[\'\"]/, ""
50
+ p a, b
51
+ case a
52
+ when "-D"
53
+ if b =~ /\//
54
+ p.cyan
55
+ $pgdata ||= b
56
+ end
57
+ when "-p"
58
+ if b =~ /^\d+$/
59
+ p.cyan
60
+ $pgport ||= b
61
+ end
62
+ end
63
+ end
64
+ }
65
+ pid = getPostgresPid
66
+ p pid
67
+ if pid
68
+ analparam.("/proc/#{pid}/cmdline".read.split("\0"))
69
+ if Process.euid == 0
70
+ if `netstat -ltnp` =~ /\n([^\n]+)\s(#{pid})\/postgres\b/
71
+ if $1 =~ /127.0.0.1:(\d+)/
72
+ $pgport = $1
73
+ end
74
+ end
75
+ end
76
+ end
77
+ #環境変数PGPORT
78
+ $pgdata ||= ENV['PGDATA']
79
+ $pgport ||= ENV['PGPORT']
80
+ #servce_poolかsystemdのポート
81
+ if !$pgdata || !$pgport
82
+ srun = "/etc/service/postgres/run"._r?(&:read) || "/service/postgres/run"._r?(&:read)
83
+ p srun
84
+ sv_pool = false
85
+ if srun
86
+ srun.lines.select{_1 =~ /\bpostgres\b/}.each do |ln|
87
+ analparam.(ln.strip.split)
88
+ if ln.strip_comment.split == %W{exec /etc/service_pool/postgres}
89
+ sv_pool = true
90
+ end
91
+ end
92
+ end
93
+ p.red
94
+ if (!$pgdata || !$pgport) && sv_pool && "/etc/service_pool/postgres"._r?
95
+ p.green
96
+ "/etc/service_pool/postgres".read_each_line do |ln|
97
+ if ln =~ /\bpostgres\b/
98
+ analparam.(ln.strip.split)
99
+ end
100
+ end
101
+ end
102
+ end
103
+ if !$pgdata || !$pgport
104
+ if "/usr/bin/systemctl"._x?
105
+ sctlRes = %W{/usr/bin/systemctl}.read_p12
106
+ p sctlRes
107
+ if sctlRes !~ /Failed to get D-Bus connection:/
108
+ $pgdata ||= `systemctl show -p Environment "${SERVICE_NAME}.service" |
109
+ sed 's/^Environment=//' | tr ' ' '\n' |
110
+ sed -n 's/^PGDATA=//p' | tail -n 1`
111
+ $pgport ||= `systemctl show -p Environment "${SERVICE_NAME}.service" |
112
+ sed 's/^Environment=//' | tr ' ' '\n' |
113
+ sed -n 's/^PGPORT=//p' | tail -n 1`
114
+ else
115
+ p
116
+ %W{/usr/lib /etc}.map{_1 / "systemd/system"}.each do |d|
117
+ p
118
+ (d / "postgresql.service")._?[:_r?]&.then do |f|
119
+ p
120
+ f.read_each_line do |ln|
121
+ case ln.strip_comment
122
+ when /^Environment\=PGPORT\=(.*)/
123
+ $pgport = $1.strip
124
+ p $pgport
125
+ when /^Environment\=PGDATA\=(.*)/
126
+ $pgdata = $1.strip
127
+ p $pgdata
128
+ end
129
+ end
130
+ end
131
+ if $pgport && $pgdata
132
+ p $pgport, $pgdata
133
+ break
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
139
+
140
+
141
+ if $pgport && (tmp = $pgport.strip) !~ /^\d+$/
142
+ if tmp.empty?
143
+ die("Empty service name specified")
144
+ end
145
+ require 'socket'
146
+ begin
147
+ p $pgport
148
+ $pgport = Addrinfo.tcp("127.0.0.1", $pgport).ip_port
149
+ rescue SocketError
150
+ if $! =~ /Servname not supported/
151
+ die("Unknown service name, '#{$pgport}' for postgres port number")
152
+ end
153
+ end
154
+ end
155
+ if !$pgdata || !$pgport
156
+ STDERR.writeln "Cannot detect database directory and/or server port number\nPlease set environmental variable, PGDATA, PGPORT"
157
+ return nil
158
+ end
159
+ if $pgdata !~ /^\//
160
+ die("Database directory #{$pgdata} is not absolute path.")
161
+ end
162
+ end
163
+
164
+ setPostgresEnvParam
165
+
166
+
167
+ def exec_psql user, cmd
168
+ res = ""
169
+ Code do |code|
170
+ res = ""
171
+ p.purple user, cmd#
172
+ ["psql", "-c", cmd].open "pT", user: user, chdir: :home do |t|
173
+ pass = (Etc::User.home(user) / ".yk_postgres" / "password")._?[:_r?]&.read&.strip
174
+ t.enter_password_if "Password: ", pass do |ln|
175
+ res += ln
176
+ end
177
+ end
178
+ if res =~ /Connection refused/ && code.first?
179
+ p.red res
180
+ restartPostgresDaemon
181
+ sleep 1
182
+ code.redo
183
+ else
184
+ p.purple res
185
+ return res
186
+ end
187
+ end
188
+ end
189
+
190
+ def get_table_schema tName
191
+ res = ""
192
+ pid = nil
193
+ %{pg_dump -t }.open "pT", pid: pid do |t|
194
+ pass = (Etc::User.home(user) / ".yk_postgres" / "password")._?[:_r?]&.read&.strip
195
+ t.enter_password_if "Password: ", pass do |ln|
196
+ res += ln
197
+ end
198
+ begin
199
+ while IO.select [t], [], [], 0.1
200
+ res += t.readpartial(1000)
201
+ end
202
+ rescue EOFError
203
+ break
204
+ end
205
+ end
206
+ res
207
+ end
208
+
209
+ def getLocale
210
+ %W{locale -a}.read_each_line_p do |ln|
211
+ if ln =~ /utf8/
212
+ return ln.strip
213
+ end
214
+ end
215
+ end
216
+
217
+ def createDatabase owner, dbname
218
+ exec_psql "postgres", "CREATE DATABASE #{dbname} TEMPLATE template0 OWNER #{owner} ENCODING = 'UTF8' LC_COLLATE = '#{getLocale}' LC_CTYPE = '#{getLocale}';"
219
+ end
220
+
221
+ def tryConnection user, pw
222
+ p.yellow user, pw
223
+ io = IO.popen '-', "r+"
224
+ p.yellow
225
+ if !io
226
+ begin
227
+ Process.uid = Process.euid = Etc::User.id(user)
228
+ _connectIt(user: user, password: pw)
229
+ rescue PG::ConnectionBad
230
+ print $!.to_s
231
+ p.green $!
232
+ end
233
+ exit 0
234
+ else
235
+ p.yellow
236
+ res = io.read
237
+ p res
238
+ case res
239
+ when /FATAL: password authentication failed for user \"#{Regexp.escape user}\"/
240
+ return :passFailure
241
+ when /role \"#{Regexp.escape user}\" does not exist/
242
+ return :noRole
243
+ when /fe_sendauth: no password supplied/
244
+ return :noPassword
245
+ when /authentication failed/
246
+ return :passFailure
247
+ when /FATAL: the database system is starting up/
248
+ sleep 1
249
+ return tryConnection(user, pw)
250
+ when ""
251
+ return :success
252
+ else
253
+ return res
254
+ end
255
+ end
256
+ end
257
+
258
+ FOR_RESET_POSTGRES_PW = <<END
259
+ # "local" is for Unix domain socket connections only
260
+ local all all peer
261
+ # IPv4 local connections:
262
+ host all all 127.0.0.1/32 ident
263
+ # IPv6 local connections:
264
+ host all all ::1/128 ident
265
+ END
266
+
267
+ FOR_RESET_PW = <<END
268
+ # "local" is for Unix domain socket connections only
269
+ local all all md5
270
+ # IPv4 local connections:
271
+ host all all 127.0.0.1/32 md5
272
+ # IPv6 local connections:
273
+ host all all ::1/128 md5
274
+ END
275
+
276
+
277
+
278
+ def tmpConfFile user
279
+ $access_conf_file = "#{$pgdata}/pg_hba.conf"
280
+ begin
281
+ $access_conf_file.cp $access_conf_file + ".org"
282
+ ($access_conf_file + ".org").chown "postgres", "postgres"
283
+ $access_conf_file.mv $access_conf_file + ".#{Time.now.strftime('%F.%T')}"
284
+ $access_conf_file.write user == "postgres" ? FOR_RESET_POSTGRES_PW : FOR_RESET_PW
285
+ $access_conf_file.chown "postgres", "postgres"
286
+ restartPostgresDaemon
287
+ sleep 3
288
+ yield
289
+ ensure
290
+ ($access_conf_file + ".org").mv $access_conf_file
291
+ restartPostgresDaemon
292
+ end
293
+ end
294
+
295
+
296
+ def resetPassword user, pass
297
+ res = nil
298
+ tmpConfFile user do
299
+ res = exec_psql "postgres", "alter role #{user} with password '#{pass}'"
300
+ end
301
+ if res =~ /role.*does not exist/
302
+ tmpConfFile user do
303
+ res = exec_psql "postgres", "create user #{user} with password '#{pass}'"
304
+ end
305
+ end
306
+ res =~ /ALTER ROLE/
307
+ end
308
+
309
+ def checkConnection user
310
+ TTY.open do |tty|
311
+ tty.writeln "Checking connection for user, '#{user}'"
312
+ pwF = (Etc::User.home(user) / ".yk_postgres").check_dir / "password"
313
+ if pwF._e?
314
+ tty.writeln "Password file, '#{pwF}', found. Use this."
315
+ pw = pwF.read.strip
316
+ else
317
+ tty.writeln "Password file, '#{pwF}', not found."
318
+ pw = tty.prompt_password "Enter password manually: "
319
+ end
320
+ if !pw.empty?
321
+ res = tryConnection user, pw
322
+ else
323
+ res = :emptyPassword
324
+ end
325
+ p.green res
326
+ case res
327
+ when :noRole
328
+ pw2 = tty.prompt_password "Reenter it for confirmation: "
329
+ if pw != pw2
330
+ die "Inconsistent password."
331
+ end
332
+ when :passFailure, :noPassword, :emptyPassword
333
+ tty.write "Authentication failed.\n" if res == :passFailure
334
+ if tty.yn? "Reset (or create new) password."
335
+ pw = tty.prompt_password "Enter new password (or directly enter to generate) : "
336
+ if pw.empty?
337
+ pw = genpassword(12)
338
+ tty.write "Password generated.\n"
339
+ tty.write "Select display(1) or save on '#{pwF}'(2) [1/2] ? "
340
+ r = tty.gets
341
+ case r.strip
342
+ when "1"
343
+ pwF._?[:_e?].unlink
344
+ tty.writeln pw
345
+ when "2"
346
+ pwF.write pw
347
+ else
348
+ die("Illeagal input.")
349
+ end
350
+ else
351
+ pw2 = tty.prompt_password "Reenter it for confirmation: "
352
+ if pw != pw2
353
+ die "Inconsistent password."
354
+ end
355
+ if tty.yn? "Save the password on '#{pwF}'"
356
+ pwF.write pw
357
+ end
358
+ end
359
+ resetPassword user, pw
360
+ else
361
+ die
362
+ end
363
+ when /FATAL: database \"(.*?)\" does not exist/
364
+ res = createDatabase user, $1
365
+ if res.lines[-1] =~ /^ERROR:/
366
+ die($& + $')
367
+ end
368
+ when :success
369
+ return true
370
+ else
371
+ die(res)
372
+ end
373
+ end
374
+ end
375
+
376
+ def _connectIt **opts
377
+ dopts = {
378
+ dbname: "yk_db_#{opts[:user] || Etc::EUser.name}",
379
+ user: opts[:user] || Etc::EUser.name,
380
+ host: '127.0.0.1',
381
+ port: $pgport
382
+ }
383
+ if dopts[:user] == "postgres"
384
+ dopts[:dbname] = "postgres"
385
+ end
386
+ YkDBPassword(dopts[:user])&.then do |pw|
387
+ dopts[:password] = pw
388
+ end
389
+ p.red dopts
390
+ dopts.each do |e, ed|
391
+ p e, ed
392
+ dopts[e] = opts[e] || eval(%{
393
+ p "#{e}"
394
+ #{e}F = ("#{Etc::User.home(dopts[:user])}" / ".yk_postgres").check_dir / "#{e}"
395
+ tmp = #{e}F._?[:_r?]&.read&.strip
396
+ p #{e}F, tmp, "#{ed.class}", Kernel::#{ed.class}(tmp)
397
+ # tmp = #{e}F.`._r?.read.strip
398
+ if tmp
399
+ Kernel::#{ed.class}(tmp)
400
+ else
401
+ #{ed.inspect}
402
+ end
403
+ })
404
+ p.yellow
405
+ end
406
+ (opts.keys - dopts.keys).each do |k|
407
+ dopts[k] = opts[k]
408
+ end
409
+ p caller
410
+ p.red dopts
411
+ begin
412
+ conn = PG.connect(**dopts)
413
+ rescue PG::ConnectionBad
414
+ $!.__defun__ :opts, **dopts
415
+ raise $!
416
+ end
417
+ p.yellow
418
+ conn
419
+ end
420
+
421
+
422
+ def connectIt **opts
423
+ begin
424
+ _connectIt **opts
425
+ rescue PG::ConnectionBad
426
+ if ["localhost", "127.0.0.1", "::1/128", nil].include?($!.opts[:host])
427
+ p.green $!.to_s
428
+ missingSomething = Proc.new do
429
+ if TTY.open do |tty|
430
+ tty.writeln "Cannot connect to local server"
431
+ if tty.yn? "Do you check the install as super user"
432
+ [__FILE__, "check", $!.opts[:user], $!.opts[:dbname]].exec user: :root
433
+ end
434
+ end; else
435
+ die($!.to_s)
436
+ end
437
+ end
438
+ case $!.to_s
439
+ when /fe_sendauth: no password supplied/
440
+ if TTY.open do |tty|
441
+ 3.times do
442
+ if (catch :retry do
443
+ pw = tty.prompt_password "Password: "
444
+ p pw
445
+ if !pw.empty?
446
+ begin
447
+ p
448
+ _connectIt password: pw
449
+ rescue PG::ConnectionBad
450
+ p.green $!
451
+ if $!.to_s !~ /password authentication failed/
452
+ die($!.to_s)
453
+ else
454
+ tty.write "Wrong password, "
455
+ tty.write "retry.\n"
456
+ throw :retry, :thrown
457
+ end
458
+ end
459
+ else
460
+ break
461
+ end
462
+ end) == :thrown; else
463
+ break
464
+ end
465
+ end
466
+ if tty.yn? "Do you reset password by super user"
467
+ [__FILE__, "check", $!.opts[:user], $!.opts[:dbname]].exec user: :root
468
+ end
469
+ end;else
470
+ die "no password supplied."
471
+ end
472
+ when /database.*does not exist/
473
+ TTY.write $&.ln
474
+ if TTY.yn? "Do you create as super user"
475
+ [__FILE__, "check", $!.opts[:user], $!.opts[:dbname]].exec user: :root
476
+ end
477
+ when /could not connect to server: Connection refused/
478
+ p.green "/var/run/postgresql"._d?
479
+ if !"/var/run/postgresql"._d? || !"/usr/bin/psql"._x?
480
+ missingSomething.call
481
+ elsif !getPostgresPid
482
+ STDERR.write $!.to_s
483
+ if TTY.yn? "Do you check as super user"
484
+ [__FILE__, "check", $!.opts[:user], $!.opts[:dbname]].exec user: :root
485
+ end
486
+ else
487
+ die($!.to_s)
488
+ end
489
+ when /FATAL: Ident authentication failed for user/
490
+ missingSomething.call
491
+ when /FATAL: the database system is starting up/
492
+ sleep 1
493
+ retry
494
+ end
495
+ p $!
496
+ die("For checking environment for default local database status for this script,\n execute '#{__FILE__} check'")
497
+ else
498
+ raise $!
499
+ end
500
+ end
501
+ end
502
+
503
+ def restartPostgresDaemon
504
+ if ! "/var/run/postgresql"._e?
505
+ "/var/run/postgresql".mkdir
506
+ "/var/run/postgresql".chown "postgres", "postgres"
507
+ end
508
+ if "/etc/service_pool/postgres"._x? && "/etc/service/postgres.list"._e?
509
+ %W{sv postgres restart}.system
510
+ sleep 1
511
+ elsif "/etc/service/postgres"._d?
512
+ "/etc/service/postgres/down".touch
513
+ sleep 3
514
+ "/etc/service/postgres/down".unlink
515
+ elsif "/service/postgres"._d?
516
+ "/service/postgres/down".touch
517
+ sleep 3
518
+ "/service/postgres/down".unlink
519
+ elsif "/usr/bin/systemctl"._x? && %W{/usr/bin/systemctl status postgres}.read_p12 !~ /Failed to get D-Bus connection:|Unit postgres could not be found/
520
+ p.yellow
521
+ %W{systemctl restart postgres}.system
522
+ sleep 1
523
+ end
524
+ end
525
+
526
+ def stopPostgresDaemon
527
+ if "/etc/service_pool/postgres"._x? && "/etc/service/postgres.list"._e?
528
+ %W{sv postgres stop}.system
529
+ elsif "/etc/service/postgres"._d?
530
+ "/etc/service/postgres/down".touch
531
+ elsif "/service/postgres"._d?
532
+ "/service/postgres/down".touch
533
+ elsif "/usr/bin/systemctl"._x? && %W{/usr/bin/systemctl status postgres}.read_p12 !~ /Failed to get D-Bus connection:|Unit postgres could not be found/
534
+ %W{systemctl stop postgres}.system
535
+ end
536
+ end
537
+
538
+ def disablePostgresDaemon
539
+ if "/etc/service_pool/postgres"._x? && "/etc/service/postgres.list"._e?
540
+ %W{sv postgres delete}.system
541
+ elsif "/usr/bin/systemctl"._x? && %W{/usr/bin/systemctl status postgres}.read_p12 !~ /Failed to get D-Bus connection:|Unit postgres could not be found/
542
+ %W{systemctl disable postgres}.system
543
+ end
544
+ end
545
+
546
+ def deletePostgresDaemon
547
+ "/etc/service_pool/postgres"._?[:_x?]&.then(&:unlink)
548
+ end
549
+
550
+
551
+ def modifyAuthConf
552
+ f = "#{$pgdata}/pg_hba.conf"
553
+ modConfLine = ""
554
+ mod = false
555
+ f.read_each_line do |ln|
556
+ case ln
557
+ when /^(local\s+all\s+all\s+)peer$/
558
+ mod = true
559
+ modConfLine += $1 + "md5".ln
560
+ when /^(host\s+all\s+all\s+127.0.0.1\/32\s+)ident$/
561
+ mod = true
562
+ modConfLine += $1 + "md5".ln
563
+ when /^(host\s+all\s+all\s+::1\/128\s+)ident$/
564
+ mod = true
565
+ modConfLine += $1 + "md5".ln
566
+ else
567
+ mod = true
568
+ modConfLine += ln
569
+ end
570
+ end
571
+ if mod
572
+ f.mv f + ".bak"
573
+ f.write modConfLine
574
+ end
575
+ restartPostgresDaemon
576
+ end
577
+
578
+ if __FILE__.expand_path == $0.expand_path
579
+ case ARGV[0]
580
+ when "check"
581
+ if Process.euid != 0
582
+ if TTY.open do |tty|
583
+ p.yellow
584
+ tty.write $!.to_s.ln
585
+ ret = ENV['PATH'].split /:/ do |pth|
586
+ if (pth / "pg_ctl")._e?
587
+ tty.write "pg_ctl found in #{pth}\n"
588
+ break :exists
589
+ end
590
+ end
591
+ if ret == :exists
592
+ tty.write "cannot connect to postgres\n"
593
+ if tty.yn? "do you want to check environment as super user?"
594
+ ["ruby", __FILE__, "check", ARGV[0]].exec :root
595
+ end
596
+ tty.write "server not running\n"
597
+ exit 1
598
+ else
599
+ if ARGV[2] # database not found
600
+ if tty.yn? "Do you create now as super user"
601
+ ["ruby", __FILE__, "check", ARGV[0], ARGV[1]].exec :root
602
+ end
603
+ else
604
+ tty.write "posgresql-server is not installed\n".red
605
+ if tty.yn? "Do you install now"
606
+ ["ruby", __FILE__, "check", ARGV[0]].exec :root
607
+ end
608
+ end
609
+ exit 1
610
+ end
611
+ end; else
612
+ STDERR.write $!.to_s.ln
613
+ exit 1
614
+ end
615
+ exit 0
616
+ else
617
+ retried = false
618
+
619
+ begin
620
+ p
621
+ _connectIt
622
+ p
623
+ rescue PG::ConnectionBad
624
+ p $!
625
+ case $!.to_s
626
+ when /Connection refused.*127\.0\.0\.1/m
627
+ p
628
+ restartPostgresDaemon
629
+ if !retried
630
+ retried = true
631
+ retry
632
+ end
633
+ when /Ident authentication failed/
634
+ TTY.open do |tty|
635
+ tty.writeln "'#{$pgdata}/pg_hba.conf' has problem."
636
+ if tty.yn? "Correnct it now"
637
+ modifyAuthConf
638
+ end
639
+ end
640
+ when /"FATAL: the database system is starting up/
641
+ sleep 1
642
+ retry
643
+ end
644
+ end
645
+ if "/usr/bin/rpm"._x?
646
+ p.yellow
647
+ doInst = false
648
+ %W{postgresql postgresql-server postgresql-devel}.each do |pkg|
649
+ if %W{/usr/bin/rpm -q #{pkg}}.read_p12 =~ /not installed/
650
+ doInst = true
651
+ break
652
+ end
653
+ end
654
+ if doInst
655
+ %W{yum -y install postgresql postgresql-server postgresql-devel}.system
656
+ end
657
+ elsif "/usr/bin/apt"._x?
658
+ p.yellow
659
+ doInst = false
660
+ lst = %W{postgresql libpq-dev libpq-dev}
661
+ lst.each do |pkg|
662
+ out, err = %W{/usr/bin/dpkg -l #{pkg}}.read_12_each
663
+ if out !~ /i*\s+#{Regexp.escape pkg}\s+/ && err =~ /dpkg\-query: no packages found matching/
664
+ doInst = true
665
+ break
666
+ end
667
+ end
668
+ %W{apt -y install #{lst * ' '}}.system
669
+ out, err = %W{/usr/bin/dpkg -l postgresql}.read_12_each
670
+ ver = '\d+'
671
+ if out =~ /i*\s+postgresql\s+(\d+)/
672
+ ver = $1
673
+ end
674
+ %W{apt list}.read_each_line_p do |ln|
675
+ if ln =~ /^(postgresql-server-dev-#{ver})\//
676
+ %W{apt -y install #{$1}}.system
677
+ end
678
+ end
679
+ end
680
+ p.yellow
681
+ useSystemd = nil
682
+ if !$pgdata || !$pgport
683
+ setPostgresEnvParam
684
+ end
685
+ if !$pgdata || !$pgport
686
+ die("")
687
+ end
688
+ if !"#{$pgdata}/postgresql.conf"._e?
689
+ TTY.open do |tty|
690
+ tty.write "#{$pgdata}/postgresql.conf not found\n"
691
+ if tty.yn? "Do you need setup database?"
692
+ if "/usr/bin/systemctl"._x?
693
+ ev = ENV.clone
694
+ sctlRes = %W{/usr/bin/systemctl}.read_p12
695
+ p sctlRes
696
+ if sctlRes =~ /Failed to get D-Bus connection:/
697
+ f = "/tmp/systemctl_dummy.#{$$}".check_dir / "systemctl"
698
+ p f
699
+ f.write <<~END
700
+ #!/usr/bin/env ruby
701
+
702
+ require 'Yk/path_aux'
703
+
704
+ ARGV.each do |s|
705
+ if s =~ /\.service$/
706
+ "/usr/lib/systemd".recursive do |f|
707
+ if f.basename == s
708
+ print f.read
709
+ exit 0
710
+ end
711
+ end
712
+ end
713
+ end
714
+ END
715
+ f.chmod 0777
716
+ ev['PATH'] = f.dirname + ":" + ev['PATH']
717
+ at_exit do
718
+ f.dirname.rm_rf
719
+ end
720
+ useSystemd = false
721
+ else
722
+ useSystemd = true
723
+ end
724
+ p ev['PATH']
725
+ res = %W{postgresql-setup initdb}.system env: ev, user: :postgres
726
+ if !res
727
+ die("Error: setup database failed.")
728
+ end
729
+ else
730
+ useSystemd = false
731
+ end
732
+ else
733
+ STDERR.write "please execute 'su posgres -c postgresql-setup initdb'\n"
734
+ exit 1
735
+ end
736
+ end
737
+ end
738
+ p.yellow
739
+ if !(rd = "/var/run/postgresql")._d?
740
+ p.yellow
741
+ rd.mkdir
742
+ rd.chown "postgres", "postgres"
743
+ end
744
+ p.yellow
745
+ if !useSystemd
746
+ checkServiceFile = Proc.new do |f|
747
+ if !f._e?
748
+ f.dirname.check_dir
749
+ p.yellow
750
+ f.write <<~END
751
+ #!/bin/bash
752
+
753
+ exec su postgres -c "postgres -D #{$pgdata} -p #{$pgport}"
754
+
755
+ END
756
+ f.chmod 0744
757
+ end
758
+ end
759
+ if "/etc/service_pool"._d? && "/usr/bin/sv"._x?
760
+ checkServiceFile.("/etc/service_pool/postgres")
761
+ if !"/etc/service/postgres.list"._e?
762
+ p
763
+ %W{sv postgres add}.system
764
+ p
765
+ end
766
+ p
767
+ %W{sv postgres start}.system
768
+ p
769
+ sleep 1
770
+ elsif (d = "/service")._d? || (d = "/etc/service")._d?
771
+ checkServiceFile.(d / "postgres/run")
772
+ end
773
+ end
774
+ p.yellow
775
+ if useSystemd
776
+ p.yellow
777
+ %W{systemctl enable postgres}.system
778
+ %W{systemctl start postgres}.system
779
+ sleep 1
780
+ end
781
+
782
+ p
783
+ checkConnection "postgres"
784
+ p
785
+ checkConnection ARGV[1]
786
+ p
787
+
788
+ Code do |code|
789
+ p.yellow
790
+ io = IO.popen '-', "r+"
791
+ p.yellow
792
+ if !io
793
+ begin
794
+ Process.uid = Process.euid = Etc::User.id(ARGV[1])
795
+ opt = {}
796
+ (Etc::EUser.home / ".yk_postgres" / "password")._?[:_r?]&.then do |f|
797
+ opt[:password] = f.read.strip
798
+ end
799
+ _connectIt **opt
800
+ rescue PG::ConnectionBad
801
+ print $!
802
+ end
803
+ exit 0
804
+ else
805
+ p.yellow
806
+ res = io.read
807
+ p res
808
+ case res
809
+ when /FATAL: password authentication failed for user \"#{Regexp.escape ARGV[1]}\"/
810
+
811
+ when /Ident authentication failed/
812
+ if code.first?
813
+ TTY.open do |tty|
814
+ tty.writeln "'#{$pgdata}/pg_hba.conf' has problem."
815
+ if tty.yn? "Correnct it now"
816
+ modifyAuthConf
817
+ code.redo
818
+ end
819
+ end
820
+ else
821
+ die($!.to_s)
822
+ end
823
+ when /FATAL: database \"(.*?)\" does not exist/
824
+ if code.first?
825
+ if TTY.yn? "Database '#{db = $1}' does not exit.\nCreate as superuser"
826
+ createDatabase ARGV[1], db
827
+ code.redo
828
+ end
829
+ else
830
+ die($!.to_s)
831
+ end
832
+ when /role \"#{Regexp.escape ARGV[1]}\" does not exist/
833
+ if TTY.open do |tty|
834
+ pFile = (Etc::User.home("postgres") / ".yk_postgres").check_dir / "password"
835
+ pass = nil
836
+ if pFile._r?
837
+ pass = pFile.read
838
+ else
839
+ if tty.yn? "setting postgres password"
840
+ p.cyan pFile
841
+ pass = tty.setting_password(pFile)
842
+ p.yellow
843
+ pFile.dirname.chown_R "postgres", "postgres"
844
+ p.green
845
+ pFile.dirname.chmod_R 0600
846
+ end
847
+ end
848
+ if pass && !pass.empty?
849
+ pass.gsub! /'/, "\\'"
850
+ res = nil
851
+ ["psql", "-c", "alter role postgres with password '#{pass}'"].open "pT", user: :postgres, chdir: :home do |t|
852
+ p t
853
+ t.enter_password_if "Password: ", pass do |ln|
854
+ res += ln
855
+ end
856
+ end
857
+ p.green res
858
+ if !res
859
+ abort
860
+ end
861
+ else
862
+ tty.write "Please setup password for user 'postgres' in default file (#{pFile}).\n"
863
+ exit 1
864
+ end
865
+ tty.write "Etc::User '#{ARGV[1]}' not registered as database user\n"
866
+ if tty.yn? "Register '#{ARGV[1]}' ?"
867
+ p.red
868
+ cures = %W{createuser -h localhost -p #{$pgport} -U postgres -d -l #{ARGV[1]}}.read_p12
869
+ p.red cures
870
+ case cures
871
+ when /FATAL: Ident authentication failed for user \"postgres\"/
872
+ modifyAuthConf
873
+ end
874
+ p.yellow
875
+ end
876
+ p.yellow
877
+ end;else
878
+ p.yellow
879
+ exit 0
880
+ end
881
+ end
882
+ end
883
+ p.yellow
884
+ break
885
+ end
886
+ end
887
+ p.yellow
888
+ exit 0
889
+ when "uninstall"
890
+ p ARGV
891
+ if ARGV[1] == "--force" || TTY.yn?("uninstall postgres and yk_postgres settings")
892
+ if Process.euid != 0
893
+ ["ruby", __FILE__, "uninstall", "--force"].exec :root
894
+ else
895
+ stopPostgresDaemon
896
+ disablePostgresDaemon
897
+ deletePostgresDaemon
898
+ %W{rpm -e postgresql postgresql-devel postgresql-server}.system
899
+ %W{rm -rf #{$pgdata} #{Etc::User.home("postgres")}}.system
900
+ Etc::User.each do |u|
901
+ (u.home / ".yk_postgres")._?[:_e?]&.rm_rf
902
+ end
903
+ end
904
+ end
905
+ exit 0
906
+ end
907
+ end
908
+
909
+ #if !"#{$pgdata}/postgresql.conf"._e?
910
+ # TTY.open do |tty|
911
+ # tty.writeln "missing #{$pgdata}/postgresql.conf"
912
+ # if tty.yn? "do you want to check environment as super user?"
913
+ # ["ruby", __FILE__, "check", Etc::EUser.name].exec :root
914
+ # end
915
+ # end
916
+ #end
917
+ end