/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@cs.vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (C): 2015, VU University Amsterdam

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    As a special exception, if you link this library with other files,
    compiled with a Free Software compiler, to produce an executable, this
    library does not by itself cause the resulting executable to be covered
    by the GNU General Public License. This exception does not however
    invalidate any other reasons why the executable file might be covered by
    the GNU General Public License.
*/

:- module(logstat,
	  [ clean_log/0,
	    read_log/1,			% +File
	    read_log/2,			% +File, +Options
	    logrecord/1,		% +List
	    logrecord/10
	  ]).
:- use_module(library(rbtrees)).
:- use_module(library(debug)).
:- use_module(library(lists)).
:- use_module(library(zlib)).
:- use_module(library(record)).

:- portray_text(true).

/** <module> Process SWI-Prolog HTTPD logfiles

This module reads SWI-Prolog HTTPD logfiles   and  allows asking queries
about them.  Below is a simple example that extracts SPARQL queries from
a [ClioPatria](http://cliopatria.swi-prolog.org) log file:

  ==
  ?- use_module(library(http/logstat)).
  ?- read_log('httpd.log').
  ?- logrecord([path('/sparql/'), search([query=Query])]).
  Query = 'PREFIX rdf: ...'
  ==

@see library(http/http_log) provides the HTTP framework component to
write logfiles that are expected by this library.
*/

%%	logrecord(?N, ?Time, ?Session, ?RemoteIP, ?Path,
%%		  ?Query, ?Referrer, ?Code, ?Result, ?Extra)
%
%	Database predicate that represents an HTTP transaction.
%
%	@arg N is the index number of the record
%	@arg Time is the POSIX time stamp the query was fired
%	@arg Session is the session-id or `-` if the request has no
%	session
%	@arg RemoteIP is the remote IP address
%	@arg Path is the HTTP location, starting with `/`
%	@arg Query is a list of `Name=Value` terms holding the (GET)
%	query parameters
%	@arg Referrer is the referer URL or `-` if unknown
%	@arg Code is the HTTP numerical reply code
%	@arg Result is Prolog notion of the result as a Prolog term
%	@arg Extra is a list with Key(Value) terms holding the
%	keys below.  Only cpu(Seconds) is always present.
%
%	  - cpu(Seconds)
%	  CPU time used to process the query
%	  - bytes(Count)
%	  Number of bytes sent (if known)
%	  - user_agent(UserAgent)
%	  Browser identifier (if known)
%	  - http_version(Major-Minor)
%	  HTTP Protocol version
%	  - city(City)
%	  Name of the city (if configured)
%	  - lat(Lat)
%	  Latitude (if configured)
%	  - lon(Lon)
%	  Longitude (if configured)

:- dynamic
	logrecord/10.

%%	field(?Index, ?Name) is nondet.
%
%	Define the field-names for the logrecord/10 predicate.

field(1, key).
field(2, time).
field(3, session).
field(4, ip).
field(5, path).
field(6, query).
field(7, referer).
field(8, code).
field(9, result).
field(10, extra).


%%	clean_log
%
%	Cleanup the database.

clean_log :-
	functor(Term, logrecord, 10),
	assertion(predicate_property(Term, dynamic)),
	retractall(Term).

:- record
	log_state(progress:boolean=true,
		  skip_bad_requests:boolean=false).

%%	read_log(+File) is det.
%%	read_log(+File, +Options) is det.
%
%	Read a SWI-Prolog HTTP logfile.  If   the  file contains errors,
%	these are printed to the terminal  and the corresponding records
%	are ignored.  Options supported:
%
%	  - progress(+Boolean)
%	  Indicate progress on the terminal (default `true`)
%	  - skip_bad_requests(+Boolean)
%	  Ignore 400 requests.

read_log(File) :-
	read_log(File, []).

read_log(File, Options) :-
	make_log_state(Options, State, _),
	rb_empty(Open),
	setup_call_cleanup(myopen(File, In),
			   (   read_skip_errors(In, Term0),
			       read_log(Term0, In, 1, Open, State)
			   ),
			   close(In)),
	nl(user_error).

myopen(File, In) :-
	exists_file(File), !,
	open(File, read, In, [encoding(utf8)]).
myopen(File, In) :-
	file_name_extension(File, gz, ZFile),
	exists_file(ZFile),!,
	gzopen(ZFile, read, In, [encoding(utf8)]).
