AnalysisServer.curry 12.9 KB
Newer Older
1
--------------------------------------------------------------------------
2
3
4
5
--- This is the main module of the analysis server.
--- It provides operations to initialize the server system,
--- start the server on a socket, or use the analysis server
--- by other Curry applications.
6
7
---
--- @author Heiko Hoffmann, Michael Hanus
8
--- @version June 2016
9
10
--------------------------------------------------------------------------

11
module AnalysisServer(mainServer, initializeAnalysisSystem, analyzeModuleAsText,
12
                      analyzeModuleForBrowser, analyzeFunctionForBrowser,
13
14
                      analyzeGeneric, analyzePublic, analyzeInterface)
  where
15

16
17
import ReadNumeric(readNat)
import Char(isSpace)
18
import Directory
19
import FlatCurry.Types(QName)
20
import Socket(Socket(..),listenOn,listenOnFresh,sClose,waitForSocketAccept)
21
22
23
import IO
import ReadShowTerm(readQTerm,showQTerm)
import System(system,sleep,setEnviron,getArgs)
24
import FileGoodies(stripSuffix,splitDirectoryBaseName)
25
26

import Analysis(Analysis,AOutFormat(..))
27
import Configuration
28
import GenericProgInfo
29
30
31
import Registry
import ServerFormats
import ServerFunctions(WorkerMessage(..))
32
33
34
35
36
37
38
39
40
41
42

-- Messages to communicate with the analysis server from external programs.
data AnalysisServerMessage = 
    GetAnalysis
  | AnalyzeModule    String String String Bool
  | AnalyzeEntity  String String String String
  | StopServer
  | SetCurryPath String
  | ParseError

--- Initializations to be done when the system is started.
43
44
initializeAnalysisSystem :: IO ()
initializeAnalysisSystem = updateRCFile
45

46
--- Start the analysis server on a socket.
47
48
mainServer :: Maybe Int -> IO ()
mainServer mbport = do
49
  putStrLn "Start Server"
50
51
52
  (port1,socket1) <- maybe listenOnFresh
                           (\p -> listenOn p >>= \s -> return (p,s))
                           mbport
53
54
55
56
57
58
59
60
  putStrLn ("Server Port: "++show port1)
  storeServerPortNumber port1
  getDefaultPath >>= setEnviron "CURRYPATH" 
  numworkers <- numberOfWorkers
  if numworkers>0
   then do
    serveraddress <- getServerAddress
    (workerport,workersocket) <- listenOnFresh
61
    debugMessage 2 ("SERVER: port to workers: "++show workerport)
62
    handles <- startWorkers numworkers workersocket serveraddress workerport []
63
    serverLoop socket1 handles
64
65
    sClose workersocket
   else
66
    serverLoop socket1 []
67
68


69
70
71
72
73
74
75
76
77
78
79
--- Run the analysis system and show the analysis results in standard textual
--- representation.
--- The third argument is a flag indicating whether the
--- (re-)analysis should be enforced.
--- Note that, before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
analyzeModuleAsText :: String -> String -> Bool -> IO String
analyzeModuleAsText ananame mname enforce =
  analyzeModule ananame (stripSuffix mname) enforce AText >>=
             return . formatResult mname "Text" Nothing True

80
81
82
83
84
--- Run the analysis system to show the analysis results in the BrowserGUI.
--- Note that, before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
analyzeModuleForBrowser :: String -> String -> AOutFormat -> IO [(QName,String)]
analyzeModuleForBrowser ananame moduleName aoutformat =
85
  analyzeModule ananame moduleName False aoutformat >>=
86
87
88
89
90
91
92
93
94
95
96
    return . either pinfo2list (const [])
 where
   pinfo2list pinfo = let (pubinfo,privinfo) = progInfo2Lists pinfo
                       in pubinfo++privinfo

--- Run the analysis system to show the analysis result of a single function
--- in the BrowserGUI.
--- Note that before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
analyzeFunctionForBrowser :: String -> QName -> AOutFormat -> IO String
analyzeFunctionForBrowser ananame qn@(mname,_) aoutformat = do
97
  analyzeModule ananame mname False aoutformat >>=
98
    return . either (maybe "" id . lookupProgInfo qn) (const "")
99

100
--- Analyze a complete module for a given analysis result format.
101
102
--- The third argument is a flag indicating whether the
--- (re-)analysis should be enforced.
103
104
--- Note that before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
105
analyzeModule :: String -> String -> Bool -> AOutFormat
106
              -> IO (Either (ProgInfo String) String)
107
analyzeModule ananame moduleName enforce aoutformat = do
108
109
110
111
  let (mdir,mname) = splitDirectoryBaseName moduleName
  getDefaultPath >>= setEnviron "CURRYPATH"
  curdir <- getCurrentDirectory
  unless (mdir==".") $ setCurrentDirectory mdir
112
  numworkers <- numberOfWorkers
