Skip to content
This repository was archived by the owner on Dec 17, 2021. It is now read-only.

Commit 4f656c7

Browse files
authored
Merge pull request #31 from splunk/develop
Develop
2 parents 1b21c8c + dd72a91 commit 4f656c7

File tree

13 files changed

+384
-146
lines changed

13 files changed

+384
-146
lines changed

.circleci/config.yml

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@ jobs:
4040
path: build-container
4141
destination: build-container
4242

43+
format-code:
44+
docker:
45+
- image: circleci/python:3.8.6
46+
steps:
47+
- checkout
48+
- run:
49+
name: "Check Formatting"
50+
command: |
51+
pip install black
52+
black --check ./ --exclude mibs
53+
4354
release:
4455
docker:
4556
- image: circleci/node:12
@@ -68,11 +79,11 @@ jobs:
6879
- run:
6980
name: Release Docker Hub
7081
command: |
71-
export VERSION=${CIRCLE_TAG:=CIRCLE_SHA1}
82+
export VERSION=${CIRCLE_TAG:=CIRCLE_SHA1}
7283
VERSION_DOCKER_MMP=$(echo $VERSION | sed -n 's/v\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/p')
7384
VERSION_DOCKER_MM=$(echo $VERSION | sed -n 's/v\([0-9]*\.[0-9]*\).*/\1/p')
7485
VERSION_DOCKER_M=$(echo $VERSION | sed -n 's/v\([0-9]*\).*/\1/p')
75-
86+
7687
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 -
7788
source $HOME/.poetry/env
7889
poetry build
@@ -112,7 +123,7 @@ jobs:
112123
command: |
113124
go get -v -u github.com/tcnksm/ghr
114125
PATH=$PATH:/usr/local/go/bin
115-
export VERSION=${CIRCLE_TAG:=CIRCLE_SHA1}
126+
export VERSION=${CIRCLE_TAG:=CIRCLE_SHA1}
116127
[[ $VERSION =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && ISPRE="-prerelease"
117128
$HOME/go/bin/ghr -t ${GH_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} ${ISPRE} ${VERSION} /tmp/workspace/
118129
- store_artifacts:
@@ -122,6 +133,8 @@ workflows:
122133
version: 2
123134
build_test:
124135
jobs:
136+
- format-code
137+
125138
- build:
126139
context:
127140
- gdi-github

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,6 @@ dmypy.json
156156
.pyre/
157157
mibs/.DS_Store
158158
.DS_Store
159+
160+
# Intellij
161+
.idea

lookups/custom_mib_string_table.csv

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
OID,Label
2-
1.3.6.1.6.3.1.1.4.1.0,paris
3-
1.3.6.1.2.1.1.3.0,london
42
1.3.6.1.4.1.6141.2.60.37.0.2,splunk-test
53
1.3.6.1.4.1.8072.2.3.0.1,mycustomNET-SNMP-EXAMPLES-MIB::netSnmpExampleHeartbeatNotification
64
1.3.6.1.4.1.8072.2.3.2.1,mycustomNET-SNMP-EXAMPLES-MIB::netSnmpExampleHeartbeatRate

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Flask = "^1.1.2"
1515
Flask-AutoIndex = "^0.6.6"
1616

1717
[tool.poetry.dev-dependencies]
18+
mongomock = "^3.22.1"
1819

1920
[tool.poetry.scripts]
2021
sc4snmp-mib-server = "splunk_connect_for_snmp_mib_server.snmp_mib_server:main"
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
import logging.config
22

3-
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(name)s | %(levelname)s | %(message)s')
3+
logging.basicConfig(
4+
level=logging.INFO, format="%(asctime)s | %(name)s | %(levelname)s | %(message)s"
5+
)
Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,53 @@
1-
from flask import Flask, request, abort, jsonify, send_from_directory
1+
from flask import Flask, request
22
from flask_autoindex import AutoIndex
3-
import os
4-
import yaml
5-
from splunk_connect_for_snmp_mib_server.mongo import MibsRepository, OidsRepository
63
from splunk_connect_for_snmp_mib_server.translator import Translator
74
import logging
85

96
logger = logging.getLogger(__name__)
107

8+
119
class MibServer:
1210
def __init__(self, args, server_config):
1311
self._args = args
1412
self._server_config = server_config
1513
self._translator = Translator(server_config)
1614
self._flask_app = self.build_flask_app()
17-
18-
def build_flask_app(self):
15+
16+
def build_flask_app(self):
1917
app = Flask(__name__)
20-
# ppath = os.environ['MIBS_SERVER_URL']
21-
ppath = self._server_config["snmp"]["mibs"]["mibs_path"]
22-
files_index = AutoIndex(app, ppath, add_url_rules=False)
18+
mibs_path = self._server_config["snmp"]["mibs"]["mibs_path"]
19+
files_index = AutoIndex(app, mibs_path, add_url_rules=False)
2320

24-
@app.route('/')
21+
@app.route("/")
2522
def hello():
2623
return "Hello, This is SNMP MIB server!"
2724

2825
# Custom indexing
29-
@app.route('/files/')
30-
@app.route('/files/<path:path>')
31-
def autoindex(path='.'):
26+
@app.route("/files/")
27+
@app.route("/files/<path:path>")
28+
def autoindex(path="."):
3229
logger.debug(f"path: {path}")
3330
return files_index.render_autoindex(path)
3431

3532
# Translate oid
36-
@app.route('/translation', methods=['POST'])
33+
@app.route("/translation", methods=["POST"])
3734
def translator():
3835
logger.debug(request.json)
39-
var_binds = request.json.get('var_binds')
36+
var_binds = request.json.get("var_binds")
4037
metric = request.args.get("metric")
4138
logger.debug(f"type of var_binds: {type(var_binds)}")
4239
logger.debug(f"var_binds: {var_binds}")
4340
logger.debug(f"type of metric: {str(metric)} -- metric: {metric}")
4441
if metric == "True":
45-
# TODO
46-
# If metric is true, var_binds just has one
42+
# if metric is true, var_binds has just one element
4743
var_bind = var_binds[0]
48-
result = self._translator.format_metric_data(var_bind)
44+
result = self._translator.format_metric_data(var_bind)
4945
else:
5046
result = self._translator.format_trap_event(var_binds)
5147
return result
52-
48+
5349
return app
54-
55-
def run_mib_server(self):
56-
# TODO poetry run fails when debug=True
57-
self._flask_app.run(host="0.0.0.0",port=self._args.port)
5850

51+
def run_mib_server(self):
52+
# poetry run fails when debug=True
53+
self._flask_app.run(host="0.0.0.0", port=self._args.port)

splunk_connect_for_snmp_mib_server/mongo.py

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from pymongo import MongoClient
1+
import pymongo
22
import os
33
import logging
44

@@ -7,10 +7,7 @@
77

88
class MibsRepository:
99
def __init__(self, mongo_config):
10-
"""
11-
Create a collection in mongodb to store mib files
12-
"""
13-
self._client = MongoClient(
10+
self._client = pymongo.MongoClient(
1411
os.environ["MONGO_SERVICE_SERVICE_HOST"],
1512
int(os.environ["MONGO_SERVICE_SERVICE_PORT"]),
1613
)
@@ -23,16 +20,9 @@ def __init__(self, mongo_config):
2320
self._mibs = self._client[mongo_config["database"]][mongo_config["collection"]]
2421

2522
def upload_files(self, mib_files_dir):
26-
"""
27-
Upload mib files from dir to mongo
28-
@param mib_files_dir: the path of the mib files directory
29-
"""
30-
# TODO check duplicate before insert, using filename as PK
3123
for filename in os.listdir(mib_files_dir):
3224
file_path = mib_files_dir + "/" + filename
33-
# print(file_path)
3425
with open(file_path, "r") as mib_file:
35-
# TODO add try catch, insert only if PK doesn't exit
3626
try:
3727
self._mibs.insert_one(
3828
dict(content=mib_file.read(), filename=filename, _id=filename)
@@ -43,34 +33,22 @@ def upload_files(self, mib_files_dir):
4333
)
4434

4535
def search_oid(self, oid):
46-
"""
47-
Search mib file based on oid
48-
@param oid: oid, format: "1, 3, 6, 1, 4, 1, 2356, 11, 0, 0, 10000"
49-
@return mib filename
50-
"""
5136
data = self._mibs.find_one({"content": {"$regex": oid}})
5237
if data:
5338
return data["filename"]
5439
else:
5540
return None
5641

5742
def delete_mib(self, filename):
58-
"""
59-
Delete mib files based on filename
60-
@param filename: mib filename
61-
"""
6243
self._mibs.delete_many({"filename": {"$regex": filename}})
6344

6445
def clear(self):
65-
"""
66-
Clear the collection
67-
"""
6846
self._mibs.remove()
6947

7048

7149
class OidsRepository:
7250
def __init__(self, mongo_config):
73-
self._client = MongoClient(
51+
self._client = pymongo.MongoClient(
7452
os.environ["MONGO_SERVICE_SERVICE_HOST"],
7553
int(os.environ["MONGO_SERVICE_SERVICE_PORT"]),
7654
)
@@ -83,7 +61,7 @@ def __init__(self, mongo_config):
8361
self._oids = self._client[mongo_config["database"]][mongo_config["collection"]]
8462

8563
def contains_oid(self, oid):
86-
return self._oids.find({"oid": oid}).count()
64+
return self._oids.count_documents({"oid": oid})
8765

8866
def add_oid(self, oid):
8967
self._oids.insert_one({"oid": oid})
Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import argparse
2-
import os
3-
import yaml
4-
from splunk_connect_for_snmp_mib_server.mongo import MibsRepository, OidsRepository
2+
import yaml
3+
from splunk_connect_for_snmp_mib_server.mongo import MibsRepository
54
from splunk_connect_for_snmp_mib_server.mib_server import MibServer
65
import logging
76

@@ -13,12 +12,13 @@ def upload_mibs(server_config):
1312
mib_files_dir = server_config["snmp"]["mibs"]["dir"]
1413
mibs_collection = MibsRepository(mibs_mongo_config)
1514
# TODO do we need to clean up before loading
16-
# Clean up
15+
# Clean up
1716
mibs_collection.clear()
1817
# Upload all mib files in specific dir into mongo
1918
mibs_collection.upload_files(mib_files_dir)
2019
logger.debug("Uploaded all mib files into mongo!")
2120

21+
2222
def main():
2323
logger.info(f"Startup Config")
2424
parser = argparse.ArgumentParser()
@@ -35,31 +35,22 @@ def main():
3535
"--hec_threads", default=10, help="Max http worker thread count", type=int
3636
)
3737
parser.add_argument("-c", "--config", default="config.yaml", help="Config File")
38-
39-
4038
args = parser.parse_args()
41-
4239
log_level = args.loglevel.upper()
4340
config_file = args.config
4441

4542
logging.getLogger().setLevel(log_level)
4643
logger.info(f"Log Level is {log_level}")
4744
logger.info(f"Config file is {config_file}")
48-
4945
logger.info("Completed Argument parsing")
5046

5147
with open(config_file, "r") as yamlfile:
5248
server_config = yaml.load(yamlfile, Loader=yaml.FullLoader)
5349

54-
55-
56-
# Upload mib fiels into mongo
5750
upload_mibs(server_config)
58-
59-
# Init MibServer
6051
mib_server = MibServer(args, server_config)
6152
mib_server.run_mib_server()
6253

6354

6455
if __name__ == "__main__":
65-
main()
56+
main()

0 commit comments

Comments
 (0)