myopen(File, In) :-			% generate error
	open(File, read, In, [encoding(utf8)]).


read_log(end_of_file, _, _, Open, _State) :- !,
	close_all(Open).
read_log(Term, In, Count0, Open0, State) :-
	(   assert_log(Term, Count0, Count1, Open0, Open1)
	->  !
	;   debugging(logstat),
	    gtrace,
	    assert_log(Term, Count0, Count1, Open0, Open1)
	),
	progress(Count1, State),
	read_skip_errors(In, Term2),
	read_log(Term2, In, Count1, Open1, State).
read_log(Term, In, Count, Open, State) :-
	(   skip_term(Term, State)
	->  true
	;   format(user_error, '~NWarning: failed to process ~p~n', [Term])
	),
	read_skip_errors(In, Term2),
	read_log(Term2, In, Count, Open, State).

read_skip_errors(In, Term) :-
	repeat,
	catch(read(In, Term), E, (print_message(error, E),fail)), !.

skip_term(completed(_, _, _, 400, _), _).
skip_term(completed(0, _, _, 500, error(_)), _).
skip_term(completed(_, _, _, _, _), State) :-
	log_state_skip_bad_requests(State, true).

assert_log(server(_StartStop, _Time), Count, Count, Open0, Open) :- !,
	close_all(Open0),
	rb_new(Open).
assert_log(request(I, Time, Request), Count0, Count, Open0, Open) :- !,
	Count is Count0+1,
	rb_insert_new(Open0, I, r(Count0, Time, Request), Open).
assert_log(completed(I, CPU, Status), Count, Count, Open0, Open) :-
	rb_delete(Open0, I, r(Id, Time, Request), Open),
	save_record(Id, I, Time, CPU, Request, 0, 0, Status).
assert_log(completed(I, CPU, Bytes, Code, Status), Count, Count, Open0, Open) :-
	rb_delete(Open0, I, r(Id, Time, Request), Open),
	save_record(Id, I, Time, CPU, Request, Bytes, Code, Status).

close_all(Open0) :-
	rb_visit(Open0, Pairs),
	close_pairs(Pairs).

close_pairs([]).
close_pairs([RID-r(Id, Time, Request)|T]) :-
	save_record(Id, RID, Time, 0, Request, 0, 500, no_reply),
	close_pairs(T).

save_record(Id, SeqNo, Time, CPU, Request, Bytes, Code, Status) :-
	session(Request, Session),
	remote_IP(Request, RemoteIP),
	path(Request, Path),
	query_parms(Request, Parms),
	referer(Request, Referer),
	extra(Request, Bytes, Extra),
	assert(logrecord(Id, Time, Session, RemoteIP,
			 Path, Parms, Referer, Code, Status,
			 [ cpu(CPU),
			   seqno(SeqNo)
			 | Extra
			 ])).


session(Request, SessionID) :-
	memberchk(session(SessionID), Request), !.
session(Request, SessionID) :-
	memberchk(cookie(Cookie), Request),
	memberchk(swipl_session=SessionID, Cookie), !.
session(_, -).

%%	remote_IP(+Request, -IP:atom) is semidet.
%
%	Find the remote IP address. This is either in x_forwarded_for if
%	we are behind a (Apache) proxy, or it is the peer.

remote_IP(Request, IP) :-
	memberchk(x_forwarded_for(IP0), Request), !,
	final_ip(IP0, IP).
remote_IP(Request, IP) :-
	memberchk(peer(Peer), Request), !,
	peer_to_ip(Peer, IP).
remote_IP(_, -).

final_ip(IP0, IP) :-
	split_string(IP0, ",", " ", IPList),
	last(IPList, IPString),
	atom_string(IP, IPString).

peer_to_ip(ip(A,B,C,D), IP) :-
	atomic_list_concat([A,B,C,D], '.', IP).

path(Request, Path) :-
	memberchk(path(Path), Request).

query_parms(Request, Parms) :-
	memberchk(search(Parms), Request), !.
query_parms(_, []).

referer(Request, Referer) :-
	memberchk(referer(Referer), Request), !.
referer(_, -).

extra(Request, Bytes, Extra) :-
	findall(E, extra_field(Request, Bytes, E), Extra).

extra_field(_, Bytes, Extra) :-
	Bytes \== 0,
	Extra = bytes(Bytes).
