1.修改README.md

2.添加avro2gtpc拦截器
This commit is contained in:
wangchengcheng
2022-09-27 11:26:19 +08:00
parent 977e827cce
commit 4194908fbc
5 changed files with 451 additions and 92 deletions

View File

@@ -1,92 +1 @@
# flume-http-avro-gtpc
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.mesalab.cn/bigdata/tsg/flume/interceptor/flume-http-avro-gtpc.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.mesalab.cn/bigdata/tsg/flume/interceptor/flume-http-avro-gtpc/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
针对福建gtpc项目基于flume实现的avro2gtpc拦截器。

168
pom.xml Normal file
View File

@@ -0,0 +1,168 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zdjizhi</groupId>
<artifactId>flume-http-avro-gtpc</artifactId>
<version>1.0</version>
<name>flume-http-avro-gtpc</name>
<url>http://www.example.com</url>
<repositories>
<repository>
<id>nexus</id>
<name>Team Nexus Repository</name>
<url>http://192.168.40.125:8099/content/groups/public</url>
</repository>
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<!--<enabled>true</enabled>-->
</releases>
<snapshots>
<!--<enabled>true</enabled>-->
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<flume.version>1.9.0</flume.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.zdjizhi.Avro2Gtpc</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.github.zlika</groupId>
<artifactId>reproducible-build-maven-plugin</artifactId>
<version>0.2</version>
<executions>
<execution>
<goals>
<goal>strip-jar</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>properties</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src\main\java</directory>
<includes>
<include>log4j.properties</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<dependency>
<groupId>org.apache.flume</groupId>
<artifactId>flume-ng-core</artifactId>
<version>${flume.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>com.zdjizhi</groupId>
<artifactId>galaxy</artifactId>
<version>1.0.8</version>
<exclusions>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>log4j-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.msgpack/msgpack -->
<dependency>
<groupId>org.msgpack</groupId>
<artifactId>msgpack</artifactId>
<version>0.6.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.avro/avro -->
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.11.0</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.17</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,240 @@
package com.zdjizhi;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.google.common.base.Preconditions;
import com.zdjizhi.utils.JsonMapper;
import com.zdjizhi.utils.StringUtil;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.io.JsonEncoder;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* @author wangchengcheng
*/
public class Avro2Gtpc implements Interceptor {
private static final Log logger = LogFactory.get();
private static Schema schemaK;
private static Schema schemaF;
private String kSchemaDir;
private String fSchemaDir;
private String schemaType;
private int commonVsysId;
private String gtpVersion;
@Override
public void initialize() {
try {
schemaK = new Schema.Parser().parse(new File(kSchemaDir));
schemaF = new Schema.Parser().parse(new File(fSchemaDir));
} catch (IOException e) {
logger.error("加载Schema文件异常!");
e.printStackTrace();
}
}
public Avro2Gtpc(String kSchemaDir, String fSchemaDir, String schemaType, int commonVsysId, String gtpVersion) {
this.kSchemaDir = kSchemaDir;
this.fSchemaDir = fSchemaDir;
this.schemaType = schemaType;
this.commonVsysId = commonVsysId;
this.gtpVersion = gtpVersion;
}
@Override
public Event intercept(Event event) {
byte[] arr = event.getBody();
String message = null;
try {
if (arr.length <= 0 ){
return null;
}
message = parsingMessage(schemaType, arr);
if (message.length() > 0) {
Map<String, Object> jsonMap = (Map<String, Object>) JsonMapper.fromJsonString(message, Map.class);
int c_cdrtype = (int) jsonMap.get("c_cdrtype");
if (c_cdrtype >= 32 && c_cdrtype <= 34) {
String userIp = (String) jsonMap.get("c_userip");
HashMap<String, Object> gtpc = new HashMap<>();
gtpc.put("common_recv_time", jsonMap.get("c_timestamp"));
gtpc.put("common_vsys_id",commonVsysId);
gtpc.put("gtp_version",gtpVersion);
gtpc.put("gtp_apn", jsonMap.get("c_apn"));
gtpc.put("gtp_imei", jsonMap.get("c_imei"));
gtpc.put("gtp_imsi", jsonMap.get("c_imsi"));
gtpc.put("gtp_phone_number", jsonMap.get("c_usernum"));
gtpc.put("gtp_uplink_teid", jsonMap.get("c_uplink_teid_c"));
gtpc.put("gtp_downlink_teid", jsonMap.get("c_downlink_teid_c"));
switch (c_cdrtype){
case 32:
gtpc.put("gtp_msg_type", "create");
break;
case 33:
gtpc.put("gtp_msg_type", "modify");
break;
case 34:
gtpc.put("gtp_msg_type", "delete");
break;
default:
break;
}
if (StringUtil.isNotBlank(userIp) && userIp.length() > 4) {
String trim = userIp.trim();
if (trim.contains("|")) {
String[] ipArr = trim.split("\\|");
gtpc.put("gtp_end_user_ipv4",ipArr[0].trim());
gtpc.put("gtp_end_user_ipv6",ipArr[1].trim());
} else if (trim.contains(".")) {
gtpc.put("gtp_end_user_ipv4", trim);
} else if (trim.contains(":")) {
gtpc.put("gtp_end_user_ipv6", trim);
}
}
String gtpcJson = JsonMapper.toJsonString(gtpc);
if (StringUtil.isNotBlank(gtpcJson)) {
event.setBody(gtpcJson.getBytes());
return event;
}
}else {
return null;
}
} else {
return null;
}
} catch (Exception e) {
logger.error("FlumeAvroApp intercept(Event event) method is error===>{" + e + "}<===,The data before serialization is"+arr.toString()+"The serialized data is"+message);
e.printStackTrace();
}
return null;
}
@Override
public List<Event> intercept(List<Event> list) {
List resultList = new ArrayList();
for (Event event : list) {
Event r = intercept(event);
if (r != null) {
resultList.add(r);
}
}
return resultList;
}
@Override
public void close() {
logger.warn("FlumeAvroApp is closed.");
}
/**
* 解析日志,并补全
*
* @param message Security原始日志
* @return 补全后的日志
* <p>
*/
private String parsingMessage(String header, byte[] message) {
String result = null;
switch (header) {
case "t_cdr_f":
result = deserlializationAvro(message, schemaF);
break;
case "t_cdr_k":
result = deserlializationAvro(message, schemaK);
break;
default:
}
return result;
}
private static String deserlializationAvro(byte[] avro, Schema schema) {
String result = null;
try {
GenericRecord readUser = null;
GenericDatumReader<GenericRecord> objectGenericDatumReader = new GenericDatumReader<>(schema);
BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(avro, null);
GenericRecord read = objectGenericDatumReader.read(readUser, binaryDecoder);
GenericDatumWriter<GenericRecord> objectGenericDatumWriter = new GenericDatumWriter<>(schema);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, outputStream);
objectGenericDatumWriter.write(read, jsonEncoder);
jsonEncoder.flush();
result = String.valueOf(read);
} catch (RuntimeException | IOException e) {
e.printStackTrace();
}
return result;
}
public static class FlumeAvroAppBuilder implements Builder {
private String kSchemaDir;
private String fSchemaDir;
private String schemaType;
private int commonVsysId;
private String gtpVersion;
@Override
public Interceptor build() {
return new Avro2Gtpc(this.kSchemaDir,
this.fSchemaDir, this.schemaType,this.commonVsysId,this.gtpVersion);
}
@Override
public void configure(Context context) {
try {
this.kSchemaDir = context.getString("kSchemaDir", "");
Preconditions.checkNotNull("".equals(kSchemaDir), "kSchemaDir must be set!!");
logger.info("FlumeAvroApp Read kSchemaDir from configuration : " + kSchemaDir);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("FlumeDynamicApp kSchemaDir invalid", e);
} catch (Exception e) {
logger.error("FlumeAvroApp Get kSchemaDir is error : " + e);
}
try {
this.fSchemaDir = context.getString("fSchemaDir", "");
Preconditions.checkNotNull("".equals(fSchemaDir), "fSchemaDir must be set!!");
logger.info("FlumeAvroApp Read fSchemaDir from configuration : " + fSchemaDir);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("FlumeDynamicApp fSchemaDir invalid", e);
} catch (Exception e) {
logger.error("FlumeAvroApp Get fSchemaDir is error : " + e);
}
try {
this.schemaType = context.getString("schemaType", "");
Preconditions.checkNotNull("".equals(schemaType), "schemaType must be set!!");
logger.info("FlumeAvroApp Read schemaType from configuration : " + schemaType);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("FlumeDynamicApp schemaType invalid", e);
} catch (Exception e) {
logger.error("FlumeAvroApp Get schemaType is error : " + e);
}
this.commonVsysId = context.getInteger("commonVsysId",1);
logger.info("FlumeAvroApp Read commonVsysId from configuration : " + commonVsysId);
this.gtpVersion = context.getString("gtpVersion","null");
logger.info("FlumeAvroApp Read gtpVersion from configuration : " + gtpVersion);
}
}
}

