ghcup-hs/lib/GHCup/Platform.hs

361 lines
14 KiB
Haskell
Raw Normal View History

2021-11-02 18:53:22 +00:00
{-# LANGUAGE CPP #-}
2020-01-11 20:15:05 +00:00
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
2020-03-21 21:19:37 +00:00
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
2020-01-11 20:15:05 +00:00
{-# LANGUAGE QuasiQuotes #-}
2022-01-12 21:55:00 +00:00
{-# LANGUAGE TemplateHaskellQuotes #-}
2020-01-11 20:15:05 +00:00
2020-07-21 23:08:58 +00:00
{-|
Module : GHCup.Plaform
Description : Retrieving platform information
Copyright : (c) Julian Ospald, 2020
2020-07-30 18:04:02 +00:00
License : LGPL-3.0
2020-07-21 23:08:58 +00:00
Maintainer : hasufell@hasufell.de
Stability : experimental
2021-05-14 21:09:45 +00:00
Portability : portable
2020-07-21 23:08:58 +00:00
-}
2020-01-11 20:15:05 +00:00
module GHCup.Platform where
import GHCup.Errors
import GHCup.Types
2021-08-30 20:41:58 +00:00
import GHCup.Types.Optics
2020-01-11 20:15:05 +00:00
import GHCup.Types.JSON ( )
import GHCup.Utils.Dirs
2022-05-21 20:54:18 +00:00
import GHCup.Prelude
import GHCup.Prelude.Logger
import GHCup.Prelude.Process
import GHCup.Prelude.String.QQ
import GHCup.Prelude.Version.QQ
import GHCup.Prelude.MegaParsec
2020-01-11 20:15:05 +00:00
2021-11-02 18:53:22 +00:00
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail ( MonadFail )
#endif
2020-01-11 20:15:05 +00:00
import Control.Applicative
import Control.Exception.Safe
import Control.Monad
import Control.Monad.Reader
import Data.ByteString ( ByteString )
2020-01-11 20:15:05 +00:00
import Data.Foldable
import Data.Maybe
import Data.Text ( Text )
import Data.Versions
import Haskus.Utils.Variant.Excepts
import Prelude hiding ( abs
, readFile
, writeFile
)
import System.Info
2020-07-04 21:28:30 +00:00
import System.OsRelease
import System.Exit
import System.FilePath
2021-06-07 18:09:18 +00:00
import Text.PrettyPrint.HughesPJClass ( prettyShow )
import Text.Regex.Posix
2020-01-11 20:15:05 +00:00
import qualified Text.Megaparsec as MP
2020-01-11 20:15:05 +00:00
import qualified Data.Text as T
2021-05-14 21:09:45 +00:00
import qualified Data.Text.IO as T
import Data.Void
import qualified Data.List as L
2021-05-14 21:09:45 +00:00
2020-01-11 20:15:05 +00:00
--------------------------
--[ Platform detection ]--
--------------------------
2020-04-10 17:27:17 +00:00
-- | Get the full platform request, consisting of architecture, distro, ...
2021-08-30 20:41:58 +00:00
platformRequest :: (MonadReader env m, Alternative m, MonadFail m, HasLog env, MonadCatch m, MonadIO m)
2020-04-10 17:27:17 +00:00
=> Excepts
2020-06-27 17:00:13 +00:00
'[NoCompatiblePlatform, NoCompatibleArch, DistroNotFound]
2020-04-10 17:27:17 +00:00
m
PlatformRequest
platformRequest = do
(PlatformResult rp rv) <- liftE getPlatform
ar <- lE getArchitecture
pure $ PlatformRequest ar rp rv
2020-01-11 20:15:05 +00:00
getArchitecture :: Either NoCompatibleArch Architecture
getArchitecture = case arch of
2020-06-27 17:00:13 +00:00
"x86_64" -> Right A_64
"i386" -> Right A_32
"powerpc" -> Right A_PowerPC
"powerpc64" -> Right A_PowerPC64
"powerpc64le" -> Right A_PowerPC64
"sparc" -> Right A_Sparc
"sparc64" -> Right A_Sparc64
"arm" -> Right A_ARM
"aarch64" -> Right A_ARM64
what -> Left (NoCompatibleArch what)
2020-01-11 20:15:05 +00:00
2021-08-30 20:41:58 +00:00
getPlatform :: (Alternative m, MonadReader env m, HasLog env, MonadCatch m, MonadIO m, MonadFail m)
2020-01-11 20:15:05 +00:00
=> Excepts
2020-06-27 17:00:13 +00:00
'[NoCompatiblePlatform, DistroNotFound]
2020-01-11 20:15:05 +00:00
m
PlatformResult
getPlatform = do
pfr <- case os of
"linux" -> do
(distro, ver) <- liftE getLinuxDistro
pure $ PlatformResult { _platform = Linux distro, _distroVersion = ver }
"darwin" -> do
ver <-
2021-03-11 16:03:51 +00:00
either (const Nothing) Just
2020-04-11 20:15:09 +00:00
. versioning
2020-06-27 17:00:13 +00:00
-- TODO: maybe do this somewhere else
2021-05-14 21:09:45 +00:00
. decUTF8Safe'
2021-03-11 16:03:51 +00:00
<$> getDarwinVersion
pure $ PlatformResult { _platform = Darwin, _distroVersion = ver }
2020-01-11 20:15:05 +00:00
"freebsd" -> do
ver <-
2021-05-14 21:09:45 +00:00
either (const Nothing) Just . versioning . decUTF8Safe'
<$> getFreeBSDVersion
2020-01-11 20:15:05 +00:00
pure $ PlatformResult { _platform = FreeBSD, _distroVersion = ver }
2021-05-14 21:09:45 +00:00
"mingw32" -> pure PlatformResult { _platform = Windows, _distroVersion = Nothing }
2020-01-11 20:15:05 +00:00
what -> throwE $ NoCompatiblePlatform what
2021-08-30 20:41:58 +00:00
lift $ logDebug $ "Identified Platform as: " <> T.pack (prettyShow pfr)
2020-01-11 20:15:05 +00:00
pure pfr
where
2021-05-14 21:09:45 +00:00
getFreeBSDVersion = lift $ fmap _stdOut $ executeOut "freebsd-version" [] Nothing
getDarwinVersion = lift $ fmap _stdOut $ executeOut "sw_vers"
2020-04-11 20:15:09 +00:00
["-productVersion"]
Nothing
2020-01-11 20:15:05 +00:00
2021-05-14 21:09:45 +00:00
getLinuxDistro :: (Alternative m, MonadCatch m, MonadIO m, MonadFail m)
2020-01-11 20:15:05 +00:00
=> Excepts '[DistroNotFound] m (LinuxDistro, Maybe Versioning)
getLinuxDistro = do
-- TODO: don't do alternative on IO, because it hides bugs
2021-05-14 21:09:45 +00:00
(name, ver) <- handleIO (\_ -> throwE DistroNotFound) $ lift $ asum
[ liftIO try_os_release
2020-01-11 20:15:05 +00:00
, try_lsb_release_cmd
2021-05-14 21:09:45 +00:00
, liftIO try_redhat_release
, liftIO try_debian_version
2020-01-11 20:15:05 +00:00
]
let parsedVer = ver >>= either (const Nothing) Just . versioning
distro = if
| hasWord name ["debian"] -> Debian
| hasWord name ["ubuntu"] -> Ubuntu
| hasWord name ["linuxmint", "Linux Mint"] -> Mint
| hasWord name ["fedora"] -> Fedora
| hasWord name ["centos"] -> CentOS
| hasWord name ["Red Hat"] -> RedHat
| hasWord name ["alpine"] -> Alpine
| hasWord name ["exherbo"] -> Exherbo
| hasWord name ["gentoo"] -> Gentoo
| hasWord name ["amazonlinux", "Amazon Linux"] -> AmazonLinux
| otherwise -> UnknownLinux
pure (distro, parsedVer)
where
2021-08-29 15:08:06 +00:00
hasWord t = any (\x -> match (regex x) (T.unpack t))
where
regex x = makeRegexOpts compIgnoreCase execBlank ([s|\<|] ++ x ++ [s|\>|])
2020-01-11 20:15:05 +00:00
2021-05-14 21:09:45 +00:00
lsb_release_cmd :: FilePath
lsb_release_cmd = "lsb-release"
redhat_release :: FilePath
redhat_release = "/etc/redhat-release"
debian_version :: FilePath
debian_version = "/etc/debian_version"
2020-01-11 20:15:05 +00:00
try_os_release :: IO (Text, Maybe Text)
try_os_release = do
2021-03-11 16:03:51 +00:00
Just OsRelease{ name = name, version_id = version_id } <-
2020-07-04 21:28:30 +00:00
fmap osRelease <$> parseOsRelease
pure (T.pack name, fmap T.pack version_id)
2020-01-11 20:15:05 +00:00
2021-05-14 21:09:45 +00:00
try_lsb_release_cmd :: (MonadFail m, MonadIO m)
=> m (Text, Maybe Text)
2020-01-11 20:15:05 +00:00
try_lsb_release_cmd = do
2021-05-14 21:09:45 +00:00
(Just _) <- liftIO $ findExecutable lsb_release_cmd
2020-03-21 21:19:37 +00:00
name <- fmap _stdOut $ executeOut lsb_release_cmd ["-si"] Nothing
ver <- fmap _stdOut $ executeOut lsb_release_cmd ["-sr"] Nothing
2021-05-14 21:09:45 +00:00
pure (decUTF8Safe' name, Just $ decUTF8Safe' ver)
2020-01-11 20:15:05 +00:00
try_redhat_release :: IO (Text, Maybe Text)
try_redhat_release = do
2021-05-14 21:09:45 +00:00
t <- T.readFile redhat_release
let nameRegex n =
2020-03-21 21:19:37 +00:00
makeRegexOpts compIgnoreCase
execBlank
2021-03-11 16:03:51 +00:00
([s|\<|] <> fS n <> [s|\>|] :: ByteString) :: Regex
let verRegex =
2020-03-21 21:19:37 +00:00
makeRegexOpts compIgnoreCase
execBlank
([s|\<([0-9])+(.([0-9])+)*\>|] :: ByteString) :: Regex
let nameRe n =
fromEmpty . match (nameRegex n) $ T.unpack t :: Maybe String
verRe = fromEmpty . match verRegex $ T.unpack t :: Maybe String
2020-01-11 20:15:05 +00:00
(Just name) <- pure
(nameRe "CentOS" <|> nameRe "Fedora" <|> nameRe "Red Hat")
pure (T.pack name, fmap T.pack verRe)
where
fromEmpty :: String -> Maybe String
2020-03-21 21:19:37 +00:00
fromEmpty "" = Nothing
fromEmpty s' = Just s'
2020-01-11 20:15:05 +00:00
try_debian_version :: IO (Text, Maybe Text)
try_debian_version = do
2021-05-14 21:09:45 +00:00
ver <- T.readFile debian_version
pure (T.pack "debian", Just ver)
getStackGhcBuilds :: (MonadReader env m, HasLog env, MonadIO m)
=> PlatformResult
-> Excepts '[ParseError, NoCompatiblePlatform, DistroNotFound, ProcessError] m [String]
getStackGhcBuilds PlatformResult{..} = do
case _platform of
Linux _ -> do
-- Some systems don't have ldconfig in the PATH, so make sure to look in
-- /sbin and /usr/sbin as well
sbinEnv <- liftIO $ addToPath sbinDirs False
ldConfig <- lift $ executeOut' "ldconfig" ["-p"] Nothing (Just sbinEnv)
firstWords <- case ldConfig of
CapturedProcess ExitSuccess so _ ->
pure . mapMaybe (listToMaybe . T.words) . T.lines . T.pack . stripNewlineEnd . T.unpack . decUTF8Safe' $ so
CapturedProcess (ExitFailure _) _ _ ->
-- throwE $ NonZeroExit c "ldconfig" ["-p" ]
pure []
let checkLib :: (MonadReader env m, HasLog env, MonadIO m) => String -> m Bool
checkLib lib
| libT `elem` firstWords = do
logDebug $ "Found shared library " <> libT <> " in 'ldconfig -p' output"
pure True
| isWindows =
-- Cannot parse /usr/lib on Windows
pure False
| otherwise = hasMatches lib usrLibDirs
-- This is a workaround for the fact that libtinfo.so.x doesn't
-- appear in the 'ldconfig -p' output on Arch or Slackware even
-- when it exists. There doesn't seem to be an easy way to get the
-- true list of directories to scan for shared libs, but this
-- works for our particular cases.
where
libT = T.pack lib
hasMatches :: (MonadReader env m, HasLog env, MonadIO m) => String -> [FilePath] -> m Bool
hasMatches lib dirs = do
matches <- filterM (liftIO . doesFileExist . (</> lib)) dirs
case matches of
[] -> logDebug ("Did not find shared library " <> libT) >> pure False
(path:_) -> logDebug ("Found shared library " <> libT <> " in " <> T.pack path) >> pure True
where
libT = T.pack lib
getLibc6Version :: MonadIO m
=> Excepts '[ParseError, ProcessError] m Version
getLibc6Version = do
CapturedProcess{..} <- lift $ executeOut "ldd" ["--version"] Nothing
case _exitCode of
ExitSuccess -> either (throwE . ParseError . show) pure
. MP.parse lddVersion "" . T.pack . stripNewlineEnd . T.unpack . decUTF8Safe' $ _stdOut
ExitFailure c -> throwE $ NonZeroExit c "ldd" ["--version" ]
-- Assumes the first line of ldd has the format:
--
-- ldd (...) nn.nn
--
-- where nn.nn corresponds to the version of libc6.
lddVersion :: MP.Parsec Void Text Version
lddVersion = do
skipWhile (/= ')')
skip (== ')')
skipSpace
version'
hasMusl <- hasMatches relFileLibcMuslx86_64So1 libDirs
mLibc6Version <- veitherToEither <$> runE getLibc6Version
case mLibc6Version of
Right libc6Version -> logDebug $ "Found shared library libc6 in version: " <> prettyVer libc6Version
Left _ -> logDebug "Did not find a version of shared library libc6."
let hasLibc6_2_32 = either (const False) (>= [vver|2.32|]) mLibc6Version
hastinfo5 <- checkLib relFileLibtinfoSo5
hastinfo6 <- checkLib relFileLibtinfoSo6
hasncurses6 <- checkLib relFileLibncurseswSo6
hasgmp5 <- checkLib relFileLibgmpSo10
hasgmp4 <- checkLib relFileLibgmpSo3
let libComponents = if hasMusl
then
[ ["musl"] ]
else
concat
[ if hastinfo6 && hasgmp5
then
if hasLibc6_2_32
then [["tinfo6"]]
else [["tinfo6-libc6-pre232"]]
else [[]]
, [ [] | hastinfo5 && hasgmp5 ]
, [ ["ncurses6"] | hasncurses6 && hasgmp5 ]
, [ ["gmp4"] | hasgmp4 ]
]
pure $ map
(\c -> case c of
[] -> []
_ -> L.intercalate "-" c)
libComponents
FreeBSD ->
case _distroVersion of
Just fVer
| fVer >= [vers|12|] -> pure []
_ -> pure ["ino64"]
Darwin -> pure []
Windows -> pure []
where
relFileLibcMuslx86_64So1 :: FilePath
relFileLibcMuslx86_64So1 = "libc.musl-x86_64.so.1"
libDirs :: [FilePath]
libDirs = ["/lib", "/lib64"]
usrLibDirs :: [FilePath]
usrLibDirs = ["/usr/lib", "/usr/lib64"]
sbinDirs :: [FilePath]
sbinDirs = ["/sbin", "/usr/sbin"]
relFileLibtinfoSo5 :: FilePath
relFileLibtinfoSo5 = "libtinfo.so.5"
relFileLibtinfoSo6 :: FilePath
relFileLibtinfoSo6 = "libtinfo.so.6"
relFileLibncurseswSo6 :: FilePath
relFileLibncurseswSo6 = "libncursesw.so.6"
relFileLibgmpSo10 :: FilePath
relFileLibgmpSo10 = "libgmp.so.10"
relFileLibgmpSo3 :: FilePath
relFileLibgmpSo3 = "libgmp.so.3"
getStackOSKey :: Monad m => PlatformRequest -> Excepts '[UnsupportedSetupCombo] m String
getStackOSKey PlatformRequest { .. } =
case (_rArch, _rPlatform) of
(A_32 , Linux _) -> pure "linux32"
(A_64 , Linux _) -> pure "linux64"
(A_32 , Darwin ) -> pure "macosx"
(A_64 , Darwin ) -> pure "macosx"
(A_32 , FreeBSD) -> pure "freebsd32"
(A_64 , FreeBSD) -> pure "freebsd64"
(A_32 , Windows) -> pure "windows32"
(A_64 , Windows) -> pure "windows64"
(A_ARM , Linux _) -> pure "linux-armv7"
(A_ARM64, Linux _) -> pure "linux-aarch64"
(A_Sparc, Linux _) -> pure "linux-sparc"
(A_ARM64, Darwin ) -> pure "macosx-aarch64"
(A_ARM64, FreeBSD) -> pure "freebsd-aarch64"
(arch', os') -> throwE $ UnsupportedSetupCombo arch' os'
getStackPlatformKey :: (MonadReader env m, MonadFail m, HasLog env, MonadCatch m, MonadIO m)
=> PlatformRequest
-> Excepts '[UnsupportedSetupCombo, ParseError, NoCompatiblePlatform, NoCompatibleArch, DistroNotFound, ProcessError] m [String]
getStackPlatformKey pfreq@PlatformRequest{..} = do
osKey <- liftE $ getStackOSKey pfreq
builds <- liftE $ getStackGhcBuilds (PlatformResult _rPlatform _rVersion)
let builds' = (\build -> if null build then osKey else osKey <> "-" <> build) <$> builds
logDebug $ "Potential GHC builds: " <> mconcat (L.intersperse ", " $ fmap T.pack builds')
pure builds'