blob: 3c3bb6f56cc824627ff316d50c8e324b135d83a1 [file] [log] [blame]
susmit shannigrahi21009e32015-03-26 17:00:32 -06001#!/usr/bin/env python3
2# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
3#
4# Copyright (c) 2015, Colorado State University.
5#
6# This file is part of ndn-atmos.
7#
8# ndn-atmos is free software: you can redistribute it and/or modify it under the
9# terms of the GNU Lesser General Public License as published by the Free Software
10# Foundation, either version 3 of the License, or (at your option) any later version.
11#
12# ndn-atmos is distributed in the hope that it will be useful, but WITHOUT ANY
13# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
14# PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
15#
16# You should have received copies of the GNU General Public License and GNU Lesser
17# General Public License along with ndn-atmos, e.g., in COPYING.md file. If not, see
18# <http://www.gnu.org/licenses/>.
19#
20# See AUTHORS.md for complete list of ndn-atmos authors and contributors.
21
22'''This module is for inserting NDN names in underlying database'''
23
24import mysql.connector as sql
25from mysql.connector import errorcode
26import sys
27import getpass
28import hashlib
29from ndn_cmmap_translators import atmos_translator
30
31def createTables(cursor):
32 TABLES = {}
33 TABLES['cmip5'] = (
34 "CREATE TABLE `cmip5` ("
35 " `id` int(100) AUTO_INCREMENT NOT NULL,"
36 " `sha256` varchar(64) UNIQUE NOT NULL,"
37 " `name` varchar(1000) NOT NULL,"
38 " `activity` varchar(100) NOT NULL,"
39 " `product` varchar(100) NOT NULL,"
40 " `organization` varchar(100) NOT NULL,"
41 " `model` varchar(100) NOT NULL,"
42 " `experiment` varchar(100) NOT NULL,"
43 " `frequency` varchar(100) NOT NULL,"
44 " `modeling_realm` varchar(100) NOT NULL,"
45 " `variable_name` varchar(100) NOT NULL,"
46 " `ensemble` varchar(100) NOT NULL,"
47 " `time` varchar(100) NOT NULL,"
48 " PRIMARY KEY (`id`)"
49 ") ENGINE=InnoDB")
50
51 #check if tables exist, if not create them
52 #create tables per schema in the wiki
53 for tableName, query in TABLES.items():
54 try:
55 print("Creating table {}: ".format(tableName))
56 cursor.execute(query)
57 print("Created table {}: ".format(tableName))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060058 return True
susmit shannigrahi21009e32015-03-26 17:00:32 -060059 except sql.Error as err:
60 if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
61 print("Table already exists: %s " %(tableName))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060062 return True
susmit shannigrahi21009e32015-03-26 17:00:32 -060063 else:
64 print("Failed to create table: %s" %(err.msg))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060065 return False
susmit shannigrahi21009e32015-03-26 17:00:32 -060066
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060067def insertName(cursor, name):
susmit shannigrahi21009e32015-03-26 17:00:32 -060068 if __debug__:
69 print("Name to insert %s " %(name))
70
71 #hashvalue is needed since name is too long for primary key (must be <767 bytes)
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060072 hashValue = hashlib.sha256(str(name).encode('utf-8')).hexdigest()
susmit shannigrahi21009e32015-03-26 17:00:32 -060073 if __debug__:
74 print("Hash of name %s " %(hashValue))
75
76 ##NOTE:must use %s to prevent sql injection in all sql queries
77 splitName = list(filter(None, name.split("/")))
78 splitName.insert(0, hashValue)
79 splitName.insert(0, name)
80 splitName = tuple(splitName)
81 if __debug__:
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060082 print("Name to insert in database %s" %(splitName,))
susmit shannigrahi21009e32015-03-26 17:00:32 -060083
84 addRecord = ("INSERT INTO cmip5 "
85 "(name, sha256, activity, product, organization, model, experiment, frequency,\
86 modeling_realm, variable_name, ensemble, time) "
87 "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
88
89 try:
90 cursor.execute(addRecord, splitName)
91 print("Inserted record %s" %(name))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060092 return True
susmit shannigrahi21009e32015-03-26 17:00:32 -060093 except sql.Error as err:
susmit shannigrahi851e88b2015-06-08 15:33:29 -060094 print("Error inserting name %s, \nError:%s" %(name, err.msg))
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -060095 return False
susmit shannigrahi21009e32015-03-26 17:00:32 -060096
97if __name__ == '__main__':
98 datafilePath = input("File/directory to translate: ")
99 configFilepath = input("Schema file path for the above file/directory: ")
100
101 #do the translation, the library should provide error messages, if any
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600102 ndnNames = atmos_translator.argsForTranslation(datafilePath, configFilepath)
susmit shannigrahi851e88b2015-06-08 15:33:29 -0600103 if ndnNames is False:
104 print("Error parsing config file, exiting")
105 sys.exit(-1)
106
susmit shannigrahi21009e32015-03-26 17:00:32 -0600107 if len(ndnNames) == 0:
108 print("No name returned from the translator, exiting.")
109 sys.exit(-1)
110 if __debug__:
111 print("Returned NDN names: %s" %(ndnNames))
112
113 #open connection to db
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600114 dbHost = input("Database Host?")
susmit shannigrahi21009e32015-03-26 17:00:32 -0600115 dbName = input("Database to store NDN names?")
116 dbUsername = input("Database username?")
117 dbPasswd = getpass.getpass("Database password?")
118
119 try:
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600120 con = sql.connect(user=dbUsername, database=dbName, password=dbPasswd, host=dbHost)
susmit shannigrahi21009e32015-03-26 17:00:32 -0600121 cursor = con.cursor()
122 if __debug__:
123 print("successfully connected to database")
124
125 #if tables do not exist, create tables
susmit shannigrahi21009e32015-03-26 17:00:32 -0600126 #if table already exists, or creation successful, continue
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600127 if createTables(cursor):
susmit shannigrahi21009e32015-03-26 17:00:32 -0600128 for ndnName in ndnNames:
129 #get list of files and insert into database
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600130 resInsertnames = insertName(cursor, ndnName)
susmit shannigrahi21009e32015-03-26 17:00:32 -0600131 if __debug__:
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600132 print("Return Code is %s for inserting name: %s" %(resInsertnames, ndnName))
susmit shannigrahi21009e32015-03-26 17:00:32 -0600133 con.commit()
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600134 else:
135 print("Error creating tables, exiting.")
136 sys.exit(-1)
137
susmit shannigrahi21009e32015-03-26 17:00:32 -0600138 except sql.Error as err:
139 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
140 print("Incorrect username or password")
141 elif err.errno == errorcode.ER_BAD_DB_ERROR:
142 print("Database does not exist")
143 else:
144 print("Error connecting to Database: %s" %(err.msg))
145 finally:
146 con.close()
susmit shannigrahiec5a9fd2015-05-15 12:59:37 -0600147