25
src/main/log4j.properties Normal file
View File

@@ -0,0 +1,25 @@
#Log4j
log4j.rootLogger=console
# 控制台日志设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=info
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}] [%-5p] [Thread\:%t] %l %x - <%m>%n
# 文件日志设置
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.Threshold=info
log4j.appender.file.encoding=UTF-8
log4j.appender.file.Append=true
#路径请用相对路径,做好相关测试输出到应用目下
log4j.appender.file.file=${nis.root}/log/galaxy-name.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{HH:mm:ss} %X{ip} [%t] %5p %c{1} %m%n
log4j.appender.file.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}] [%-5p] %X{ip} [Thread\:%t] %l %x - %m%n
##MyBatis 配置com.nis.web.dao是mybatis接口所在包
#log4j.logger.com.nis.web.dao=debug
##bonecp数据源配置
#log4j.category.com.jolbox=debug,console

View File

@@ -0,0 +1,17 @@
package com.zdjizhi.avro;
public class SplitIp {
public static void main(String[] args) {
String s = "2409:8134:2801:5c81::1";
String trim = s.trim();
if (trim.contains("|")) {
String[] arr = trim.split("\\|");
System.out.println(arr[0].trim());
System.out.println(arr[1].trim());
} else if (trim.contains(".")) {
System.out.println(trim);
} else if (trim.contains(":")) {
System.out.println(trim);
}
}
}