This repository was archived by the owner on May 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMain.hs
More file actions
524 lines (435 loc) · 17.8 KB
/
Copy pathMain.hs
File metadata and controls
524 lines (435 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS -fno-warn-orphans #-}
{-# OPTIONS -fno-warn-unused-do-bind #-}
module Main where
import Control.Applicative (empty, (<|>))
import Control.Exception (SomeException)
import qualified Control.Exception
import Control.Monad
import Control.Monad.IO.Class (MonadIO)
import qualified Data.ByteString.Lazy as BL
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import NeatInterpolation
import qualified Options.Applicative as Options
import Options.Generic
import Prelude hiding (FilePath)
import qualified System.IO
import Turtle (ExitCode (..), FilePath, fp, liftIO, s,
(%), (</>))
import qualified Turtle
import Turtle.Line
data Options w
= Path
{ direction :: Direction
, sudo :: w ::: Bool <?> "Prepend with sudo"
, noSign :: w ::: Bool <?> "Don't sign payload (not recommended)"
, path :: w ::: Maybe FilePath <?> "Path to deploy"
, profilePath :: w ::: Maybe FilePath <?> "Path to parent profile directory (default: /nix/var/nix/profiles)"
, profileName :: w ::: Maybe Line <?> "Name of profile to set (example: upgrade-tools)"
}
| System
{ direction :: Direction
, failOnPartialSuccess :: w ::: Bool <?> "Fail if system activation partially succeeds"
, noSign :: w ::: Bool <?> "Don't sign payload (not recommended)"
, path :: w ::: Maybe FilePath <?> "Path to deploy"
, systemName :: w ::: Maybe Line <?> "Alternative system profile name (default: system)"
, switchMethod :: Maybe SwitchMethod
}
deriving (Generic)
instance ParseRecord (Options Wrapped)
deriving instance Show (Options Unwrapped)
data SwitchMethod
= Switch
| Boot
| Test
| DryActivate
| Reboot
-- ^ Same as `Boot` except followed by a @reboot@
deriving (Eq, Show, ParseFields)
instance ParseField SwitchMethod where
readField = Options.readerError "Internal, fatal error: unexpected use of readField"
parseField _ _ _ =
Options.flag' Switch (Options.long "switch")
<|> Options.flag' Boot (Options.long "boot")
<|> Options.flag' Test (Options.long "test")
<|> Options.flag' DryActivate (Options.long "dry-activate")
<|> Options.flag' Reboot (Options.long "reboot")
instance ParseRecord SwitchMethod where
parseRecord = fmap Options.Generic.getOnly parseRecord
renderSwitch :: SwitchMethod -> Text
renderSwitch Switch = "switch"
renderSwitch Boot = "boot"
renderSwitch Test = "test"
renderSwitch DryActivate = "dry-activate"
renderSwitch Reboot = "boot"
data Direction = To Line | From Line
deriving (Show, ParseFields)
instance ParseField Direction where
readField = Options.readerError "Internal, fatal error: unexpected use of readField"
parseField _ _ _ = (To <$> parseTo) <|> (From <$> parseFrom)
where
parseTo = parser "to" "Deploy software to this address (ex: user@192.168.0.1)"
parseFrom = parser "from" "Deploy software from this address (ex: user@192.168.0.1)"
line = Options.maybeReader (textToLine . Text.pack)
parser l h =
(Options.option line $
( Options.metavar "USER@HOST"
<> Options.long l
<> Options.help h
)
)
instance ParseRecord Direction where
parseRecord = fmap Options.Generic.getOnly parseRecord
instance ParseRecord Line where
parseRecord = fmap Options.Generic.getOnly parseRecord
instance ParseFields Line where
instance ParseField Line where
readField = Options.maybeReader (textToLine . Text.pack)
parseField h m c = do
let metavar = "LINE"
let line = Options.maybeReader (textToLine . Text.pack)
case m of
Nothing ->
(Options.argument line
( Options.metavar metavar
<> foldMap (Options.help . Text.unpack) h))
Just name ->
(Options.option line
( Options.metavar metavar
<> foldMap Options.short c
<> Options.long (Text.unpack name)
<> foldMap (Options.help . Text.unpack) h))
renderDirection :: Direction -> (Text, Line)
renderDirection (To target) = ("to", target)
renderDirection (From target) = ("from", target)
progSummary :: Text
progSummary = "Deploy software or an entire NixOS system configuration to another NixOS system"
main :: IO ()
main =
unwrapRecord progSummary >>= \case
Path{..} -> do
pathText <-
case path of
Just p -> pure (Turtle.format fp p)
Nothing -> liftIO pathFromStdin
let (txDir, target) = renderDirection direction
let targetText = lineToText target
let sign = not noSign
when sign $ exchangeKeys targetText
stderrLines [text|[+] Copying $pathText|]
let transfer =
Turtle.procs "nix-copy-closure"
((if sign then ["--sign"] else []) <>
[ (Turtle.format ("--"%s) txDir)
, "--gzip"
, targetText
, pathText
])
empty
-- Transfer path to target
liftIO (Control.Exception.catch transfer (errorHandler [text|
[x] Failed transferring $pathText $txDir $targetText
1. $pathText does not exist
2. Make sure you have an authorized key configured on $targetText
|]))
let sudoAnyway =
case profilePath of
Nothing -> True -- The default profile path requires `sudo`
_ -> sudo
updateProfile line = do
let profile = fromMaybe "/nix/var/nix/profiles" profilePath
</> Turtle.fromText (lineToText line)
let profileText = Turtle.format fp profile
setProfile direction sudoAnyway profileText pathText
mapM_ updateProfile profileName
System{..} -> do
pathText <-
case path of
Just p -> pure (Turtle.format fp p)
Nothing -> liftIO pathFromStdin
let profileText =
case systemName of
Nothing -> "/nix/var/nix/profiles/system"
Just p ->
let profiles = Turtle.fromText "/nix/var/nix/profiles/system-profiles"
name = Turtle.fromText (lineToText p)
in Turtle.format fp (profiles </> name)
let (txDir, target) = renderDirection direction
let targetText = lineToText target
let sign = not noSign
when sign $ exchangeKeys targetText
stderrLines [text|[+] Installing system: $pathText|]
let transfer =
Turtle.procs "nix-copy-closure"
((if sign then ["--sign"] else []) <>
[ (Turtle.format ("--"%s) txDir)
, "--gzip"
, targetText
, pathText
])
empty
let method = fromMaybe Test switchMethod
let switchSystem =
Turtle.proc "ssh"
[ targetText
, "sudo"
, "/nix/var/nix/profiles/system/bin/switch-to-configuration"
, (renderSwitch method)
]
empty
-- Transfer path to target
liftIO (Control.Exception.catch transfer (errorHandler [text|
[x] Failed transferring $pathText $txDir $targetText
1. $pathText may not exist, make sure you built it with nix-build first
2. Make sure you have an authorized key configured on $targetText so that you can SSH
|]))
setProfile direction True profileText pathText
let successMsg = [text|[+] Succeeded switching $targetText to $pathText|]
let partialMsg = [text|
$successMsg
However, some services failed to start or restart.
|]
switchSystem >>= \case
ExitSuccess -> stderrLines successMsg
-- This is the exit code returned by switch-to-configuration
-- if the configuration is successfully switched-to (using
-- `--switch`) but a service failed to start or restart during
-- the switch. We want to treat this as success but should
-- tell the user what happened...
ExitFailure 4 | failOnPartialSuccess -> Turtle.die partialMsg
| otherwise -> stderrLines partialMsg
ExitFailure _ ->
Turtle.die [text|[x] Failed to switch $targetText to $pathText|]
when (method == Reboot)$ do
let success =
stderrLines [text|[+] $pathText successfully activated, $targetText is rebooting|]
rebootCmd targetText >>= \case
-- This is the exit code returned by `ssh` when the machine closes
-- the connection due to a successful reboot. We can't really
-- distinguish the connection being closed for other reasons,
-- unfortunately, so we have to assume that this meant success
ExitFailure 255 -> success
ExitFailure _ ->
Turtle.die [text|[x] Failed to reboot $targetText after activating $pathText at $profileText|]
-- The command should always fail because the remote machine closes
-- connection when rebooting, but we include this case for
-- completeness
ExitSuccess -> success
-- | Given a 'Text' that may have newlines, split using
-- 'Turtle.Line.textToLines' and print each line to stderr.
stderrLines :: MonadIO io => Text -> io ()
stderrLines = mapM_ Turtle.err . textToLines
-- | Given an error preamble and 'SomeException', format the exception
-- message and render it with the preamble into a useful error.
errorHandler :: MonadIO io => Text -> SomeException -> io ()
errorHandler msg err = do
let excText0 = Text.justifyRight 4 ' ' <$> Text.lines (Text.pack $ show err)
let excText1 = Text.unlines excText0
Turtle.die [text|
$msg
Original error was:
$excText1
|]
rebootCmd :: MonadIO io => Text -> io Turtle.ExitCode
rebootCmd target = Turtle.shell [text|ssh $target sudo reboot|] empty
pathFromStdin :: IO Text
pathFromStdin = do
let h = System.IO.stdin
System.IO.hWaitForInput h (-1)
ls <- Turtle.textToLines <$> Text.IO.hGetContents h
pure (Turtle.lineToText $ NonEmpty.head ls)
exchangeKeys :: Text -> IO ()
exchangeKeys host = do
-- When performing a distributed build you need to share a key pair
-- (both the public and private key) with the machine you're
-- deploying to (or from). Both machines must store the same private
-- key at `/etc/nix/signing-key.sec` and the same public key at
-- `/etc/nix/signing-key.pub`. The private must also be only
-- user-readable and not group- or world-readable (i.e. `400`
-- permissions using `chmod` notation).
--
-- By default, neither machine will have a key pair installed. This script
-- will first ensure that the remote machine has a key pair (creating one if
-- if missing) and copy the remote key pair to the local machine. We
-- install the remote key pair locally on every run of this script because we
-- do not assume that all remote machines share the same key pair. Quite the
-- opposite: every production machine should have a unique signing key pair.
let privateKey = "/etc/nix/signing-key.sec"
let publicKey = "/etc/nix/signing-key.pub"
let handler0 :: SomeException -> IO ()
handler0 e = do
let exceptionText = Text.pack (show e)
let msg = [text|
[x] Could not ensure that the remote machine has signing keys installed
Debugging tips:
1. Check if you can log into the remote machine by running:
$ ssh $host
2. If you can log in, then check if you have permission to `sudo` without a
password by running the following command on the remote machine:
$ sudo -n true
$ echo $?
0
Original error: $exceptionText
|]
Turtle.die msg
let openssl :: Turtle.Format a a
openssl =
"$(nix-build --no-out-link \"<nixpkgs>\" -A libressl)/bin/openssl"
let fmt = "ssh "%s%" '"
% "test -e "%fp%" || "
% "sudo sh -c \""
% "(umask 277 && "%openssl%" genrsa -out "%fp%" 2048) && "
% openssl%" rsa -in "%fp%" -pubout > "%fp
% "\""
% "'"
let cmd = Turtle.format fmt host privateKey privateKey privateKey publicKey
Control.Exception.handle handler0 (Turtle.shells cmd empty)
let mirror path = Turtle.runManaged $ do
-- NB: path shouldn't is a FilePath and won't have any
-- newlines, so this should be okay
stderrLines (Turtle.format ("[+] Downloading: "%fp) path)
localPath <- Turtle.mktempfile "/tmp" "signing-key"
let download =
Turtle.procs "rsync"
[ "--archive"
, "--checksum"
, "--rsh", "ssh"
, "--rsync-path", "sudo rsync"
, Turtle.format (s%":"%fp) host path
, Turtle.format fp localPath
]
empty
let handler1 :: SomeException -> IO ()
handler1 e = do
let pathText = Turtle.format fp path
let exceptionText = Text.pack (show e)
let msg = [text|
[x] Could not download: $pathText
Debugging tips:
1. Check if you can log into the remote machine by running:
$ ssh $host
2. If you can log in, then check if you have permission to `sudo` without a
password by running the following command on the remote machine:
$ sudo -n true
$ echo $?
0
3. If you can `sudo` without a password, then check if the file exists by
running the following command on the remote machine:
$ test -e $pathText
$ echo $?
0
Original error: $exceptionText
|]
Turtle.die msg
liftIO (Control.Exception.handle handler1 download)
new <- liftIO . BL.readFile . Text.unpack $
Turtle.format fp localPath
old <- liftIO . BL.readFile . Text.unpack $
Turtle.format fp path
if new == old
then do
let same = Turtle.format ("[+] Unchanged: "%fp) path
mapM_ Turtle.err (Turtle.Line.textToLines same)
else do
exitCode <- Turtle.shell "sudo -n true 2>/dev/null" empty
-- NB: path shouldn't is a FilePath and won't have any
-- newlines, so this should be okay
Turtle.err (Turtle.unsafeTextToLine $ Turtle.format ("[+] Installing: "%fp) path)
case exitCode of
ExitFailure _ -> do
Turtle.err ""
Turtle.err " This will prompt you for your `sudo` password"
_ -> do
return ()
let install =
Turtle.procs "sudo"
[ "mv"
, Turtle.format fp localPath
, Turtle.format fp path
]
empty
let handler2 :: SomeException -> IO ()
handler2 e = do
let pathText = Turtle.format fp path
let exceptionText = Text.pack (show e)
let msg = [text|
[x] Could not install: $pathText
Debugging tips:
1. Check to see that you have permission to `sudo` by running:
$ sudo true
$ echo $?
0
Original error: $exceptionText
|]
Turtle.die msg
liftIO (Control.Exception.handle handler2 install)
mirror privateKey
mirror publicKey
setProfile
:: MonadIO io
=> Direction
-> Bool
-- ^ `True` to use `sudo`
-> Text
-- ^ Profile name (such as @"system"@, or @"default"@)
-> Text
-- ^ File path to install (rendered as `Text`)
-> io ()
setProfile direction sudo profileText pathText = do
command <- case direction of
To target -> do
let command =
Turtle.procs "ssh"
( [ lineToText target
]
++ (if sudo then [ "sudo" ] else [])
++ [ "nix-env"
, "--profile"
, profileText
, "--set"
, pathText
]
)
empty
return command
From _ -> do
let command =
if sudo
then
Turtle.procs "sudo"
[ "nix-env"
, "--profile"
, profileText
, "--set"
, pathText
]
empty
else
Turtle.procs "nix-env"
[ "--profile"
, profileText
, "--set"
, pathText
]
empty
return command
-- Set or create a profile pointing at the transferred path
let msg = [text|[x] Failed setting $profileText to $pathText|]
liftIO (Control.Exception.handle (errorHandler msg) command)