summaryrefslogtreecommitdiff
path: root/Omni/Deploy/Systemd.hs
blob: 7b64d1f47ca8b18a5239b69f227539c85afe547c (plain)
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
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Systemd unit file generator for the mini-PaaS deployment system.
--
-- : out deploy-systemd
-- : dep directory
module Omni.Deploy.Systemd
  ( generateUnit,
    writeUnit,
    createSymlink,
    reloadAndRestart,
    stopAndDisable,
    removeUnit,
    getRunningStorePath,
    servicesDir,
    main,
    test,
  )
where

import Alpha
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import Omni.Deploy.Manifest (Artifact (..), Exec (..), Hardening (..), Service (..), Systemd (..))
import qualified Omni.Test as Test
import qualified System.Directory as Dir
import System.FilePath ((</>))
import qualified System.Process as Process

servicesDir :: FilePath
servicesDir = "/var/lib/biz-deployer/services"

generateUnit :: Service -> Text
generateUnit Service {..} =
  Text.unlines <| unitSection ++ serviceSection ++ hardeningSection ++ installSection
  where
    binary = fromMaybe serviceName (execCommand serviceExec)
    execStart = storePath serviceArtifact <> "/bin/" <> binary

    unitSection =
      [ "[Unit]",
        "Description=" <> serviceName,
        "After=" <> Text.intercalate " " (systemdAfter serviceSystemd)
      ]
        ++ requiresLine

    requiresLine =
      ["Requires=" <> Text.intercalate " " (systemdRequires serviceSystemd) | not (null (systemdRequires serviceSystemd))]

    serviceSection =
      [ "",
        "[Service]",
        "Type=simple",
        "ExecStart=" <> execStart,
        "User=" <> execUser serviceExec,
        "Group=" <> execGroup serviceExec,
        "Restart=" <> systemdRestart serviceSystemd,
        "RestartSec=" <> tshow (systemdRestartSec serviceSystemd)
      ]
        ++ envLines
        ++ envFileLine

    envLines =
      Map.toList serviceEnv
        |> map (\(k, v) -> "Environment=\"" <> k <> "=" <> v <> "\"")

    envFileLine = case serviceEnvFile of
      Nothing -> []
      Just path -> ["EnvironmentFile=" <> path]

    hardeningSection =
      [ "",
        "# Hardening",
        "PrivateTmp=" <> boolToYesNo (hardeningPrivateTmp serviceHardening),
        "ProtectSystem=" <> hardeningProtectSystem serviceHardening,
        "ProtectHome=" <> boolToYesNo (hardeningProtectHome serviceHardening),
        "NoNewPrivileges=yes"
      ]
        ++ readWritePathsLine

    readWritePathsLine =
      case Map.lookup "DATA_DIR" serviceEnv of
        Just dataDir -> ["ReadWritePaths=" <> dataDir]
        Nothing -> []

    installSection =
      [ "",
        "[Install]",
        "WantedBy=multi-user.target"
      ]

    boolToYesNo True = "yes"
    boolToYesNo False = "no"

writeUnit :: FilePath -> Service -> IO FilePath
writeUnit baseDir svc = do
  Dir.createDirectoryIfMissing True baseDir
  let path = baseDir </> Text.unpack (serviceName svc) <> ".service"
      content = generateUnit svc
  Text.IO.writeFile path content
  pure path

createSymlink :: FilePath -> FilePath -> Service -> IO FilePath
createSymlink baseDir sysDir svc = do
  let unitPath = baseDir </> Text.unpack (serviceName svc) <> ".service"
      linkPath = sysDir </> Text.unpack (serviceName svc) <> ".service"
  exists <- Dir.doesPathExist linkPath
  when exists <| Dir.removeFile linkPath
  Dir.createFileLink unitPath linkPath
  pure linkPath