113
114
115
116
117
118
  aresult <-
   if numworkers>0
     then do
      serveraddress <- getServerAddress
      (port,socket) <- listenOnFresh
      handles <- startWorkers numworkers socket serveraddress port []
119
      result <- runAnalysisWithWorkers ananame aoutformat enforce handles mname
120
121
122
      stopWorkers handles
      sClose socket
      return result
123
     else runAnalysisWithWorkers ananame aoutformat enforce [] mname
124
125
126
  setCurrentDirectory curdir
  return aresult

127
128
129
130
131
132
--- Start the analysis system with a particular analysis.
--- The analysis must be a registered one if workers are used.
--- If it is a combined analysis, the base analysis must be also
--- a registered one.
analyzeGeneric :: Analysis a -> String -> IO (Either (ProgInfo a) String)
analyzeGeneric analysis moduleName = do
133
  initializeAnalysisSystem
134
  let (mdir,mname) = splitDirectoryBaseName moduleName
135
  getDefaultPath >>= setEnviron "CURRYPATH" 
136
137
  curdir <- getCurrentDirectory
  unless (mdir==".") $ setCurrentDirectory mdir
138
  numworkers <- numberOfWorkers
139
140
141
142
143
144
  aresult <-
    if numworkers>0
     then do
      serveraddress <- getServerAddress
      (port,socket) <- listenOnFresh
      handles <- startWorkers numworkers socket serveraddress port []
145
      result <- analyzeMain analysis mname handles False True
146
147
148
149
      stopWorkers handles
      sClose socket
      return result
     else
150
      analyzeMain analysis mname [] False True
151
152
153
  setCurrentDirectory curdir
  return aresult
 
154
155
156
157
158
159
160
161
162
163
--- Start the analysis system with a given analysis to compute properties
--- of a module interface.
--- The analysis must be a registered one if workers are used.
--- If it is a combined analysis, the base analysis must be also
--- a registered one.
analyzePublic :: Analysis a -> String -> IO (Either (ProgInfo a) String)
analyzePublic analysis moduleName =
  analyzeGeneric analysis moduleName
  >>= return . either (Left . publicProgInfo) Right

164
165
166
167
168
169
--- Start the analysis system with a given analysis to compute properties
--- of a module interface.
--- The analysis must be a registered one if workers are used.
--- If it is a combined analysis, the base analysis must be also
--- a registered one.
analyzeInterface :: Analysis a -> String -> IO (Either [(QName,a)] String)
170
analyzeInterface analysis moduleName =
171
  analyzeGeneric analysis moduleName
172
  >>= return . either (Left . publicListFromProgInfo) Right
173
174
175
176
177
178
179

--------------------------------------------------------------------------
-- start a number of workers at server start
startWorkers:: Int -> Socket -> String -> Int -> [Handle] -> IO [Handle]
startWorkers number workersocket serveraddress workerport handles = do
  if number>0
    then do
180
      debugMessage 4 ("Number:"++(show number))
181
182
      let command = baseDir++"/cass_worker "++serveraddress++" "
                                            ++(show workerport)++" &"
183
      debugMessage 4 ("system command: "++command)
184
      system command
185
      debugMessage 4 ("Wait for socket accept for client "++show number)
186
      connection <- waitForSocketAccept workersocket waitTime
187
      debugMessage 4 ("Socket accept for client "++show number)
188
189
190
191
192
193
194
195
196
197
      case connection of
        Just (_,handle) -> do
          startWorkers (number-1) workersocket serveraddress workerport
                       (handle:handles)
        Nothing -> do
          putStrLn ("startWorkers: connection error worker "++(show number))
          startWorkers (number-1) workersocket serveraddress workerport handles
    else return handles

-- stop all workers at server stop
Michael Hanus 's avatar
Michael Hanus committed
198
stopWorkers :: [Handle] -> IO ()
199
200
201
202
203
204
205
206
stopWorkers [] = done
stopWorkers (handle:whandles) = do
  hPutStrLn handle (showQTerm StopWorker)
  hClose handle
  stopWorkers whandles

--------------------------------------------------------------------------
-- server loop to answer analysis requests over network
Michael Hanus 's avatar
Michael Hanus committed
207
serverLoop :: Socket -> [Handle] -> IO ()
208
serverLoop socket1 whandles = do
209
  --debugMessage 3 "SERVER: serverLoop"
210
211
  connection <- waitForSocketAccept socket1 waitTime
  case connection of 
212
213
214
    Just (_,handle) -> serverLoopOnHandle socket1 whandles handle
    Nothing -> do
      putStrLn "serverLoop: connection error: time out in waitForSocketAccept"
215
      sleep 1
216
217
218
219
220
221
222
223
224
225
226
227
228
      serverLoop socket1 whandles

--- Reads a line from an input handle and returns it.
hGetLineUntilEOF  :: Handle -> IO String
hGetLineUntilEOF h = do
  eof <- hIsEOF h
  if eof
   then return ""
   else do c <- hGetChar h
           if c=='\n' then return ""
                      else do cs <- hGetLineUntilEOF h
                              return (c:cs)

