Some small changes in preparation for hscan
[ganeti-local] / Ganeti / HTools / Utils.hs
1 {-| Utility functions -}
2
3 module Ganeti.HTools.Utils where
4
5 import Data.Either
6 import Data.List
7 import qualified Data.Version
8 import Monad
9 import System
10 import System.IO
11 import System.Info
12 import Text.Printf
13 import qualified Ganeti.HTools.Version as Version
14
15 import Debug.Trace
16
17 -- | To be used only for debugging, breaks referential integrity.
18 debug :: Show a => a -> a
19 debug x = trace (show x) x
20
21 -- | Check if the given argument is Left something
22 isLeft :: Either a b -> Bool
23 isLeft val =
24     case val of
25       Left _ -> True
26       _ -> False
27
28 fromLeft :: Either a b -> a
29 fromLeft = either (\x -> x) (\_ -> undefined)
30
31 fromRight :: Either a b -> b
32 fromRight = either (\_ -> undefined) id
33
34 -- | Comma-join a string list.
35 commaJoin :: [String] -> String
36 commaJoin = intercalate ","
37
38 -- | Split a string on a separator and return an array.
39 sepSplit :: Char -> String -> [String]
40 sepSplit sep s
41     | x == "" && xs == [] = []
42     | xs == []            = [x]
43     | ys == []            = x:"":[]
44     | otherwise           = x:(sepSplit sep ys)
45     where (x, xs) = break (== sep) s
46           ys = drop 1 xs
47
48 -- | Partial application of sepSplit to @'.'@
49 commaSplit :: String -> [String]
50 commaSplit = sepSplit ','
51
52 -- | Swap a list of @(a, b)@ into @(b, a)@
53 swapPairs :: [(a, b)] -> [(b, a)]
54 swapPairs = map (\ (a, b) -> (b, a))
55
56 -- Simple and slow statistical functions, please replace with better versions
57
58 -- | Mean value of a list.
59 meanValue :: Floating a => [a] -> a
60 meanValue lst = (sum lst) / (fromIntegral $ length lst)
61
62 -- | Standard deviation.
63 stdDev :: Floating a => [a] -> a
64 stdDev lst =
65     let mv = meanValue lst
66         square = (^ (2::Int)) -- silences "defaulting the constraint..."
67         av = sum $ map square $ map (\e -> e - mv) lst
68         bv = sqrt (av / (fromIntegral $ length lst))
69     in bv
70
71
72 -- | Coefficient of variation.
73 varianceCoeff :: Floating a => [a] -> a
74 varianceCoeff lst = (stdDev lst) / (fromIntegral $ length lst)
75
76 -- | Get a Right result or print the error and exit
77 readData :: (String -> IO (Either String String)) -> String -> IO String
78 readData fn host = do
79   nd <- fn host
80   when (isLeft nd) $
81        do
82          putStrLn $ fromLeft nd
83          exitWith $ ExitFailure 1
84   return $ fromRight nd
85
86 showVersion :: String -- ^ The program name
87             -> String -- ^ The formatted version and other information data
88 showVersion name =
89     printf "%s %s\ncompiled with %s %s\nrunning on %s %s\n"
90            name Version.version
91            compilerName (Data.Version.showVersion compilerVersion)
92            os arch