百度统计(tongji.baidu.com)是百度推出的一款免费的专业网站流量分析工具,能够告诉用户访客是如何找到并浏览用户的网站的,以及在网站上浏览了哪些页面。这些信息可以帮助用户改善访客在其网站上的使用体验,不断提升网站的投资回报率。
百度统计提供了几十种图形化报告,包括:趋势分析、来源分析、页面分析、访客分析、定制分析等多种统计分析服务。
这里我们参考百度统计的功能,基于 Spark Streaming 简单实现一个分析系统,使之包括以下分析功能。
- 流量分析。一段时间内用户网站的流量变化趋势,针对不同的 IP 对用户网站的流量进行细分。常见指标是总 PV 和各 IP 的PV。
- 来源分析。各种搜索引擎来源给用户网站带来的流量情况,需要精确到具体搜索引擎、具体关键词。通过来源分析,用户可以及时了解哪种类型的来源为其带来了更多访客。常见指标是搜索引擎、关键词和终端类型的 PV 。
- 网站分析。各个页面的访问情况,包括及时了解哪些页面最吸引访客以及哪些页面最容易导致访客流失,从而帮助用户更有针对性地改善网站质量。常见指标是各页面的 PV 。
2.1 日志实时采集
Web log 一般在 HTTP 服务器收集,比如 Nginx access 日志文件。一个典型的方案是 Nginx 日志文件 + Flume + Kafka + Spark Streaming,如下所述:
- 接收服务器用 Nginx ,根据负载可以部署多台,数据落地至本地日志文件;
- 每个 Nginx 节点上部署 Flume ,使用 tail -f 实时读取 Nginx 日志,发送至 KafKa 集群;
- 专用的 Kafka 集群用户连接实时日志与 Spark 集群,详细配置可以参考 http://spark.apache.org/docs/2.1.1/streaming-kafka-integration.html ;
- Spark Streaming 程序实时消费 Kafka 集群上的数据,实时分析,输出;
- 结果写入 MySQL 数据库。
当然,还可以进一步优化,比如 CGI 程序直接发日志消息到 Kafka ,节省了写访问日志的磁盘开销。这里主要专注 Spark Streaming 的应用,所以我们不做详细论述
touch sample_web_log.py vim sample_web_log.py
当前编辑完成的代码还不能直接通过 ./sample_web_log.py 的方式执行,我们需要为其增加可执行权限。
chmod +x sample_web_log.py
采样生成web日志
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random import time class WebLogGeneration(object): # 类属性,由所有类的对象共享 site_url_base = "http://www.xxx.com/" # 基本构造函数 def __init__(self): # 前面7条是IE,所以大概浏览器类型70%为IE ,接入类型上,20%为移动设备,分别是7和8条,5% 为空 # https://github.com/mssola/user_agent/blob/master/all_test.go self.user_agent_dist = { 0.0: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)", 0.1: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)", 0.2: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)", 0.3: "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)", 0.4: "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko", 0.5: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0", 0.6: "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)", 0.7: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_3 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B511 Safari/9537.53", 0.8: "Mozilla/5.0 (Linux; Android 4.2.1; Galaxy Nexus Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19", 0.9: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36", 1: " ", } self.ip_slice_list = [10, 29, 30, 46, 55, 63, 72, 87, 98, 132, 156, 124, 167, 143, 187, 168, 190, 201, 202, 214, 215, 222] self.url_path_list = ["login.php", "view.php", "list.php", "upload.php", "admin/login.php", "edit.php", "index.html"] self.http_refer = ["http://www.baidu.com/s?wd={query}", "http://www.google.cn/search?q={query}", "http://www.sogou.com/web?query={query}", "http://one.cn.yahoo.com/s?p={query}", "http://cn.bing.com/search?q={query}"] self.search_keyword = ["spark", "hadoop", "hive", "spark mlib", "spark sql"] def sample_ip(self): slice = random.sample(self.ip_slice_list, 4) # 从ip_slice_list中随机获取4个元素,作为一个片断返回 return ".".join([str(item) for item in slice]) # todo def sample_url(self): return random.sample(self.url_path_list, 1)[0] def sample_user_agent(self): dist_uppon = random.uniform(0, 1) return self.user_agent_dist[float('%0.1f' % dist_uppon)] # 主要搜索引擎referrer参数 def sample_refer(self): if random.uniform(0, 1) > 0.2: # 只有20% 流量有refer return "-" refer_str = random.sample(self.http_refer, 1) query_str = random.sample(self.search_keyword, 1) return refer_str[0].format(query=query_str[0]) def sample_one_log(self, count=3): time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) while count > 1: query_log = "{ip} - - [{local_time}] 'GET /{url} HTTP/1.1' 200 0 '{refer}' '{user_agent}' '-' ".format( ip=self.sample_ip(), local_time=time_str, url=self.sample_url(), refer=self.sample_refer(), user_agent=self.sample_user_agent()) print(query_log) count = count - 1 if __name__ == "__main__": web_log_gene = WebLogGeneration() web_log_gene.sample_one_log(random.uniform(10, 100))
生成样例
72.46.143.190 - - [2019-03-14 00:36:13] "GET /index.html HTTP/1.1" 200 0 "-" "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)" "-"
124.10.72.87 - - [2019-03-14 00:36:13] "GET /upload.php HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0" "-"
98.202.29.190 - - [2019-03-14 00:36:13] "GET /admin/login.php HTTP/1.1" 200 0 "-" "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)" "-"
190.132.63.215 - - [2019-03-14 00:36:13] "GET /login.php HTTP/1.1" 200 0 "-" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)" "-"
156.10.222.190 - - [2019-03-14 00:36:13] "GET /login.php HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko" "-"
98.46.168.187 - - [2019-03-14 00:36:13] "GET /list.php HTTP/1.1" 200 0 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)" "-"
脚本来调用上面的脚本以随机生成日志,上传至 HDFS ,然后移动到目标目录:
#!/bin/bash # HDFS命令 HDFS="/usr/local/myhadoop/hadoop-2.7.3/bin/hadoop fs" # Streaming程序监听的目录,注意跟后面Streaming程序的配置要保持一致 streaming_dir=”/spark/streaming” # 清空旧数据 $HDFS -rm "${streaming_dir}"'/tmp/*' > /dev/null 2>&1 $HDFS -rm "${streaming_dir}"'/*' > /dev/null 2>&1 # 一直运行 while [ 1 ]; do ./sample_web_log.py > test.log # 给日志文件加上时间戳,避免重名 tmplog="access.`date +'%s'`.log" # 先放在临时目录,再move至Streaming程序监控的目录下,确保原子性 # 临时目录用的是监控目录的子目录,因为子目录不会被监控 $HDFS -put test.log ${streaming_dir}/tmp/$tmplog $HDFS -mv ${streaming_dir}/tmp/$tmplog ${streaming_dir}/ echo "`date +"%F %T"` put $tmplog to HDFS succeed" sleep 1 done
日志文件生成脚本
touch genLog.sh vim genLog.sh
同时需要修改该脚本文件的执行权限。
chmod +x genLog.sh
稍有不同的是,生成的日志文件只是被保存在本地目录中,而不是 HDFS
#!/bin/bash while [ 1 ]; do ./sample_web_log.py > test.log tmplog="access.`date +'%s'`.log" cp test.log streaming/tmp/$tmplog mv streaming/tmp/$tmplog streaming/ echo "`date +"%F %T"` generating $tmplog succeed" sleep 1 done
Spark Streaming 程序代码如下所示,可以在 bin/spark-shell 交互式环境下运行,如果要以 Spark 程序的方式运行,按注释中的说明调整一下 StreamingContext 的生成方式即可。启动 bin/spark-shell 时,为了避免因 DEBUG 日志信息太多而影响观察输出,可以将 DEBUG 日志重定向至文件,屏幕上只显示主要输出,方法是 ./bin/spark-shell 2>spark-shell-debug.log:
// 导入类 import org.apache.spark.SparkConf import org.apache.spark.streaming.{Seconds, StreamingContext} // 设计计算的周期,单位秒 val batch = 10 /* * 这是bin/spark-shell交互式模式下创建StreamingContext的方法 * 非交互式请使用下面的方法来创建 */ val ssc = new StreamingContext(sc, Seconds(batch)) /* // 非交互式下创建StreamingContext的方法 val conf = new SparkConf().setAppName("NginxAnay") val ssc = new StreamingContext(conf, Seconds(batch)) */ /* * 创建输入DStream,是文本文件目录类型 * 本地模式下也可以使用本地文件系统的目录,比如 file:///home/spark/streaming */ val lines = ssc.textFileStream("hdfs:///spark/streaming") /* * 下面是统计各项指标,调试时可以只进行部分统计,方便观察结果 */ // 1. 总PV lines.count().print() // 2. 各IP的PV,按PV倒序 // 空格分隔的第一个字段就是IP lines.map(line => {(line.split(" ")(0), 1)}).reduceByKey(_ + _).transform(rdd => { rdd.map(ip_pv => (ip_pv._2, ip_pv._1)). sortByKey(false). map(ip_pv => (ip_pv._2, ip_pv._1)) }).print() // 3. 搜索引擎PV val refer = lines.map(_.split("\"")(3)) // 先输出搜索引擎和查询关键词,避免统计搜索关键词时重复计算 // 输出(host, query_keys) val searchEnginInfo = refer.map(r => { val f = r.split('/') val searchEngines = Map( "www.google.cn" -> "q", "www.yahoo.com" -> "p", "cn.bing.com" -> "q", "www.baidu.com" -> "wd", "www.sogou.com" -> "query" ) if (f.length > 2) { val host = f(2) if (searchEngines.contains(host)) { val query = r.split('?')(1) if (query.length > 0) { val arr_search_q = query.split('&').filter(_.indexOf(searchEngines(host)+"=") == 0) if (arr_search_q.length > 0) (host, arr_search_q(0).split('=')(1)) else (host, "") } else { (host, "") } } else ("", "") } else ("", "") }) // 输出搜索引擎PV searchEnginInfo.filter(_._1.length > 0).map(p => {(p._1, 1)}).reduceByKey(_ + _).print() // 4. 关键词PV searchEnginInfo.filter(_._2.length > 0).map(p => {(p._2, 1)}).reduceByKey(_ + _).print() // 5. 终端类型PV lines.map(_.split("\"")(5)).map(agent => { val types = Seq("iPhone", "Android") var r = "Default" for (t <- types) { if (agent.indexOf(t) != -1) r = t } (r, 1) }).reduceByKey(_ + _).print() // 6. 各页面PV lines.map(line => {(line.split("\"")(1).split(" ")(1), 1)}).reduceByKey(_ + _).print() // 启动计算,等待执行结束(出错或Ctrl-C退出) ssc.start() ssc.awaitTermination()
Python版
from pyspark import SparkContext from pyspark.streaming import StreamingContext # 设计计算的周期,单位秒 batch = 10 # Create a local StreamingContext with two working thread and batch interval of 1 second sc = SparkContext("local[2]", "NetworkWordCount") ssc = StreamingContext(sc, batch) # 创建输入DStream,是文本文件目录类型 lines = ssc.textFileStream("file:///home/ztf/Desktop/workSpace/streaming") # 1. 总PV lines.count().pprint() # 2. 各IP的PV,按PV倒序 # 空格分隔的第一个字段就是IP pairs = lines.map(lambda line: (line.split(" ")[0], 1)) ipCounts = pairs.reduceByKey(lambda x, y: x + y) ipCounts.transform( lambda rdd: rdd.map(lambda ip_pv: (ip_pv[1], ip_pv[0])).sortByKey(False).map(lambda ip_pv: (ip_pv[1], ip_pv[0])) ).pprint() # 3. 搜索引擎PV refer = lines.map(lambda line: line.split("\"")[3]) # 先输出搜索引擎和查询关键词,避免统计搜索关键词时重复计算 # 输出(host, query_keys) def engine_keyword(rdd): f = rdd.split('/') search_engines = { "www.google.cn": "q", "www.yahoo.com": "p", "cn.bing.com": "q", "www.baidu.com": "wd", "www.sogou.com": "query" } if len(f) <= 2: return "", "" host = f[2] if host not in search_engines: return "", "" query = rdd.split("?")[1] if len(query) <= 0: return host, "" arr_search_q = [x for x in query.split('&') if (x.index(search_engines[host] + "=") == 0)] if len(arr_search_q) <= 0: return host, "" return host, arr_search_q[0].split('=')[1] searchEnginInfo = refer.map(engine_keyword) # 输出搜索引擎PV searchEnginInfo.filter(lambda _: len(_[0]) > 0).map(lambda _: (_[0], 1)).reduceByKey(lambda x, y: x + y).pprint() # 4. 关键词PV searchEnginInfo.filter(lambda _: len(_[1]) > 0).map(lambda _: (_[1], 1)).reduceByKey(lambda x, y: x + y).pprint() # 5. 终端类型PV def agent_function(agent): types = ["iPhone", "Android"] r = "Default" for t in types: if t in agent: r = t return r, 1 lines.map(lambda _: _.split("\"")[5]).map(agent_function).reduceByKey(lambda x, y: x + y).pprint() # 6. 各页面PV lines.map(lambda line: (line.split("\"")[1].split(" ")[1], 1)).reduceByKey(lambda x, y: x + y).pprint() ssc.start() # Start the computation ssc.awaitTermination() # Wait for the computation to terminate
打开两个终端,一个调用上面的 bash 脚本模拟提交日志,一个在交互式环境下运行上面的 Streaming 程序。你可以看到各项指标的输出,比如某个批次下的输出为(依次对应上面的 6 个计算项):
总PV
-------------------------------------------
Time: 1448533850000 ms
-------------------------------------------
44374
各IP的PV,按PV倒序
-------------------------------------------
Time: 1448533850000 ms
-------------------------------------------
(72.63.87.30,30)
(63.72.46.55,30)
(98.30.63.10,29)
(72.55.63.46,29)
(63.29.10.30,29)
(29.30.63.46,29)
(55.10.98.87,27)
(46.29.98.30,27)
(72.46.63.30,27)
(87.29.55.10,26)
搜索引擎PV
-------------------------------------------
Time: 1448533850000 ms
-------------------------------------------
(cn.bing.com,1745)
(www.baidu.com,1773)
(www.google.cn,1793)
(www.sogou.com,1845)
关键词PV
-------------------------------------------
Time: 1448533850000 ms
-------------------------------------------
(spark,1426)
(hadoop,1455)
(spark sql,1429)
(spark mlib,1426)
(hive,1420)
终端类型PV
-------------------------------------------
Time: 1448533850000 ms
-------------------------------------------
(Android,4281)
(Default,35745)
(iPhone,4348)
各页面PV
-------------------------------------------
Time: 1448533850000 ms
-------------------------------------------
(/edit.php,6435)
(/admin/login.php,6271)
(/login.php,6320)
(/upload.php,6278)
(/list.php,6411)
(/index.html,6309)
(/view.php,6350)