extra_field(Request, _, user_agent(Agent)) :-
	memberchk(user_agent(Agent), Request).
extra_field(Request, _, http_version(Agent)) :-
	memberchk(http_version(Agent), Request).
extra_field(Request, _, city(City)) :-
	memberchk(x_geoip_city(City), Request).
extra_field(Request, _, lat(Lat)) :-
	memberchk(x_geoip_latitude(LatAtom), Request),
	atom_number(LatAtom, Lat).
extra_field(Request, _, lon(Lon)) :-
	memberchk(x_geoip_longitude(LonAtom), Request),
	atom_number(LonAtom, Lon).

%%	logrecord(+Query) is nondet.
%
%	Query by list of fieldnames. Query   list  a list of Name(Value)
%	specifications.  Name is one of:
%
%	    * key(Integer)
%	    Integer number of the request (1,2,3,...)
%	    * seqno(Integer)
%	    Original sequence number from the log file (may have
%	    duplicates)
%	    * time(Float)
%	    POSIX time stamp of the request.
%	    * session(Atom)
%	    The session-id or `-` if the request has no session
%	    * ip(Atom)
%	    The remote IP address
%	    * path(Atom)
%	    The HTTP location, starting with `/`
%	    * query(list(Name=Value))
%	    List of `Name=Value` terms holding the (GET) query parameters
%	    * referer(Atom)
%	    The referer URL or `-` if unknown
%	    * code(Integer)
%	    Code is the HTTP numerical reply code
%	    * result(Term)
%	    Prolog notion of the result as a Prolog term
%	    * cpu(Seconds)
%	    CPU time used to process the query
%	    * bytes(Count)
%	    Number of bytes sent (if known)
%	    * user_agent(UserAgent)
%	    Browser identifier (if known)
%	    * http_version(Major-Minor)
%	    HTTP Protocol version
%	    * city(City)
%	    Name of the city (if configured)
%	    * lat(Lat)
%	    Latitude (if configured)
%	    * lon(Lon)
%	    Longitude (if configured)
%	    * after(+TimeSpec)
%	    Only consider records created after TimeSpec.  TimeSpec is
%	    one of:
%	        * Year/Month/Day
%	    * before(+TimeSpec)
%	    See after(TimeSpec).
%	    * search([Name=Value...])
%	    Demand the following fields to be present in the query.

logrecord(Query) :-
	must_be(list, Query),
	functor(Term, logrecord, 10),
	make_query(Query, Term, RestQuery),
	make_condition(RestQuery, Extra, Term, Cond),
	(   Extra == [], Cond == true
	->  call(Term)
	;   Extra == []
	->  call((Term,Cond))
	;   field(I, extra)
	->  arg(I, Term, ExtraDB),
	    call((Term,Cond)),
	    subset(Extra, ExtraDB)
	).

make_query([], _, []).
make_query([Q|T0], Goal, Extra) :-
	Q =.. [Name,Value],
	fill_field(Name, Goal, Value), !,
	make_query(T0, Goal, Extra).
make_query([Q|T0], Goal, [Q|Extra]) :-
	make_query(T0, Goal, Extra).

fill_field(Name, Term, Value) :-
	field(I, Name),
	arg(I, Term, Value).

make_condition([], [], _, true).
make_condition([C0|T0], T, Term, (Goal,More)) :-
	condition(C0, Term, Goal), !,
	make_condition(T0, T, Term, More).
make_condition([H|T0], [H|T], Term, Cond) :-
	make_condition(T0, T, Term, Cond).


condition(after(TimeSpec), Term, Stamp >= Time) :-
	field(I, time), !,
	arg(I, Term, Stamp),
	time_spec_to_stamp(TimeSpec, Time).
condition(before(TimeSpec), Term, Stamp < Time) :-
	field(I, time), !,
	arg(I, Term, Stamp),
	time_spec_to_stamp(TimeSpec, Time).
condition(search(Fields), Term, subset(Fields, Query)) :-
	field(I, query), !,
	arg(I, Term, Query).


time_spec_to_stamp(Y/M/D, Stamp) :-
	date_time_stamp(date(Y,M,D,0,0,0,0,-,-), Stamp).


		 /*******************************
		 *	       FEEDBACK		*
		 *******************************/

progress(Count, State) :-
	log_state_progress(State, true),
	Count mod 1000 =:= 0, !,
	format(user_error, '\r~t~D~20|', [Count]).
progress(_, _).