Michael Hanus 's avatar
Michael Hanus committed
229
serverLoopOnHandle :: Socket -> [Handle] -> Handle -> IO ()
230
231
232
233
serverLoopOnHandle socket1 whandles handle = do
  eof <- hIsEOF handle
  if eof
   then do hClose handle
234
           debugMessage 2 "SERVER connection: eof"
235
236
237
           serverLoop socket1 whandles
   else do
     string <- hGetLineUntilEOF handle
238
     debugMessage 2 ("SERVER got message: "++string)
239
     let force = False
240
241
242
243
244
245
246
247
     case parseServerMessage string of
       ParseError -> do
         sendServerError handle ("Illegal message received: "++string)
         serverLoopOnHandle socket1 whandles handle
       GetAnalysis -> do
         sendServerResult handle showAnalysisNamesAndFormats
         serverLoopOnHandle socket1 whandles handle
       AnalyzeModule ananame outForm modname public ->
248
         catch (runAnalysisWithWorkers ananame AText force whandles modname >>=
249
250
251
252
                return . formatResult modname outForm Nothing public >>=
                sendResult)
               sendAnalysisError
       AnalyzeEntity ananame outForm modname functionName ->
253
         catch (runAnalysisWithWorkers ananame AText force whandles modname >>=
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
                return . formatResult modname outForm
                                      (Just functionName) False >>= sendResult)
               sendAnalysisError
       SetCurryPath path -> do
         setEnviron "CURRYPATH" path
         changeWorkerPath path whandles
         sendServerResult handle ""
         serverLoopOnHandle socket1 whandles handle
       StopServer -> do
         stopWorkers whandles
         sendServerResult handle ""
         hClose handle
         sClose socket1
         putStrLn "Stop Server"
         removeServerPortNumber
269
 where
270
  sendResult resultstring = do
271
    debugMessage 4 ("formatted result:\n"++resultstring)
272
273
    sendServerResult handle resultstring
    serverLoopOnHandle socket1 whandles handle
274

275
276
277
  sendAnalysisError err = do
    sendServerError handle ("ERROR in analysis server: "++showError err)
    serverLoopOnHandle socket1 whandles handle
278
279

-- Send a server result in the format "ok <n>\n<result text>" where <n>
280
-- is the number of lines of the <result text>.
Michael Hanus 's avatar
Michael Hanus committed
281
sendServerResult :: Handle -> String -> IO ()
282
283
284
285
286
287
sendServerResult handle resultstring = do
  let resultlines = lines resultstring
  hPutStrLn handle ("ok " ++ show (length resultlines))
  hPutStr handle (unlines resultlines)
  hFlush handle

288
-- Send a server error in the format "error <error message>\n".
Michael Hanus 's avatar
Michael Hanus committed
289
sendServerError :: Handle -> String -> IO ()
290
sendServerError handle errstring = do
291
  debugMessage 1 errstring
292
293
294
  hPutStrLn handle ("error "++errstring)
  hFlush handle

295
296
297
-- Inform the worker threads about a given changed library search path
changeWorkerPath :: String -> [Handle] -> IO ()
changeWorkerPath _ [] = done
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
changeWorkerPath path (handle:whandles) = do
  hPutStrLn handle (showQTerm (ChangePath path))
  changeWorkerPath path whandles

-- parse incoming message for type of request
parseServerMessage :: String -> AnalysisServerMessage
parseServerMessage message = case words message of
  [] -> ParseError
  w:ws -> case w of 
    "GetAnalysis" -> GetAnalysis
    "AnalyzeModule" -> case ws of 
      s1:s2:s3:[] -> checkFormat s2 $ AnalyzeModule s1 s2 s3 False
    "AnalyzeInterface" -> case ws of 
      s1:s2:s3:[] -> checkFormat s2 $ AnalyzeModule s1 s2 s3 True
      _ -> ParseError
    "AnalyzeFunction" -> case ws of
      s1:s2:s3:s4:[] -> checkFormat s2 $ AnalyzeEntity s1 s2 s3 s4
      _ -> ParseError
    "AnalyzeTypeConstructor" -> case ws of
      s1:s2:s3:s4:[] -> checkFormat s2 $ AnalyzeEntity s1 s2 s3 s4
      _ -> ParseError
    "AnalyzeDataConstructor" -> case ws of
      s1:s2:s3:s4:[] -> checkFormat s2 $ AnalyzeEntity s1 s2 s3 s4
      _ -> ParseError  
    "SetCurryPath" -> case ws of
      s:[] -> SetCurryPath s
      _ -> ParseError
    "StopServer" -> StopServer
    _ -> ParseError 
 where
  checkFormat fmt msg = if fmt `elem` serverFormats then msg else ParseError

--- Show all analysis names and formats.
showAnalysisNamesAndFormats :: String
showAnalysisNamesAndFormats =
  unlines (concatMap (\an -> map ((an++" ")++) serverFormats)
334
                     registeredAnalysisNames)
335