httpcompiler.pp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. unit httpcompiler;
  2. {$mode objfpc}
  3. {$H+}
  4. interface
  5. uses
  6. sysutils, classes, fpjson, contnrs, syncobjs, fpmimetypes, custhttpapp,
  7. fpwebfile, httproute, httpdefs, dirwatch, Pas2JSFSCompiler, Pas2JSCompilerCfg;
  8. Const
  9. nErrTooManyThreads = -1;
  10. Type
  11. TDirWatcher = Class;
  12. THTTPCompilerApplication = Class;
  13. { TCompileItem }
  14. TCompileItem = Class(TCollectionItem)
  15. private
  16. FBaseDir: string;
  17. FConfigFile: String;
  18. FFileName: string;
  19. FOutput : TStrings;
  20. FOptions : TStrings;
  21. FSuccess: Boolean;
  22. FThread: TThread;
  23. function GetOptions: TStrings;
  24. function GetOutput: TStrings;
  25. Public
  26. Destructor Destroy; override;
  27. Property BaseDir : string Read FBaseDir Write FBaseDir;
  28. Property FileName : string Read FFileName Write FFileName;
  29. Property ConfigFile: String Read FConfigFile Write FConfigFile;
  30. Property Options : TStrings Read GetOptions;
  31. Property Output : TStrings Read GetOutput;
  32. Property Thread : TThread Read FThread;
  33. Property Success : Boolean Read FSuccess;
  34. end;
  35. { TCompiles }
  36. TCompiles = Class(TCollection)
  37. private
  38. function GetC(AIndex : Integer): TCompileItem;
  39. Public
  40. Property Compiles[AIndex : Integer] : TCompileItem Read GetC; default;
  41. end;
  42. { TCompileThread }
  43. TCompileThread = class(TThread)
  44. private
  45. FApp : THTTPCompilerApplication;
  46. FItem: TCompileItem;
  47. procedure DoCompilerLog(Sender: TObject; const Msg: String);
  48. procedure SetItem(AValue: TCompileItem);
  49. Public
  50. Constructor create(App : THTTPCompilerApplication; aItem : TCompileItem);
  51. Procedure Execute; override;
  52. Property Item : TCompileItem read FItem write SetItem;
  53. end;
  54. { TDirWatcher }
  55. TDirWatcher = Class(TComponent)
  56. Private
  57. FApp : THTTPCompilerApplication;
  58. FDW : TDirWatch;
  59. procedure DoChange(Sender: TObject; aEntry: TDirectoryEntry; AEvents: TFileEvents);
  60. Public
  61. Constructor Create(App : THTTPCompilerApplication; ADir : String);overload;
  62. Destructor Destroy; override;
  63. end;
  64. { THTTPCompilerApplication }
  65. THTTPCompilerApplication = Class(TCustomHTTPApplication)
  66. private
  67. FBaseDir: String;
  68. FConfigFile: String;
  69. FProjectFile: String;
  70. FStatusLock : TCriticalSection;
  71. FQuiet: Boolean;
  72. FWatch: Boolean;
  73. FDW : TDirWatcher;
  74. FStatusList : TFPObjectList;
  75. FCompiles : TCompiles;
  76. FServeOnly : Boolean;
  77. procedure AddToStatus(O: TJSONObject);
  78. function HandleCompileOptions(aDir: String): Boolean;
  79. function ProcessOptions: Boolean;
  80. Procedure ReportBuilding(AItem : TCompileItem);
  81. Procedure ReportBuilt(AItem : TCompileItem);
  82. Procedure AddToStatus(AEntry : TDirectoryEntry; AEvents : TFileEvents);
  83. procedure DoStatusRequest(ARequest: TRequest; AResponse: TResponse);
  84. procedure DoRecompile(ARequest: TRequest; AResponse: TResponse);
  85. function ScheduleCompile(const aProjectFile: String; Options : TStrings = Nil): Integer;
  86. procedure StartWatch(ADir: String);
  87. protected
  88. procedure Usage(Msg: String); virtual;
  89. function GetDefaultMimeTypesFile: string; virtual;
  90. procedure LoadDefaultMimeTypes; virtual;
  91. public
  92. Constructor Create(AOWner : TComponent); override;
  93. Destructor Destroy; override;
  94. procedure DoLog(EventType: TEventType; const Msg: String); override;
  95. Procedure DoRun; override;
  96. property Quiet : Boolean read FQuiet Write FQuiet;
  97. Property Watch : Boolean Read FWatch Write FWatch;
  98. Property ProjectFile : String Read FProjectFile Write FProjectFile;
  99. Property ConfigFile : String Read FConfigFile Write FConfigFile;
  100. Property BaseDir : String Read FBaseDir;
  101. Property ServeOnly : Boolean Read FServeOnly;
  102. end;
  103. Implementation
  104. { TCompileThread }
  105. procedure TCompileThread.SetItem(AValue: TCompileItem);
  106. begin
  107. if FItem=AValue then Exit;
  108. FItem:=AValue;
  109. end;
  110. procedure TCompileThread.DoCompilerLog(Sender: TObject; const Msg: String);
  111. begin
  112. If Assigned(Item) then
  113. Item.Output.Add(Msg);
  114. end;
  115. constructor TCompileThread.create(App: THTTPCompilerApplication; aItem: TCompileItem);
  116. begin
  117. FItem:=aItem;
  118. FApp:=App;
  119. FreeOnTerminate:=True;
  120. inherited create(False);
  121. end;
  122. procedure TCompileThread.Execute;
  123. Var
  124. C : TPas2JSFSCompiler;
  125. L : TStrings;
  126. begin
  127. L:=Nil;
  128. C:=TPas2JSFSCompiler.Create;
  129. Try
  130. C.ConfigSupport:=TPas2JSFileConfigSupport.Create(C);
  131. FApp.ReportBuilding(Item);
  132. L:=TStringList.Create;
  133. L.Assign(Item.Options);
  134. if (Item.ConfigFile<>'') then
  135. L.Add('@'+Item.ConfigFile);
  136. L.Add(Item.FileName);
  137. C.Log.OnLog:=@DoCompilerLog;
  138. try
  139. C.Run(ParamStr(0),Item.BaseDir,L,True);
  140. Item.FSuccess:=True;
  141. except
  142. On E : Exception do
  143. Item.Output.Add(Format('Error %s compiling %s: %s',[E.ClassName,Item.FileName,E.Message]));
  144. end;
  145. FApp.ReportBuilt(Item);
  146. Finally
  147. C.Free;
  148. L.Free;
  149. end;
  150. Item.FThread:=Nil;
  151. end;
  152. { TCompiles }
  153. function TCompiles.GetC(AIndex : Integer): TCompileItem;
  154. begin
  155. Result:=Items[Aindex] as TCompileItem;
  156. end;
  157. { TCompileItem }
  158. function TCompileItem.GetOutput: TStrings;
  159. begin
  160. If (FOutput=Nil) then
  161. FOutput:=TStringList.Create;
  162. Result:=FOutput;
  163. end;
  164. function TCompileItem.GetOptions: TStrings;
  165. begin
  166. If (FOptions=Nil) then
  167. FOptions:=TStringList.Create;
  168. Result:=FOptions;
  169. end;
  170. destructor TCompileItem.Destroy;
  171. begin
  172. FreeAndNil(FOutput);
  173. FreeAndNil(FOptions);
  174. inherited Destroy;
  175. end;
  176. { TDirWatcher }
  177. procedure TDirWatcher.DoChange(Sender: TObject; aEntry: TDirectoryEntry; AEvents: TFileEvents);
  178. begin
  179. if Assigned(FApp) then
  180. FApp.AddToStatus(AEntry,AEvents);
  181. end;
  182. constructor TDirWatcher.Create(App: THTTPCompilerApplication; ADir: String);
  183. begin
  184. Inherited create(APP);
  185. FApp:=App;
  186. FDW:=TDirwatch.Create(Self);
  187. FDW.AddWatch(ADir,allEvents);
  188. FDW.OnChange:=@DoChange;
  189. TThread.ExecuteInThread(@FDW.StartWatch);
  190. end;
  191. destructor TDirWatcher.Destroy;
  192. begin
  193. FApp:=Nil;
  194. FDW.Terminate;
  195. FreeAndNil(FDW);
  196. inherited Destroy;
  197. end;
  198. { THTTPCompilerApplication }
  199. procedure THTTPCompilerApplication.DoLog(EventType: TEventType; const Msg: String);
  200. begin
  201. {AllowWriteln}
  202. if Quiet then
  203. exit;
  204. if IsConsole then
  205. Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Now),' [',EventType,'] ',Msg)
  206. else
  207. inherited DoLog(EventType, Msg);
  208. {AllowWriteln-}
  209. end;
  210. procedure THTTPCompilerApplication.Usage(Msg : String);
  211. begin
  212. {AllowWriteln}
  213. if (Msg<>'') then
  214. Writeln('Error: ',Msg);
  215. Writeln('Usage ',ExtractFileName(ParamStr(0)),' [options] ');
  216. Writeln('Where options is one or more of : ');
  217. Writeln('-d --directory=dir Base directory from which to serve files.');
  218. Writeln(' Default is current working directory: ',GetCurrentDir);
  219. Writeln('-h --help This help text');
  220. Writeln('-i --indexpage=name Directory index page to use (default: index.html)');
  221. Writeln('-n --noindexpage Do not allow index page.');
  222. Writeln('-p --port=NNNN TCP/IP port to listen on (default is 3000)');
  223. Writeln('-q --quiet Do not write diagnostic messages');
  224. Writeln('-w --watch Watch directory for changes');
  225. Writeln('-c --compile[=proj] Recompile project if pascal files change. Default project is app.lpr');
  226. Writeln('-m --mimetypes=file filename of mimetypes. Default is ',GetDefaultMimeTypesFile);
  227. Writeln('-s --simpleserver Only serve files, do not enable compilation.');
  228. Halt(Ord(Msg<>''));
  229. {AllowWriteln-}
  230. end;
  231. function THTTPCompilerApplication.GetDefaultMimeTypesFile: string;
  232. begin
  233. {$ifdef unix}
  234. Result:='/etc/mime.types';
  235. {$ifdef darwin}
  236. if not FileExists(Result) then
  237. Result:='/private/etc/apache2/mime.types';
  238. {$endif}
  239. {$else}
  240. Result:=ExtractFilePath(System.ParamStr(0))+'mime.types';
  241. {$endif}
  242. end;
  243. procedure THTTPCompilerApplication.LoadDefaultMimeTypes;
  244. begin
  245. MimeTypes.AddType('application/xhtml+xml','xhtml;xht');
  246. MimeTypes.AddType('text/html','htmll;htm');
  247. MimeTypes.AddType('text/plain','txt');
  248. MimeTypes.AddType('application/javascript','js');
  249. MimeTypes.AddType('text/plain','map');
  250. MimeTypes.AddType('application/json','json');
  251. MimeTypes.AddType('image/png','png');
  252. MimeTypes.AddType('image/jpeg','jpeg;jpg');
  253. MimeTypes.AddType('image/gif','gif');
  254. MimeTypes.AddType('image/jp2','jp2');
  255. MimeTypes.AddType('image/tiff','tiff;tif');
  256. MimeTypes.AddType('application/pdf','pdf');
  257. end;
  258. constructor THTTPCompilerApplication.Create(AOWner: TComponent);
  259. begin
  260. inherited Create(AOWner);
  261. FStatusLock:=TCriticalSection.Create;
  262. FStatusList:=TFPObjectList.Create(False);
  263. FCompiles:=TCompiles.Create(TCompileItem);
  264. end;
  265. destructor THTTPCompilerApplication.Destroy;
  266. begin
  267. FStatusLock.Enter;
  268. try
  269. FreeAndNil(FCompiles);
  270. FreeAndNil(FStatusList);
  271. finally
  272. FStatusLock.Leave;
  273. end;
  274. FreeAndNil(FStatusLock);
  275. inherited Destroy;
  276. end;
  277. procedure THTTPCompilerApplication.StartWatch(ADir : String);
  278. begin
  279. FDW:=TDirWatcher.Create(Self,ADir);
  280. end;
  281. procedure THTTPCompilerApplication.ReportBuilding(AItem: TCompileItem);
  282. Var
  283. O : TJSONObject;
  284. begin
  285. O:=TJSONObject.Create(['action','building','compileID',AItem.ID,'project',AItem.FileName,'config',AItem.ConfigFile]);
  286. AddToStatus(O);
  287. end;
  288. procedure THTTPCompilerApplication.ReportBuilt(AItem: TCompileItem);
  289. Var
  290. O : TJSONObject;
  291. A : TJSONArray;
  292. I : Integer;
  293. begin
  294. A:=TJSONArray.Create;
  295. For I:=0 to AItem.Output.Count-1 do
  296. A.Add(AItem.Output[i]);
  297. O:=TJSONObject.Create(['action','built','compileID',AItem.ID,'project',AItem.FileName,'config',AItem.ConfigFile,'output',A,'success',AItem.Success]);
  298. AddToStatus(O);
  299. end;
  300. procedure THTTPCompilerApplication.AddToStatus(O : TJSONObject);
  301. begin
  302. FStatusLock.Enter;
  303. try
  304. {$ifdef VerboseHTTPCompiler}
  305. Writeln('Adding to status ',Assigned(O),' : ',O.ClassName);
  306. {$endif}
  307. FStatusList.Add(O);
  308. finally
  309. FStatusLock.Leave;
  310. end;
  311. end;
  312. procedure THTTPCompilerApplication.AddToStatus(AEntry: TDirectoryEntry; AEvents: TFileEvents);
  313. Var
  314. O : TJSONObject;
  315. FN : String;
  316. begin
  317. Log(etDebug,'File change detected: %s (%s)',[AEntry.name,FileEventsToStr(AEvents)]);
  318. O:=TJSONObject.Create(['action','file','name',AEntry.name,'events',FileEventsToStr(AEvents)]);
  319. if Pos(ExtractFileExt(AEntry.Name),'.lpr.pas.pp.inc.dpr')>0 then
  320. FN:=AEntry.Name;
  321. if (FN<>'') then
  322. O.Add('recompile',true);
  323. AddToStatus(O);
  324. if (FN<>'') then
  325. begin
  326. Log(etDebug,'File change forces recompile: %s',[AEntry.name]);
  327. ScheduleCompile('',Nil);
  328. end;
  329. end;
  330. procedure THTTPCompilerApplication.DoStatusRequest(ARequest : TRequest; AResponse : TResponse);
  331. Var
  332. R,O : TJSONObject;
  333. A : TJSONArray;
  334. I : integer;
  335. begin
  336. Log(etDebug,'Status request from: %s',[ARequest.RemoteAddress]);
  337. R:=Nil;
  338. try
  339. FStatusLock.Enter;
  340. try
  341. if (FStatusList.Count=0) then
  342. R:=TJSONObject.Create(['ping',True])
  343. else
  344. begin
  345. {$ifdef VerboseHTTPCompiler}
  346. Writeln(FStatusList[0].ClassName);
  347. {$endif}
  348. O:=FStatusList[0] as TJSONObject;
  349. FStatusList.Delete(0);
  350. if O.Get('action','')<>'file' then
  351. R:=O
  352. else
  353. begin
  354. // If first event is file event, then add and delete all file events in list.
  355. A:=TJSONArray.Create([O]);
  356. O.Delete('action');
  357. R:=TJSONObject.Create(['action','sync','files',A]);
  358. For I:=FStatusList.Count-1 downto 0 do
  359. begin
  360. O:=FStatusList[I] as TJSONObject;
  361. if (O.Get('action','')='file') then
  362. begin
  363. A.Add(O);
  364. O.Delete('action');
  365. FStatusList.Delete(I);
  366. end;
  367. end;
  368. end
  369. end;
  370. finally
  371. FStatusLock.Leave;
  372. end;
  373. AResponse.ContentType:='application/json';
  374. AResponse.Content:=R.AsJSON;
  375. AResponse.SendResponse;
  376. finally
  377. R.Free;
  378. end;
  379. end;
  380. function THTTPCompilerApplication.ScheduleCompile(const aProjectFile: String;
  381. Options: TStrings): Integer;
  382. Var
  383. CI : TCompileItem;
  384. I,TC : Integer;
  385. begin
  386. TC:=0;
  387. For I:=0 to FCompiles.Count-1 do
  388. if Assigned(FCompiles[I].THread) then
  389. Inc(TC);
  390. if TC>10 then
  391. begin
  392. Log(etError,'Refusing compile of file "%s" using config file "%s"',[AProjectFile, ConfigFile]);
  393. Exit(nErrTooManyThreads);
  394. end;
  395. CI:=FCompiles.Add as TCompileItem;
  396. Log(etInfo,'Scheduling compile ID %d of file "%s" using config file "%s"',[CI.ID,AProjectFile, ConfigFile]);
  397. CI.BaseDir:=BaseDir;
  398. CI.FileName:=AProjectFile;
  399. CI.ConfigFile:=ConfigFile;
  400. if Assigned(Options) then
  401. CI.Options.Assign(Options);
  402. TCompileThread.Create(Self,CI);
  403. Result:=CI.ID;
  404. end;
  405. procedure THTTPCompilerApplication.DoRecompile(ARequest: TRequest; AResponse: TResponse);
  406. Var
  407. ID : Integer;
  408. PF,CL : String;
  409. Options: TStrings;
  410. begin
  411. PF:=ARequest.ContentFields.Values['ProjectFile'];
  412. CL:=ARequest.ContentFields.Values['CompileOptions'];
  413. if PF='' then
  414. PF:=ProjectFile;
  415. If (PF='') then
  416. begin
  417. AResponse.Code:=404;
  418. AResponse.CodeText:='No project file';
  419. AResponse.ContentType:='application/json';
  420. AResponse.Content:='{ "success" : false, "message": "no project file set or provided" }';
  421. end
  422. else
  423. begin
  424. Options:=Nil;
  425. try
  426. if CL<>'' then
  427. begin
  428. Options:=TStringList.Create;
  429. Options.Text:=Cl;
  430. end;
  431. ID:=ScheduleCompile(PF,Options);
  432. finally
  433. FreeAndNil(Options);
  434. end;
  435. if ID=nErrTooManyThreads then
  436. begin
  437. AResponse.Code:=403;
  438. AResponse.CodeText:='Too many compiles';
  439. AResponse.ContentType:='application/json';
  440. AResponse.Content:='{ "success" : false, "message": "Too many compiles running" }';
  441. end
  442. else
  443. begin
  444. AResponse.Code:=200;
  445. AResponse.ContentType:='application/json';
  446. AResponse.Content:=Format('{ "success" : true, "file": "%s", "commandLine" : "%s", "compileID": %d }',[StringToJSONString(PF),StringToJSONString(CL),ID]);
  447. end
  448. end;
  449. AResponse.SendResponse;
  450. end;
  451. function THTTPCompilerApplication.HandleCompileOptions(aDir: String): Boolean;
  452. begin
  453. Result:=False;
  454. Watch:=HasOption('w','watch');
  455. if Hasoption('P','project') then
  456. begin
  457. ProjectFile:=GetOptionValue('P','project');
  458. if ProjectFile='' then
  459. ProjectFile:=IncludeTrailingPathDelimiter(aDir)+'app.lpr';
  460. If Not FileExists(ProjectFile) then
  461. begin
  462. Terminate;
  463. Log(etError,'Project file "%s" does not exist, aborting.',[ProjectFile]);
  464. Exit;
  465. end;
  466. ConfigFile:=GetOptionValue('c','config');
  467. if (ConfigFile='') then
  468. ConfigFile:=ChangeFileExt(Projectfile,'.cfg');
  469. if not FileExists(ConfigFile) then
  470. ConfigFile:='';
  471. end;
  472. if Watch then
  473. begin
  474. if (ProjectFile='') then
  475. Log(etWarning,'No project file specified, disabling watch.') ;
  476. StartWatch(aDir);
  477. end;
  478. Result:=True;
  479. end;
  480. function THTTPCompilerApplication.ProcessOptions: Boolean;
  481. Var
  482. S,IndexPage,D : String;
  483. begin
  484. Result:=False;
  485. S:=Checkoptions('shqd:ni:p:wP::cm:',['help','quiet','noindexpage','directory:','port:','indexpage:','watch','project::','config:','simpleserver','mimetypes:']);
  486. if (S<>'') or HasOption('h','help') then
  487. usage(S);
  488. FServeOnly:=HasOption('s','serve-only');
  489. Quiet:=HasOption('q','quiet');
  490. Port:=StrToIntDef(GetOptionValue('p','port'),3000);
  491. D:=GetOptionValue('d','directory');
  492. if D='' then
  493. D:=GetCurrentDir;
  494. if HasOption('m','mimetypes') then
  495. MimeTypesFile:=GetOptionValue('m','mimetypes');
  496. if MimeTypesFile='' then
  497. begin
  498. MimeTypesFile:=GetDefaultMimeTypesFile;
  499. if not FileExists(MimeTypesFile) then
  500. begin
  501. MimeTypesFile:='';
  502. LoadDefaultMimeTypes;
  503. end;
  504. end
  505. else if not FileExists(MimeTypesFile) then
  506. Log(etWarning,'mimetypes file not found: '+MimeTypesFile);
  507. FBaseDir:=D;
  508. if not ServeOnly then
  509. if not HandleCompileOptions(D) then
  510. exit(False);
  511. TSimpleFileModule.BaseDir:=IncludeTrailingPathDelimiter(D);
  512. TSimpleFileModule.OnLog:=@Log;
  513. Log(etInfo,'Listening on port %d, serving files from directory: %s',[Port,D]);
  514. if ServeOnly then
  515. Log(etInfo,'Compile requests will be ignored.');
  516. If not HasOption('n','noindexpage') then
  517. begin
  518. IndexPage:=GetOptionValue('i','indexpage');
  519. if (IndexPage='') then
  520. IndexPage:='index.html';
  521. Log(etInfo,'Using index page %s',[IndexPage]);
  522. TSimpleFileModule.IndexPageName:=IndexPage;
  523. end;
  524. Result:=True;
  525. end;
  526. procedure THTTPCompilerApplication.DoRun;
  527. begin
  528. If not ProcessOptions then
  529. begin
  530. Terminate;
  531. exit;
  532. end;
  533. if not ServeOnly then
  534. begin
  535. httprouter.RegisterRoute('$sys/compile',rmPost,@DoRecompile);
  536. httprouter.RegisterRoute('$sys/status',rmGet,@DoStatusRequest);
  537. end;
  538. TSimpleFileModule.RegisterDefaultRoute;
  539. inherited;
  540. end;
  541. end.