reloadAndRestart :: Text -> IO ()
reloadAndRestart serviceName' = do
  _ <- Process.readProcessWithExitCode "systemctl" ["daemon-reload"] ""
  _ <-
    Process.readProcessWithExitCode
      "systemctl"
      ["enable", "--now", Text.unpack serviceName' <> ".service"]
      ""
  pure ()

stopAndDisable :: Text -> IO ()
stopAndDisable serviceName' = do
  _ <-
    Process.readProcessWithExitCode
      "systemctl"
      ["disable", "--now", Text.unpack serviceName' <> ".service"]
      ""
  pure ()

removeUnit :: FilePath -> FilePath -> Text -> IO ()
removeUnit baseDir sysDir serviceName' = do
  let unitPath = baseDir </> Text.unpack serviceName' <> ".service"
      linkPath = sysDir </> Text.unpack serviceName' <> ".service"
  linkExists <- Dir.doesPathExist linkPath
  when linkExists <| Dir.removeFile linkPath
  unitExists <- Dir.doesPathExist unitPath
  when unitExists <| Dir.removeFile unitPath
  _ <- Process.readProcessWithExitCode "systemctl" ["daemon-reload"] ""
  pure ()

-- | Get the store path of the currently running service by reading its unit file.
getRunningStorePath :: Text -> IO (Maybe Text)
getRunningStorePath serviceName' = do
  let unitPath = servicesDir </> Text.unpack serviceName' <> ".service"
  exists <- Dir.doesFileExist unitPath
  if not exists
    then pure Nothing
    else do
      content <- Text.IO.readFile unitPath
      pure <| extractStorePath content
  where
    -- Extract /nix/store/...-service-name from ExecStart=/nix/store/.../bin/...
    extractStorePath content =
      content
        |> Text.lines
        |> find (Text.isPrefixOf "ExecStart=")
        |> fmap (Text.drop (Text.length "ExecStart="))
        |> fmap (Text.dropWhile (/= '/'))
        |> fmap (Text.drop 1)
        |> fmap (Text.takeWhile (/= '/'))
        |> fmap ("/nix/store/" <>)

test :: Test.Tree
test =
  Test.group
    "Omni.Deploy.Systemd"
    [ test_generateBasicUnit,
      test_generateUnitWithEnv,
      test_generateUnitWithCustomExec,
      test_generateUnitWithEnvFile,
      test_generateUnitWithDependencies,
      test_generateUnitWithHardening
    ]

mkTestService :: Text -> Text -> Service
mkTestService name path =
  Service
    { serviceName = name,
      serviceArtifact = Artifact "nix-closure" path,
      serviceHosts = ["biz"],
      serviceExec = Exec Nothing "root" "root",
      serviceEnv = mempty,
      serviceEnvFile = Nothing,
      serviceHttp = Nothing,
      serviceSystemd = Systemd ["network-online.target"] [] "on-failure" 5,
      serviceHardening = Hardening False True "strict" True,
      serviceRevision = Nothing
    }

test_generateBasicUnit :: Test.Tree
test_generateBasicUnit =
  Test.unit "generates basic unit file" <| do
    let svc = mkTestService "test-service" "/nix/store/abc123-test"
        unit = generateUnit svc
    Text.isInfixOf "[Unit]" unit Test.@=? True
    Text.isInfixOf "Description=test-service" unit Test.@=? True
    Text.isInfixOf "[Service]" unit Test.@=? True
    Text.isInfixOf "ExecStart=/nix/store/abc123-test/bin/test-service" unit Test.@=? True
    Text.isInfixOf "[Install]" unit Test.@=? True
    Text.isInfixOf "WantedBy=multi-user.target" unit Test.@=? True

test_generateUnitWithEnv :: Test.Tree
test_generateUnitWithEnv =
  Test.unit "generates unit with environment" <| do
    let svc =
          (mkTestService "env-test" "/nix/store/xyz")
            { serviceEnv = Map.fromList [("PORT", "8000"), ("DEBUG", "true")]
            }
        unit = generateUnit svc
    Text.isInfixOf "Environment=\"PORT=8000\"" unit Test.@=? True
    Text.isInfixOf "Environment=\"DEBUG=true\"" unit Test.@=? True

test_generateUnitWithCustomExec :: Test.Tree
test_generateUnitWithCustomExec =
  Test.unit "generates unit with custom exec" <| do
    let svc =
          (mkTestService "custom-exec" "/nix/store/abc")
            { serviceExec = Exec (Just "my-binary") "www-data" "www-data"
            }
        unit = generateUnit svc
    Text.isInfixOf "ExecStart=/nix/store/abc/bin/my-binary" unit Test.@=? True
    Text.isInfixOf "User=www-data" unit Test.@=? True
    Text.isInfixOf "Group=www-data" unit Test.@=? True

test_generateUnitWithEnvFile :: Test.Tree
test_generateUnitWithEnvFile =
  Test.unit "generates unit with env file" <| do
    let svc =
          (mkTestService "env-file-test" "/nix/store/xyz")
            { serviceEnvFile = Just "/var/lib/biz-secrets/test.env"
            }
        unit = generateUnit svc
    Text.isInfixOf "EnvironmentFile=/var/lib/biz-secrets/test.env" unit Test.@=? True

test_generateUnitWithDependencies :: Test.Tree
test_generateUnitWithDependencies =
  Test.unit "generates unit with dependencies" <| do
    let svc =
          (mkTestService "dep-test" "/nix/store/abc")
            { serviceSystemd =
                Systemd
                  ["network-online.target", "postgresql.service"]
                  ["postgresql.service"]
                  "on-failure"
                  5
            }
        unit = generateUnit svc
    Text.isInfixOf "After=network-online.target postgresql.service" unit Test.@=? True
    Text.isInfixOf "Requires=postgresql.service" unit Test.@=? True

test_generateUnitWithHardening :: Test.Tree
test_generateUnitWithHardening =
  Test.unit "generates unit with hardening" <| do
    let svc =
          (mkTestService "hardened" "/nix/store/abc")
            { serviceHardening = Hardening False True "full" True
            }
        unit = generateUnit svc
    Text.isInfixOf "PrivateTmp=yes" unit Test.@=? True
    Text.isInfixOf "ProtectSystem=full" unit Test.@=? True
    Text.isInfixOf "ProtectHome=yes" unit Test.@=? True
    Text.isInfixOf "NoNewPrivileges=yes" unit Test.@=? True

main :: IO ()
main = Test.run test