file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
query_external_sheets_permanent_table.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def
(dataset_id): # [START bigquery_query_external_sheets_perm] from google.cloud import bigquery import google.auth # Create credentials with Drive & BigQuery API scopes. # Both APIs must be enabled for your project before running this code. # # If you are using credentials from gcloud, you must authorize the # application first with the following command: # # gcloud auth application-default login \ # --scopes=https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/cloud-platform credentials, project = google.auth.default( scopes=[ "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/bigquery", ] ) # Construct a BigQuery client object. client = bigquery.Client(credentials=credentials, project=project) # TODO(developer): Set dataset_id to the ID of the dataset to fetch. # dataset_id = "your-project.your_dataset" # Configure the external data source. dataset = client.get_dataset(dataset_id) table_id = "us_states" schema = [ bigquery.SchemaField("name", "STRING"), bigquery.SchemaField("post_abbr", "STRING"), ] table = bigquery.Table(dataset.table(table_id), schema=schema) external_config = bigquery.ExternalConfig("GOOGLE_SHEETS") # Use a shareable link or grant viewing access to the email address you # used to authenticate with BigQuery (this example Sheet is public). sheet_url = ( "https://docs.google.com/spreadsheets" "/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing" ) external_config.source_uris = [sheet_url] external_config.options.skip_leading_rows = 1 # Optionally skip header row. external_config.options.range = ( "us-states!A20:B49" # Optionally set range of the sheet to query from. ) table.external_data_configuration = external_config # Create a permanent table linked to the Sheets file. table = client.create_table(table) # Make an API request. # Example query to find states starting with "W". sql = 'SELECT * FROM `{}.{}` WHERE name LIKE "W%"'.format(dataset_id, table_id) query_job = client.query(sql) # Make an API request. # Wait for the query to complete. w_states = list(query_job) print( "There are {} states with names starting with W in the selected range.".format( len(w_states) ) ) # [END bigquery_query_external_sheets_perm]
query_external_sheets_permanent_table
identifier_name
query_external_sheets_permanent_table.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def query_external_sheets_permanent_table(dataset_id): # [START bigquery_query_external_sheets_perm]
from google.cloud import bigquery import google.auth # Create credentials with Drive & BigQuery API scopes. # Both APIs must be enabled for your project before running this code. # # If you are using credentials from gcloud, you must authorize the # application first with the following command: # # gcloud auth application-default login \ # --scopes=https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/cloud-platform credentials, project = google.auth.default( scopes=[ "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/bigquery", ] ) # Construct a BigQuery client object. client = bigquery.Client(credentials=credentials, project=project) # TODO(developer): Set dataset_id to the ID of the dataset to fetch. # dataset_id = "your-project.your_dataset" # Configure the external data source. dataset = client.get_dataset(dataset_id) table_id = "us_states" schema = [ bigquery.SchemaField("name", "STRING"), bigquery.SchemaField("post_abbr", "STRING"), ] table = bigquery.Table(dataset.table(table_id), schema=schema) external_config = bigquery.ExternalConfig("GOOGLE_SHEETS") # Use a shareable link or grant viewing access to the email address you # used to authenticate with BigQuery (this example Sheet is public). sheet_url = ( "https://docs.google.com/spreadsheets" "/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing" ) external_config.source_uris = [sheet_url] external_config.options.skip_leading_rows = 1 # Optionally skip header row. external_config.options.range = ( "us-states!A20:B49" # Optionally set range of the sheet to query from. ) table.external_data_configuration = external_config # Create a permanent table linked to the Sheets file. table = client.create_table(table) # Make an API request. # Example query to find states starting with "W". sql = 'SELECT * FROM `{}.{}` WHERE name LIKE "W%"'.format(dataset_id, table_id) query_job = client.query(sql) # Make an API request. # Wait for the query to complete. w_states = list(query_job) print( "There are {} states with names starting with W in the selected range.".format( len(w_states) ) ) # [END bigquery_query_external_sheets_perm]
identifier_body
query_external_sheets_permanent_table.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def query_external_sheets_permanent_table(dataset_id): # [START bigquery_query_external_sheets_perm] from google.cloud import bigquery import google.auth # Create credentials with Drive & BigQuery API scopes. # Both APIs must be enabled for your project before running this code. # # If you are using credentials from gcloud, you must authorize the # application first with the following command: # # gcloud auth application-default login \ # --scopes=https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/cloud-platform credentials, project = google.auth.default( scopes=[ "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/bigquery", ] ) # Construct a BigQuery client object. client = bigquery.Client(credentials=credentials, project=project) # TODO(developer): Set dataset_id to the ID of the dataset to fetch. # dataset_id = "your-project.your_dataset" # Configure the external data source. dataset = client.get_dataset(dataset_id) table_id = "us_states" schema = [ bigquery.SchemaField("name", "STRING"), bigquery.SchemaField("post_abbr", "STRING"), ] table = bigquery.Table(dataset.table(table_id), schema=schema) external_config = bigquery.ExternalConfig("GOOGLE_SHEETS") # Use a shareable link or grant viewing access to the email address you # used to authenticate with BigQuery (this example Sheet is public). sheet_url = ( "https://docs.google.com/spreadsheets" "/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing" ) external_config.source_uris = [sheet_url] external_config.options.skip_leading_rows = 1 # Optionally skip header row. external_config.options.range = ( "us-states!A20:B49" # Optionally set range of the sheet to query from. ) table.external_data_configuration = external_config # Create a permanent table linked to the Sheets file. table = client.create_table(table) # Make an API request. # Example query to find states starting with "W". sql = 'SELECT * FROM `{}.{}` WHERE name LIKE "W%"'.format(dataset_id, table_id) query_job = client.query(sql) # Make an API request. # Wait for the query to complete. w_states = list(query_job) print( "There are {} states with names starting with W in the selected range.".format( len(w_states) ) ) # [END bigquery_query_external_sheets_perm]
random_line_split
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client 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 lai-client. If not, see <http://www.gnu.org/licenses/>. import pymongo from pymongo.errors import AutoReconnect from lai.db.base import DBBase from lai.database import UPDATE_PROCESS, COMMIT_PROCESS from lai.database import DatabaseException, NotFoundError from lai import Document class DBMongo(DBBase):
def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: raise DatabaseException("It's not possible connect to the database") def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id'] def search(self, regex): try: spec = {'$or': [{'data.content' : {'$regex': regex, '$options': 'im'}}, {'data.description': {'$regex': regex, '$options': 'im'}}]} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id)) def getall(self): try: spec = {'data': {'$exists': 1}} fields = {'_id': 0} sort = [('tid', 1)] cur = self.db.docs.find(spec, fields, sort=sort) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def save(self, doc): if doc.id: return self.update(doc) else: return self.insert(doc) def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS: pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced} else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): if doc.id is None: raise DatabaseException('Document does not have id') if doc.sid is None: try: rs = self.db.docs.remove({'id': doc.id}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return None doc.data = None return self.update(doc) def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e) def get_docs_to_commit(self): try: spec = {'synced': False} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return list(cur) def get_last_tid(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs = {'updated' : [], 'committed': [], 'to_commit': []} row = self.db.internal.find_one({'_id': 'last_sync'}) if row and 'update' in row: for id in row['update']: docs['updated'].append(self.get(id, deleted=True)) if row and 'commit' in row: for id in row['commit']: docs['committed'].append(self.get(id, deleted=True)) to_commit = self.get_docs_to_commit() for row in to_commit: doc = Document(**row) docs['to_commit'].append(doc) return docs def __str__(self): return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)
identifier_body
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client 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 lai-client. If not, see <http://www.gnu.org/licenses/>. import pymongo from pymongo.errors import AutoReconnect from lai.db.base import DBBase from lai.database import UPDATE_PROCESS, COMMIT_PROCESS from lai.database import DatabaseException, NotFoundError from lai import Document class DBMongo(DBBase): def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: raise DatabaseException("It's not possible connect to the database") def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id'] def search(self, regex): try: spec = {'$or': [{'data.content' : {'$regex': regex, '$options': 'im'}}, {'data.description': {'$regex': regex, '$options': 'im'}}]} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id)) def getall(self): try: spec = {'data': {'$exists': 1}} fields = {'_id': 0} sort = [('tid', 1)] cur = self.db.docs.find(spec, fields, sort=sort) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def save(self, doc): if doc.id: return self.update(doc) else: return self.insert(doc) def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS: pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced} else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): if doc.id is None: raise DatabaseException('Document does not have id') if doc.sid is None: try: rs = self.db.docs.remove({'id': doc.id}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return None doc.data = None return self.update(doc) def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e) def get_docs_to_commit(self): try: spec = {'synced': False} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return list(cur) def
(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs = {'updated' : [], 'committed': [], 'to_commit': []} row = self.db.internal.find_one({'_id': 'last_sync'}) if row and 'update' in row: for id in row['update']: docs['updated'].append(self.get(id, deleted=True)) if row and 'commit' in row: for id in row['commit']: docs['committed'].append(self.get(id, deleted=True)) to_commit = self.get_docs_to_commit() for row in to_commit: doc = Document(**row) docs['to_commit'].append(doc) return docs def __str__(self): return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)
get_last_tid
identifier_name
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client 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 lai-client. If not, see <http://www.gnu.org/licenses/>. import pymongo from pymongo.errors import AutoReconnect from lai.db.base import DBBase from lai.database import UPDATE_PROCESS, COMMIT_PROCESS from lai.database import DatabaseException, NotFoundError from lai import Document class DBMongo(DBBase): def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: raise DatabaseException("It's not possible connect to the database") def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id'] def search(self, regex): try: spec = {'$or': [{'data.content' : {'$regex': regex, '$options': 'im'}}, {'data.description': {'$regex': regex, '$options': 'im'}}]} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id)) def getall(self): try: spec = {'data': {'$exists': 1}} fields = {'_id': 0} sort = [('tid', 1)] cur = self.db.docs.find(spec, fields, sort=sort) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def save(self, doc): if doc.id: return self.update(doc) else: return self.insert(doc) def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS:
else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): if doc.id is None: raise DatabaseException('Document does not have id') if doc.sid is None: try: rs = self.db.docs.remove({'id': doc.id}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return None doc.data = None return self.update(doc) def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e) def get_docs_to_commit(self): try: spec = {'synced': False} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return list(cur) def get_last_tid(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs = {'updated' : [], 'committed': [], 'to_commit': []} row = self.db.internal.find_one({'_id': 'last_sync'}) if row and 'update' in row: for id in row['update']: docs['updated'].append(self.get(id, deleted=True)) if row and 'commit' in row: for id in row['commit']: docs['committed'].append(self.get(id, deleted=True)) to_commit = self.get_docs_to_commit() for row in to_commit: doc = Document(**row) docs['to_commit'].append(doc) return docs def __str__(self): return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)
pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced}
conditional_block
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client.
# # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client 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 lai-client. If not, see <http://www.gnu.org/licenses/>. import pymongo from pymongo.errors import AutoReconnect from lai.db.base import DBBase from lai.database import UPDATE_PROCESS, COMMIT_PROCESS from lai.database import DatabaseException, NotFoundError from lai import Document class DBMongo(DBBase): def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: raise DatabaseException("It's not possible connect to the database") def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id'] def search(self, regex): try: spec = {'$or': [{'data.content' : {'$regex': regex, '$options': 'im'}}, {'data.description': {'$regex': regex, '$options': 'im'}}]} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id)) def getall(self): try: spec = {'data': {'$exists': 1}} fields = {'_id': 0} sort = [('tid', 1)] cur = self.db.docs.find(spec, fields, sort=sort) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def save(self, doc): if doc.id: return self.update(doc) else: return self.insert(doc) def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS: pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced} else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): if doc.id is None: raise DatabaseException('Document does not have id') if doc.sid is None: try: rs = self.db.docs.remove({'id': doc.id}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return None doc.data = None return self.update(doc) def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e) def get_docs_to_commit(self): try: spec = {'synced': False} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return list(cur) def get_last_tid(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs = {'updated' : [], 'committed': [], 'to_commit': []} row = self.db.internal.find_one({'_id': 'last_sync'}) if row and 'update' in row: for id in row['update']: docs['updated'].append(self.get(id, deleted=True)) if row and 'commit' in row: for id in row['commit']: docs['committed'].append(self.get(id, deleted=True)) to_commit = self.get_docs_to_commit() for row in to_commit: doc = Document(**row) docs['to_commit'].append(doc) return docs def __str__(self): return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)
random_line_split
__init__.py
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ import shoop.apps class
(shoop.apps.AppConfig): name = __name__ verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], "front_template_helper_namespace": [ "shoop.simple_cms.template_helpers:SimpleCMSTemplateHelpers" ] } default_app_config = __name__ + ".AppConfig"
AppConfig
identifier_name
__init__.py
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ import shoop.apps
verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], "front_template_helper_namespace": [ "shoop.simple_cms.template_helpers:SimpleCMSTemplateHelpers" ] } default_app_config = __name__ + ".AppConfig"
class AppConfig(shoop.apps.AppConfig): name = __name__
random_line_split
__init__.py
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ import shoop.apps class AppConfig(shoop.apps.AppConfig):
default_app_config = __name__ + ".AppConfig"
name = __name__ verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], "front_template_helper_namespace": [ "shoop.simple_cms.template_helpers:SimpleCMSTemplateHelpers" ] }
identifier_body
ecies_hkdf_recipient_kem.rs
// Copyright 2021 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use crate::{subtle, subtle::EcPrivateKey}; use tink_core::TinkError; use tink_proto::{EcPointFormat, HashType}; /// Represents a HKDF-based KEM (key encapsulation mechanism) for ECIES recipient. pub(crate) struct
<'a> { recipient_private_key: &'a EcPrivateKey, } impl<'a> EciesHkdfRecipientKem<'a> { pub fn new(priv_key: &'a EcPrivateKey) -> Self { Self { recipient_private_key: priv_key, } } /// Uses the KEM to generate a new HKDF-based key. pub(crate) fn decapsulate( &self, kem: &[u8], hash_alg: HashType, salt: &[u8], info: &[u8], key_size: usize, point_format: EcPointFormat, ) -> Result<Vec<u8>, TinkError> { let pub_point = subtle::point_decode( self.recipient_private_key.public_key().curve(), point_format, kem, )?; let secret = subtle::compute_shared_secret(&pub_point, self.recipient_private_key)?; let mut i = kem.to_vec(); i.extend_from_slice(&secret); tink_core::subtle::compute_hkdf(hash_alg, &i, salt, info, key_size) } }
EciesHkdfRecipientKem
identifier_name
ecies_hkdf_recipient_kem.rs
// Copyright 2021 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use crate::{subtle, subtle::EcPrivateKey}; use tink_core::TinkError; use tink_proto::{EcPointFormat, HashType}; /// Represents a HKDF-based KEM (key encapsulation mechanism) for ECIES recipient. pub(crate) struct EciesHkdfRecipientKem<'a> { recipient_private_key: &'a EcPrivateKey, } impl<'a> EciesHkdfRecipientKem<'a> { pub fn new(priv_key: &'a EcPrivateKey) -> Self { Self {
recipient_private_key: priv_key, } } /// Uses the KEM to generate a new HKDF-based key. pub(crate) fn decapsulate( &self, kem: &[u8], hash_alg: HashType, salt: &[u8], info: &[u8], key_size: usize, point_format: EcPointFormat, ) -> Result<Vec<u8>, TinkError> { let pub_point = subtle::point_decode( self.recipient_private_key.public_key().curve(), point_format, kem, )?; let secret = subtle::compute_shared_secret(&pub_point, self.recipient_private_key)?; let mut i = kem.to_vec(); i.extend_from_slice(&secret); tink_core::subtle::compute_hkdf(hash_alg, &i, salt, info, key_size) } }
random_line_split
ecies_hkdf_recipient_kem.rs
// Copyright 2021 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// use crate::{subtle, subtle::EcPrivateKey}; use tink_core::TinkError; use tink_proto::{EcPointFormat, HashType}; /// Represents a HKDF-based KEM (key encapsulation mechanism) for ECIES recipient. pub(crate) struct EciesHkdfRecipientKem<'a> { recipient_private_key: &'a EcPrivateKey, } impl<'a> EciesHkdfRecipientKem<'a> { pub fn new(priv_key: &'a EcPrivateKey) -> Self { Self { recipient_private_key: priv_key, } } /// Uses the KEM to generate a new HKDF-based key. pub(crate) fn decapsulate( &self, kem: &[u8], hash_alg: HashType, salt: &[u8], info: &[u8], key_size: usize, point_format: EcPointFormat, ) -> Result<Vec<u8>, TinkError>
}
{ let pub_point = subtle::point_decode( self.recipient_private_key.public_key().curve(), point_format, kem, )?; let secret = subtle::compute_shared_secret(&pub_point, self.recipient_private_key)?; let mut i = kem.to_vec(); i.extend_from_slice(&secret); tink_core::subtle::compute_hkdf(hash_alg, &i, salt, info, key_size) }
identifier_body
column.spec.ts
/** * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> * @author David Sehnal <david.sehnal@gmail.com> */ import { FixedColumnProvider as FixedColumn } from '../common/text/column/fixed'; import { TokenColumnProvider as TokenColumn } from '../common/text/column/token'; import { Column, ColumnHelpers } from '../../../mol-data/db'; const lines = [ '1.123 abc', '1.00 a', '1.1 bcd ', '', ' 5' ]; const linesData = lines.join('\n'); const linesTokens = (function () { const tokens: number[] = []; let last = 0;
for (const l of lines) { tokens.push(last, last + l.length); last += l.length + 1; } if (tokens[tokens.length - 1] > linesData.length) tokens[tokens.length - 1] = linesData.length; return tokens; }()); describe('fixed text column', () => { const col = FixedColumn({ data: linesData, indices: linesTokens, count: lines.length }); const col1 = col(0, 5, Column.Schema.float); const col2 = col(5, 4, Column.Schema.str); it('number', () => { expect(col1.value(0)).toBe(1.123); expect(col1.value(1)).toBe(1.0); expect(col1.value(2)).toBe(1.1); expect(col1.value(3)).toBe(0); expect(col1.value(4)).toBe(5); }); it('str', () => { expect(col2.value(0)).toBe('abc'); expect(col2.value(1)).toBe('a'); expect(col2.value(2)).toBe('bc'); expect(col2.value(3)).toBe(''); expect(col2.value(4)).toBe(''); }); }); describe('token text column', () => { const tokensData = '321'; const col = TokenColumn({ data: tokensData, indices: [0, 1, 1, 2, 2, 3], count: 3 }); const col1 = col(Column.Schema.int); it('number', () => { expect(col1.value(0)).toBe(3); expect(col1.value(1)).toBe(2); expect(col1.value(2)).toBe(1); }); }); describe('binary column', () => { it('window works', () => { const xs = new Float64Array([1, 2, 3, 4]); const w1 = ColumnHelpers.typedArrayWindow(xs, { start: 1 }); const w2 = ColumnHelpers.typedArrayWindow(xs, { start: 2, end: 4 }); expect(w1.length).toBe(3); for (let i = 0; i < w1.length; i++) expect(w1[i]).toBe(xs[i + 1]); expect(w2.length).toBe(2); for (let i = 0; i < w2.length; i++) expect(w2[i]).toBe(xs[i + 2]); }); });
random_line_split
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class DNSLabel(object): """ Container for DNS label Supports IDNA encoding for unicode domain names >>> l1 = DNSLabel("aaa.bbb.ccc.") >>> l2 = DNSLabel([b"aaa",b"bbb",b"ccc"]) >>> l1 == l2 True >>> l3 = DNSLabel("AAA.BBB.CCC") >>> l1 == l3 True >>> l1 == 'AAA.BBB.CCC' True >>> x = { l1 : 1 } >>> x[l1] 1 >>> l1 <DNSLabel: 'aaa.bbb.ccc.'> >>> str(l1) 'aaa.bbb.ccc.' >>> l3 = l1.add("xxx.yyy") >>> l3 <DNSLabel: 'xxx.yyy.aaa.bbb.ccc.'> >>> l3.matchSuffix(l1) True >>> l3.matchSuffix("xxx.yyy.") False >>> l3.stripSuffix("bbb.ccc.") <DNSLabel: 'xxx.yyy.aaa.'> >>> l3.matchGlob("*.[abc]aa.BBB.ccc") True >>> l3.matchGlob("*.[abc]xx.bbb.ccc") False # Too hard to get unicode doctests to work on Python 3.2 # (works on 3.3) # >>> u1 = DNSLabel(u'\u2295.com') # >>> u1.__str__() == u'\u2295.com.' # True # >>> u1.label == ( b"xn--keh", b"com" ) # True """ def __init__(self,label): """ Create DNS label instance Label can be specified as: - a list/tuple of byte strings - a byte string (split into components separated by b'.') - a unicode string which will be encoded according to RFC3490/IDNA """ if type(label) == DNSLabel: self.label = label.label elif type(label) in (list,tuple): self.label = tuple(label) else: if not label or label in (b'.','.'): self.label = () elif type(label) is not bytes: self.label = tuple(label.encode("idna").\ rstrip(b".").split(b".")) else: self.label = tuple(label.rstrip(b".").split(b".")) def add(self,name): """ Prepend name to label """ new = DNSLabel(name) if self.label: new.label += self.label return new def matchGlob(self,pattern): if type(pattern) != DNSLabel: pattern = DNSLabel(pattern) return fnmatch.fnmatch(str(self).lower(),str(pattern).lower()) def matchSuffix(self,suffix): """ Return True if label suffix matches """ suffix = DNSLabel(suffix) return self.label[-len(suffix.label):] == suffix.label def stripSuffix(self,suffix): """ Strip suffix from label """ suffix = DNSLabel(suffix) if self.label[-len(suffix.label):] == suffix.label: return DNSLabel(self.label[:-len(suffix.label)]) else: return self def idna(self): return ".".join([ s.decode("idna") for s in self.label ]) + "." def __str__(self):
def __repr__(self): return "<DNSLabel: '%s'>" % str(self) def __hash__(self): return hash(self.label) def __ne__(self,other): return not self == other def __eq__(self,other): if type(other) != DNSLabel: return self.__eq__(DNSLabel(other)) else: return [ l.lower() for l in self.label ] == \ [ l.lower() for l in other.label ] def __len__(self): return len(b'.'.join(self.label)) class DNSBuffer(Buffer): """ Extends Buffer to provide DNS name encoding/decoding (with caching) # Needed for Python 2/3 doctest compatibility >>> def p(s): ... if not isinstance(s,str): ... return s.decode() ... return s >>> b = DNSBuffer() >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 15 >>> b.encode_name(b'xxx.yyy.zzz') >>> len(b) 28 >>> b.encode_name(b'zzz.xxx.bbb.ccc.') >>> len(b) 38 >>> b.encode_name(b'aaa.xxx.bbb.ccc') >>> len(b) 44 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) xxx.yyy.zzz. >>> print(b.decode_name()) zzz.xxx.bbb.ccc. >>> print(b.decode_name()) aaa.xxx.bbb.ccc. >>> b = DNSBuffer() >>> b.encode_name([b'a.aa',b'b.bb',b'c.cc']) >>> b.offset = 0 >>> len(b.decode_name().label) 3 >>> b = DNSBuffer() >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 26 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. """ def __init__(self,data=b''): """ Add 'names' dict to cache stored labels """ super(DNSBuffer,self).__init__(data) self.names = {} def decode_name(self,last=-1): """ Decode label at current offset in buffer (following pointers to cached elements where necessary) """ label = [] done = False while not done: (length,) = self.unpack("!B") if get_bits(length,6,2) == 3: # Pointer self.offset -= 1 pointer = get_bits(self.unpack("!H")[0],0,14) save = self.offset if last == save: raise BufferError("Recursive pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) if pointer < self.offset: self.offset = pointer else: # Pointer can't point forwards raise BufferError("Invalid pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) label.extend(self.decode_name(save).label) self.offset = save done = True else: if length > 0: l = self.get(length) try: l.decode() except UnicodeDecodeError: raise BufferError("Invalid label <%s>" % l) label.append(l) else: done = True return DNSLabel(label) def encode_name(self,name): """ Encode label and store at end of buffer (compressing cached elements where needed) and store elements in 'names' dict """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: if tuple(name) in self.names: # Cached - set pointer pointer = self.names[tuple(name)] pointer = set_bits(pointer,3,14,2) self.pack("!H",pointer) return else: self.names[tuple(name)] = self.offset element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') def encode_name_nocompress(self,name): """ Encode and store label with no compression (needed for RRSIG) """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') if __name__ == '__main__': import doctest doctest.testmod()
return ".".join([ s.decode() for s in self.label ]) + "."
identifier_body
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class DNSLabel(object): """ Container for DNS label Supports IDNA encoding for unicode domain names >>> l1 = DNSLabel("aaa.bbb.ccc.") >>> l2 = DNSLabel([b"aaa",b"bbb",b"ccc"]) >>> l1 == l2 True >>> l3 = DNSLabel("AAA.BBB.CCC") >>> l1 == l3 True >>> l1 == 'AAA.BBB.CCC' True >>> x = { l1 : 1 } >>> x[l1] 1 >>> l1 <DNSLabel: 'aaa.bbb.ccc.'> >>> str(l1) 'aaa.bbb.ccc.' >>> l3 = l1.add("xxx.yyy") >>> l3 <DNSLabel: 'xxx.yyy.aaa.bbb.ccc.'> >>> l3.matchSuffix(l1) True >>> l3.matchSuffix("xxx.yyy.") False >>> l3.stripSuffix("bbb.ccc.") <DNSLabel: 'xxx.yyy.aaa.'> >>> l3.matchGlob("*.[abc]aa.BBB.ccc") True >>> l3.matchGlob("*.[abc]xx.bbb.ccc") False # Too hard to get unicode doctests to work on Python 3.2 # (works on 3.3) # >>> u1 = DNSLabel(u'\u2295.com') # >>> u1.__str__() == u'\u2295.com.' # True # >>> u1.label == ( b"xn--keh", b"com" ) # True """ def __init__(self,label): """ Create DNS label instance Label can be specified as: - a list/tuple of byte strings - a byte string (split into components separated by b'.') - a unicode string which will be encoded according to RFC3490/IDNA """ if type(label) == DNSLabel: self.label = label.label elif type(label) in (list,tuple): self.label = tuple(label) else: if not label or label in (b'.','.'): self.label = () elif type(label) is not bytes: self.label = tuple(label.encode("idna").\ rstrip(b".").split(b".")) else: self.label = tuple(label.rstrip(b".").split(b".")) def add(self,name): """ Prepend name to label """ new = DNSLabel(name) if self.label: new.label += self.label return new def matchGlob(self,pattern): if type(pattern) != DNSLabel: pattern = DNSLabel(pattern) return fnmatch.fnmatch(str(self).lower(),str(pattern).lower()) def matchSuffix(self,suffix): """ Return True if label suffix matches """ suffix = DNSLabel(suffix) return self.label[-len(suffix.label):] == suffix.label def stripSuffix(self,suffix): """ Strip suffix from label """ suffix = DNSLabel(suffix) if self.label[-len(suffix.label):] == suffix.label: return DNSLabel(self.label[:-len(suffix.label)]) else: return self def idna(self): return ".".join([ s.decode("idna") for s in self.label ]) + "." def __str__(self): return ".".join([ s.decode() for s in self.label ]) + "." def __repr__(self): return "<DNSLabel: '%s'>" % str(self) def __hash__(self): return hash(self.label) def __ne__(self,other): return not self == other def __eq__(self,other): if type(other) != DNSLabel: return self.__eq__(DNSLabel(other)) else: return [ l.lower() for l in self.label ] == \ [ l.lower() for l in other.label ] def __len__(self): return len(b'.'.join(self.label)) class DNSBuffer(Buffer): """ Extends Buffer to provide DNS name encoding/decoding (with caching) # Needed for Python 2/3 doctest compatibility >>> def p(s): ... if not isinstance(s,str): ... return s.decode() ... return s >>> b = DNSBuffer() >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 15 >>> b.encode_name(b'xxx.yyy.zzz') >>> len(b) 28 >>> b.encode_name(b'zzz.xxx.bbb.ccc.') >>> len(b) 38 >>> b.encode_name(b'aaa.xxx.bbb.ccc') >>> len(b) 44 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) xxx.yyy.zzz. >>> print(b.decode_name()) zzz.xxx.bbb.ccc. >>> print(b.decode_name()) aaa.xxx.bbb.ccc. >>> b = DNSBuffer() >>> b.encode_name([b'a.aa',b'b.bb',b'c.cc'])
>>> b = DNSBuffer() >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 26 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. """ def __init__(self,data=b''): """ Add 'names' dict to cache stored labels """ super(DNSBuffer,self).__init__(data) self.names = {} def decode_name(self,last=-1): """ Decode label at current offset in buffer (following pointers to cached elements where necessary) """ label = [] done = False while not done: (length,) = self.unpack("!B") if get_bits(length,6,2) == 3: # Pointer self.offset -= 1 pointer = get_bits(self.unpack("!H")[0],0,14) save = self.offset if last == save: raise BufferError("Recursive pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) if pointer < self.offset: self.offset = pointer else: # Pointer can't point forwards raise BufferError("Invalid pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) label.extend(self.decode_name(save).label) self.offset = save done = True else: if length > 0: l = self.get(length) try: l.decode() except UnicodeDecodeError: raise BufferError("Invalid label <%s>" % l) label.append(l) else: done = True return DNSLabel(label) def encode_name(self,name): """ Encode label and store at end of buffer (compressing cached elements where needed) and store elements in 'names' dict """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: if tuple(name) in self.names: # Cached - set pointer pointer = self.names[tuple(name)] pointer = set_bits(pointer,3,14,2) self.pack("!H",pointer) return else: self.names[tuple(name)] = self.offset element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') def encode_name_nocompress(self,name): """ Encode and store label with no compression (needed for RRSIG) """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') if __name__ == '__main__': import doctest doctest.testmod()
>>> b.offset = 0 >>> len(b.decode_name().label) 3
random_line_split
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class DNSLabel(object): """ Container for DNS label Supports IDNA encoding for unicode domain names >>> l1 = DNSLabel("aaa.bbb.ccc.") >>> l2 = DNSLabel([b"aaa",b"bbb",b"ccc"]) >>> l1 == l2 True >>> l3 = DNSLabel("AAA.BBB.CCC") >>> l1 == l3 True >>> l1 == 'AAA.BBB.CCC' True >>> x = { l1 : 1 } >>> x[l1] 1 >>> l1 <DNSLabel: 'aaa.bbb.ccc.'> >>> str(l1) 'aaa.bbb.ccc.' >>> l3 = l1.add("xxx.yyy") >>> l3 <DNSLabel: 'xxx.yyy.aaa.bbb.ccc.'> >>> l3.matchSuffix(l1) True >>> l3.matchSuffix("xxx.yyy.") False >>> l3.stripSuffix("bbb.ccc.") <DNSLabel: 'xxx.yyy.aaa.'> >>> l3.matchGlob("*.[abc]aa.BBB.ccc") True >>> l3.matchGlob("*.[abc]xx.bbb.ccc") False # Too hard to get unicode doctests to work on Python 3.2 # (works on 3.3) # >>> u1 = DNSLabel(u'\u2295.com') # >>> u1.__str__() == u'\u2295.com.' # True # >>> u1.label == ( b"xn--keh", b"com" ) # True """ def __init__(self,label): """ Create DNS label instance Label can be specified as: - a list/tuple of byte strings - a byte string (split into components separated by b'.') - a unicode string which will be encoded according to RFC3490/IDNA """ if type(label) == DNSLabel: self.label = label.label elif type(label) in (list,tuple): self.label = tuple(label) else: if not label or label in (b'.','.'): self.label = () elif type(label) is not bytes: self.label = tuple(label.encode("idna").\ rstrip(b".").split(b".")) else: self.label = tuple(label.rstrip(b".").split(b".")) def add(self,name): """ Prepend name to label """ new = DNSLabel(name) if self.label:
return new def matchGlob(self,pattern): if type(pattern) != DNSLabel: pattern = DNSLabel(pattern) return fnmatch.fnmatch(str(self).lower(),str(pattern).lower()) def matchSuffix(self,suffix): """ Return True if label suffix matches """ suffix = DNSLabel(suffix) return self.label[-len(suffix.label):] == suffix.label def stripSuffix(self,suffix): """ Strip suffix from label """ suffix = DNSLabel(suffix) if self.label[-len(suffix.label):] == suffix.label: return DNSLabel(self.label[:-len(suffix.label)]) else: return self def idna(self): return ".".join([ s.decode("idna") for s in self.label ]) + "." def __str__(self): return ".".join([ s.decode() for s in self.label ]) + "." def __repr__(self): return "<DNSLabel: '%s'>" % str(self) def __hash__(self): return hash(self.label) def __ne__(self,other): return not self == other def __eq__(self,other): if type(other) != DNSLabel: return self.__eq__(DNSLabel(other)) else: return [ l.lower() for l in self.label ] == \ [ l.lower() for l in other.label ] def __len__(self): return len(b'.'.join(self.label)) class DNSBuffer(Buffer): """ Extends Buffer to provide DNS name encoding/decoding (with caching) # Needed for Python 2/3 doctest compatibility >>> def p(s): ... if not isinstance(s,str): ... return s.decode() ... return s >>> b = DNSBuffer() >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 15 >>> b.encode_name(b'xxx.yyy.zzz') >>> len(b) 28 >>> b.encode_name(b'zzz.xxx.bbb.ccc.') >>> len(b) 38 >>> b.encode_name(b'aaa.xxx.bbb.ccc') >>> len(b) 44 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) xxx.yyy.zzz. >>> print(b.decode_name()) zzz.xxx.bbb.ccc. >>> print(b.decode_name()) aaa.xxx.bbb.ccc. >>> b = DNSBuffer() >>> b.encode_name([b'a.aa',b'b.bb',b'c.cc']) >>> b.offset = 0 >>> len(b.decode_name().label) 3 >>> b = DNSBuffer() >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 26 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. """ def __init__(self,data=b''): """ Add 'names' dict to cache stored labels """ super(DNSBuffer,self).__init__(data) self.names = {} def decode_name(self,last=-1): """ Decode label at current offset in buffer (following pointers to cached elements where necessary) """ label = [] done = False while not done: (length,) = self.unpack("!B") if get_bits(length,6,2) == 3: # Pointer self.offset -= 1 pointer = get_bits(self.unpack("!H")[0],0,14) save = self.offset if last == save: raise BufferError("Recursive pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) if pointer < self.offset: self.offset = pointer else: # Pointer can't point forwards raise BufferError("Invalid pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) label.extend(self.decode_name(save).label) self.offset = save done = True else: if length > 0: l = self.get(length) try: l.decode() except UnicodeDecodeError: raise BufferError("Invalid label <%s>" % l) label.append(l) else: done = True return DNSLabel(label) def encode_name(self,name): """ Encode label and store at end of buffer (compressing cached elements where needed) and store elements in 'names' dict """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: if tuple(name) in self.names: # Cached - set pointer pointer = self.names[tuple(name)] pointer = set_bits(pointer,3,14,2) self.pack("!H",pointer) return else: self.names[tuple(name)] = self.offset element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') def encode_name_nocompress(self,name): """ Encode and store label with no compression (needed for RRSIG) """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') if __name__ == '__main__': import doctest doctest.testmod()
new.label += self.label
conditional_block
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class
(object): """ Container for DNS label Supports IDNA encoding for unicode domain names >>> l1 = DNSLabel("aaa.bbb.ccc.") >>> l2 = DNSLabel([b"aaa",b"bbb",b"ccc"]) >>> l1 == l2 True >>> l3 = DNSLabel("AAA.BBB.CCC") >>> l1 == l3 True >>> l1 == 'AAA.BBB.CCC' True >>> x = { l1 : 1 } >>> x[l1] 1 >>> l1 <DNSLabel: 'aaa.bbb.ccc.'> >>> str(l1) 'aaa.bbb.ccc.' >>> l3 = l1.add("xxx.yyy") >>> l3 <DNSLabel: 'xxx.yyy.aaa.bbb.ccc.'> >>> l3.matchSuffix(l1) True >>> l3.matchSuffix("xxx.yyy.") False >>> l3.stripSuffix("bbb.ccc.") <DNSLabel: 'xxx.yyy.aaa.'> >>> l3.matchGlob("*.[abc]aa.BBB.ccc") True >>> l3.matchGlob("*.[abc]xx.bbb.ccc") False # Too hard to get unicode doctests to work on Python 3.2 # (works on 3.3) # >>> u1 = DNSLabel(u'\u2295.com') # >>> u1.__str__() == u'\u2295.com.' # True # >>> u1.label == ( b"xn--keh", b"com" ) # True """ def __init__(self,label): """ Create DNS label instance Label can be specified as: - a list/tuple of byte strings - a byte string (split into components separated by b'.') - a unicode string which will be encoded according to RFC3490/IDNA """ if type(label) == DNSLabel: self.label = label.label elif type(label) in (list,tuple): self.label = tuple(label) else: if not label or label in (b'.','.'): self.label = () elif type(label) is not bytes: self.label = tuple(label.encode("idna").\ rstrip(b".").split(b".")) else: self.label = tuple(label.rstrip(b".").split(b".")) def add(self,name): """ Prepend name to label """ new = DNSLabel(name) if self.label: new.label += self.label return new def matchGlob(self,pattern): if type(pattern) != DNSLabel: pattern = DNSLabel(pattern) return fnmatch.fnmatch(str(self).lower(),str(pattern).lower()) def matchSuffix(self,suffix): """ Return True if label suffix matches """ suffix = DNSLabel(suffix) return self.label[-len(suffix.label):] == suffix.label def stripSuffix(self,suffix): """ Strip suffix from label """ suffix = DNSLabel(suffix) if self.label[-len(suffix.label):] == suffix.label: return DNSLabel(self.label[:-len(suffix.label)]) else: return self def idna(self): return ".".join([ s.decode("idna") for s in self.label ]) + "." def __str__(self): return ".".join([ s.decode() for s in self.label ]) + "." def __repr__(self): return "<DNSLabel: '%s'>" % str(self) def __hash__(self): return hash(self.label) def __ne__(self,other): return not self == other def __eq__(self,other): if type(other) != DNSLabel: return self.__eq__(DNSLabel(other)) else: return [ l.lower() for l in self.label ] == \ [ l.lower() for l in other.label ] def __len__(self): return len(b'.'.join(self.label)) class DNSBuffer(Buffer): """ Extends Buffer to provide DNS name encoding/decoding (with caching) # Needed for Python 2/3 doctest compatibility >>> def p(s): ... if not isinstance(s,str): ... return s.decode() ... return s >>> b = DNSBuffer() >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name(b'aaa.bbb.ccc.') >>> len(b) 15 >>> b.encode_name(b'xxx.yyy.zzz') >>> len(b) 28 >>> b.encode_name(b'zzz.xxx.bbb.ccc.') >>> len(b) 38 >>> b.encode_name(b'aaa.xxx.bbb.ccc') >>> len(b) 44 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) xxx.yyy.zzz. >>> print(b.decode_name()) zzz.xxx.bbb.ccc. >>> print(b.decode_name()) aaa.xxx.bbb.ccc. >>> b = DNSBuffer() >>> b.encode_name([b'a.aa',b'b.bb',b'c.cc']) >>> b.offset = 0 >>> len(b.decode_name().label) 3 >>> b = DNSBuffer() >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 26 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. """ def __init__(self,data=b''): """ Add 'names' dict to cache stored labels """ super(DNSBuffer,self).__init__(data) self.names = {} def decode_name(self,last=-1): """ Decode label at current offset in buffer (following pointers to cached elements where necessary) """ label = [] done = False while not done: (length,) = self.unpack("!B") if get_bits(length,6,2) == 3: # Pointer self.offset -= 1 pointer = get_bits(self.unpack("!H")[0],0,14) save = self.offset if last == save: raise BufferError("Recursive pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) if pointer < self.offset: self.offset = pointer else: # Pointer can't point forwards raise BufferError("Invalid pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % (self.offset,pointer,len(self.data))) label.extend(self.decode_name(save).label) self.offset = save done = True else: if length > 0: l = self.get(length) try: l.decode() except UnicodeDecodeError: raise BufferError("Invalid label <%s>" % l) label.append(l) else: done = True return DNSLabel(label) def encode_name(self,name): """ Encode label and store at end of buffer (compressing cached elements where needed) and store elements in 'names' dict """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: if tuple(name) in self.names: # Cached - set pointer pointer = self.names[tuple(name)] pointer = set_bits(pointer,3,14,2) self.pack("!H",pointer) return else: self.names[tuple(name)] = self.offset element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') def encode_name_nocompress(self,name): """ Encode and store label with no compression (needed for RRSIG) """ if not isinstance(name,DNSLabel): name = DNSLabel(name) if len(name) > 253: raise DNSLabelError("Domain label too long: %r" % name) name = list(name.label) while name: element = name.pop(0) if len(element) > 63: raise DNSLabelError("Label component too long: %r" % element) self.pack("!B",len(element)) self.append(element) self.append(b'\x00') if __name__ == '__main__': import doctest doctest.testmod()
DNSLabel
identifier_name
about-assistant.js
function AboutAssistant()
AboutAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: "Records", command: 'do-records' }, { label: "PuzzleMaker", command: 'do-puzzlemaker' }, { label: "Help", command: 'do-help' } ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); } AboutAssistant.prototype.activate = function(event) { /* put in event handlers here that should only be in effect when this scene is active. For example, key handlers that are observing the document */ } AboutAssistant.prototype.deactivate = function(event) { /* remove any event handlers you added in activate and do any other cleanup that should happen before this scene is popped or another scene is pushed on top */ } AboutAssistant.prototype.cleanup = function(event) { /* this function should do any cleanup needed before the scene is destroyed as a result of being popped off the scene stack */ }
{ /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene controller should be done in the setup function below. */ }
identifier_body
about-assistant.js
function AboutAssistant() { /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene controller should be done in the setup function below. */ } AboutAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: "Records", command: 'do-records' }, { label: "PuzzleMaker", command: 'do-puzzlemaker' },
{ label: "Help", command: 'do-help' } ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); } AboutAssistant.prototype.activate = function(event) { /* put in event handlers here that should only be in effect when this scene is active. For example, key handlers that are observing the document */ } AboutAssistant.prototype.deactivate = function(event) { /* remove any event handlers you added in activate and do any other cleanup that should happen before this scene is popped or another scene is pushed on top */ } AboutAssistant.prototype.cleanup = function(event) { /* this function should do any cleanup needed before the scene is destroyed as a result of being popped off the scene stack */ }
random_line_split
about-assistant.js
function
() { /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene controller should be done in the setup function below. */ } AboutAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: "Records", command: 'do-records' }, { label: "PuzzleMaker", command: 'do-puzzlemaker' }, { label: "Help", command: 'do-help' } ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); } AboutAssistant.prototype.activate = function(event) { /* put in event handlers here that should only be in effect when this scene is active. For example, key handlers that are observing the document */ } AboutAssistant.prototype.deactivate = function(event) { /* remove any event handlers you added in activate and do any other cleanup that should happen before this scene is popped or another scene is pushed on top */ } AboutAssistant.prototype.cleanup = function(event) { /* this function should do any cleanup needed before the scene is destroyed as a result of being popped off the scene stack */ }
AboutAssistant
identifier_name
constructPermissionHierarchy.ts
import { topologicalSort } from 'gracl'; import * as _ from 'lodash'; import { GraclPlugin } from '../classes/GraclPlugin'; import { Hash, PermissionHierarchy, PermissionTypeList, PermissionHierarchyNode } from '../interfaces'; import { parsePermissionString } from '../permission/parsePermissionString'; /** * validate and insert provided permissionHierarchy into model */ export function constructPermissionHierarchy(plugin: GraclPlugin)
{ plugin.log(`constructing permissions hierarchy...`); if (!plugin.graclHierarchy) { plugin.error( `Must build subject/resource hierarchy before creating permission hierarchy` ); } /** * Run topological sort on permissions values, checking for circular dependencies / missing nodes */ const sorted = _.compact( topologicalSort( _.map(plugin.permissionTypes, perm => { if (perm.abstract === undefined && !perm.collection) { plugin.error( `Must set { abstract: true | false } property for all permission types ` + `unless it is a collection-specific permission ` + `permission ${JSON.stringify( perm )} does not have "abstract" or "collection" property` ); } const singleParent = perm.parent; if (singleParent) { perm.parents = [singleParent]; } /** * Check for non-abstract permissions (as parents) which will not have a node listed in the permissionType list, but whose "action" should be a node in the list. */ const parents = perm.parents as string[]; if (parents) { if (!Array.isArray(parents)) { plugin.error( `parents of permission type must be given as an array!` ); } const colParents = [] as string[]; for (const parent of parents) { // if we have an <action>-<collection> permission... if (parent && /-/.test(parent)) { if (!perm.abstract && !perm.collection) { plugin.error( `Cannot set collection-specific permission to be the parent of a non-abstract permission!` ); } const parsed = parsePermissionString(plugin, parent); if ( !( parsed.collection && plugin.graclHierarchy.resources.has(parsed.collection) ) ) { plugin.error( `Collection ${parsed.collection} in permission ` + `"${parent}" does not exist in the resource hierarchy!` ); } // add it to the list of parents of this nodes, to insure the action // is a listed valid permission given to the plugin if (parsed.action) { colParents.push(parsed.action); } else { plugin.error(`parent permission had no action! ${parent}`); } } else if (parent) { colParents.push(parent); } } perm.collection_parents = _.uniq(colParents); } return perm; }), 'name', 'collection_parents' ) ) as PermissionTypeList; const duplicates = new Set(); const exist = new Set(); for (const perm of sorted) { const name = perm && perm.name; if (name && exist.has(name)) { duplicates.add(name); } else if (name) { exist.add(name); } } if (duplicates.size) { plugin.error( `Duplicate permission types provided: ${[...duplicates].join(', ')}` ); } const hierarchy: PermissionHierarchy = {}; _.each(sorted, node => { const name = node.name; const parents = (node.parents || []) as string[]; const abstract = node.abstract || false; const collection = node.collection || false; if (!(abstract || collection)) { plugin.crudPermissionSet.add(name); } hierarchy[name] = { name, abstract, collection, format: node.format, // need to add parents, that may be non-abstract nodes that don't directly exist in hierarchy parents: _.map(parents, (p: string) => { const hierarchyParent = hierarchy[p]; if (abstract && hierarchyParent && !hierarchyParent.abstract) { plugin.error( `If a permission is abstract, it either needs an abstract parent ` + `or a parent that references a specific collection.` ); } if (hierarchyParent) { return hierarchyParent; } const parsed = parsePermissionString(plugin, p); const action = parsed.action; if (abstract && !parsed.collection) { plugin.error( `Parent permissions of abstract permission must ` + `themseleves be abstract or reference a specific collection. ` + `Abstract permission ${name} has parent permission ${p} which is not specific to a collection` ); } if ( !( parsed.collection && plugin.graclHierarchy.resources.has(parsed.collection) ) ) { plugin.error( `Collection ${parsed.collection} in permission ` + `"${p}" does not exist in the resource hierarchy!` ); } // the non-abstract parent, must itself have a parent in the hierarchy... const subParents: Array<PermissionHierarchyNode> = []; if (action) { subParents.push(hierarchy[action]); } else { plugin.error(`No parent of action in permission ${p} exists!`); } return { name: p, parents: subParents }; }) }; }); // store the hierarchy and set of all permissions plugin.permissionHierarchy = hierarchy; plugin.setOfAllPermissions = new Set(plugin.getAllPossiblePermissionTypes()); }
identifier_body
constructPermissionHierarchy.ts
import { topologicalSort } from 'gracl'; import * as _ from 'lodash'; import { GraclPlugin } from '../classes/GraclPlugin'; import { Hash, PermissionHierarchy, PermissionTypeList, PermissionHierarchyNode } from '../interfaces'; import { parsePermissionString } from '../permission/parsePermissionString'; /**
if (!plugin.graclHierarchy) { plugin.error( `Must build subject/resource hierarchy before creating permission hierarchy` ); } /** * Run topological sort on permissions values, checking for circular dependencies / missing nodes */ const sorted = _.compact( topologicalSort( _.map(plugin.permissionTypes, perm => { if (perm.abstract === undefined && !perm.collection) { plugin.error( `Must set { abstract: true | false } property for all permission types ` + `unless it is a collection-specific permission ` + `permission ${JSON.stringify( perm )} does not have "abstract" or "collection" property` ); } const singleParent = perm.parent; if (singleParent) { perm.parents = [singleParent]; } /** * Check for non-abstract permissions (as parents) which will not have a node listed in the permissionType list, but whose "action" should be a node in the list. */ const parents = perm.parents as string[]; if (parents) { if (!Array.isArray(parents)) { plugin.error( `parents of permission type must be given as an array!` ); } const colParents = [] as string[]; for (const parent of parents) { // if we have an <action>-<collection> permission... if (parent && /-/.test(parent)) { if (!perm.abstract && !perm.collection) { plugin.error( `Cannot set collection-specific permission to be the parent of a non-abstract permission!` ); } const parsed = parsePermissionString(plugin, parent); if ( !( parsed.collection && plugin.graclHierarchy.resources.has(parsed.collection) ) ) { plugin.error( `Collection ${parsed.collection} in permission ` + `"${parent}" does not exist in the resource hierarchy!` ); } // add it to the list of parents of this nodes, to insure the action // is a listed valid permission given to the plugin if (parsed.action) { colParents.push(parsed.action); } else { plugin.error(`parent permission had no action! ${parent}`); } } else if (parent) { colParents.push(parent); } } perm.collection_parents = _.uniq(colParents); } return perm; }), 'name', 'collection_parents' ) ) as PermissionTypeList; const duplicates = new Set(); const exist = new Set(); for (const perm of sorted) { const name = perm && perm.name; if (name && exist.has(name)) { duplicates.add(name); } else if (name) { exist.add(name); } } if (duplicates.size) { plugin.error( `Duplicate permission types provided: ${[...duplicates].join(', ')}` ); } const hierarchy: PermissionHierarchy = {}; _.each(sorted, node => { const name = node.name; const parents = (node.parents || []) as string[]; const abstract = node.abstract || false; const collection = node.collection || false; if (!(abstract || collection)) { plugin.crudPermissionSet.add(name); } hierarchy[name] = { name, abstract, collection, format: node.format, // need to add parents, that may be non-abstract nodes that don't directly exist in hierarchy parents: _.map(parents, (p: string) => { const hierarchyParent = hierarchy[p]; if (abstract && hierarchyParent && !hierarchyParent.abstract) { plugin.error( `If a permission is abstract, it either needs an abstract parent ` + `or a parent that references a specific collection.` ); } if (hierarchyParent) { return hierarchyParent; } const parsed = parsePermissionString(plugin, p); const action = parsed.action; if (abstract && !parsed.collection) { plugin.error( `Parent permissions of abstract permission must ` + `themseleves be abstract or reference a specific collection. ` + `Abstract permission ${name} has parent permission ${p} which is not specific to a collection` ); } if ( !( parsed.collection && plugin.graclHierarchy.resources.has(parsed.collection) ) ) { plugin.error( `Collection ${parsed.collection} in permission ` + `"${p}" does not exist in the resource hierarchy!` ); } // the non-abstract parent, must itself have a parent in the hierarchy... const subParents: Array<PermissionHierarchyNode> = []; if (action) { subParents.push(hierarchy[action]); } else { plugin.error(`No parent of action in permission ${p} exists!`); } return { name: p, parents: subParents }; }) }; }); // store the hierarchy and set of all permissions plugin.permissionHierarchy = hierarchy; plugin.setOfAllPermissions = new Set(plugin.getAllPossiblePermissionTypes()); }
* validate and insert provided permissionHierarchy into model */ export function constructPermissionHierarchy(plugin: GraclPlugin) { plugin.log(`constructing permissions hierarchy...`);
random_line_split
constructPermissionHierarchy.ts
import { topologicalSort } from 'gracl'; import * as _ from 'lodash'; import { GraclPlugin } from '../classes/GraclPlugin'; import { Hash, PermissionHierarchy, PermissionTypeList, PermissionHierarchyNode } from '../interfaces'; import { parsePermissionString } from '../permission/parsePermissionString'; /** * validate and insert provided permissionHierarchy into model */ export function
(plugin: GraclPlugin) { plugin.log(`constructing permissions hierarchy...`); if (!plugin.graclHierarchy) { plugin.error( `Must build subject/resource hierarchy before creating permission hierarchy` ); } /** * Run topological sort on permissions values, checking for circular dependencies / missing nodes */ const sorted = _.compact( topologicalSort( _.map(plugin.permissionTypes, perm => { if (perm.abstract === undefined && !perm.collection) { plugin.error( `Must set { abstract: true | false } property for all permission types ` + `unless it is a collection-specific permission ` + `permission ${JSON.stringify( perm )} does not have "abstract" or "collection" property` ); } const singleParent = perm.parent; if (singleParent) { perm.parents = [singleParent]; } /** * Check for non-abstract permissions (as parents) which will not have a node listed in the permissionType list, but whose "action" should be a node in the list. */ const parents = perm.parents as string[]; if (parents) { if (!Array.isArray(parents)) { plugin.error( `parents of permission type must be given as an array!` ); } const colParents = [] as string[]; for (const parent of parents) { // if we have an <action>-<collection> permission... if (parent && /-/.test(parent)) { if (!perm.abstract && !perm.collection) { plugin.error( `Cannot set collection-specific permission to be the parent of a non-abstract permission!` ); } const parsed = parsePermissionString(plugin, parent); if ( !( parsed.collection && plugin.graclHierarchy.resources.has(parsed.collection) ) ) { plugin.error( `Collection ${parsed.collection} in permission ` + `"${parent}" does not exist in the resource hierarchy!` ); } // add it to the list of parents of this nodes, to insure the action // is a listed valid permission given to the plugin if (parsed.action) { colParents.push(parsed.action); } else { plugin.error(`parent permission had no action! ${parent}`); } } else if (parent) { colParents.push(parent); } } perm.collection_parents = _.uniq(colParents); } return perm; }), 'name', 'collection_parents' ) ) as PermissionTypeList; const duplicates = new Set(); const exist = new Set(); for (const perm of sorted) { const name = perm && perm.name; if (name && exist.has(name)) { duplicates.add(name); } else if (name) { exist.add(name); } } if (duplicates.size) { plugin.error( `Duplicate permission types provided: ${[...duplicates].join(', ')}` ); } const hierarchy: PermissionHierarchy = {}; _.each(sorted, node => { const name = node.name; const parents = (node.parents || []) as string[]; const abstract = node.abstract || false; const collection = node.collection || false; if (!(abstract || collection)) { plugin.crudPermissionSet.add(name); } hierarchy[name] = { name, abstract, collection, format: node.format, // need to add parents, that may be non-abstract nodes that don't directly exist in hierarchy parents: _.map(parents, (p: string) => { const hierarchyParent = hierarchy[p]; if (abstract && hierarchyParent && !hierarchyParent.abstract) { plugin.error( `If a permission is abstract, it either needs an abstract parent ` + `or a parent that references a specific collection.` ); } if (hierarchyParent) { return hierarchyParent; } const parsed = parsePermissionString(plugin, p); const action = parsed.action; if (abstract && !parsed.collection) { plugin.error( `Parent permissions of abstract permission must ` + `themseleves be abstract or reference a specific collection. ` + `Abstract permission ${name} has parent permission ${p} which is not specific to a collection` ); } if ( !( parsed.collection && plugin.graclHierarchy.resources.has(parsed.collection) ) ) { plugin.error( `Collection ${parsed.collection} in permission ` + `"${p}" does not exist in the resource hierarchy!` ); } // the non-abstract parent, must itself have a parent in the hierarchy... const subParents: Array<PermissionHierarchyNode> = []; if (action) { subParents.push(hierarchy[action]); } else { plugin.error(`No parent of action in permission ${p} exists!`); } return { name: p, parents: subParents }; }) }; }); // store the hierarchy and set of all permissions plugin.permissionHierarchy = hierarchy; plugin.setOfAllPermissions = new Set(plugin.getAllPossiblePermissionTypes()); }
constructPermissionHierarchy
identifier_name
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY = 'pokeybill/bftest' DIGEST = 'sha256:79215d32e5896c1ccd3f57d22ee6aaa7c9d79c9c87737f2b96673186de6ab060' @click.group() def default(): """ A basic docker container management wrapper """ pass @click.command() @click.argument('container') def run(container): """ attempts to start the docker container specified """ try: fetch_client() this.client.pull(REGISTRY) start_container(container) result = health_check(container) except docker.errors.APIError as e: click.echo('[!] Docker API Error: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() @click.argument('container') def stop(container): """ attempts to stop the docker container specified """ try: fetch_client() this.client.stop(container) this.client.remove_container(container) except docker.errors.APIError as e: click.echo('[!] Error stopping container: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() def test(): """ basic functional test to ensure containers can be managed """ click.echo('[*] Testing docker container creation/removal') cont_name = 'funky_aardvark' try: runner = CliRunner() # Test the RUN command result = runner.invoke(run, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application START failed: {}'.format(result_txt) assert 'Your app is running on' in result.output, \ '[!] Unexpected output: {}'.format(result.output) click.echo(result_txt) # Test container access click.echo('[*] Ensuring we can communicate with the containerized application') result = requests.get('http://127.0.0.1:8888/hello') assert result.status_code == 200, \ '[!] Unexpected HTTP response: {}'.format(result.status_code) click.echo('\t{}'.format(result.text)) # Test the STOP command result = runner.invoke(stop, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application STOP failed: {}'.format(result_txt) click.echo('[*] Container {} stopped'.format(cont_name)) except requests.exceptions.ConnectionError as e: click.echo('[!] Failed to communicate with the application') click.echo(e[0]) except AssertionError as e: click.echo('[*] Test failed - {}'.format(e)) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') else: click.echo('[*] Test succeeded') default.add_command(run) default.add_command(stop) default.add_command(test) # Functions start here def health_check(inst_name): def __check_state(): cont_state = this.client.inspect_container(inst_name)['State'] if cont_state['Status']=='running': return cont_state['Health']['Status'] else: click.echo('[!] Container is not running!') repeat = 0 while True: cont_status = __check_state() if cont_status == 'healthy': click.echo('[*] Your app is running on http://127.0.0.1:8888') return True elif cont_status == 'starting': if repeat > 6: return time.sleep(1) repeat += 1 else: click.echo('[!] Container status: {}'.format(cont_status)) return def start_container(inst_name):
def fetch_client(base_url=BASE_URL): this.client = docker.APIClient(base_url=base_url, version='1.24') try: this.client.version() except requests.exceptions.ConnectionError as e: click.echo('[!] Unable to connect to Docker daemon @ {}'.format(BASE_URL)) sys.exit(1) if __name__=="__main__": default()
this.client.create_container( REGISTRY, detach=False, name=inst_name, ports=[8888], host_config=this.client.create_host_config( port_bindings={8888: ('127.0.0.1',8888)} ), ) this.client.start(inst_name)
identifier_body
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY = 'pokeybill/bftest' DIGEST = 'sha256:79215d32e5896c1ccd3f57d22ee6aaa7c9d79c9c87737f2b96673186de6ab060' @click.group() def default(): """ A basic docker container management wrapper """ pass @click.command() @click.argument('container') def run(container): """ attempts to start the docker container specified """ try: fetch_client() this.client.pull(REGISTRY) start_container(container) result = health_check(container) except docker.errors.APIError as e: click.echo('[!] Docker API Error: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() @click.argument('container') def stop(container): """ attempts to stop the docker container specified """ try: fetch_client() this.client.stop(container) this.client.remove_container(container) except docker.errors.APIError as e: click.echo('[!] Error stopping container: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() def test(): """ basic functional test to ensure containers can be managed """ click.echo('[*] Testing docker container creation/removal') cont_name = 'funky_aardvark' try: runner = CliRunner() # Test the RUN command result = runner.invoke(run, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application START failed: {}'.format(result_txt) assert 'Your app is running on' in result.output, \ '[!] Unexpected output: {}'.format(result.output) click.echo(result_txt) # Test container access click.echo('[*] Ensuring we can communicate with the containerized application') result = requests.get('http://127.0.0.1:8888/hello') assert result.status_code == 200, \ '[!] Unexpected HTTP response: {}'.format(result.status_code) click.echo('\t{}'.format(result.text)) # Test the STOP command result = runner.invoke(stop, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application STOP failed: {}'.format(result_txt) click.echo('[*] Container {} stopped'.format(cont_name)) except requests.exceptions.ConnectionError as e: click.echo('[!] Failed to communicate with the application') click.echo(e[0]) except AssertionError as e: click.echo('[*] Test failed - {}'.format(e)) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') else: click.echo('[*] Test succeeded') default.add_command(run) default.add_command(stop) default.add_command(test) # Functions start here def health_check(inst_name): def __check_state(): cont_state = this.client.inspect_container(inst_name)['State'] if cont_state['Status']=='running': return cont_state['Health']['Status'] else: click.echo('[!] Container is not running!') repeat = 0 while True: cont_status = __check_state() if cont_status == 'healthy': click.echo('[*] Your app is running on http://127.0.0.1:8888') return True elif cont_status == 'starting': if repeat > 6:
time.sleep(1) repeat += 1 else: click.echo('[!] Container status: {}'.format(cont_status)) return def start_container(inst_name): this.client.create_container( REGISTRY, detach=False, name=inst_name, ports=[8888], host_config=this.client.create_host_config( port_bindings={8888: ('127.0.0.1',8888)} ), ) this.client.start(inst_name) def fetch_client(base_url=BASE_URL): this.client = docker.APIClient(base_url=base_url, version='1.24') try: this.client.version() except requests.exceptions.ConnectionError as e: click.echo('[!] Unable to connect to Docker daemon @ {}'.format(BASE_URL)) sys.exit(1) if __name__=="__main__": default()
return
conditional_block
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY = 'pokeybill/bftest' DIGEST = 'sha256:79215d32e5896c1ccd3f57d22ee6aaa7c9d79c9c87737f2b96673186de6ab060' @click.group() def default(): """ A basic docker container management wrapper """ pass @click.command() @click.argument('container') def run(container): """ attempts to start the docker container specified """ try: fetch_client() this.client.pull(REGISTRY) start_container(container) result = health_check(container) except docker.errors.APIError as e: click.echo('[!] Docker API Error: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() @click.argument('container') def stop(container): """ attempts to stop the docker container specified """ try: fetch_client() this.client.stop(container) this.client.remove_container(container) except docker.errors.APIError as e: click.echo('[!] Error stopping container: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() def
(): """ basic functional test to ensure containers can be managed """ click.echo('[*] Testing docker container creation/removal') cont_name = 'funky_aardvark' try: runner = CliRunner() # Test the RUN command result = runner.invoke(run, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application START failed: {}'.format(result_txt) assert 'Your app is running on' in result.output, \ '[!] Unexpected output: {}'.format(result.output) click.echo(result_txt) # Test container access click.echo('[*] Ensuring we can communicate with the containerized application') result = requests.get('http://127.0.0.1:8888/hello') assert result.status_code == 200, \ '[!] Unexpected HTTP response: {}'.format(result.status_code) click.echo('\t{}'.format(result.text)) # Test the STOP command result = runner.invoke(stop, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application STOP failed: {}'.format(result_txt) click.echo('[*] Container {} stopped'.format(cont_name)) except requests.exceptions.ConnectionError as e: click.echo('[!] Failed to communicate with the application') click.echo(e[0]) except AssertionError as e: click.echo('[*] Test failed - {}'.format(e)) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') else: click.echo('[*] Test succeeded') default.add_command(run) default.add_command(stop) default.add_command(test) # Functions start here def health_check(inst_name): def __check_state(): cont_state = this.client.inspect_container(inst_name)['State'] if cont_state['Status']=='running': return cont_state['Health']['Status'] else: click.echo('[!] Container is not running!') repeat = 0 while True: cont_status = __check_state() if cont_status == 'healthy': click.echo('[*] Your app is running on http://127.0.0.1:8888') return True elif cont_status == 'starting': if repeat > 6: return time.sleep(1) repeat += 1 else: click.echo('[!] Container status: {}'.format(cont_status)) return def start_container(inst_name): this.client.create_container( REGISTRY, detach=False, name=inst_name, ports=[8888], host_config=this.client.create_host_config( port_bindings={8888: ('127.0.0.1',8888)} ), ) this.client.start(inst_name) def fetch_client(base_url=BASE_URL): this.client = docker.APIClient(base_url=base_url, version='1.24') try: this.client.version() except requests.exceptions.ConnectionError as e: click.echo('[!] Unable to connect to Docker daemon @ {}'.format(BASE_URL)) sys.exit(1) if __name__=="__main__": default()
test
identifier_name
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY = 'pokeybill/bftest' DIGEST = 'sha256:79215d32e5896c1ccd3f57d22ee6aaa7c9d79c9c87737f2b96673186de6ab060'
@click.group() def default(): """ A basic docker container management wrapper """ pass @click.command() @click.argument('container') def run(container): """ attempts to start the docker container specified """ try: fetch_client() this.client.pull(REGISTRY) start_container(container) result = health_check(container) except docker.errors.APIError as e: click.echo('[!] Docker API Error: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() @click.argument('container') def stop(container): """ attempts to stop the docker container specified """ try: fetch_client() this.client.stop(container) this.client.remove_container(container) except docker.errors.APIError as e: click.echo('[!] Error stopping container: {}'.format(e)) sys.exit(1) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') @click.command() def test(): """ basic functional test to ensure containers can be managed """ click.echo('[*] Testing docker container creation/removal') cont_name = 'funky_aardvark' try: runner = CliRunner() # Test the RUN command result = runner.invoke(run, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application START failed: {}'.format(result_txt) assert 'Your app is running on' in result.output, \ '[!] Unexpected output: {}'.format(result.output) click.echo(result_txt) # Test container access click.echo('[*] Ensuring we can communicate with the containerized application') result = requests.get('http://127.0.0.1:8888/hello') assert result.status_code == 200, \ '[!] Unexpected HTTP response: {}'.format(result.status_code) click.echo('\t{}'.format(result.text)) # Test the STOP command result = runner.invoke(stop, [cont_name]) result_txt = result.output.strip('\n') assert result.exit_code == 0, '[!] Application STOP failed: {}'.format(result_txt) click.echo('[*] Container {} stopped'.format(cont_name)) except requests.exceptions.ConnectionError as e: click.echo('[!] Failed to communicate with the application') click.echo(e[0]) except AssertionError as e: click.echo('[*] Test failed - {}'.format(e)) except KeyboardInterrupt, SystemExit: click.echo('[!] Aborting') else: click.echo('[*] Test succeeded') default.add_command(run) default.add_command(stop) default.add_command(test) # Functions start here def health_check(inst_name): def __check_state(): cont_state = this.client.inspect_container(inst_name)['State'] if cont_state['Status']=='running': return cont_state['Health']['Status'] else: click.echo('[!] Container is not running!') repeat = 0 while True: cont_status = __check_state() if cont_status == 'healthy': click.echo('[*] Your app is running on http://127.0.0.1:8888') return True elif cont_status == 'starting': if repeat > 6: return time.sleep(1) repeat += 1 else: click.echo('[!] Container status: {}'.format(cont_status)) return def start_container(inst_name): this.client.create_container( REGISTRY, detach=False, name=inst_name, ports=[8888], host_config=this.client.create_host_config( port_bindings={8888: ('127.0.0.1',8888)} ), ) this.client.start(inst_name) def fetch_client(base_url=BASE_URL): this.client = docker.APIClient(base_url=base_url, version='1.24') try: this.client.version() except requests.exceptions.ConnectionError as e: click.echo('[!] Unable to connect to Docker daemon @ {}'.format(BASE_URL)) sys.exit(1) if __name__=="__main__": default()
random_line_split
fields.py
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.MultipleChoiceField): widget = CommaSeparatedWidget def clean(self, value): return ','.join(super(CommaSeparatedField, self).clean(value)) class OATHPasswordField(forms.CharField): """A string of between 6 or 8 digits.""" widget = forms.widgets.TextInput(attrs={ 'autocomplete': 'off', 'autofocus': 'autofocus' }) SIX = re.compile('[0-9]{6}$') EIGHT = re.compile('[0-9]{8}$') def clean(self, value):
"""Validate otp and detect type""" # remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value): return value elif self.EIGHT.match(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
identifier_body
fields.py
# GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.MultipleChoiceField): widget = CommaSeparatedWidget def clean(self, value): return ','.join(super(CommaSeparatedField, self).clean(value)) class OATHPasswordField(forms.CharField): """A string of between 6 or 8 digits.""" widget = forms.widgets.TextInput(attrs={ 'autocomplete': 'off', 'autofocus': 'autofocus' }) SIX = re.compile('[0-9]{6}$') EIGHT = re.compile('[0-9]{8}$') def clean(self, value): """Validate otp and detect type""" # remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value): return value elif self.EIGHT.match(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
# Copyright 2010 Canonical Ltd. This software is licensed under the
random_line_split
fields.py
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.MultipleChoiceField): widget = CommaSeparatedWidget def clean(self, value): return ','.join(super(CommaSeparatedField, self).clean(value)) class OATHPasswordField(forms.CharField): """A string of between 6 or 8 digits.""" widget = forms.widgets.TextInput(attrs={ 'autocomplete': 'off', 'autofocus': 'autofocus' }) SIX = re.compile('[0-9]{6}$') EIGHT = re.compile('[0-9]{8}$') def clean(self, value): """Validate otp and detect type""" # remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value):
elif self.EIGHT.match(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
return value
conditional_block
fields.py
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.MultipleChoiceField): widget = CommaSeparatedWidget def clean(self, value): return ','.join(super(CommaSeparatedField, self).clean(value)) class
(forms.CharField): """A string of between 6 or 8 digits.""" widget = forms.widgets.TextInput(attrs={ 'autocomplete': 'off', 'autofocus': 'autofocus' }) SIX = re.compile('[0-9]{6}$') EIGHT = re.compile('[0-9]{8}$') def clean(self, value): """Validate otp and detect type""" # remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value): return value elif self.EIGHT.match(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
OATHPasswordField
identifier_name
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser 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 // use std::str::FromStr; use filters::filter::Filter; use chrono::NaiveDateTime; use libimagerror::trace::trace_error; use libimagerror::trace::MapErrTrace; use libimagerror::iter::TraceIterator; use libimagstore::store::FileLockEntry; use libimagtimetrack::timetrackingstore::TimeTrackStore; use libimagtimetrack::timetracking::TimeTracking; use libimagtimetrack::tag::TimeTrackingTag; use libimagtimetrack::iter::filter::*; use libimagrt::runtime::Runtime; pub fn year(rt: &Runtime) -> i32
{ let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) { None => NaiveDate::from_ymd(now.year(), 1, 1).and_hms(0, 0, 0), Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) { None => { NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0) }, Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let tags = cmd .values_of("tags") .map(|ts| ts.into_iter().map(String::from).map(TimeTrackingTag::from).collect()); let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| { start <= *dt }); let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| { end >= *dt }); let tags_filter = move |fle: &FileLockEntry| { match tags { Some(ref tags) => has_one_of_tags(&tags).filter(fle), None => true, } }; tags_filter.and(start_time_filter).and(end_time_filter) }; rt.store() .get_timetrackings() .and_then(|iter| { iter.trace_unwrap() .filter(|e| filter.filter(e)) .fold(Ok(()), |acc, e| { acc.and_then(|_| { debug!("Processing {:?}", e.get_location()); let tag = e.get_timetrack_tag()?; debug!(" -> tag = {:?}", tag); let start = e.get_start_datetime()?; debug!(" -> start = {:?}", start); let end = e.get_end_datetime()?; debug!(" -> end = {:?}", end); match (start, end) { (None, _) => println!("{} has no start time.", tag), (Some(s), None) => println!("{} | {} - ...", tag, s), (Some(s), Some(e)) => println!("{} | {} - {}", tag, s, e), } Ok(()) }) }) }) .map(|_| 0) .map_err_trace() .unwrap_or(1) }
identifier_body
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser 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 // use std::str::FromStr; use filters::filter::Filter; use chrono::NaiveDateTime; use libimagerror::trace::trace_error; use libimagerror::trace::MapErrTrace; use libimagerror::iter::TraceIterator; use libimagstore::store::FileLockEntry; use libimagtimetrack::timetrackingstore::TimeTrackStore; use libimagtimetrack::timetracking::TimeTracking; use libimagtimetrack::tag::TimeTrackingTag; use libimagtimetrack::iter::filter::*; use libimagrt::runtime::Runtime; pub fn year(rt: &Runtime) -> i32 { let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) { None => NaiveDate::from_ymd(now.year(), 1, 1).and_hms(0, 0, 0), Some(Ok(dt)) => dt, Some(Err(e)) =>
}; let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) { None => { NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0) }, Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let tags = cmd .values_of("tags") .map(|ts| ts.into_iter().map(String::from).map(TimeTrackingTag::from).collect()); let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| { start <= *dt }); let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| { end >= *dt }); let tags_filter = move |fle: &FileLockEntry| { match tags { Some(ref tags) => has_one_of_tags(&tags).filter(fle), None => true, } }; tags_filter.and(start_time_filter).and(end_time_filter) }; rt.store() .get_timetrackings() .and_then(|iter| { iter.trace_unwrap() .filter(|e| filter.filter(e)) .fold(Ok(()), |acc, e| { acc.and_then(|_| { debug!("Processing {:?}", e.get_location()); let tag = e.get_timetrack_tag()?; debug!(" -> tag = {:?}", tag); let start = e.get_start_datetime()?; debug!(" -> start = {:?}", start); let end = e.get_end_datetime()?; debug!(" -> end = {:?}", end); match (start, end) { (None, _) => println!("{} has no start time.", tag), (Some(s), None) => println!("{} | {} - ...", tag, s), (Some(s), Some(e)) => println!("{} | {} - {}", tag, s, e), } Ok(()) }) }) }) .map(|_| 0) .map_err_trace() .unwrap_or(1) }
{ trace_error(&e); return 1 }
conditional_block
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser 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 // use std::str::FromStr; use filters::filter::Filter; use chrono::NaiveDateTime; use libimagerror::trace::trace_error; use libimagerror::trace::MapErrTrace; use libimagerror::iter::TraceIterator; use libimagstore::store::FileLockEntry; use libimagtimetrack::timetrackingstore::TimeTrackStore; use libimagtimetrack::timetracking::TimeTracking; use libimagtimetrack::tag::TimeTrackingTag; use libimagtimetrack::iter::filter::*; use libimagrt::runtime::Runtime; pub fn
(rt: &Runtime) -> i32 { let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) { None => NaiveDate::from_ymd(now.year(), 1, 1).and_hms(0, 0, 0), Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) { None => { NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0) }, Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let tags = cmd .values_of("tags") .map(|ts| ts.into_iter().map(String::from).map(TimeTrackingTag::from).collect()); let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| { start <= *dt }); let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| { end >= *dt }); let tags_filter = move |fle: &FileLockEntry| { match tags { Some(ref tags) => has_one_of_tags(&tags).filter(fle), None => true, } }; tags_filter.and(start_time_filter).and(end_time_filter) }; rt.store() .get_timetrackings() .and_then(|iter| { iter.trace_unwrap() .filter(|e| filter.filter(e)) .fold(Ok(()), |acc, e| { acc.and_then(|_| { debug!("Processing {:?}", e.get_location()); let tag = e.get_timetrack_tag()?; debug!(" -> tag = {:?}", tag); let start = e.get_start_datetime()?; debug!(" -> start = {:?}", start); let end = e.get_end_datetime()?; debug!(" -> end = {:?}", end); match (start, end) { (None, _) => println!("{} has no start time.", tag), (Some(s), None) => println!("{} | {} - ...", tag, s), (Some(s), Some(e)) => println!("{} | {} - {}", tag, s, e), } Ok(()) }) }) }) .map(|_| 0) .map_err_trace() .unwrap_or(1) }
year
identifier_name
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser 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 // use std::str::FromStr; use filters::filter::Filter; use chrono::NaiveDateTime; use libimagerror::trace::trace_error; use libimagerror::trace::MapErrTrace; use libimagerror::iter::TraceIterator; use libimagstore::store::FileLockEntry; use libimagtimetrack::timetrackingstore::TimeTrackStore; use libimagtimetrack::timetracking::TimeTracking; use libimagtimetrack::tag::TimeTrackingTag; use libimagtimetrack::iter::filter::*; use libimagrt::runtime::Runtime; pub fn year(rt: &Runtime) -> i32 { let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local;
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) { None => NaiveDate::from_ymd(now.year(), 1, 1).and_hms(0, 0, 0), Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) { None => { NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0) }, Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; let tags = cmd .values_of("tags") .map(|ts| ts.into_iter().map(String::from).map(TimeTrackingTag::from).collect()); let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| { start <= *dt }); let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| { end >= *dt }); let tags_filter = move |fle: &FileLockEntry| { match tags { Some(ref tags) => has_one_of_tags(&tags).filter(fle), None => true, } }; tags_filter.and(start_time_filter).and(end_time_filter) }; rt.store() .get_timetrackings() .and_then(|iter| { iter.trace_unwrap() .filter(|e| filter.filter(e)) .fold(Ok(()), |acc, e| { acc.and_then(|_| { debug!("Processing {:?}", e.get_location()); let tag = e.get_timetrack_tag()?; debug!(" -> tag = {:?}", tag); let start = e.get_start_datetime()?; debug!(" -> start = {:?}", start); let end = e.get_end_datetime()?; debug!(" -> end = {:?}", end); match (start, end) { (None, _) => println!("{} has no start time.", tag), (Some(s), None) => println!("{} | {} - ...", tag, s), (Some(s), Some(e)) => println!("{} | {} - {}", tag, s, e), } Ok(()) }) }) }) .map(|_| 0) .map_err_trace() .unwrap_or(1) }
use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now();
random_line_split
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def getActionScore(action): if action == "rec": return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data):
def compute_user_history_interaction(trainFile): records = [] lineList = [] lineNum = 1 result = [] lineList = [line for line in file(trainFile)] for line in lineList: if lineNum == 1: #ignore the title in first line lineNum += 1 continue records.append(line) lineNum += 1 interaction = compute_interaction(records) out = file('user_interaction.txt', 'w') for (key, times) in interaction.items(): out.write('%s %d' % (key, times)) out.write('\n') for (key, times) in interaction.items(): user, action = key.split(' '); result.append((user, action, times)) return result #get the weight for each type of action def get_action_weight(action): pop = 0; if action == "rec": pop = 1 elif action == "click": pop = 10 elif action == "msg": pop = 100 return pop; #trainFile line like: [userA, userB, action_times, action_type(rec|click|msg)] def compute_user_popularity(trainFile, user_popularity_file): popDict = {} rankedscores = [] result = [] print "-----compute_user_history_interaction ... " interaction = compute_user_history_interaction(trainFile) print "-----compute_user_popularity ... " for (user, action, times) in interaction[0:len(interaction)]: popDict.setdefault(user, 0) popDict[user] += get_action_weight(action) * times ranked_popularity = [(popularity, user) for (user, popularity) in popDict.items()] ranked_popularity.sort() ranked_popularity.reverse() print "-----ranking_user_popularity ... " result = [(user, popularity) for (popularity, user) in ranked_popularity[0:len(ranked_popularity)]] print "-----output user_popularity ... " out = file(user_popularity_file, 'w') for (user, popularity) in result[0:len(result)]: out.write('%s %d\n' % (user, popularity)) print "-----Ending ... " return result
interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.setdefault(key, 0) interaction[key] += 1 return interaction
identifier_body
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def getActionScore(action):
return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data): interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.setdefault(key, 0) interaction[key] += 1 return interaction def compute_user_history_interaction(trainFile): records = [] lineList = [] lineNum = 1 result = [] lineList = [line for line in file(trainFile)] for line in lineList: if lineNum == 1: #ignore the title in first line lineNum += 1 continue records.append(line) lineNum += 1 interaction = compute_interaction(records) out = file('user_interaction.txt', 'w') for (key, times) in interaction.items(): out.write('%s %d' % (key, times)) out.write('\n') for (key, times) in interaction.items(): user, action = key.split(' '); result.append((user, action, times)) return result #get the weight for each type of action def get_action_weight(action): pop = 0; if action == "rec": pop = 1 elif action == "click": pop = 10 elif action == "msg": pop = 100 return pop; #trainFile line like: [userA, userB, action_times, action_type(rec|click|msg)] def compute_user_popularity(trainFile, user_popularity_file): popDict = {} rankedscores = [] result = [] print "-----compute_user_history_interaction ... " interaction = compute_user_history_interaction(trainFile) print "-----compute_user_popularity ... " for (user, action, times) in interaction[0:len(interaction)]: popDict.setdefault(user, 0) popDict[user] += get_action_weight(action) * times ranked_popularity = [(popularity, user) for (user, popularity) in popDict.items()] ranked_popularity.sort() ranked_popularity.reverse() print "-----ranking_user_popularity ... " result = [(user, popularity) for (popularity, user) in ranked_popularity[0:len(ranked_popularity)]] print "-----output user_popularity ... " out = file(user_popularity_file, 'w') for (user, popularity) in result[0:len(result)]: out.write('%s %d\n' % (user, popularity)) print "-----Ending ... " return result
if action == "rec":
random_line_split
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def getActionScore(action): if action == "rec": return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data): interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.setdefault(key, 0) interaction[key] += 1 return interaction def compute_user_history_interaction(trainFile): records = [] lineList = [] lineNum = 1 result = [] lineList = [line for line in file(trainFile)] for line in lineList:
interaction = compute_interaction(records) out = file('user_interaction.txt', 'w') for (key, times) in interaction.items(): out.write('%s %d' % (key, times)) out.write('\n') for (key, times) in interaction.items(): user, action = key.split(' '); result.append((user, action, times)) return result #get the weight for each type of action def get_action_weight(action): pop = 0; if action == "rec": pop = 1 elif action == "click": pop = 10 elif action == "msg": pop = 100 return pop; #trainFile line like: [userA, userB, action_times, action_type(rec|click|msg)] def compute_user_popularity(trainFile, user_popularity_file): popDict = {} rankedscores = [] result = [] print "-----compute_user_history_interaction ... " interaction = compute_user_history_interaction(trainFile) print "-----compute_user_popularity ... " for (user, action, times) in interaction[0:len(interaction)]: popDict.setdefault(user, 0) popDict[user] += get_action_weight(action) * times ranked_popularity = [(popularity, user) for (user, popularity) in popDict.items()] ranked_popularity.sort() ranked_popularity.reverse() print "-----ranking_user_popularity ... " result = [(user, popularity) for (popularity, user) in ranked_popularity[0:len(ranked_popularity)]] print "-----output user_popularity ... " out = file(user_popularity_file, 'w') for (user, popularity) in result[0:len(result)]: out.write('%s %d\n' % (user, popularity)) print "-----Ending ... " return result
if lineNum == 1: #ignore the title in first line lineNum += 1 continue records.append(line) lineNum += 1
conditional_block
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def
(action): if action == "rec": return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data): interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.setdefault(key, 0) interaction[key] += 1 return interaction def compute_user_history_interaction(trainFile): records = [] lineList = [] lineNum = 1 result = [] lineList = [line for line in file(trainFile)] for line in lineList: if lineNum == 1: #ignore the title in first line lineNum += 1 continue records.append(line) lineNum += 1 interaction = compute_interaction(records) out = file('user_interaction.txt', 'w') for (key, times) in interaction.items(): out.write('%s %d' % (key, times)) out.write('\n') for (key, times) in interaction.items(): user, action = key.split(' '); result.append((user, action, times)) return result #get the weight for each type of action def get_action_weight(action): pop = 0; if action == "rec": pop = 1 elif action == "click": pop = 10 elif action == "msg": pop = 100 return pop; #trainFile line like: [userA, userB, action_times, action_type(rec|click|msg)] def compute_user_popularity(trainFile, user_popularity_file): popDict = {} rankedscores = [] result = [] print "-----compute_user_history_interaction ... " interaction = compute_user_history_interaction(trainFile) print "-----compute_user_popularity ... " for (user, action, times) in interaction[0:len(interaction)]: popDict.setdefault(user, 0) popDict[user] += get_action_weight(action) * times ranked_popularity = [(popularity, user) for (user, popularity) in popDict.items()] ranked_popularity.sort() ranked_popularity.reverse() print "-----ranking_user_popularity ... " result = [(user, popularity) for (popularity, user) in ranked_popularity[0:len(ranked_popularity)]] print "-----output user_popularity ... " out = file(user_popularity_file, 'w') for (user, popularity) in result[0:len(result)]: out.write('%s %d\n' % (user, popularity)) print "-----Ending ... " return result
getActionScore
identifier_name
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html import json, math from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App.__init__(self, *args) # do not redirect for now self.user = None self.cfg = conf self.printer = None def OnInit(self): return True @staticmethod def GetInstance(): return App.instance def Quit(self): wx.Exit() sys.exit() def Run(self): if not os.path.isfile( self.cfg.datapath ): self.setup() else: self.bootstrap() self.checkExpiration() AuthFrame(self).Show() def bootstrap(self): self.dbconn = DB.getInstance().conn self.modelUser = ModelUser( self.dbconn ) self.modelSheet= ModelSheet( self.dbconn ) self.logger = XLog.getDefaultLogger() def setup(self): try: os.makedirs( os.path.join(self.cfg.rootdir, r'data') ) os.makedirs( os.path.join(self.cfg.rootdir, r'log') ) os.makedirs( os.path.join(self.cfg.rootdir, r'cache') ) except: alert( u'程序初始化失败, 即将退出' ) self.Quit() self.bootstrap() self.modelUser.initTable() self.modelSheet.initTable() def checkExpiration(self): self.expirationTip =
self.Quit() def authOk(self, user): self.user = user self.cfg.user = user mf = MainFrame(parent=None, title=self.user['name'] + u' 你好,欢迎使用本软件') #( {} )'.format(self.expirationTip) ) mf.app = self if self.user.isAdmin(): ManagerPanel(mf, self) else: OperatorPanel(mf) mf.maxWindow() def getPrinter(self): if not self.printer: self.printer = wx.html.HtmlEasyPrinting() return self.printer def printSheet(self, sheet): # self.printViaHtml( sheet ) self.getPrinter().GetPrintData().SetPaperSize( wx.Size(-1, 400) ) self.getPrinter().GetPrintData().PaperSize = wx.Size(-1, 400) self.getPrinter().PrintText( self.getSheetHtml(sheet) ) def getSheetHtml(self, sheet): data = sheet.getDict() data['bigamount'] = cnNumber( data['amount'] ) return getPrintTpl().format( **data ) def printViaHtml(self, sheet): filepath = os.path.join(self.cfg.cachepath, "{}.html".format(sheet['id']) ) file = open(filepath, 'wb') file.write( self.getSheetHtml(sheet).encode('utf-8') ) file.close() webbrowser.open(filepath) # if '__main__'==__name__: app = App(config, False) # True, os.path.join(ctx.dir, 'run.dat') ) App.instance = app config.app = app app.Run() app.MainLoop()
'' return True # skip expiration check self.appExpireInDays = self.cfg.expiration time0 = self.modelUser.getEarliestDate() daysElapsed = 0 if time0>0: daysElapsed = int( (time.time()-time0)/86400 ) if daysElapsed > -1: if self.appExpireInDays < daysElapsed: self.expire() self.appExpireInDays -= daysElapsed daysElapsed self.expirationTip = u'试用版,{}天后过期'.format(self.appExpireInDays) else: self.expire(u'×系统时间混乱×\n程序退出') def expire(self): alert(u'本软件已过期,\n不能继续使用', u'试用过期啦~')
identifier_body
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html import json, math from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App.__init__(self, *args) # do not redirect for now self.user = None self.cfg = conf self.printer = None def OnInit(self): return True @staticmethod def GetInstance(): return App.instance def Quit(self): wx.Exit() sys.exit() def Run(self): if not os.path.isfile( self.cfg.datapath ): self.setup() else: self.bootstrap() self.checkExpiration() AuthFrame(self).Show() def bootstrap(self): self.dbconn = DB.getInstance().conn self.modelUser = ModelUser( self.dbconn ) self.modelSheet= ModelSheet( self.dbconn ) self.logger = XLog.getDefaultLogger() def setup(self): try: os.makedirs( os.path.join(self.cfg.rootdir, r'data') ) os.makedirs( os.path.join(self.cfg.rootdir, r'log') ) os.makedirs( os.path.join(self.cfg.rootdir, r'cache') ) except: alert( u'程序初始化失败, 即将退出' ) self.Quit() self.bootstrap() self.modelUser.initTable() self.modelSheet.initTable() def checkExpiration(self): self.expirationTip = '' return True # skip expiration check self.appExpireInDays = self.cfg.expiration time0 = self.modelUser.getEarliestDate() daysElapsed = 0 if time0>0: daysElapsed = int( (time.time()-time0)/86400 ) if daysElapsed > -1: if self.appExpireInDays < daysElapsed: self.expire() self.appExpireInDays -= daysElapsed daysElapsed self.expirationTip = u'试用版,{}天后过期'.format(self.appExpireInDays) else: self.expire(u'×系统时间混乱×\n程序退出') def expire(self): alert(u'本软件已过期,\n不能继续使用', u'试用过期啦~') self.Quit() def authOk(self, user): self.user = user self.cfg.user = user mf = MainFrame(parent=None, title=self.user['name'] + u' 你好,欢迎使用本软件') #( {} )'.format(self.expirationTip) ) mf.app = self if self.user.isAdmin(): ManagerPanel(mf, self) else: OperatorPanel(mf) mf.maxWindow() def getPrinter(self): if not self.printer: self.printer = wx.html.HtmlEasyPrinting() return self.printer def printSheet(self, sheet): # self.printViaHtml(
().SetPaperSize( wx.Size(-1, 400) ) self.getPrinter().GetPrintData().PaperSize = wx.Size(-1, 400) self.getPrinter().PrintText( self.getSheetHtml(sheet) ) def getSheetHtml(self, sheet): data = sheet.getDict() data['bigamount'] = cnNumber( data['amount'] ) return getPrintTpl().format( **data ) def printViaHtml(self, sheet): filepath = os.path.join(self.cfg.cachepath, "{}.html".format(sheet['id']) ) file = open(filepath, 'wb') file.write( self.getSheetHtml(sheet).encode('utf-8') ) file.close() webbrowser.open(filepath) # if '__main__'==__name__: app = App(config, False) # True, os.path.join(ctx.dir, 'run.dat') ) App.instance = app config.app = app app.Run() app.MainLoop()
sheet ) self.getPrinter().GetPrintData
conditional_block
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html
from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App.__init__(self, *args) # do not redirect for now self.user = None self.cfg = conf self.printer = None def OnInit(self): return True @staticmethod def GetInstance(): return App.instance def Quit(self): wx.Exit() sys.exit() def Run(self): if not os.path.isfile( self.cfg.datapath ): self.setup() else: self.bootstrap() self.checkExpiration() AuthFrame(self).Show() def bootstrap(self): self.dbconn = DB.getInstance().conn self.modelUser = ModelUser( self.dbconn ) self.modelSheet= ModelSheet( self.dbconn ) self.logger = XLog.getDefaultLogger() def setup(self): try: os.makedirs( os.path.join(self.cfg.rootdir, r'data') ) os.makedirs( os.path.join(self.cfg.rootdir, r'log') ) os.makedirs( os.path.join(self.cfg.rootdir, r'cache') ) except: alert( u'程序初始化失败, 即将退出' ) self.Quit() self.bootstrap() self.modelUser.initTable() self.modelSheet.initTable() def checkExpiration(self): self.expirationTip = '' return True # skip expiration check self.appExpireInDays = self.cfg.expiration time0 = self.modelUser.getEarliestDate() daysElapsed = 0 if time0>0: daysElapsed = int( (time.time()-time0)/86400 ) if daysElapsed > -1: if self.appExpireInDays < daysElapsed: self.expire() self.appExpireInDays -= daysElapsed daysElapsed self.expirationTip = u'试用版,{}天后过期'.format(self.appExpireInDays) else: self.expire(u'×系统时间混乱×\n程序退出') def expire(self): alert(u'本软件已过期,\n不能继续使用', u'试用过期啦~') self.Quit() def authOk(self, user): self.user = user self.cfg.user = user mf = MainFrame(parent=None, title=self.user['name'] + u' 你好,欢迎使用本软件') #( {} )'.format(self.expirationTip) ) mf.app = self if self.user.isAdmin(): ManagerPanel(mf, self) else: OperatorPanel(mf) mf.maxWindow() def getPrinter(self): if not self.printer: self.printer = wx.html.HtmlEasyPrinting() return self.printer def printSheet(self, sheet): # self.printViaHtml( sheet ) self.getPrinter().GetPrintData().SetPaperSize( wx.Size(-1, 400) ) self.getPrinter().GetPrintData().PaperSize = wx.Size(-1, 400) self.getPrinter().PrintText( self.getSheetHtml(sheet) ) def getSheetHtml(self, sheet): data = sheet.getDict() data['bigamount'] = cnNumber( data['amount'] ) return getPrintTpl().format( **data ) def printViaHtml(self, sheet): filepath = os.path.join(self.cfg.cachepath, "{}.html".format(sheet['id']) ) file = open(filepath, 'wb') file.write( self.getSheetHtml(sheet).encode('utf-8') ) file.close() webbrowser.open(filepath) # if '__main__'==__name__: app = App(config, False) # True, os.path.join(ctx.dir, 'run.dat') ) App.instance = app config.app = app app.Run() app.MainLoop()
import json, math
random_line_split
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html import json, math from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App.__init__(self, *args) # do not redirect for now self.user = None self.cfg = conf self.printer = None def OnInit(self): return True @staticmethod def GetInstance(): return App.instance def Quit(self): wx.Exit() sys.exit() def
(self): if not os.path.isfile( self.cfg.datapath ): self.setup() else: self.bootstrap() self.checkExpiration() AuthFrame(self).Show() def bootstrap(self): self.dbconn = DB.getInstance().conn self.modelUser = ModelUser( self.dbconn ) self.modelSheet= ModelSheet( self.dbconn ) self.logger = XLog.getDefaultLogger() def setup(self): try: os.makedirs( os.path.join(self.cfg.rootdir, r'data') ) os.makedirs( os.path.join(self.cfg.rootdir, r'log') ) os.makedirs( os.path.join(self.cfg.rootdir, r'cache') ) except: alert( u'程序初始化失败, 即将退出' ) self.Quit() self.bootstrap() self.modelUser.initTable() self.modelSheet.initTable() def checkExpiration(self): self.expirationTip = '' return True # skip expiration check self.appExpireInDays = self.cfg.expiration time0 = self.modelUser.getEarliestDate() daysElapsed = 0 if time0>0: daysElapsed = int( (time.time()-time0)/86400 ) if daysElapsed > -1: if self.appExpireInDays < daysElapsed: self.expire() self.appExpireInDays -= daysElapsed daysElapsed self.expirationTip = u'试用版,{}天后过期'.format(self.appExpireInDays) else: self.expire(u'×系统时间混乱×\n程序退出') def expire(self): alert(u'本软件已过期,\n不能继续使用', u'试用过期啦~') self.Quit() def authOk(self, user): self.user = user self.cfg.user = user mf = MainFrame(parent=None, title=self.user['name'] + u' 你好,欢迎使用本软件') #( {} )'.format(self.expirationTip) ) mf.app = self if self.user.isAdmin(): ManagerPanel(mf, self) else: OperatorPanel(mf) mf.maxWindow() def getPrinter(self): if not self.printer: self.printer = wx.html.HtmlEasyPrinting() return self.printer def printSheet(self, sheet): # self.printViaHtml( sheet ) self.getPrinter().GetPrintData().SetPaperSize( wx.Size(-1, 400) ) self.getPrinter().GetPrintData().PaperSize = wx.Size(-1, 400) self.getPrinter().PrintText( self.getSheetHtml(sheet) ) def getSheetHtml(self, sheet): data = sheet.getDict() data['bigamount'] = cnNumber( data['amount'] ) return getPrintTpl().format( **data ) def printViaHtml(self, sheet): filepath = os.path.join(self.cfg.cachepath, "{}.html".format(sheet['id']) ) file = open(filepath, 'wb') file.write( self.getSheetHtml(sheet).encode('utf-8') ) file.close() webbrowser.open(filepath) # if '__main__'==__name__: app = App(config, False) # True, os.path.join(ctx.dir, 'run.dat') ) App.instance = app config.app = app app.Run() app.MainLoop()
Run
identifier_name
PanelHeaderButton.js
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "primary", "label"]; import { createScopedElement } from "../../lib/jsxRuntime"; import Tappable from "../Tappable/Tappable"; import { getClassName } from "../../helpers/getClassName"; import { classNames } from "../../lib/classNames"; import { usePlatform } from "../../hooks/usePlatform"; import { isPrimitiveReactNode } from "../../lib/utils"; import { IOS, VKCOM, ANDROID } from "../../lib/platform"; import Text from "../Typography/Text/Text"; import Title from "../Typography/Title/Title"; var ButtonTypography = function ButtonTypography(_ref) { var primary = _ref.primary, children = _ref.children; var platform = usePlatform(); if (platform === IOS) { return createScopedElement(Title, { Component: "span", level: "3", weight: primary ? "semibold" : "regular" }, children); } return createScopedElement(Text, { weight: platform === VKCOM ? "regular" : "medium" }, children); }; export var PanelHeaderButton = function PanelHeaderButton(_ref2) { var children = _ref2.children, primary = _ref2.primary, label = _ref2.label, restProps = _objectWithoutProperties(_ref2, _excluded); var isPrimitive = isPrimitiveReactNode(children); var isPrimitiveLabel = isPrimitiveReactNode(label); var platform = usePlatform(); var hoverMode; var activeMode; switch (platform) { case ANDROID: hoverMode = "background"; activeMode = "background"; break; case IOS:
case VKCOM: hoverMode = "PanelHeaderButton--hover"; activeMode = "PanelHeaderButton--active"; } return createScopedElement(Tappable, _extends({}, restProps, { hoverMode: hoverMode, Component: restProps.href ? "a" : "button", activeEffectDelay: 200, activeMode: activeMode, vkuiClass: classNames(getClassName("PanelHeaderButton", platform), { "PanelHeaderButton--primary": primary, "PanelHeaderButton--primitive": isPrimitive, "PanelHeaderButton--notPrimitive": !isPrimitive && !isPrimitiveLabel }) }), isPrimitive ? createScopedElement(ButtonTypography, { primary: primary }, children) : children, isPrimitiveLabel ? createScopedElement(ButtonTypography, { primary: primary }, label) : label); }; PanelHeaderButton.defaultProps = { primary: false, "aria-label": "Закрыть" }; //# sourceMappingURL=PanelHeaderButton.js.map
hoverMode = "background"; activeMode = "opacity"; break;
random_line_split
PanelHeaderButton.js
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "primary", "label"]; import { createScopedElement } from "../../lib/jsxRuntime"; import Tappable from "../Tappable/Tappable"; import { getClassName } from "../../helpers/getClassName"; import { classNames } from "../../lib/classNames"; import { usePlatform } from "../../hooks/usePlatform"; import { isPrimitiveReactNode } from "../../lib/utils"; import { IOS, VKCOM, ANDROID } from "../../lib/platform"; import Text from "../Typography/Text/Text"; import Title from "../Typography/Title/Title"; var ButtonTypography = function ButtonTypography(_ref) { var primary = _ref.primary, children = _ref.children; var platform = usePlatform(); if (platform === IOS)
return createScopedElement(Text, { weight: platform === VKCOM ? "regular" : "medium" }, children); }; export var PanelHeaderButton = function PanelHeaderButton(_ref2) { var children = _ref2.children, primary = _ref2.primary, label = _ref2.label, restProps = _objectWithoutProperties(_ref2, _excluded); var isPrimitive = isPrimitiveReactNode(children); var isPrimitiveLabel = isPrimitiveReactNode(label); var platform = usePlatform(); var hoverMode; var activeMode; switch (platform) { case ANDROID: hoverMode = "background"; activeMode = "background"; break; case IOS: hoverMode = "background"; activeMode = "opacity"; break; case VKCOM: hoverMode = "PanelHeaderButton--hover"; activeMode = "PanelHeaderButton--active"; } return createScopedElement(Tappable, _extends({}, restProps, { hoverMode: hoverMode, Component: restProps.href ? "a" : "button", activeEffectDelay: 200, activeMode: activeMode, vkuiClass: classNames(getClassName("PanelHeaderButton", platform), { "PanelHeaderButton--primary": primary, "PanelHeaderButton--primitive": isPrimitive, "PanelHeaderButton--notPrimitive": !isPrimitive && !isPrimitiveLabel }) }), isPrimitive ? createScopedElement(ButtonTypography, { primary: primary }, children) : children, isPrimitiveLabel ? createScopedElement(ButtonTypography, { primary: primary }, label) : label); }; PanelHeaderButton.defaultProps = { primary: false, "aria-label": "Закрыть" }; //# sourceMappingURL=PanelHeaderButton.js.map
{ return createScopedElement(Title, { Component: "span", level: "3", weight: primary ? "semibold" : "regular" }, children); }
conditional_block
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import MySQLdb import MySQLdb.cursors from airflow.hooks.dbapi_hook import DbApiHook class MySqlHook(DbApiHook): """ Interact with MySQL. You can specify charset in the extra field of your connection as ``{"charset": "utf8"}``. Also you can choose cursor as ``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details. Note: For AWS IAM authentication, use iam in the extra connection parameters and set it to true. Leave the password field empty. This will use the "aws_default" connection to get the temporary token unless you override in extras. extras example: ``{"iam":true, "aws_conn_id":"my_aws_conn"}`` """ conn_name_attr = 'mysql_conn_id' default_conn_name = 'mysql_default' supports_autocommit = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.schema = kwargs.pop("schema", None) self.connection = kwargs.pop("connection", None) def set_autocommit(self, conn, autocommit): """ MySql connection sets autocommit in a different way. """ conn.autocommit(autocommit) def get_autocommit(self, conn): """ MySql connection gets autocommit in a different way. :param conn: connection to get autocommit setting from. :type conn: connection object. :return: connection autocommit setting :rtype: bool """ return conn.get_autocommit() def get_conn(self): """ Returns a mysql connection object """ conn = self.connection or self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '', "host": conn.host or 'localhost', "db": self.schema or conn.schema or '' } # check for authentication via AWS IAM if conn.extra_dejson.get('iam', False): conn_config['passwd'], conn.port = self.get_iam_token(conn) conn_config["read_default_group"] = 'enable-cleartext-plugin' if not conn.port: conn_config["port"] = 3306 else: conn_config["port"] = int(conn.port) if conn.extra_dejson.get('charset', False): conn_config["charset"] = conn.extra_dejson["charset"] if (conn_config["charset"]).lower() == 'utf8' or\ (conn_config["charset"]).lower() == 'utf-8': conn_config["use_unicode"] = True if conn.extra_dejson.get('cursor', False): if (conn.extra_dejson["cursor"]).lower() == 'sscursor': conn_config["cursorclass"] = MySQLdb.cursors.SSCursor elif (conn.extra_dejson["cursor"]).lower() == 'dictcursor': conn_config["cursorclass"] = MySQLdb.cursors.DictCursor elif (conn.extra_dejson["cursor"]).lower() == 'ssdictcursor': conn_config["cursorclass"] = MySQLdb.cursors.SSDictCursor local_infile = conn.extra_dejson.get('local_infile', False) if conn.extra_dejson.get('ssl', False): # SSL parameter for MySQL has to be a dictionary and in case # of extra/dejson we can get string if extra is passed via # URL parameters dejson_ssl = conn.extra_dejson['ssl'] if isinstance(dejson_ssl, str):
conn_config['ssl'] = dejson_ssl if conn.extra_dejson.get('unix_socket'): conn_config['unix_socket'] = conn.extra_dejson['unix_socket'] if local_infile: conn_config["local_infile"] = 1 conn = MySQLdb.connect(**conn_config) return conn def bulk_load(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' INTO TABLE {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() def bulk_dump(self, table, tmp_file): """ Dumps a database table into a tab-delimited file """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" SELECT * INTO OUTFILE '{tmp_file}' FROM {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() @staticmethod def _serialize_cell(cell, conn): """ MySQLdb converts an argument to a literal when passing those separately to execute. Hence, this method does nothing. :param cell: The cell to insert into the table :type cell: object :param conn: The database connection :type conn: connection object :return: The same cell :rtype: object """ return cell def get_iam_token(self, conn): """ Uses AWSHook to retrieve a temporary password to connect to MySQL Port is required. If none is provided, default 3306 is used """ from airflow.contrib.hooks.aws_hook import AwsHook aws_conn_id = conn.extra_dejson.get('aws_conn_id', 'aws_default') aws_hook = AwsHook(aws_conn_id) if conn.port is None: port = 3306 else: port = conn.port client = aws_hook.get_client_type('rds') token = client.generate_db_auth_token(conn.host, port, conn.login) return token, port def bulk_load_custom(self, table, tmp_file, duplicate_key_handling='IGNORE', extra_options=''): """ A more configurable way to load local data from a file into the database. .. warning:: According to the mysql docs using this function is a `security risk <https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html>`_. If you want to use it anyway you can do so by setting a client-side + server-side option. This depends on the mysql client library used. :param table: The table were the file will be loaded into. :type table: str :param tmp_file: The file (name) that contains the data. :type tmp_file: str :param duplicate_key_handling: Specify what should happen to duplicate data. You can choose either `IGNORE` or `REPLACE`. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-duplicate-key-handling :type duplicate_key_handling: str :param extra_options: More sql options to specify exactly how to load the data. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html :type extra_options: str """ conn = self.get_conn() cursor = conn.cursor() cursor.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' {duplicate_key_handling} INTO TABLE {table} {extra_options} """.format( tmp_file=tmp_file, table=table, duplicate_key_handling=duplicate_key_handling, extra_options=extra_options )) cursor.close() conn.commit()
dejson_ssl = json.loads(dejson_ssl)
conditional_block
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import MySQLdb import MySQLdb.cursors from airflow.hooks.dbapi_hook import DbApiHook class MySqlHook(DbApiHook): """ Interact with MySQL. You can specify charset in the extra field of your connection as ``{"charset": "utf8"}``. Also you can choose cursor as ``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details. Note: For AWS IAM authentication, use iam in the extra connection parameters and set it to true. Leave the password field empty. This will use the "aws_default" connection to get the temporary token unless you override in extras. extras example: ``{"iam":true, "aws_conn_id":"my_aws_conn"}`` """ conn_name_attr = 'mysql_conn_id' default_conn_name = 'mysql_default' supports_autocommit = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.schema = kwargs.pop("schema", None) self.connection = kwargs.pop("connection", None) def set_autocommit(self, conn, autocommit): """ MySql connection sets autocommit in a different way. """ conn.autocommit(autocommit) def get_autocommit(self, conn): """ MySql connection gets autocommit in a different way. :param conn: connection to get autocommit setting from. :type conn: connection object. :return: connection autocommit setting :rtype: bool """ return conn.get_autocommit() def get_conn(self): """ Returns a mysql connection object """ conn = self.connection or self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '', "host": conn.host or 'localhost', "db": self.schema or conn.schema or '' } # check for authentication via AWS IAM if conn.extra_dejson.get('iam', False): conn_config['passwd'], conn.port = self.get_iam_token(conn) conn_config["read_default_group"] = 'enable-cleartext-plugin' if not conn.port: conn_config["port"] = 3306 else: conn_config["port"] = int(conn.port) if conn.extra_dejson.get('charset', False): conn_config["charset"] = conn.extra_dejson["charset"] if (conn_config["charset"]).lower() == 'utf8' or\ (conn_config["charset"]).lower() == 'utf-8': conn_config["use_unicode"] = True if conn.extra_dejson.get('cursor', False): if (conn.extra_dejson["cursor"]).lower() == 'sscursor': conn_config["cursorclass"] = MySQLdb.cursors.SSCursor elif (conn.extra_dejson["cursor"]).lower() == 'dictcursor': conn_config["cursorclass"] = MySQLdb.cursors.DictCursor elif (conn.extra_dejson["cursor"]).lower() == 'ssdictcursor': conn_config["cursorclass"] = MySQLdb.cursors.SSDictCursor local_infile = conn.extra_dejson.get('local_infile', False) if conn.extra_dejson.get('ssl', False): # SSL parameter for MySQL has to be a dictionary and in case # of extra/dejson we can get string if extra is passed via # URL parameters dejson_ssl = conn.extra_dejson['ssl'] if isinstance(dejson_ssl, str): dejson_ssl = json.loads(dejson_ssl) conn_config['ssl'] = dejson_ssl if conn.extra_dejson.get('unix_socket'): conn_config['unix_socket'] = conn.extra_dejson['unix_socket'] if local_infile: conn_config["local_infile"] = 1 conn = MySQLdb.connect(**conn_config) return conn def
(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' INTO TABLE {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() def bulk_dump(self, table, tmp_file): """ Dumps a database table into a tab-delimited file """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" SELECT * INTO OUTFILE '{tmp_file}' FROM {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() @staticmethod def _serialize_cell(cell, conn): """ MySQLdb converts an argument to a literal when passing those separately to execute. Hence, this method does nothing. :param cell: The cell to insert into the table :type cell: object :param conn: The database connection :type conn: connection object :return: The same cell :rtype: object """ return cell def get_iam_token(self, conn): """ Uses AWSHook to retrieve a temporary password to connect to MySQL Port is required. If none is provided, default 3306 is used """ from airflow.contrib.hooks.aws_hook import AwsHook aws_conn_id = conn.extra_dejson.get('aws_conn_id', 'aws_default') aws_hook = AwsHook(aws_conn_id) if conn.port is None: port = 3306 else: port = conn.port client = aws_hook.get_client_type('rds') token = client.generate_db_auth_token(conn.host, port, conn.login) return token, port def bulk_load_custom(self, table, tmp_file, duplicate_key_handling='IGNORE', extra_options=''): """ A more configurable way to load local data from a file into the database. .. warning:: According to the mysql docs using this function is a `security risk <https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html>`_. If you want to use it anyway you can do so by setting a client-side + server-side option. This depends on the mysql client library used. :param table: The table were the file will be loaded into. :type table: str :param tmp_file: The file (name) that contains the data. :type tmp_file: str :param duplicate_key_handling: Specify what should happen to duplicate data. You can choose either `IGNORE` or `REPLACE`. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-duplicate-key-handling :type duplicate_key_handling: str :param extra_options: More sql options to specify exactly how to load the data. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html :type extra_options: str """ conn = self.get_conn() cursor = conn.cursor() cursor.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' {duplicate_key_handling} INTO TABLE {table} {extra_options} """.format( tmp_file=tmp_file, table=table, duplicate_key_handling=duplicate_key_handling, extra_options=extra_options )) cursor.close() conn.commit()
bulk_load
identifier_name
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import MySQLdb import MySQLdb.cursors from airflow.hooks.dbapi_hook import DbApiHook class MySqlHook(DbApiHook): """ Interact with MySQL. You can specify charset in the extra field of your connection as ``{"charset": "utf8"}``. Also you can choose cursor as ``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details. Note: For AWS IAM authentication, use iam in the extra connection parameters and set it to true. Leave the password field empty. This will use the "aws_default" connection to get the temporary token unless you override in extras. extras example: ``{"iam":true, "aws_conn_id":"my_aws_conn"}`` """ conn_name_attr = 'mysql_conn_id' default_conn_name = 'mysql_default' supports_autocommit = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.schema = kwargs.pop("schema", None) self.connection = kwargs.pop("connection", None) def set_autocommit(self, conn, autocommit): """ MySql connection sets autocommit in a different way. """ conn.autocommit(autocommit) def get_autocommit(self, conn): """ MySql connection gets autocommit in a different way. :param conn: connection to get autocommit setting from. :type conn: connection object. :return: connection autocommit setting :rtype: bool """ return conn.get_autocommit() def get_conn(self): """ Returns a mysql connection object """ conn = self.connection or self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '', "host": conn.host or 'localhost', "db": self.schema or conn.schema or '' } # check for authentication via AWS IAM if conn.extra_dejson.get('iam', False): conn_config['passwd'], conn.port = self.get_iam_token(conn) conn_config["read_default_group"] = 'enable-cleartext-plugin' if not conn.port: conn_config["port"] = 3306 else: conn_config["port"] = int(conn.port) if conn.extra_dejson.get('charset', False): conn_config["charset"] = conn.extra_dejson["charset"] if (conn_config["charset"]).lower() == 'utf8' or\ (conn_config["charset"]).lower() == 'utf-8': conn_config["use_unicode"] = True if conn.extra_dejson.get('cursor', False): if (conn.extra_dejson["cursor"]).lower() == 'sscursor': conn_config["cursorclass"] = MySQLdb.cursors.SSCursor elif (conn.extra_dejson["cursor"]).lower() == 'dictcursor': conn_config["cursorclass"] = MySQLdb.cursors.DictCursor elif (conn.extra_dejson["cursor"]).lower() == 'ssdictcursor': conn_config["cursorclass"] = MySQLdb.cursors.SSDictCursor local_infile = conn.extra_dejson.get('local_infile', False) if conn.extra_dejson.get('ssl', False): # SSL parameter for MySQL has to be a dictionary and in case # of extra/dejson we can get string if extra is passed via # URL parameters dejson_ssl = conn.extra_dejson['ssl'] if isinstance(dejson_ssl, str): dejson_ssl = json.loads(dejson_ssl) conn_config['ssl'] = dejson_ssl if conn.extra_dejson.get('unix_socket'): conn_config['unix_socket'] = conn.extra_dejson['unix_socket'] if local_infile: conn_config["local_infile"] = 1 conn = MySQLdb.connect(**conn_config) return conn def bulk_load(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' INTO TABLE {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() def bulk_dump(self, table, tmp_file): """ Dumps a database table into a tab-delimited file """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" SELECT * INTO OUTFILE '{tmp_file}' FROM {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() @staticmethod def _serialize_cell(cell, conn):
def get_iam_token(self, conn): """ Uses AWSHook to retrieve a temporary password to connect to MySQL Port is required. If none is provided, default 3306 is used """ from airflow.contrib.hooks.aws_hook import AwsHook aws_conn_id = conn.extra_dejson.get('aws_conn_id', 'aws_default') aws_hook = AwsHook(aws_conn_id) if conn.port is None: port = 3306 else: port = conn.port client = aws_hook.get_client_type('rds') token = client.generate_db_auth_token(conn.host, port, conn.login) return token, port def bulk_load_custom(self, table, tmp_file, duplicate_key_handling='IGNORE', extra_options=''): """ A more configurable way to load local data from a file into the database. .. warning:: According to the mysql docs using this function is a `security risk <https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html>`_. If you want to use it anyway you can do so by setting a client-side + server-side option. This depends on the mysql client library used. :param table: The table were the file will be loaded into. :type table: str :param tmp_file: The file (name) that contains the data. :type tmp_file: str :param duplicate_key_handling: Specify what should happen to duplicate data. You can choose either `IGNORE` or `REPLACE`. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-duplicate-key-handling :type duplicate_key_handling: str :param extra_options: More sql options to specify exactly how to load the data. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html :type extra_options: str """ conn = self.get_conn() cursor = conn.cursor() cursor.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' {duplicate_key_handling} INTO TABLE {table} {extra_options} """.format( tmp_file=tmp_file, table=table, duplicate_key_handling=duplicate_key_handling, extra_options=extra_options )) cursor.close() conn.commit()
""" MySQLdb converts an argument to a literal when passing those separately to execute. Hence, this method does nothing. :param cell: The cell to insert into the table :type cell: object :param conn: The database connection :type conn: connection object :return: The same cell :rtype: object """ return cell
identifier_body
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import MySQLdb import MySQLdb.cursors from airflow.hooks.dbapi_hook import DbApiHook class MySqlHook(DbApiHook): """ Interact with MySQL. You can specify charset in the extra field of your connection as ``{"charset": "utf8"}``. Also you can choose cursor as ``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details. Note: For AWS IAM authentication, use iam in the extra connection parameters and set it to true. Leave the password field empty. This will use the "aws_default" connection to get the temporary token unless you override in extras. extras example: ``{"iam":true, "aws_conn_id":"my_aws_conn"}`` """ conn_name_attr = 'mysql_conn_id' default_conn_name = 'mysql_default' supports_autocommit = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.schema = kwargs.pop("schema", None) self.connection = kwargs.pop("connection", None) def set_autocommit(self, conn, autocommit): """ MySql connection sets autocommit in a different way. """ conn.autocommit(autocommit) def get_autocommit(self, conn): """ MySql connection gets autocommit in a different way. :param conn: connection to get autocommit setting from. :type conn: connection object. :return: connection autocommit setting :rtype: bool """ return conn.get_autocommit() def get_conn(self): """ Returns a mysql connection object """ conn = self.connection or self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '',
"db": self.schema or conn.schema or '' } # check for authentication via AWS IAM if conn.extra_dejson.get('iam', False): conn_config['passwd'], conn.port = self.get_iam_token(conn) conn_config["read_default_group"] = 'enable-cleartext-plugin' if not conn.port: conn_config["port"] = 3306 else: conn_config["port"] = int(conn.port) if conn.extra_dejson.get('charset', False): conn_config["charset"] = conn.extra_dejson["charset"] if (conn_config["charset"]).lower() == 'utf8' or\ (conn_config["charset"]).lower() == 'utf-8': conn_config["use_unicode"] = True if conn.extra_dejson.get('cursor', False): if (conn.extra_dejson["cursor"]).lower() == 'sscursor': conn_config["cursorclass"] = MySQLdb.cursors.SSCursor elif (conn.extra_dejson["cursor"]).lower() == 'dictcursor': conn_config["cursorclass"] = MySQLdb.cursors.DictCursor elif (conn.extra_dejson["cursor"]).lower() == 'ssdictcursor': conn_config["cursorclass"] = MySQLdb.cursors.SSDictCursor local_infile = conn.extra_dejson.get('local_infile', False) if conn.extra_dejson.get('ssl', False): # SSL parameter for MySQL has to be a dictionary and in case # of extra/dejson we can get string if extra is passed via # URL parameters dejson_ssl = conn.extra_dejson['ssl'] if isinstance(dejson_ssl, str): dejson_ssl = json.loads(dejson_ssl) conn_config['ssl'] = dejson_ssl if conn.extra_dejson.get('unix_socket'): conn_config['unix_socket'] = conn.extra_dejson['unix_socket'] if local_infile: conn_config["local_infile"] = 1 conn = MySQLdb.connect(**conn_config) return conn def bulk_load(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' INTO TABLE {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() def bulk_dump(self, table, tmp_file): """ Dumps a database table into a tab-delimited file """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" SELECT * INTO OUTFILE '{tmp_file}' FROM {table} """.format(tmp_file=tmp_file, table=table)) conn.commit() @staticmethod def _serialize_cell(cell, conn): """ MySQLdb converts an argument to a literal when passing those separately to execute. Hence, this method does nothing. :param cell: The cell to insert into the table :type cell: object :param conn: The database connection :type conn: connection object :return: The same cell :rtype: object """ return cell def get_iam_token(self, conn): """ Uses AWSHook to retrieve a temporary password to connect to MySQL Port is required. If none is provided, default 3306 is used """ from airflow.contrib.hooks.aws_hook import AwsHook aws_conn_id = conn.extra_dejson.get('aws_conn_id', 'aws_default') aws_hook = AwsHook(aws_conn_id) if conn.port is None: port = 3306 else: port = conn.port client = aws_hook.get_client_type('rds') token = client.generate_db_auth_token(conn.host, port, conn.login) return token, port def bulk_load_custom(self, table, tmp_file, duplicate_key_handling='IGNORE', extra_options=''): """ A more configurable way to load local data from a file into the database. .. warning:: According to the mysql docs using this function is a `security risk <https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html>`_. If you want to use it anyway you can do so by setting a client-side + server-side option. This depends on the mysql client library used. :param table: The table were the file will be loaded into. :type table: str :param tmp_file: The file (name) that contains the data. :type tmp_file: str :param duplicate_key_handling: Specify what should happen to duplicate data. You can choose either `IGNORE` or `REPLACE`. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-duplicate-key-handling :type duplicate_key_handling: str :param extra_options: More sql options to specify exactly how to load the data. .. seealso:: https://dev.mysql.com/doc/refman/8.0/en/load-data.html :type extra_options: str """ conn = self.get_conn() cursor = conn.cursor() cursor.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' {duplicate_key_handling} INTO TABLE {table} {extra_options} """.format( tmp_file=tmp_file, table=table, duplicate_key_handling=duplicate_key_handling, extra_options=extra_options )) cursor.close() conn.commit()
"host": conn.host or 'localhost',
random_line_split
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the constants declaring what the colors are. RED = 'red' BLUE = 'blue' GREEN = 'green' ORANGE = 'orange' PURPLE = 'purple' PINK = 'pink' class Color: pass c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to refer to you as your name. c1.name = input('Hello! What is your name?\n') c2.color = [BLUE, GREEN, RED, ORANGE, PURPLE, PINK] # This randomizes what color is chosen c2.color = random.choice(c2.color) print ('Well, {0}, I am thinking of a color between blue, green, red, orange, purple and pink.'.format(c1.name)) while guesses_made < 3: c3.guess = input('Take a guess: ') guesses_made += 1 if c3.guess != c2.color: print ('Your guess is wrong.') if c3.guess == c2.color: break if c3.guess == c2.color: print ('Good job, {0}! You guessed my color in {1} guesses!'.format(c1.name, guesses_made))
program()
else: print ('Nope. The color I was thinking of was {0}'.format(c2.color)) if __name__ == "__main__":
random_line_split
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the constants declaring what the colors are. RED = 'red' BLUE = 'blue' GREEN = 'green' ORANGE = 'orange' PURPLE = 'purple' PINK = 'pink' class Color:
c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to refer to you as your name. c1.name = input('Hello! What is your name?\n') c2.color = [BLUE, GREEN, RED, ORANGE, PURPLE, PINK] # This randomizes what color is chosen c2.color = random.choice(c2.color) print ('Well, {0}, I am thinking of a color between blue, green, red, orange, purple and pink.'.format(c1.name)) while guesses_made < 3: c3.guess = input('Take a guess: ') guesses_made += 1 if c3.guess != c2.color: print ('Your guess is wrong.') if c3.guess == c2.color: break if c3.guess == c2.color: print ('Good job, {0}! You guessed my color in {1} guesses!'.format(c1.name, guesses_made)) else: print ('Nope. The color I was thinking of was {0}'.format(c2.color)) if __name__ == "__main__": program()
pass
identifier_body
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def
(): # These are the constants declaring what the colors are. RED = 'red' BLUE = 'blue' GREEN = 'green' ORANGE = 'orange' PURPLE = 'purple' PINK = 'pink' class Color: pass c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to refer to you as your name. c1.name = input('Hello! What is your name?\n') c2.color = [BLUE, GREEN, RED, ORANGE, PURPLE, PINK] # This randomizes what color is chosen c2.color = random.choice(c2.color) print ('Well, {0}, I am thinking of a color between blue, green, red, orange, purple and pink.'.format(c1.name)) while guesses_made < 3: c3.guess = input('Take a guess: ') guesses_made += 1 if c3.guess != c2.color: print ('Your guess is wrong.') if c3.guess == c2.color: break if c3.guess == c2.color: print ('Good job, {0}! You guessed my color in {1} guesses!'.format(c1.name, guesses_made)) else: print ('Nope. The color I was thinking of was {0}'.format(c2.color)) if __name__ == "__main__": program()
program
identifier_name
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the constants declaring what the colors are. RED = 'red' BLUE = 'blue' GREEN = 'green' ORANGE = 'orange' PURPLE = 'purple' PINK = 'pink' class Color: pass c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to refer to you as your name. c1.name = input('Hello! What is your name?\n') c2.color = [BLUE, GREEN, RED, ORANGE, PURPLE, PINK] # This randomizes what color is chosen c2.color = random.choice(c2.color) print ('Well, {0}, I am thinking of a color between blue, green, red, orange, purple and pink.'.format(c1.name)) while guesses_made < 3: c3.guess = input('Take a guess: ') guesses_made += 1 if c3.guess != c2.color: print ('Your guess is wrong.') if c3.guess == c2.color: break if c3.guess == c2.color:
else: print ('Nope. The color I was thinking of was {0}'.format(c2.color)) if __name__ == "__main__": program()
print ('Good job, {0}! You guessed my color in {1} guesses!'.format(c1.name, guesses_made))
conditional_block
skip_step.js
/** * @license * Copyright 2014 The Lovefield Project Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('lf.proc.SkipStep'); goog.require('lf.proc.PhysicalQueryPlanNode'); goog.require('lf.proc.Relation'); /** * @constructor @struct * @extends {lf.proc.PhysicalQueryPlanNode} */ lf.proc.SkipStep = function() { lf.proc.SkipStep.base(this, 'constructor', 1, lf.proc.PhysicalQueryPlanNode.ExecType.FIRST_CHILD); }; goog.inherits(lf.proc.SkipStep, lf.proc.PhysicalQueryPlanNode); /** @override */ lf.proc.SkipStep.prototype.toString = function() {
/** @override */ lf.proc.SkipStep.prototype.toContextString = function(context) { return this.toString().replace('?', context.skip.toString()); }; /** @override */ lf.proc.SkipStep.prototype.execInternal = function( relations, opt_journal, context) { return [new lf.proc.Relation( relations[0].entries.slice(context.skip), relations[0].getTables())]; };
return 'skip(?)'; };
random_line_split
ExplorerUrlMigrations.ts
import { Url } from "../../clientUtils/urls/Url.js" import { performUrlMigrations,
import { covidUrlMigration } from "./CovidUrlMigration.js" export enum ExplorerUrlMigrationId { legacyToGridCovidExplorer = "legacyToGridCovidExplorer", } export interface ExplorerUrlMigrationSpec { explorerSlug: string migrateUrl: (url: Url, baseQueryStr: string) => Url } export const explorerUrlMigrationsById: Record< ExplorerUrlMigrationId, ExplorerUrlMigrationSpec > = { legacyToGridCovidExplorer: legacyCovidMigrationSpec, } const explorerUrlMigrations: UrlMigration[] = [ // NOTE: The order of migrations matters! co2UrlMigration, energyUrlMigration, covidUrlMigration, ] export const migrateExplorerUrl: UrlMigration = (url: Url): Url => { return performUrlMigrations(explorerUrlMigrations, url) }
UrlMigration, } from "../../clientUtils/urls/UrlMigration.js" import { legacyCovidMigrationSpec } from "./LegacyCovidUrlMigration.js" import { co2UrlMigration } from "./CO2UrlMigration.js" import { energyUrlMigration } from "./EnergyUrlMigration.js"
random_line_split
image-alt.js
/** * @license Copyright 2017 The Lighthouse Authors. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; /** * @fileoverview Ensures <img> elements have alternate text or a role of none or presentation. * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit.js'); const i18n = require('../../lib/i18n/i18n.js'); const UIStrings = { /** Title of an accesibility audit that evaluates if all image elements have the alt HTML attribute to describe their contents. This title is descriptive of the successful state and is shown to users when no user action is required. */ title: 'Image elements have `[alt]` attributes', /** Title of an accesibility audit that evaluates if all image elements have the alt HTML attribute to describe their contents. This title is descriptive of the failing state and is shown to users when there is a failure that needs to be addressed. */ failureTitle: 'Image elements do not have `[alt]` attributes', /** Description of a Lighthouse audit that tells the user *why* they should try to pass. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ description: 'Informative elements should aim for short, descriptive alternate text. ' + 'Decorative elements can be ignored with an empty alt attribute. ' + '[Learn more](https://web.dev/image-alt/).', }; const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); class ImageAlt extends AxeAudit { /** * @return {LH.Audit.Meta} */ static get meta() { return { id: 'image-alt', title: str_(UIStrings.title),
} module.exports = ImageAlt; module.exports.UIStrings = UIStrings;
failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), requiredArtifacts: ['Accessibility'], }; }
random_line_split
image-alt.js
/** * @license Copyright 2017 The Lighthouse Authors. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; /** * @fileoverview Ensures <img> elements have alternate text or a role of none or presentation. * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit.js'); const i18n = require('../../lib/i18n/i18n.js'); const UIStrings = { /** Title of an accesibility audit that evaluates if all image elements have the alt HTML attribute to describe their contents. This title is descriptive of the successful state and is shown to users when no user action is required. */ title: 'Image elements have `[alt]` attributes', /** Title of an accesibility audit that evaluates if all image elements have the alt HTML attribute to describe their contents. This title is descriptive of the failing state and is shown to users when there is a failure that needs to be addressed. */ failureTitle: 'Image elements do not have `[alt]` attributes', /** Description of a Lighthouse audit that tells the user *why* they should try to pass. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */ description: 'Informative elements should aim for short, descriptive alternate text. ' + 'Decorative elements can be ignored with an empty alt attribute. ' + '[Learn more](https://web.dev/image-alt/).', }; const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); class ImageAlt extends AxeAudit { /** * @return {LH.Audit.Meta} */ static get
() { return { id: 'image-alt', title: str_(UIStrings.title), failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), requiredArtifacts: ['Accessibility'], }; } } module.exports = ImageAlt; module.exports.UIStrings = UIStrings;
meta
identifier_name
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def main():
if __name__ == '__main__': main()
print('Append version stamp to UBOOT.bin') latest_cl = ['0','0','0','0','0','0','0','0'] stamp_index = 0 stamp_flag_found = 0 ver_string_chip_customer="C300000" check_input() check_sum_odd=0 check_sum_even=0 check_sum_version =0 count=0 size_without_version = os.path.getsize(sys.argv[1]) - 32 target_file =open(sys.argv[1],'rb') while (count != size_without_version): byte = target_file.read(1) if byte == "": break; if count%2 == 1: check_sum_odd += ord(byte) else: check_sum_even += ord(byte) count+=1 if 0 == stamp_flag_found: if 0==stamp_index and 'M'==byte: stamp_index=1 elif 1==stamp_index and 'S'==byte: stamp_index=2 elif 2==stamp_index and 'V'==byte: stamp_index=3 elif 3==stamp_index and 'C'==byte: stamp_index=4 elif 3<stamp_index and stamp_index<22: if stamp_index>13: latest_cl[stamp_index-14]=byte stamp_index+=1 elif 22==stamp_index: stamp_index=0 stamp_flag_found=1 else: stamp_index=0 target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-32,2) target_file.write(ver_string_head+ver_string_lib+ver_string_build_number) target_file.write(bytearray(latest_cl)) print ('ChangeList:'+str(latest_cl)) target_file.write(ver_string_chip_customer) target_file.write('%c' % (check_sum_even & 0xff)) print ('check_sum_even: 0x%X' % (check_sum_even & 0xff)) target_file.write('%c' % (check_sum_odd & 0xff)) print ('check_sum_odd: 0x%X' % (check_sum_odd & 0xff)) target_file.close() count = 0 target_file =open(sys.argv[1],"r+b") target_file.seek(-32, 2) while 1: byte = target_file.read(1) if count == 31 or byte == "": break; check_sum_version += ord(byte) count+=1 check_sum_version &= 0xff check_sum_version = (0x100 - check_sum_version) & 0xff target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-1,2) target_file.write('%c' % check_sum_version) print ('check_sum_version: 0x%X' % check_sum_version) target_file.close()
identifier_body
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def main(): print('Append version stamp to UBOOT.bin') latest_cl = ['0','0','0','0','0','0','0','0'] stamp_index = 0 stamp_flag_found = 0 ver_string_chip_customer="C300000" check_input() check_sum_odd=0 check_sum_even=0 check_sum_version =0 count=0 size_without_version = os.path.getsize(sys.argv[1]) - 32 target_file =open(sys.argv[1],'rb') while (count != size_without_version): byte = target_file.read(1) if byte == "": break; if count%2 == 1: check_sum_odd += ord(byte) else: check_sum_even += ord(byte) count+=1 if 0 == stamp_flag_found: if 0==stamp_index and 'M'==byte: stamp_index=1 elif 1==stamp_index and 'S'==byte: stamp_index=2 elif 2==stamp_index and 'V'==byte: stamp_index=3 elif 3==stamp_index and 'C'==byte: stamp_index=4 elif 3<stamp_index and stamp_index<22: if stamp_index>13: latest_cl[stamp_index-14]=byte stamp_index+=1 elif 22==stamp_index: stamp_index=0 stamp_flag_found=1 else:
stamp_index=0 target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-32,2) target_file.write(ver_string_head+ver_string_lib+ver_string_build_number) target_file.write(bytearray(latest_cl)) print ('ChangeList:'+str(latest_cl)) target_file.write(ver_string_chip_customer) target_file.write('%c' % (check_sum_even & 0xff)) print ('check_sum_even: 0x%X' % (check_sum_even & 0xff)) target_file.write('%c' % (check_sum_odd & 0xff)) print ('check_sum_odd: 0x%X' % (check_sum_odd & 0xff)) target_file.close() count = 0 target_file =open(sys.argv[1],"r+b") target_file.seek(-32, 2) while 1: byte = target_file.read(1) if count == 31 or byte == "": break; check_sum_version += ord(byte) count+=1 check_sum_version &= 0xff check_sum_version = (0x100 - check_sum_version) & 0xff target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-1,2) target_file.write('%c' % check_sum_version) print ('check_sum_version: 0x%X' % check_sum_version) target_file.close() if __name__ == '__main__': main()
random_line_split
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def main(): print('Append version stamp to UBOOT.bin') latest_cl = ['0','0','0','0','0','0','0','0'] stamp_index = 0 stamp_flag_found = 0 ver_string_chip_customer="C300000" check_input() check_sum_odd=0 check_sum_even=0 check_sum_version =0 count=0 size_without_version = os.path.getsize(sys.argv[1]) - 32 target_file =open(sys.argv[1],'rb') while (count != size_without_version): byte = target_file.read(1) if byte == "": break; if count%2 == 1: check_sum_odd += ord(byte) else: check_sum_even += ord(byte) count+=1 if 0 == stamp_flag_found: if 0==stamp_index and 'M'==byte: stamp_index=1 elif 1==stamp_index and 'S'==byte:
elif 2==stamp_index and 'V'==byte: stamp_index=3 elif 3==stamp_index and 'C'==byte: stamp_index=4 elif 3<stamp_index and stamp_index<22: if stamp_index>13: latest_cl[stamp_index-14]=byte stamp_index+=1 elif 22==stamp_index: stamp_index=0 stamp_flag_found=1 else: stamp_index=0 target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-32,2) target_file.write(ver_string_head+ver_string_lib+ver_string_build_number) target_file.write(bytearray(latest_cl)) print ('ChangeList:'+str(latest_cl)) target_file.write(ver_string_chip_customer) target_file.write('%c' % (check_sum_even & 0xff)) print ('check_sum_even: 0x%X' % (check_sum_even & 0xff)) target_file.write('%c' % (check_sum_odd & 0xff)) print ('check_sum_odd: 0x%X' % (check_sum_odd & 0xff)) target_file.close() count = 0 target_file =open(sys.argv[1],"r+b") target_file.seek(-32, 2) while 1: byte = target_file.read(1) if count == 31 or byte == "": break; check_sum_version += ord(byte) count+=1 check_sum_version &= 0xff check_sum_version = (0x100 - check_sum_version) & 0xff target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-1,2) target_file.write('%c' % check_sum_version) print ('check_sum_version: 0x%X' % check_sum_version) target_file.close() if __name__ == '__main__': main()
stamp_index=2
conditional_block
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def
(): print('Append version stamp to UBOOT.bin') latest_cl = ['0','0','0','0','0','0','0','0'] stamp_index = 0 stamp_flag_found = 0 ver_string_chip_customer="C300000" check_input() check_sum_odd=0 check_sum_even=0 check_sum_version =0 count=0 size_without_version = os.path.getsize(sys.argv[1]) - 32 target_file =open(sys.argv[1],'rb') while (count != size_without_version): byte = target_file.read(1) if byte == "": break; if count%2 == 1: check_sum_odd += ord(byte) else: check_sum_even += ord(byte) count+=1 if 0 == stamp_flag_found: if 0==stamp_index and 'M'==byte: stamp_index=1 elif 1==stamp_index and 'S'==byte: stamp_index=2 elif 2==stamp_index and 'V'==byte: stamp_index=3 elif 3==stamp_index and 'C'==byte: stamp_index=4 elif 3<stamp_index and stamp_index<22: if stamp_index>13: latest_cl[stamp_index-14]=byte stamp_index+=1 elif 22==stamp_index: stamp_index=0 stamp_flag_found=1 else: stamp_index=0 target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-32,2) target_file.write(ver_string_head+ver_string_lib+ver_string_build_number) target_file.write(bytearray(latest_cl)) print ('ChangeList:'+str(latest_cl)) target_file.write(ver_string_chip_customer) target_file.write('%c' % (check_sum_even & 0xff)) print ('check_sum_even: 0x%X' % (check_sum_even & 0xff)) target_file.write('%c' % (check_sum_odd & 0xff)) print ('check_sum_odd: 0x%X' % (check_sum_odd & 0xff)) target_file.close() count = 0 target_file =open(sys.argv[1],"r+b") target_file.seek(-32, 2) while 1: byte = target_file.read(1) if count == 31 or byte == "": break; check_sum_version += ord(byte) count+=1 check_sum_version &= 0xff check_sum_version = (0x100 - check_sum_version) & 0xff target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-1,2) target_file.write('%c' % check_sum_version) print ('check_sum_version: 0x%X' % check_sum_version) target_file.close() if __name__ == '__main__': main()
main
identifier_name
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import netaddr from oslo_log import log as logging from oslo_utils import excutils from neutron.agent.l3 import dvr_fip_ns from neutron.agent.l3 import router_info as router from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import exceptions from neutron.common import utils as common_utils from neutron.i18n import _LE LOG = logging.getLogger(__name__) # xor-folding mask used for IPv6 rule index MASK_30 = 0x3fffffff class DvrLocalRouter(router.RouterInfo): def __init__(self, agent, host, *args, **kwargs): super(DvrLocalRouter, self).__init__(*args, **kwargs) self.agent = agent self.host = host self.floating_ips_dict = {} self.snat_iptables_manager = None # Linklocal subnet for router and floating IP namespace link self.rtr_fip_subnet = None self.dist_fip_count = None self.fip_ns = None def get_floating_ips(self): """Filter Floating IPs to be hosted on this agent.""" floating_ips = super(DvrLocalRouter, self).get_floating_ips() return [i for i in floating_ips if i['host'] == self.host] def get_snat_interfaces(self): return self.router.get(l3_constants.SNAT_ROUTER_INTF_KEY, []) def _handle_fip_nat_rules(self, interface_name, action): """Configures NAT rules for Floating IPs for DVR. Remove all the rules. This is safe because if use_namespaces is set as False then the agent can only configure one router, otherwise each router's NAT rules will be in their own namespace. """ self.iptables_manager.ipv4['nat'].empty_chain('POSTROUTING') self.iptables_manager.ipv4['nat'].empty_chain('snat') # Add back the jump to float-snat self.iptables_manager.ipv4['nat'].add_rule('snat', '-j $float-snat') # And add them back if the action is add_rules if action == 'add_rules' and interface_name: rule = ('POSTROUTING', '! -i %(interface_name)s ' '! -o %(interface_name)s -m conntrack ! ' '--ctstate DNAT -j ACCEPT' % {'interface_name': interface_name}) self.iptables_manager.ipv4['nat'].add_rule(*rule) self.iptables_manager.apply() def floating_ip_added_dist(self, fip, fip_cidr): """Add floating IP to FIP namespace.""" floating_ip = fip['floating_ip_address'] fixed_ip = fip['fixed_ip_address'] rule_pr = self.fip_ns.allocate_rule_priority() self.floating_ips_dict[floating_ip] = rule_pr fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.add(ip=fixed_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) #Add routing rule in fip namespace fip_ns_name = self.fip_ns.get_name() rtr_2_fip, _ = self.rtr_fip_subnet.get_pair() device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.add_route(fip_cidr, str(rtr_2_fip.ip)) interface_name = ( self.fip_ns.get_ext_device_name( self.fip_ns.agent_gateway_port['id'])) ip_lib.send_ip_addr_adv_notif(fip_ns_name, interface_name, floating_ip, self.agent_conf) # update internal structures self.dist_fip_count = self.dist_fip_count + 1 def floating_ip_removed_dist(self, fip_cidr): """Remove floating IP from FIP namespace.""" floating_ip = fip_cidr.split('/')[0] rtr_2_fip_name = self.fip_ns.get_rtr_ext_device_name(self.router_id) fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) if self.rtr_fip_subnet is None: self.rtr_fip_subnet = self.fip_ns.local_subnets.allocate( self.router_id) rtr_2_fip, fip_2_rtr = self.rtr_fip_subnet.get_pair() fip_ns_name = self.fip_ns.get_name() if floating_ip in self.floating_ips_dict: rule_pr = self.floating_ips_dict[floating_ip] ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.delete(ip=floating_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) self.fip_ns.deallocate_rule_priority(rule_pr) #TODO(rajeev): Handle else case - exception/log? device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.delete_route(fip_cidr, str(rtr_2_fip.ip)) # check if this is the last FIP for this router self.dist_fip_count = self.dist_fip_count - 1 if self.dist_fip_count == 0: #remove default route entry device = ip_lib.IPDevice(rtr_2_fip_name, namespace=self.ns_name) ns_ip = ip_lib.IPWrapper(namespace=fip_ns_name) device.route.delete_gateway(str(fip_2_rtr.ip), table=dvr_fip_ns.FIP_RT_TBL) self.fip_ns.local_subnets.release(self.router_id) self.rtr_fip_subnet = None ns_ip.del_veth(fip_2_rtr_name) is_last = self.fip_ns.unsubscribe(self.router_id) if is_last: # TODO(Carl) I can't help but think that another router could # come in and want to start using this namespace while this is # destroying it. The two could end up conflicting on # creating/destroying interfaces and such. I think I'd like a # semaphore to sync creation/deletion of this namespace. self.fip_ns.delete() self.fip_ns = None def add_floating_ip(self, fip, interface_name, device): if not self._add_fip_addr_to_device(fip, device): return l3_constants.FLOATINGIP_STATUS_ERROR # Special Handling for DVR - update FIP namespace ip_cidr = common_utils.ip_to_cidr(fip['floating_ip_address']) self.floating_ip_added_dist(fip, ip_cidr) return l3_constants.FLOATINGIP_STATUS_ACTIVE def remove_floating_ip(self, device, ip_cidr): super(DvrLocalRouter, self).remove_floating_ip(device, ip_cidr) self.floating_ip_removed_dist(ip_cidr) def _get_internal_port(self, subnet_id): """Return internal router port based on subnet_id.""" router_ports = self.router.get(l3_constants.INTERFACE_KEY, []) for port in router_ports: fips = port['fixed_ips'] for f in fips: if f['subnet_id'] == subnet_id: return port def _update_arp_entry(self, ip, mac, subnet_id, operation): """Add or delete arp entry into router namespace for the subnet.""" port = self._get_internal_port(subnet_id) # update arp entry only if the subnet is attached to the router if not port: return try: # TODO(mrsmith): optimize the calls below for bulk calls interface_name = self.get_internal_device_name(port['id']) device = ip_lib.IPDevice(interface_name, namespace=self.ns_name) if operation == 'add': device.neigh.add(ip, mac) elif operation == 'delete': device.neigh.delete(ip, mac) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("DVR: Failed updating arp entry")) def _set_subnet_arp_info(self, subnet_id): """Set ARP info retrieved from Plugin for existing ports.""" # TODO(Carl) Can we eliminate the need to make this RPC while # processing a router. subnet_ports = self.agent.get_ports_by_subnet(subnet_id) for p in subnet_ports: if p['device_owner'] not in l3_constants.ROUTER_INTERFACE_OWNERS: for fixed_ip in p['fixed_ips']: self._update_arp_entry(fixed_ip['ip_address'], p['mac_address'], subnet_id, 'add') def _map_internal_interfaces(self, int_port, snat_ports): """Return the SNAT port for the given internal interface port.""" fixed_ip = int_port['fixed_ips'][0] subnet_id = fixed_ip['subnet_id'] match_port = [p for p in snat_ports if p['fixed_ips'][0]['subnet_id'] == subnet_id] if match_port: return match_port[0] else: LOG.error(_LE('DVR: no map match_port found!')) @staticmethod def _get_snat_idx(ip_cidr): """Generate index for DVR snat rules and route tables. The index value has to be 32 bits or less but more than the system generated entries i.e. 32768. For IPv4 use the numeric value of the cidr. For IPv6 generate a crc32 bit hash and xor-fold to 30 bits. Use the freed range to extend smaller values so that they become greater than system generated entries. """ net = netaddr.IPNetwork(ip_cidr) if net.version == 6: # the crc32 & 0xffffffff is for Python 2.6 and 3.0 compatibility snat_idx = binascii.crc32(ip_cidr) & 0xffffffff # xor-fold the hash to reserve upper range to extend smaller values snat_idx = (snat_idx >> 30) ^ (snat_idx & MASK_30) if snat_idx < 32768: snat_idx = snat_idx + MASK_30 else: snat_idx = net.value return snat_idx def _delete_gateway_device_if_exists(self, ns_ip_device, gw_ip_addr, snat_idx): try: ns_ip_device.route.delete_gateway(gw_ip_addr, table=snat_idx) except exceptions.DeviceNotFoundError: pass def _snat_redirect_modify(self, gateway, sn_port, sn_int, is_add): """Adds or removes rules and routes for SNAT redirection.""" try: ns_ipr = ip_lib.IPRule(namespace=self.ns_name) ns_ipd = ip_lib.IPDevice(sn_int, namespace=self.ns_name) if is_add: ns_ipwrapr = ip_lib.IPWrapper(namespace=self.ns_name) for port_fixed_ip in sn_port['fixed_ips']: # Find the first gateway IP address matching this IP version port_ip_addr = port_fixed_ip['ip_address'] port_ip_vers = netaddr.IPAddress(port_ip_addr).version for gw_fixed_ip in gateway['fixed_ips']: gw_ip_addr = gw_fixed_ip['ip_address'] if netaddr.IPAddress(gw_ip_addr).version == port_ip_vers: sn_port_cidr = common_utils.ip_to_cidr( port_ip_addr, port_fixed_ip['prefixlen']) snat_idx = self._get_snat_idx(sn_port_cidr) if is_add: ns_ipd.route.add_gateway(gw_ip_addr, table=snat_idx) ns_ipr.rule.add(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) ns_ipwrapr.netns.execute( ['sysctl', '-w', 'net.ipv4.conf.%s.send_redirects=0' % sn_int]) else: self._delete_gateway_device_if_exists(ns_ipd, gw_ip_addr, snat_idx) ns_ipr.rule.delete(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) break except Exception: if is_add: exc = _LE('DVR: error adding redirection logic') else: exc = _LE('DVR: removed snat failed') LOG.exception(exc) def _snat_redirect_add(self, gateway, sn_port, sn_int): """Adds rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=True) def _snat_redirect_remove(self, gateway, sn_port, sn_int): """Removes rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=False) def get_gw_port_host(self): host = self.router.get('gw_port_host') if not host: LOG.debug("gw_port_host missing from router: %s", self.router['id']) return host def internal_network_added(self, port): super(DvrLocalRouter, self).internal_network_added(port) # NOTE: The following function _set_subnet_arp_info # should be called to dynamically populate the arp # entries for the dvr services ports into the router # namespace. This does not have dependency on the # external_gateway port or the agent_mode. for subnet in port['subnets']: self._set_subnet_arp_info(subnet['id']) ex_gw_port = self.get_ex_gw_port() if not ex_gw_port: return snat_ports = self.get_snat_interfaces() sn_port = self._map_internal_interfaces(port, snat_ports) if not sn_port: return interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_add(sn_port, port, interface_name) def _dvr_internal_network_removed(self, port): if not self.ex_gw_port: return sn_port = self._map_internal_interfaces(port, self.snat_ports) if not sn_port: return # DVR handling code for SNAT interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_remove(sn_port, port, interface_name) def internal_network_removed(self, port): self._dvr_internal_network_removed(port) super(DvrLocalRouter, self).internal_network_removed(port) def get_floating_agent_gw_interface(self, ext_net_id): """Filter Floating Agent GW port for the external network.""" fip_ports = self.router.get(l3_constants.FLOATINGIP_AGENT_INTF_KEY, []) return next( (p for p in fip_ports if p['network_id'] == ext_net_id), None) def get_external_device_interface_name(self, ex_gw_port): fip_int = self.fip_ns.get_int_device_name(self.router_id) if ip_lib.device_exists(fip_int, namespace=self.fip_ns.get_name()): return self.fip_ns.get_rtr_ext_device_name(self.router_id) def external_gateway_added(self, ex_gw_port, interface_name): # TODO(Carl) Refactor external_gateway_added/updated/removed to use # super class implementation where possible. Looks like preserve_ips, # and ns_name are the key differences. ip_wrapr = ip_lib.IPWrapper(namespace=self.ns_name) ip_wrapr.netns.execute(['sysctl', '-w', 'net.ipv4.conf.all.send_redirects=0']) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) id_name = self.get_internal_device_name(p['id']) if gateway: self._snat_redirect_add(gateway, p, id_name) for port in snat_ports: for ip in port['fixed_ips']: self._update_arp_entry(ip['ip_address'], port['mac_address'], ip['subnet_id'], 'add') def external_gateway_updated(self, ex_gw_port, interface_name): pass def external_gateway_removed(self, ex_gw_port, interface_name): # TODO(Carl) Should this be calling process_snat_dnat_for_fip? self.process_floating_ip_nat_rules() if self.fip_ns: to_fip_interface_name = ( self.get_external_device_interface_name(ex_gw_port)) self.process_floating_ip_addresses(to_fip_interface_name) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) internal_interface = self.get_internal_device_name(p['id']) self._snat_redirect_remove(gateway, p, internal_interface) def _handle_router_snat_rules(self, ex_gw_port, interface_name, action): if not self.snat_iptables_manager: LOG.debug("DVR router: no snat rules to be handled") return with self.snat_iptables_manager.defer_apply(): self._empty_snat_chains(self.snat_iptables_manager) # NOTE DVR doesn't add the jump to float snat like the super class. self._add_snat_rules(ex_gw_port, self.snat_iptables_manager, interface_name, action) def perform_snat_action(self, snat_callback, *args): # NOTE DVR skips this step in a few cases... if not self.get_ex_gw_port(): return if self.get_gw_port_host() != self.host: return super(DvrLocalRouter, self).perform_snat_action(snat_callback, *args) def process_external(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.create_dvr_fip_interfaces(ex_gw_port) super(DvrLocalRouter, self).process_external(agent) def create_dvr_fip_interfaces(self, ex_gw_port): floating_ips = self.get_floating_ips() fip_agent_port = self.get_floating_agent_gw_interface( ex_gw_port['network_id']) LOG.debug("FloatingIP agent gateway port received from the plugin: " "%s", fip_agent_port) is_first = False if floating_ips: is_first = self.fip_ns.subscribe(self.router_id) if is_first and not fip_agent_port: LOG.debug("No FloatingIP agent gateway port possibly due to " "late binding of the private port to the host, " "requesting agent gateway port for 'network-id' :" "%s", ex_gw_port['network_id']) fip_agent_port = self.agent.plugin_rpc.get_agent_gateway_port( self.agent.context, ex_gw_port['network_id'])
"%s"), ex_gw_port['network_id']) if is_first and fip_agent_port: if 'subnets' not in fip_agent_port: LOG.error(_LE('Missing subnet/agent_gateway_port')) else: self.fip_ns.create_gateway_port(fip_agent_port) if self.fip_ns.agent_gateway_port and floating_ips: if self.dist_fip_count == 0 or is_first: self.fip_ns.create_rtr_2_fip_link(self) # kicks the FW Agent to add rules for the IR namespace if # configured self.agent.process_router_add(self) def process(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.fip_ns = agent.get_fip_ns(ex_gw_port['network_id']) self.fip_ns.scan_fip_ports(self) super(DvrLocalRouter, self).process(agent)
if not fip_agent_port: LOG.error(_LE("No FloatingIP agent gateway port " "returned from server for 'network-id': "
random_line_split
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import netaddr from oslo_log import log as logging from oslo_utils import excutils from neutron.agent.l3 import dvr_fip_ns from neutron.agent.l3 import router_info as router from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import exceptions from neutron.common import utils as common_utils from neutron.i18n import _LE LOG = logging.getLogger(__name__) # xor-folding mask used for IPv6 rule index MASK_30 = 0x3fffffff class DvrLocalRouter(router.RouterInfo): def __init__(self, agent, host, *args, **kwargs): super(DvrLocalRouter, self).__init__(*args, **kwargs) self.agent = agent self.host = host self.floating_ips_dict = {} self.snat_iptables_manager = None # Linklocal subnet for router and floating IP namespace link self.rtr_fip_subnet = None self.dist_fip_count = None self.fip_ns = None def get_floating_ips(self): """Filter Floating IPs to be hosted on this agent.""" floating_ips = super(DvrLocalRouter, self).get_floating_ips() return [i for i in floating_ips if i['host'] == self.host] def get_snat_interfaces(self): return self.router.get(l3_constants.SNAT_ROUTER_INTF_KEY, []) def _handle_fip_nat_rules(self, interface_name, action): """Configures NAT rules for Floating IPs for DVR. Remove all the rules. This is safe because if use_namespaces is set as False then the agent can only configure one router, otherwise each router's NAT rules will be in their own namespace. """ self.iptables_manager.ipv4['nat'].empty_chain('POSTROUTING') self.iptables_manager.ipv4['nat'].empty_chain('snat') # Add back the jump to float-snat self.iptables_manager.ipv4['nat'].add_rule('snat', '-j $float-snat') # And add them back if the action is add_rules if action == 'add_rules' and interface_name: rule = ('POSTROUTING', '! -i %(interface_name)s ' '! -o %(interface_name)s -m conntrack ! ' '--ctstate DNAT -j ACCEPT' % {'interface_name': interface_name}) self.iptables_manager.ipv4['nat'].add_rule(*rule) self.iptables_manager.apply() def floating_ip_added_dist(self, fip, fip_cidr): """Add floating IP to FIP namespace.""" floating_ip = fip['floating_ip_address'] fixed_ip = fip['fixed_ip_address'] rule_pr = self.fip_ns.allocate_rule_priority() self.floating_ips_dict[floating_ip] = rule_pr fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.add(ip=fixed_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) #Add routing rule in fip namespace fip_ns_name = self.fip_ns.get_name() rtr_2_fip, _ = self.rtr_fip_subnet.get_pair() device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.add_route(fip_cidr, str(rtr_2_fip.ip)) interface_name = ( self.fip_ns.get_ext_device_name( self.fip_ns.agent_gateway_port['id'])) ip_lib.send_ip_addr_adv_notif(fip_ns_name, interface_name, floating_ip, self.agent_conf) # update internal structures self.dist_fip_count = self.dist_fip_count + 1 def floating_ip_removed_dist(self, fip_cidr): """Remove floating IP from FIP namespace.""" floating_ip = fip_cidr.split('/')[0] rtr_2_fip_name = self.fip_ns.get_rtr_ext_device_name(self.router_id) fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) if self.rtr_fip_subnet is None: self.rtr_fip_subnet = self.fip_ns.local_subnets.allocate( self.router_id) rtr_2_fip, fip_2_rtr = self.rtr_fip_subnet.get_pair() fip_ns_name = self.fip_ns.get_name() if floating_ip in self.floating_ips_dict: rule_pr = self.floating_ips_dict[floating_ip] ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.delete(ip=floating_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) self.fip_ns.deallocate_rule_priority(rule_pr) #TODO(rajeev): Handle else case - exception/log? device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.delete_route(fip_cidr, str(rtr_2_fip.ip)) # check if this is the last FIP for this router self.dist_fip_count = self.dist_fip_count - 1 if self.dist_fip_count == 0: #remove default route entry device = ip_lib.IPDevice(rtr_2_fip_name, namespace=self.ns_name) ns_ip = ip_lib.IPWrapper(namespace=fip_ns_name) device.route.delete_gateway(str(fip_2_rtr.ip), table=dvr_fip_ns.FIP_RT_TBL) self.fip_ns.local_subnets.release(self.router_id) self.rtr_fip_subnet = None ns_ip.del_veth(fip_2_rtr_name) is_last = self.fip_ns.unsubscribe(self.router_id) if is_last: # TODO(Carl) I can't help but think that another router could # come in and want to start using this namespace while this is # destroying it. The two could end up conflicting on # creating/destroying interfaces and such. I think I'd like a # semaphore to sync creation/deletion of this namespace. self.fip_ns.delete() self.fip_ns = None def add_floating_ip(self, fip, interface_name, device): if not self._add_fip_addr_to_device(fip, device): return l3_constants.FLOATINGIP_STATUS_ERROR # Special Handling for DVR - update FIP namespace ip_cidr = common_utils.ip_to_cidr(fip['floating_ip_address']) self.floating_ip_added_dist(fip, ip_cidr) return l3_constants.FLOATINGIP_STATUS_ACTIVE def remove_floating_ip(self, device, ip_cidr): super(DvrLocalRouter, self).remove_floating_ip(device, ip_cidr) self.floating_ip_removed_dist(ip_cidr) def _get_internal_port(self, subnet_id): """Return internal router port based on subnet_id.""" router_ports = self.router.get(l3_constants.INTERFACE_KEY, []) for port in router_ports: fips = port['fixed_ips'] for f in fips: if f['subnet_id'] == subnet_id: return port def _update_arp_entry(self, ip, mac, subnet_id, operation): """Add or delete arp entry into router namespace for the subnet.""" port = self._get_internal_port(subnet_id) # update arp entry only if the subnet is attached to the router if not port: return try: # TODO(mrsmith): optimize the calls below for bulk calls interface_name = self.get_internal_device_name(port['id']) device = ip_lib.IPDevice(interface_name, namespace=self.ns_name) if operation == 'add': device.neigh.add(ip, mac) elif operation == 'delete': device.neigh.delete(ip, mac) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("DVR: Failed updating arp entry")) def _set_subnet_arp_info(self, subnet_id): """Set ARP info retrieved from Plugin for existing ports.""" # TODO(Carl) Can we eliminate the need to make this RPC while # processing a router. subnet_ports = self.agent.get_ports_by_subnet(subnet_id) for p in subnet_ports: if p['device_owner'] not in l3_constants.ROUTER_INTERFACE_OWNERS: for fixed_ip in p['fixed_ips']: self._update_arp_entry(fixed_ip['ip_address'], p['mac_address'], subnet_id, 'add') def _map_internal_interfaces(self, int_port, snat_ports): """Return the SNAT port for the given internal interface port.""" fixed_ip = int_port['fixed_ips'][0] subnet_id = fixed_ip['subnet_id'] match_port = [p for p in snat_ports if p['fixed_ips'][0]['subnet_id'] == subnet_id] if match_port: return match_port[0] else: LOG.error(_LE('DVR: no map match_port found!')) @staticmethod def _get_snat_idx(ip_cidr): """Generate index for DVR snat rules and route tables. The index value has to be 32 bits or less but more than the system generated entries i.e. 32768. For IPv4 use the numeric value of the cidr. For IPv6 generate a crc32 bit hash and xor-fold to 30 bits. Use the freed range to extend smaller values so that they become greater than system generated entries. """ net = netaddr.IPNetwork(ip_cidr) if net.version == 6: # the crc32 & 0xffffffff is for Python 2.6 and 3.0 compatibility snat_idx = binascii.crc32(ip_cidr) & 0xffffffff # xor-fold the hash to reserve upper range to extend smaller values snat_idx = (snat_idx >> 30) ^ (snat_idx & MASK_30) if snat_idx < 32768: snat_idx = snat_idx + MASK_30 else: snat_idx = net.value return snat_idx def _delete_gateway_device_if_exists(self, ns_ip_device, gw_ip_addr, snat_idx): try: ns_ip_device.route.delete_gateway(gw_ip_addr, table=snat_idx) except exceptions.DeviceNotFoundError: pass def _snat_redirect_modify(self, gateway, sn_port, sn_int, is_add): """Adds or removes rules and routes for SNAT redirection.""" try: ns_ipr = ip_lib.IPRule(namespace=self.ns_name) ns_ipd = ip_lib.IPDevice(sn_int, namespace=self.ns_name) if is_add: ns_ipwrapr = ip_lib.IPWrapper(namespace=self.ns_name) for port_fixed_ip in sn_port['fixed_ips']: # Find the first gateway IP address matching this IP version port_ip_addr = port_fixed_ip['ip_address'] port_ip_vers = netaddr.IPAddress(port_ip_addr).version for gw_fixed_ip in gateway['fixed_ips']: gw_ip_addr = gw_fixed_ip['ip_address'] if netaddr.IPAddress(gw_ip_addr).version == port_ip_vers: sn_port_cidr = common_utils.ip_to_cidr( port_ip_addr, port_fixed_ip['prefixlen']) snat_idx = self._get_snat_idx(sn_port_cidr) if is_add: ns_ipd.route.add_gateway(gw_ip_addr, table=snat_idx) ns_ipr.rule.add(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) ns_ipwrapr.netns.execute( ['sysctl', '-w', 'net.ipv4.conf.%s.send_redirects=0' % sn_int]) else: self._delete_gateway_device_if_exists(ns_ipd, gw_ip_addr, snat_idx) ns_ipr.rule.delete(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) break except Exception: if is_add: exc = _LE('DVR: error adding redirection logic') else: exc = _LE('DVR: removed snat failed') LOG.exception(exc) def _snat_redirect_add(self, gateway, sn_port, sn_int): """Adds rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=True) def _snat_redirect_remove(self, gateway, sn_port, sn_int): """Removes rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=False) def
(self): host = self.router.get('gw_port_host') if not host: LOG.debug("gw_port_host missing from router: %s", self.router['id']) return host def internal_network_added(self, port): super(DvrLocalRouter, self).internal_network_added(port) # NOTE: The following function _set_subnet_arp_info # should be called to dynamically populate the arp # entries for the dvr services ports into the router # namespace. This does not have dependency on the # external_gateway port or the agent_mode. for subnet in port['subnets']: self._set_subnet_arp_info(subnet['id']) ex_gw_port = self.get_ex_gw_port() if not ex_gw_port: return snat_ports = self.get_snat_interfaces() sn_port = self._map_internal_interfaces(port, snat_ports) if not sn_port: return interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_add(sn_port, port, interface_name) def _dvr_internal_network_removed(self, port): if not self.ex_gw_port: return sn_port = self._map_internal_interfaces(port, self.snat_ports) if not sn_port: return # DVR handling code for SNAT interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_remove(sn_port, port, interface_name) def internal_network_removed(self, port): self._dvr_internal_network_removed(port) super(DvrLocalRouter, self).internal_network_removed(port) def get_floating_agent_gw_interface(self, ext_net_id): """Filter Floating Agent GW port for the external network.""" fip_ports = self.router.get(l3_constants.FLOATINGIP_AGENT_INTF_KEY, []) return next( (p for p in fip_ports if p['network_id'] == ext_net_id), None) def get_external_device_interface_name(self, ex_gw_port): fip_int = self.fip_ns.get_int_device_name(self.router_id) if ip_lib.device_exists(fip_int, namespace=self.fip_ns.get_name()): return self.fip_ns.get_rtr_ext_device_name(self.router_id) def external_gateway_added(self, ex_gw_port, interface_name): # TODO(Carl) Refactor external_gateway_added/updated/removed to use # super class implementation where possible. Looks like preserve_ips, # and ns_name are the key differences. ip_wrapr = ip_lib.IPWrapper(namespace=self.ns_name) ip_wrapr.netns.execute(['sysctl', '-w', 'net.ipv4.conf.all.send_redirects=0']) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) id_name = self.get_internal_device_name(p['id']) if gateway: self._snat_redirect_add(gateway, p, id_name) for port in snat_ports: for ip in port['fixed_ips']: self._update_arp_entry(ip['ip_address'], port['mac_address'], ip['subnet_id'], 'add') def external_gateway_updated(self, ex_gw_port, interface_name): pass def external_gateway_removed(self, ex_gw_port, interface_name): # TODO(Carl) Should this be calling process_snat_dnat_for_fip? self.process_floating_ip_nat_rules() if self.fip_ns: to_fip_interface_name = ( self.get_external_device_interface_name(ex_gw_port)) self.process_floating_ip_addresses(to_fip_interface_name) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) internal_interface = self.get_internal_device_name(p['id']) self._snat_redirect_remove(gateway, p, internal_interface) def _handle_router_snat_rules(self, ex_gw_port, interface_name, action): if not self.snat_iptables_manager: LOG.debug("DVR router: no snat rules to be handled") return with self.snat_iptables_manager.defer_apply(): self._empty_snat_chains(self.snat_iptables_manager) # NOTE DVR doesn't add the jump to float snat like the super class. self._add_snat_rules(ex_gw_port, self.snat_iptables_manager, interface_name, action) def perform_snat_action(self, snat_callback, *args): # NOTE DVR skips this step in a few cases... if not self.get_ex_gw_port(): return if self.get_gw_port_host() != self.host: return super(DvrLocalRouter, self).perform_snat_action(snat_callback, *args) def process_external(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.create_dvr_fip_interfaces(ex_gw_port) super(DvrLocalRouter, self).process_external(agent) def create_dvr_fip_interfaces(self, ex_gw_port): floating_ips = self.get_floating_ips() fip_agent_port = self.get_floating_agent_gw_interface( ex_gw_port['network_id']) LOG.debug("FloatingIP agent gateway port received from the plugin: " "%s", fip_agent_port) is_first = False if floating_ips: is_first = self.fip_ns.subscribe(self.router_id) if is_first and not fip_agent_port: LOG.debug("No FloatingIP agent gateway port possibly due to " "late binding of the private port to the host, " "requesting agent gateway port for 'network-id' :" "%s", ex_gw_port['network_id']) fip_agent_port = self.agent.plugin_rpc.get_agent_gateway_port( self.agent.context, ex_gw_port['network_id']) if not fip_agent_port: LOG.error(_LE("No FloatingIP agent gateway port " "returned from server for 'network-id': " "%s"), ex_gw_port['network_id']) if is_first and fip_agent_port: if 'subnets' not in fip_agent_port: LOG.error(_LE('Missing subnet/agent_gateway_port')) else: self.fip_ns.create_gateway_port(fip_agent_port) if self.fip_ns.agent_gateway_port and floating_ips: if self.dist_fip_count == 0 or is_first: self.fip_ns.create_rtr_2_fip_link(self) # kicks the FW Agent to add rules for the IR namespace if # configured self.agent.process_router_add(self) def process(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.fip_ns = agent.get_fip_ns(ex_gw_port['network_id']) self.fip_ns.scan_fip_ports(self) super(DvrLocalRouter, self).process(agent)
get_gw_port_host
identifier_name
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import netaddr from oslo_log import log as logging from oslo_utils import excutils from neutron.agent.l3 import dvr_fip_ns from neutron.agent.l3 import router_info as router from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import exceptions from neutron.common import utils as common_utils from neutron.i18n import _LE LOG = logging.getLogger(__name__) # xor-folding mask used for IPv6 rule index MASK_30 = 0x3fffffff class DvrLocalRouter(router.RouterInfo): def __init__(self, agent, host, *args, **kwargs): super(DvrLocalRouter, self).__init__(*args, **kwargs) self.agent = agent self.host = host self.floating_ips_dict = {} self.snat_iptables_manager = None # Linklocal subnet for router and floating IP namespace link self.rtr_fip_subnet = None self.dist_fip_count = None self.fip_ns = None def get_floating_ips(self): """Filter Floating IPs to be hosted on this agent.""" floating_ips = super(DvrLocalRouter, self).get_floating_ips() return [i for i in floating_ips if i['host'] == self.host] def get_snat_interfaces(self): return self.router.get(l3_constants.SNAT_ROUTER_INTF_KEY, []) def _handle_fip_nat_rules(self, interface_name, action): """Configures NAT rules for Floating IPs for DVR. Remove all the rules. This is safe because if use_namespaces is set as False then the agent can only configure one router, otherwise each router's NAT rules will be in their own namespace. """ self.iptables_manager.ipv4['nat'].empty_chain('POSTROUTING') self.iptables_manager.ipv4['nat'].empty_chain('snat') # Add back the jump to float-snat self.iptables_manager.ipv4['nat'].add_rule('snat', '-j $float-snat') # And add them back if the action is add_rules if action == 'add_rules' and interface_name: rule = ('POSTROUTING', '! -i %(interface_name)s ' '! -o %(interface_name)s -m conntrack ! ' '--ctstate DNAT -j ACCEPT' % {'interface_name': interface_name}) self.iptables_manager.ipv4['nat'].add_rule(*rule) self.iptables_manager.apply() def floating_ip_added_dist(self, fip, fip_cidr): """Add floating IP to FIP namespace.""" floating_ip = fip['floating_ip_address'] fixed_ip = fip['fixed_ip_address'] rule_pr = self.fip_ns.allocate_rule_priority() self.floating_ips_dict[floating_ip] = rule_pr fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.add(ip=fixed_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) #Add routing rule in fip namespace fip_ns_name = self.fip_ns.get_name() rtr_2_fip, _ = self.rtr_fip_subnet.get_pair() device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.add_route(fip_cidr, str(rtr_2_fip.ip)) interface_name = ( self.fip_ns.get_ext_device_name( self.fip_ns.agent_gateway_port['id'])) ip_lib.send_ip_addr_adv_notif(fip_ns_name, interface_name, floating_ip, self.agent_conf) # update internal structures self.dist_fip_count = self.dist_fip_count + 1 def floating_ip_removed_dist(self, fip_cidr): """Remove floating IP from FIP namespace.""" floating_ip = fip_cidr.split('/')[0] rtr_2_fip_name = self.fip_ns.get_rtr_ext_device_name(self.router_id) fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) if self.rtr_fip_subnet is None: self.rtr_fip_subnet = self.fip_ns.local_subnets.allocate( self.router_id) rtr_2_fip, fip_2_rtr = self.rtr_fip_subnet.get_pair() fip_ns_name = self.fip_ns.get_name() if floating_ip in self.floating_ips_dict: rule_pr = self.floating_ips_dict[floating_ip] ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.delete(ip=floating_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) self.fip_ns.deallocate_rule_priority(rule_pr) #TODO(rajeev): Handle else case - exception/log? device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.delete_route(fip_cidr, str(rtr_2_fip.ip)) # check if this is the last FIP for this router self.dist_fip_count = self.dist_fip_count - 1 if self.dist_fip_count == 0: #remove default route entry device = ip_lib.IPDevice(rtr_2_fip_name, namespace=self.ns_name) ns_ip = ip_lib.IPWrapper(namespace=fip_ns_name) device.route.delete_gateway(str(fip_2_rtr.ip), table=dvr_fip_ns.FIP_RT_TBL) self.fip_ns.local_subnets.release(self.router_id) self.rtr_fip_subnet = None ns_ip.del_veth(fip_2_rtr_name) is_last = self.fip_ns.unsubscribe(self.router_id) if is_last: # TODO(Carl) I can't help but think that another router could # come in and want to start using this namespace while this is # destroying it. The two could end up conflicting on # creating/destroying interfaces and such. I think I'd like a # semaphore to sync creation/deletion of this namespace. self.fip_ns.delete() self.fip_ns = None def add_floating_ip(self, fip, interface_name, device): if not self._add_fip_addr_to_device(fip, device): return l3_constants.FLOATINGIP_STATUS_ERROR # Special Handling for DVR - update FIP namespace ip_cidr = common_utils.ip_to_cidr(fip['floating_ip_address']) self.floating_ip_added_dist(fip, ip_cidr) return l3_constants.FLOATINGIP_STATUS_ACTIVE def remove_floating_ip(self, device, ip_cidr): super(DvrLocalRouter, self).remove_floating_ip(device, ip_cidr) self.floating_ip_removed_dist(ip_cidr) def _get_internal_port(self, subnet_id): """Return internal router port based on subnet_id.""" router_ports = self.router.get(l3_constants.INTERFACE_KEY, []) for port in router_ports: fips = port['fixed_ips'] for f in fips: if f['subnet_id'] == subnet_id: return port def _update_arp_entry(self, ip, mac, subnet_id, operation): """Add or delete arp entry into router namespace for the subnet.""" port = self._get_internal_port(subnet_id) # update arp entry only if the subnet is attached to the router if not port: return try: # TODO(mrsmith): optimize the calls below for bulk calls interface_name = self.get_internal_device_name(port['id']) device = ip_lib.IPDevice(interface_name, namespace=self.ns_name) if operation == 'add': device.neigh.add(ip, mac) elif operation == 'delete':
except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("DVR: Failed updating arp entry")) def _set_subnet_arp_info(self, subnet_id): """Set ARP info retrieved from Plugin for existing ports.""" # TODO(Carl) Can we eliminate the need to make this RPC while # processing a router. subnet_ports = self.agent.get_ports_by_subnet(subnet_id) for p in subnet_ports: if p['device_owner'] not in l3_constants.ROUTER_INTERFACE_OWNERS: for fixed_ip in p['fixed_ips']: self._update_arp_entry(fixed_ip['ip_address'], p['mac_address'], subnet_id, 'add') def _map_internal_interfaces(self, int_port, snat_ports): """Return the SNAT port for the given internal interface port.""" fixed_ip = int_port['fixed_ips'][0] subnet_id = fixed_ip['subnet_id'] match_port = [p for p in snat_ports if p['fixed_ips'][0]['subnet_id'] == subnet_id] if match_port: return match_port[0] else: LOG.error(_LE('DVR: no map match_port found!')) @staticmethod def _get_snat_idx(ip_cidr): """Generate index for DVR snat rules and route tables. The index value has to be 32 bits or less but more than the system generated entries i.e. 32768. For IPv4 use the numeric value of the cidr. For IPv6 generate a crc32 bit hash and xor-fold to 30 bits. Use the freed range to extend smaller values so that they become greater than system generated entries. """ net = netaddr.IPNetwork(ip_cidr) if net.version == 6: # the crc32 & 0xffffffff is for Python 2.6 and 3.0 compatibility snat_idx = binascii.crc32(ip_cidr) & 0xffffffff # xor-fold the hash to reserve upper range to extend smaller values snat_idx = (snat_idx >> 30) ^ (snat_idx & MASK_30) if snat_idx < 32768: snat_idx = snat_idx + MASK_30 else: snat_idx = net.value return snat_idx def _delete_gateway_device_if_exists(self, ns_ip_device, gw_ip_addr, snat_idx): try: ns_ip_device.route.delete_gateway(gw_ip_addr, table=snat_idx) except exceptions.DeviceNotFoundError: pass def _snat_redirect_modify(self, gateway, sn_port, sn_int, is_add): """Adds or removes rules and routes for SNAT redirection.""" try: ns_ipr = ip_lib.IPRule(namespace=self.ns_name) ns_ipd = ip_lib.IPDevice(sn_int, namespace=self.ns_name) if is_add: ns_ipwrapr = ip_lib.IPWrapper(namespace=self.ns_name) for port_fixed_ip in sn_port['fixed_ips']: # Find the first gateway IP address matching this IP version port_ip_addr = port_fixed_ip['ip_address'] port_ip_vers = netaddr.IPAddress(port_ip_addr).version for gw_fixed_ip in gateway['fixed_ips']: gw_ip_addr = gw_fixed_ip['ip_address'] if netaddr.IPAddress(gw_ip_addr).version == port_ip_vers: sn_port_cidr = common_utils.ip_to_cidr( port_ip_addr, port_fixed_ip['prefixlen']) snat_idx = self._get_snat_idx(sn_port_cidr) if is_add: ns_ipd.route.add_gateway(gw_ip_addr, table=snat_idx) ns_ipr.rule.add(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) ns_ipwrapr.netns.execute( ['sysctl', '-w', 'net.ipv4.conf.%s.send_redirects=0' % sn_int]) else: self._delete_gateway_device_if_exists(ns_ipd, gw_ip_addr, snat_idx) ns_ipr.rule.delete(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) break except Exception: if is_add: exc = _LE('DVR: error adding redirection logic') else: exc = _LE('DVR: removed snat failed') LOG.exception(exc) def _snat_redirect_add(self, gateway, sn_port, sn_int): """Adds rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=True) def _snat_redirect_remove(self, gateway, sn_port, sn_int): """Removes rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=False) def get_gw_port_host(self): host = self.router.get('gw_port_host') if not host: LOG.debug("gw_port_host missing from router: %s", self.router['id']) return host def internal_network_added(self, port): super(DvrLocalRouter, self).internal_network_added(port) # NOTE: The following function _set_subnet_arp_info # should be called to dynamically populate the arp # entries for the dvr services ports into the router # namespace. This does not have dependency on the # external_gateway port or the agent_mode. for subnet in port['subnets']: self._set_subnet_arp_info(subnet['id']) ex_gw_port = self.get_ex_gw_port() if not ex_gw_port: return snat_ports = self.get_snat_interfaces() sn_port = self._map_internal_interfaces(port, snat_ports) if not sn_port: return interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_add(sn_port, port, interface_name) def _dvr_internal_network_removed(self, port): if not self.ex_gw_port: return sn_port = self._map_internal_interfaces(port, self.snat_ports) if not sn_port: return # DVR handling code for SNAT interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_remove(sn_port, port, interface_name) def internal_network_removed(self, port): self._dvr_internal_network_removed(port) super(DvrLocalRouter, self).internal_network_removed(port) def get_floating_agent_gw_interface(self, ext_net_id): """Filter Floating Agent GW port for the external network.""" fip_ports = self.router.get(l3_constants.FLOATINGIP_AGENT_INTF_KEY, []) return next( (p for p in fip_ports if p['network_id'] == ext_net_id), None) def get_external_device_interface_name(self, ex_gw_port): fip_int = self.fip_ns.get_int_device_name(self.router_id) if ip_lib.device_exists(fip_int, namespace=self.fip_ns.get_name()): return self.fip_ns.get_rtr_ext_device_name(self.router_id) def external_gateway_added(self, ex_gw_port, interface_name): # TODO(Carl) Refactor external_gateway_added/updated/removed to use # super class implementation where possible. Looks like preserve_ips, # and ns_name are the key differences. ip_wrapr = ip_lib.IPWrapper(namespace=self.ns_name) ip_wrapr.netns.execute(['sysctl', '-w', 'net.ipv4.conf.all.send_redirects=0']) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) id_name = self.get_internal_device_name(p['id']) if gateway: self._snat_redirect_add(gateway, p, id_name) for port in snat_ports: for ip in port['fixed_ips']: self._update_arp_entry(ip['ip_address'], port['mac_address'], ip['subnet_id'], 'add') def external_gateway_updated(self, ex_gw_port, interface_name): pass def external_gateway_removed(self, ex_gw_port, interface_name): # TODO(Carl) Should this be calling process_snat_dnat_for_fip? self.process_floating_ip_nat_rules() if self.fip_ns: to_fip_interface_name = ( self.get_external_device_interface_name(ex_gw_port)) self.process_floating_ip_addresses(to_fip_interface_name) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) internal_interface = self.get_internal_device_name(p['id']) self._snat_redirect_remove(gateway, p, internal_interface) def _handle_router_snat_rules(self, ex_gw_port, interface_name, action): if not self.snat_iptables_manager: LOG.debug("DVR router: no snat rules to be handled") return with self.snat_iptables_manager.defer_apply(): self._empty_snat_chains(self.snat_iptables_manager) # NOTE DVR doesn't add the jump to float snat like the super class. self._add_snat_rules(ex_gw_port, self.snat_iptables_manager, interface_name, action) def perform_snat_action(self, snat_callback, *args): # NOTE DVR skips this step in a few cases... if not self.get_ex_gw_port(): return if self.get_gw_port_host() != self.host: return super(DvrLocalRouter, self).perform_snat_action(snat_callback, *args) def process_external(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.create_dvr_fip_interfaces(ex_gw_port) super(DvrLocalRouter, self).process_external(agent) def create_dvr_fip_interfaces(self, ex_gw_port): floating_ips = self.get_floating_ips() fip_agent_port = self.get_floating_agent_gw_interface( ex_gw_port['network_id']) LOG.debug("FloatingIP agent gateway port received from the plugin: " "%s", fip_agent_port) is_first = False if floating_ips: is_first = self.fip_ns.subscribe(self.router_id) if is_first and not fip_agent_port: LOG.debug("No FloatingIP agent gateway port possibly due to " "late binding of the private port to the host, " "requesting agent gateway port for 'network-id' :" "%s", ex_gw_port['network_id']) fip_agent_port = self.agent.plugin_rpc.get_agent_gateway_port( self.agent.context, ex_gw_port['network_id']) if not fip_agent_port: LOG.error(_LE("No FloatingIP agent gateway port " "returned from server for 'network-id': " "%s"), ex_gw_port['network_id']) if is_first and fip_agent_port: if 'subnets' not in fip_agent_port: LOG.error(_LE('Missing subnet/agent_gateway_port')) else: self.fip_ns.create_gateway_port(fip_agent_port) if self.fip_ns.agent_gateway_port and floating_ips: if self.dist_fip_count == 0 or is_first: self.fip_ns.create_rtr_2_fip_link(self) # kicks the FW Agent to add rules for the IR namespace if # configured self.agent.process_router_add(self) def process(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.fip_ns = agent.get_fip_ns(ex_gw_port['network_id']) self.fip_ns.scan_fip_ports(self) super(DvrLocalRouter, self).process(agent)
device.neigh.delete(ip, mac)
conditional_block
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import netaddr from oslo_log import log as logging from oslo_utils import excutils from neutron.agent.l3 import dvr_fip_ns from neutron.agent.l3 import router_info as router from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import exceptions from neutron.common import utils as common_utils from neutron.i18n import _LE LOG = logging.getLogger(__name__) # xor-folding mask used for IPv6 rule index MASK_30 = 0x3fffffff class DvrLocalRouter(router.RouterInfo): def __init__(self, agent, host, *args, **kwargs): super(DvrLocalRouter, self).__init__(*args, **kwargs) self.agent = agent self.host = host self.floating_ips_dict = {} self.snat_iptables_manager = None # Linklocal subnet for router and floating IP namespace link self.rtr_fip_subnet = None self.dist_fip_count = None self.fip_ns = None def get_floating_ips(self): """Filter Floating IPs to be hosted on this agent.""" floating_ips = super(DvrLocalRouter, self).get_floating_ips() return [i for i in floating_ips if i['host'] == self.host] def get_snat_interfaces(self): return self.router.get(l3_constants.SNAT_ROUTER_INTF_KEY, []) def _handle_fip_nat_rules(self, interface_name, action): """Configures NAT rules for Floating IPs for DVR. Remove all the rules. This is safe because if use_namespaces is set as False then the agent can only configure one router, otherwise each router's NAT rules will be in their own namespace. """ self.iptables_manager.ipv4['nat'].empty_chain('POSTROUTING') self.iptables_manager.ipv4['nat'].empty_chain('snat') # Add back the jump to float-snat self.iptables_manager.ipv4['nat'].add_rule('snat', '-j $float-snat') # And add them back if the action is add_rules if action == 'add_rules' and interface_name: rule = ('POSTROUTING', '! -i %(interface_name)s ' '! -o %(interface_name)s -m conntrack ! ' '--ctstate DNAT -j ACCEPT' % {'interface_name': interface_name}) self.iptables_manager.ipv4['nat'].add_rule(*rule) self.iptables_manager.apply() def floating_ip_added_dist(self, fip, fip_cidr): """Add floating IP to FIP namespace.""" floating_ip = fip['floating_ip_address'] fixed_ip = fip['fixed_ip_address'] rule_pr = self.fip_ns.allocate_rule_priority() self.floating_ips_dict[floating_ip] = rule_pr fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.add(ip=fixed_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) #Add routing rule in fip namespace fip_ns_name = self.fip_ns.get_name() rtr_2_fip, _ = self.rtr_fip_subnet.get_pair() device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.add_route(fip_cidr, str(rtr_2_fip.ip)) interface_name = ( self.fip_ns.get_ext_device_name( self.fip_ns.agent_gateway_port['id'])) ip_lib.send_ip_addr_adv_notif(fip_ns_name, interface_name, floating_ip, self.agent_conf) # update internal structures self.dist_fip_count = self.dist_fip_count + 1 def floating_ip_removed_dist(self, fip_cidr): """Remove floating IP from FIP namespace.""" floating_ip = fip_cidr.split('/')[0] rtr_2_fip_name = self.fip_ns.get_rtr_ext_device_name(self.router_id) fip_2_rtr_name = self.fip_ns.get_int_device_name(self.router_id) if self.rtr_fip_subnet is None: self.rtr_fip_subnet = self.fip_ns.local_subnets.allocate( self.router_id) rtr_2_fip, fip_2_rtr = self.rtr_fip_subnet.get_pair() fip_ns_name = self.fip_ns.get_name() if floating_ip in self.floating_ips_dict: rule_pr = self.floating_ips_dict[floating_ip] ip_rule = ip_lib.IPRule(namespace=self.ns_name) ip_rule.rule.delete(ip=floating_ip, table=dvr_fip_ns.FIP_RT_TBL, priority=rule_pr) self.fip_ns.deallocate_rule_priority(rule_pr) #TODO(rajeev): Handle else case - exception/log? device = ip_lib.IPDevice(fip_2_rtr_name, namespace=fip_ns_name) device.route.delete_route(fip_cidr, str(rtr_2_fip.ip)) # check if this is the last FIP for this router self.dist_fip_count = self.dist_fip_count - 1 if self.dist_fip_count == 0: #remove default route entry device = ip_lib.IPDevice(rtr_2_fip_name, namespace=self.ns_name) ns_ip = ip_lib.IPWrapper(namespace=fip_ns_name) device.route.delete_gateway(str(fip_2_rtr.ip), table=dvr_fip_ns.FIP_RT_TBL) self.fip_ns.local_subnets.release(self.router_id) self.rtr_fip_subnet = None ns_ip.del_veth(fip_2_rtr_name) is_last = self.fip_ns.unsubscribe(self.router_id) if is_last: # TODO(Carl) I can't help but think that another router could # come in and want to start using this namespace while this is # destroying it. The two could end up conflicting on # creating/destroying interfaces and such. I think I'd like a # semaphore to sync creation/deletion of this namespace. self.fip_ns.delete() self.fip_ns = None def add_floating_ip(self, fip, interface_name, device): if not self._add_fip_addr_to_device(fip, device): return l3_constants.FLOATINGIP_STATUS_ERROR # Special Handling for DVR - update FIP namespace ip_cidr = common_utils.ip_to_cidr(fip['floating_ip_address']) self.floating_ip_added_dist(fip, ip_cidr) return l3_constants.FLOATINGIP_STATUS_ACTIVE def remove_floating_ip(self, device, ip_cidr): super(DvrLocalRouter, self).remove_floating_ip(device, ip_cidr) self.floating_ip_removed_dist(ip_cidr) def _get_internal_port(self, subnet_id): """Return internal router port based on subnet_id.""" router_ports = self.router.get(l3_constants.INTERFACE_KEY, []) for port in router_ports: fips = port['fixed_ips'] for f in fips: if f['subnet_id'] == subnet_id: return port def _update_arp_entry(self, ip, mac, subnet_id, operation): """Add or delete arp entry into router namespace for the subnet.""" port = self._get_internal_port(subnet_id) # update arp entry only if the subnet is attached to the router if not port: return try: # TODO(mrsmith): optimize the calls below for bulk calls interface_name = self.get_internal_device_name(port['id']) device = ip_lib.IPDevice(interface_name, namespace=self.ns_name) if operation == 'add': device.neigh.add(ip, mac) elif operation == 'delete': device.neigh.delete(ip, mac) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("DVR: Failed updating arp entry")) def _set_subnet_arp_info(self, subnet_id): """Set ARP info retrieved from Plugin for existing ports.""" # TODO(Carl) Can we eliminate the need to make this RPC while # processing a router. subnet_ports = self.agent.get_ports_by_subnet(subnet_id) for p in subnet_ports: if p['device_owner'] not in l3_constants.ROUTER_INTERFACE_OWNERS: for fixed_ip in p['fixed_ips']: self._update_arp_entry(fixed_ip['ip_address'], p['mac_address'], subnet_id, 'add') def _map_internal_interfaces(self, int_port, snat_ports): """Return the SNAT port for the given internal interface port.""" fixed_ip = int_port['fixed_ips'][0] subnet_id = fixed_ip['subnet_id'] match_port = [p for p in snat_ports if p['fixed_ips'][0]['subnet_id'] == subnet_id] if match_port: return match_port[0] else: LOG.error(_LE('DVR: no map match_port found!')) @staticmethod def _get_snat_idx(ip_cidr): """Generate index for DVR snat rules and route tables. The index value has to be 32 bits or less but more than the system generated entries i.e. 32768. For IPv4 use the numeric value of the cidr. For IPv6 generate a crc32 bit hash and xor-fold to 30 bits. Use the freed range to extend smaller values so that they become greater than system generated entries. """ net = netaddr.IPNetwork(ip_cidr) if net.version == 6: # the crc32 & 0xffffffff is for Python 2.6 and 3.0 compatibility snat_idx = binascii.crc32(ip_cidr) & 0xffffffff # xor-fold the hash to reserve upper range to extend smaller values snat_idx = (snat_idx >> 30) ^ (snat_idx & MASK_30) if snat_idx < 32768: snat_idx = snat_idx + MASK_30 else: snat_idx = net.value return snat_idx def _delete_gateway_device_if_exists(self, ns_ip_device, gw_ip_addr, snat_idx): try: ns_ip_device.route.delete_gateway(gw_ip_addr, table=snat_idx) except exceptions.DeviceNotFoundError: pass def _snat_redirect_modify(self, gateway, sn_port, sn_int, is_add): """Adds or removes rules and routes for SNAT redirection.""" try: ns_ipr = ip_lib.IPRule(namespace=self.ns_name) ns_ipd = ip_lib.IPDevice(sn_int, namespace=self.ns_name) if is_add: ns_ipwrapr = ip_lib.IPWrapper(namespace=self.ns_name) for port_fixed_ip in sn_port['fixed_ips']: # Find the first gateway IP address matching this IP version port_ip_addr = port_fixed_ip['ip_address'] port_ip_vers = netaddr.IPAddress(port_ip_addr).version for gw_fixed_ip in gateway['fixed_ips']: gw_ip_addr = gw_fixed_ip['ip_address'] if netaddr.IPAddress(gw_ip_addr).version == port_ip_vers: sn_port_cidr = common_utils.ip_to_cidr( port_ip_addr, port_fixed_ip['prefixlen']) snat_idx = self._get_snat_idx(sn_port_cidr) if is_add: ns_ipd.route.add_gateway(gw_ip_addr, table=snat_idx) ns_ipr.rule.add(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) ns_ipwrapr.netns.execute( ['sysctl', '-w', 'net.ipv4.conf.%s.send_redirects=0' % sn_int]) else: self._delete_gateway_device_if_exists(ns_ipd, gw_ip_addr, snat_idx) ns_ipr.rule.delete(ip=sn_port_cidr, table=snat_idx, priority=snat_idx) break except Exception: if is_add: exc = _LE('DVR: error adding redirection logic') else: exc = _LE('DVR: removed snat failed') LOG.exception(exc) def _snat_redirect_add(self, gateway, sn_port, sn_int): """Adds rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=True) def _snat_redirect_remove(self, gateway, sn_port, sn_int): """Removes rules and routes for SNAT redirection.""" self._snat_redirect_modify(gateway, sn_port, sn_int, is_add=False) def get_gw_port_host(self): host = self.router.get('gw_port_host') if not host: LOG.debug("gw_port_host missing from router: %s", self.router['id']) return host def internal_network_added(self, port): super(DvrLocalRouter, self).internal_network_added(port) # NOTE: The following function _set_subnet_arp_info # should be called to dynamically populate the arp # entries for the dvr services ports into the router # namespace. This does not have dependency on the # external_gateway port or the agent_mode. for subnet in port['subnets']: self._set_subnet_arp_info(subnet['id']) ex_gw_port = self.get_ex_gw_port() if not ex_gw_port: return snat_ports = self.get_snat_interfaces() sn_port = self._map_internal_interfaces(port, snat_ports) if not sn_port: return interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_add(sn_port, port, interface_name) def _dvr_internal_network_removed(self, port): if not self.ex_gw_port: return sn_port = self._map_internal_interfaces(port, self.snat_ports) if not sn_port: return # DVR handling code for SNAT interface_name = self.get_internal_device_name(port['id']) self._snat_redirect_remove(sn_port, port, interface_name) def internal_network_removed(self, port):
def get_floating_agent_gw_interface(self, ext_net_id): """Filter Floating Agent GW port for the external network.""" fip_ports = self.router.get(l3_constants.FLOATINGIP_AGENT_INTF_KEY, []) return next( (p for p in fip_ports if p['network_id'] == ext_net_id), None) def get_external_device_interface_name(self, ex_gw_port): fip_int = self.fip_ns.get_int_device_name(self.router_id) if ip_lib.device_exists(fip_int, namespace=self.fip_ns.get_name()): return self.fip_ns.get_rtr_ext_device_name(self.router_id) def external_gateway_added(self, ex_gw_port, interface_name): # TODO(Carl) Refactor external_gateway_added/updated/removed to use # super class implementation where possible. Looks like preserve_ips, # and ns_name are the key differences. ip_wrapr = ip_lib.IPWrapper(namespace=self.ns_name) ip_wrapr.netns.execute(['sysctl', '-w', 'net.ipv4.conf.all.send_redirects=0']) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) id_name = self.get_internal_device_name(p['id']) if gateway: self._snat_redirect_add(gateway, p, id_name) for port in snat_ports: for ip in port['fixed_ips']: self._update_arp_entry(ip['ip_address'], port['mac_address'], ip['subnet_id'], 'add') def external_gateway_updated(self, ex_gw_port, interface_name): pass def external_gateway_removed(self, ex_gw_port, interface_name): # TODO(Carl) Should this be calling process_snat_dnat_for_fip? self.process_floating_ip_nat_rules() if self.fip_ns: to_fip_interface_name = ( self.get_external_device_interface_name(ex_gw_port)) self.process_floating_ip_addresses(to_fip_interface_name) snat_ports = self.get_snat_interfaces() for p in self.internal_ports: gateway = self._map_internal_interfaces(p, snat_ports) internal_interface = self.get_internal_device_name(p['id']) self._snat_redirect_remove(gateway, p, internal_interface) def _handle_router_snat_rules(self, ex_gw_port, interface_name, action): if not self.snat_iptables_manager: LOG.debug("DVR router: no snat rules to be handled") return with self.snat_iptables_manager.defer_apply(): self._empty_snat_chains(self.snat_iptables_manager) # NOTE DVR doesn't add the jump to float snat like the super class. self._add_snat_rules(ex_gw_port, self.snat_iptables_manager, interface_name, action) def perform_snat_action(self, snat_callback, *args): # NOTE DVR skips this step in a few cases... if not self.get_ex_gw_port(): return if self.get_gw_port_host() != self.host: return super(DvrLocalRouter, self).perform_snat_action(snat_callback, *args) def process_external(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.create_dvr_fip_interfaces(ex_gw_port) super(DvrLocalRouter, self).process_external(agent) def create_dvr_fip_interfaces(self, ex_gw_port): floating_ips = self.get_floating_ips() fip_agent_port = self.get_floating_agent_gw_interface( ex_gw_port['network_id']) LOG.debug("FloatingIP agent gateway port received from the plugin: " "%s", fip_agent_port) is_first = False if floating_ips: is_first = self.fip_ns.subscribe(self.router_id) if is_first and not fip_agent_port: LOG.debug("No FloatingIP agent gateway port possibly due to " "late binding of the private port to the host, " "requesting agent gateway port for 'network-id' :" "%s", ex_gw_port['network_id']) fip_agent_port = self.agent.plugin_rpc.get_agent_gateway_port( self.agent.context, ex_gw_port['network_id']) if not fip_agent_port: LOG.error(_LE("No FloatingIP agent gateway port " "returned from server for 'network-id': " "%s"), ex_gw_port['network_id']) if is_first and fip_agent_port: if 'subnets' not in fip_agent_port: LOG.error(_LE('Missing subnet/agent_gateway_port')) else: self.fip_ns.create_gateway_port(fip_agent_port) if self.fip_ns.agent_gateway_port and floating_ips: if self.dist_fip_count == 0 or is_first: self.fip_ns.create_rtr_2_fip_link(self) # kicks the FW Agent to add rules for the IR namespace if # configured self.agent.process_router_add(self) def process(self, agent): ex_gw_port = self.get_ex_gw_port() if ex_gw_port: self.fip_ns = agent.get_fip_ns(ex_gw_port['network_id']) self.fip_ns.scan_fip_ports(self) super(DvrLocalRouter, self).process(agent)
self._dvr_internal_network_removed(port) super(DvrLocalRouter, self).internal_network_removed(port)
identifier_body
template.js
define( ({ "viewer": { "main": { "scaleBarUnits": "metric", "timePattern": "h:mma", // added 2.5.2013 "datePattern": "MMM d, yyyy" // added 2.5.2013 }, "applicationTitle": { "PIM": "خريطة المعلومات العامة" // added 8.26.2013 }, "hashTagLabel": { "hashTagFlickr": "تستخدم العلامة # لـ Flickr", // added 8.26.2013 "hashTagTwitter": "تستخدم العلامة # لـ Twitter", // added 8.26.2013 "hashTagYoutube": "تستخدم العلامة # لـ YouTube" // added 8.26.2013 }, "errors": { "createMap": "يتعذر إنشاء الخريطة", "general": "خطأ", "bingError": "يتطلب نشر هذا التطبيق مفتاح خرائط Bing.", "noLegend": "لا يوجد وسيلة إيضاح", "heatmap": "تكون الخرائط الحرارية غير مدعومة في هذا المستعرض.", "noText": "الرجاء ادخال موقع البحث.", "noLocation": "يتعذر العثور على الموقع.", "integersOnly": "يمكنك ادخال أعداد صحيحة فقط في هذا الحقل.", "nodesc": "لا يوجد وصف", "notAvailable": "غير متاح", // added 8.26.2013 "outsideArea": "أنت حاليًا خارج المنطقة المدعومة", // added 8.26.2013 "geoLocationTimeOut": "تم تجاوز المهلة. يتعذر إجراء العملية", // added 8.26.2013 "positionUnavailable": "الموضع غير متاح", // added 8.26.2013 "permissionDenied": "الإذن مرفوض لتحديد الموقع الحالي", // added 8.26.2013 "unknownError": "حدث خطأ غير معروف. يتعذر تحديد الموقع الحالي", // added 8.26.2013 "tinyURLError": "يتعذر إنشاء TinyURL", // added 8.26.2013 "invalidSearch": "بحث غير صحيح" // added 8.26.2013 }, "legend": { "menuTitle": "مفتاح الخريطة" }, "search": { "location": "موقع", "clearLocation": "مسح الموقع", "placeholder": "العثور على مكان" }, "layers": { "menuTitle": "طبقات" }, "locator": { "menuTitle": "عنوان البحث" // added 8.26.2013 }, "layer": { "information": "معلومات", "transparency": "معدل الشفافية:", "searchSettings": "إعدادات البحث", "filteredBy": "تم التنقية من قبل:" }, "general": { "at": "عند", "of": "من", "homeExtent": "تحميل العرض الرئيسي", "ok": "موافق", "close": "إغلاق" }, "basemap": { "menuTitle": "تحديد خريطة أساس" }, "settings": { "title": "الإعدادات", "searchAll": "البحث عن الكل", "usingThisKeyword": "استخدام الكلمات الأساسية", "search": "بحث", "fromThePast": "من الماضي", "today": "يوم", "this_week": "اسبوع", "this_month": "شهر", "all_time": "طول الوقت", "atLocation": "في هذا الموقع", "centerOfMap": "مركز الخريطة", "centerOfMapTitle": "استخدم مركز الخريطة", "withinThisDistance": "في هذه المسافة", "latitude": "خطوط الطول:", "longitude": "دوائر العرض:", "locationText": "انقر فوق الخريطة لتعيين نقطة الأصل", "twSearch": "كيفية استخدام البحث المتقدم على Twitter", "screenName": "اسم الشاشة", // added 8.26.2013 "signIn": "تسجيل الدخول", // added 8.26.2013 "switchAccount": "تبديل الحساب" // added 8.26.2013 }, "autoComplete": { "menuTitle": "Results&hellip;" }, "places": { "menuTitle": "الأماكن التي تم وضع إشارة مرجعية إليها", "places": "إشارات مرجعية",
"distanceSlider": { "local": "محلي", "regional": "إقليمي", "national": "وطني" }, "about": { "title": "نبذة عن", "access": "قيود الاستخدام والوصول" }, "buttons": { "legend": "مفتاح الخريطة", "legendTitle": "إظهار وسيلة الإيضاح", "basemap": "خريطة أساسية", "basemapTitle": "تبديل خريطة الأساس", "layers": "طبقات", "layersTitle": "استكشاف الطبقات", "social": "اجتماعي", "socialTitle": "موقع التواصل الاجتماعي", "link": "رابط", "linkTitle": "مشاركة تطبيق الويب", "about": "نبذة عن", "aboutTitle": "نبذة عن هذه الخريطة", "displayAs": "عرض في شكل", "point": "نقاط", "cluster": "تجمعات", "heatmap": "الكثافة", // added 8.26.2013 "map": "خريطة", // added 8.26.2013 "share": "مشاركة", // added 8.26.2013 "home": "الصفحة الرئيسية", // added 8.26.2013 "bookmarks": "إشارات مرجعية", // added 8.26.2013 "noBookmarks": "لا يوجد علامات مرجعية", // added 8.26.2013 "layerVisible": "رؤية الطبقة", // added 8.26.2013 "flagAppropriate": "وضع علامة غير مناسبة", // added 8.26.2013 "flatReporting": "إعداد تقرير", // added 8.26.2013 "zoomToLabel": "تكبير إلى", // added 8.26.2013 "contentFlagged": "تم وضع علامة على المحتوى", // added 8.26.2013 "locator": "إظهار محدد الموقع", // added 8.26.2013 "tinyUrl": "إظهار عنوان url الصغير", // added 8.26.2013 "refresh": "تحديث", // added 8.26.2013 "refreshContext": "انقر لتحميل الموجزات الجديدة." // added 8.26.2013 }, "shareMenu": { "menuTitle": "مشاركة العرض الحالي", "shareHeader": "مشاركة رابط في تطبيق الويب", "facebook": "Facebook", "facebookHeader": "مشاركة على Facebook", "twitter": "Twitter", "twitterHeader": "مشاركة على Twitter", "instructionHeader": "نسخ/لصق HTML داخل صفحة الويب الخاصة بك.", "preview": "المعاينة والتخصيص" }, "itemInfo": { "createdLabel": "تم إنشاء", "ratingsLabel": "تصنيف", "ratingsLabelPlural": "تصنيفات", "viewsLabel": "عرض", "viewsLabelPlural": "المشاهدات", "commentsLabel": "تعليق", "commentsLabelPlural": "تعليقات", "modifiedLabel": "آخر تعديل", "by": "حسب", "separator": "," }, "social": { "menuTitle": "طبقات الوسائط الاجتماعية", "screenName": "اسم الشاشة", "signIn": "تسجيل الدخول", "switchAccount": "حساب التبديل" }, "preview": { "minWidth": "الحد الأدنى للعرض هو", "minHeight": "الحد الأدنى للارتفاع هو", "maxWidth": "الحد الأقصى للعرض هو", "maxHeight": "الحد الأقصى للارتفاع هو", "customize": "تخصيص", "small": "صغير", "medium": "متوسط", "large": "كبير", "custom": "تخصيص", "embed": "مضمن", "instruction": "نسخ ولصق HTML التالي لتضمين الخريطة على موقع الويب الخاص بك." }, "flickr": { "title": "Flickr", "description": "صور من Flickr" }, "twitter": { "title": "تويتر", "description": "تويت من تويتر" }, "youtube": { "title": "YouTube", "description": "مقاطع فيديو من YouTube" }, "panoramio": { "title": "Panoramio", "description": "صور من Panoramio" }, "ushahidi": { "title": "Ushahidi", "description": "تقارير طارئة من Ushahidi" } } }) );
"placesTitle": "أماكن العلامة المرجعية", "myLocation": "موقعي الحالي", "myLocationTitle": "تمركز الخريطة على موقعي" },
random_line_split
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss)
growl.append(message); if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset }; } return growl; } function makeAlign(alert, options) { switch (options.align) { case "center": alert.css({ "left": "50%", "margin-left": "-" + (alert.outerWidth() / 2) + "px" }); break; case "left": alert.css("left", "20px"); break; default: alert.css("right", "20px"); } } function createOptionsDefault() { return { ele: "body", type: "info", offset: { from: "top", amount: 20 }, align: "right", width: 400, delay: 4000, allow_dismiss: true, stackup_spacing: 10 }; } function createStyleClass(options) { return { "position": (options.ele === "body" ? "fixed" : "absolute"), "margin": 0, "z-index": "9999", "display": "none" }; } function calcNextPosition(options) { let offsetAmount = options.offset.amount; $(".bootstrap-growl").each(function() { offsetAmount = Math.max(offsetAmount, parseInt($(this).css(options.offset.from)) + $(this).outerHeight() + options.stackup_spacing); return offsetAmount; }); return offsetAmount; } function isArray(obj) { return obj && (obj.constructor == Array); } let GrowlNotify = { notify: function(message, opt) { let options = $.extend({}, createOptionsDefault(), opt); let growl = createGrowl(options, message); let offsetAmount = calcNextPosition(options); let css = createStyleClass(options); css[options.offset.from] = offsetAmount + "px"; growl.css(css); if (options.width !== "auto") { growl.css("width", options.width + "px"); } $(options.ele).append(growl); makeAlign(growl, options); growl.fadeIn(); if (options.delay > 0) { growl.delay(options.delay).fadeOut(function() { return $(this).alert("close"); }); } return growl; }, notifyOnErrors: function(msg) { if (isArray(msg)) { msg.map((value, index) => { this.notify(value.texto, { type: 'danger' }); }); return; } this.notify(msg, { type: 'danger' }); } } export default GrowlNotify;
{ growl.addClass("alert-dismissible"); growl.append("<button class=\"close\" data-dismiss=\"alert\" type=\"button\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>"); }
conditional_block
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss) { growl.addClass("alert-dismissible"); growl.append("<button class=\"close\" data-dismiss=\"alert\" type=\"button\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>"); } growl.append(message);
}; } return growl; } function makeAlign(alert, options) { switch (options.align) { case "center": alert.css({ "left": "50%", "margin-left": "-" + (alert.outerWidth() / 2) + "px" }); break; case "left": alert.css("left", "20px"); break; default: alert.css("right", "20px"); } } function createOptionsDefault() { return { ele: "body", type: "info", offset: { from: "top", amount: 20 }, align: "right", width: 400, delay: 4000, allow_dismiss: true, stackup_spacing: 10 }; } function createStyleClass(options) { return { "position": (options.ele === "body" ? "fixed" : "absolute"), "margin": 0, "z-index": "9999", "display": "none" }; } function calcNextPosition(options) { let offsetAmount = options.offset.amount; $(".bootstrap-growl").each(function() { offsetAmount = Math.max(offsetAmount, parseInt($(this).css(options.offset.from)) + $(this).outerHeight() + options.stackup_spacing); return offsetAmount; }); return offsetAmount; } function isArray(obj) { return obj && (obj.constructor == Array); } let GrowlNotify = { notify: function(message, opt) { let options = $.extend({}, createOptionsDefault(), opt); let growl = createGrowl(options, message); let offsetAmount = calcNextPosition(options); let css = createStyleClass(options); css[options.offset.from] = offsetAmount + "px"; growl.css(css); if (options.width !== "auto") { growl.css("width", options.width + "px"); } $(options.ele).append(growl); makeAlign(growl, options); growl.fadeIn(); if (options.delay > 0) { growl.delay(options.delay).fadeOut(function() { return $(this).alert("close"); }); } return growl; }, notifyOnErrors: function(msg) { if (isArray(msg)) { msg.map((value, index) => { this.notify(value.texto, { type: 'danger' }); }); return; } this.notify(msg, { type: 'danger' }); } } export default GrowlNotify;
if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset
random_line_split
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss) { growl.addClass("alert-dismissible"); growl.append("<button class=\"close\" data-dismiss=\"alert\" type=\"button\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>"); } growl.append(message); if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset }; } return growl; } function makeAlign(alert, options) { switch (options.align) { case "center": alert.css({ "left": "50%", "margin-left": "-" + (alert.outerWidth() / 2) + "px" }); break; case "left": alert.css("left", "20px"); break; default: alert.css("right", "20px"); } } function createOptionsDefault() { return { ele: "body", type: "info", offset: { from: "top", amount: 20 }, align: "right", width: 400, delay: 4000, allow_dismiss: true, stackup_spacing: 10 }; } function createStyleClass(options) { return { "position": (options.ele === "body" ? "fixed" : "absolute"), "margin": 0, "z-index": "9999", "display": "none" }; } function calcNextPosition(options) { let offsetAmount = options.offset.amount; $(".bootstrap-growl").each(function() { offsetAmount = Math.max(offsetAmount, parseInt($(this).css(options.offset.from)) + $(this).outerHeight() + options.stackup_spacing); return offsetAmount; }); return offsetAmount; } function isArray(obj)
let GrowlNotify = { notify: function(message, opt) { let options = $.extend({}, createOptionsDefault(), opt); let growl = createGrowl(options, message); let offsetAmount = calcNextPosition(options); let css = createStyleClass(options); css[options.offset.from] = offsetAmount + "px"; growl.css(css); if (options.width !== "auto") { growl.css("width", options.width + "px"); } $(options.ele).append(growl); makeAlign(growl, options); growl.fadeIn(); if (options.delay > 0) { growl.delay(options.delay).fadeOut(function() { return $(this).alert("close"); }); } return growl; }, notifyOnErrors: function(msg) { if (isArray(msg)) { msg.map((value, index) => { this.notify(value.texto, { type: 'danger' }); }); return; } this.notify(msg, { type: 'danger' }); } } export default GrowlNotify;
{ return obj && (obj.constructor == Array); }
identifier_body
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss) { growl.addClass("alert-dismissible"); growl.append("<button class=\"close\" data-dismiss=\"alert\" type=\"button\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>"); } growl.append(message); if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset }; } return growl; } function makeAlign(alert, options) { switch (options.align) { case "center": alert.css({ "left": "50%", "margin-left": "-" + (alert.outerWidth() / 2) + "px" }); break; case "left": alert.css("left", "20px"); break; default: alert.css("right", "20px"); } } function createOptionsDefault() { return { ele: "body", type: "info", offset: { from: "top", amount: 20 }, align: "right", width: 400, delay: 4000, allow_dismiss: true, stackup_spacing: 10 }; } function
(options) { return { "position": (options.ele === "body" ? "fixed" : "absolute"), "margin": 0, "z-index": "9999", "display": "none" }; } function calcNextPosition(options) { let offsetAmount = options.offset.amount; $(".bootstrap-growl").each(function() { offsetAmount = Math.max(offsetAmount, parseInt($(this).css(options.offset.from)) + $(this).outerHeight() + options.stackup_spacing); return offsetAmount; }); return offsetAmount; } function isArray(obj) { return obj && (obj.constructor == Array); } let GrowlNotify = { notify: function(message, opt) { let options = $.extend({}, createOptionsDefault(), opt); let growl = createGrowl(options, message); let offsetAmount = calcNextPosition(options); let css = createStyleClass(options); css[options.offset.from] = offsetAmount + "px"; growl.css(css); if (options.width !== "auto") { growl.css("width", options.width + "px"); } $(options.ele).append(growl); makeAlign(growl, options); growl.fadeIn(); if (options.delay > 0) { growl.delay(options.delay).fadeOut(function() { return $(this).alert("close"); }); } return growl; }, notifyOnErrors: function(msg) { if (isArray(msg)) { msg.map((value, index) => { this.notify(value.texto, { type: 'danger' }); }); return; } this.notify(msg, { type: 'danger' }); } } export default GrowlNotify;
createStyleClass
identifier_name
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import generate_roster_pdf from ...forms.admin.blocks import BlockForm, QuickBlockForm from ...models import EighthBlock, EighthScheduledActivity from ....auth.decorators import eighth_admin_required logger = logging.getLogger(__name__) @eighth_admin_required def add_block_view(request): if request.method == "POST" and "custom_block" in request.POST: form = QuickBlockForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Successfully added block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") request.session["add_block_form"] = pickle.dumps(form) date = None show_letters = None if "date" in request.GET: date = request.GET.get("date") if "date" in request.POST: date = request.POST.get("date") title_suffix = "" if date: date_format = re.compile(r'([0-9]{2})\/([0-9]{2})\/([0-9]{4})') fmtdate = date_format.sub(r'\3-\1-\2', date) logger.debug(fmtdate) title_suffix = " - {}".format(fmtdate) show_letters = True if "modify_blocks" in request.POST: letters = request.POST.getlist("blocks") current_letters = [] blocks_day = EighthBlock.objects.filter(date=fmtdate) for day in blocks_day: current_letters.append(day.block_letter) logger.debug(letters) logger.debug(current_letters) for l in letters: if len(l) == 0: continue if l not in current_letters: EighthBlock.objects.create(date=fmtdate, block_letter=l) messages.success(request, "Successfully added {} Block on {}".format(l, fmtdate)) for l in current_letters: if len(l) == 0: continue if l not in letters: EighthBlock.objects.get(date=fmtdate, block_letter=l).delete() messages.success(request, "Successfully removed {} Block on {}".format(l, fmtdate)) invalidate_model(EighthBlock) letters = [] visible_blocks = ["A", "B", "C", "D", "E", "F", "G", "H"] if show_letters: onday = EighthBlock.objects.filter(date=fmtdate) for l in visible_blocks: exists = onday.filter(block_letter=l) letters.append({"name": l, "exists": exists}) for blk in onday: if blk.block_letter not in visible_blocks: visible_blocks.append(blk.block_letter) letters.append({"name": blk.block_letter, "exists": True}) context = {"admin_page_title": "Add or Remove Blocks{}".format(title_suffix), "date": date, "letters": letters, "show_letters": show_letters, "add_block_form": QuickBlockForm} return render(request, "eighth/admin/add_block.html", context) @eighth_admin_required def edit_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": form = BlockForm(request.POST, instance=block) if form.is_valid(): form.save() invalidate_model(EighthBlock) messages.success(request, "Successfully edited block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") else: form = BlockForm(instance=block) context = {"form": form, "delete_url": reverse("eighth_admin_delete_block", args=[block_id]), "admin_page_title": "Edit Block"} return render(request, "eighth/admin/edit_form.html", context) @eighth_admin_required def delete_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST":
else: context = {"admin_page_title": "Delete Block", "item_name": str(block), "help_text": "Deleting this block will remove all records " "of it related to eighth period."} return render(request, "eighth/admin/delete_form.html", context) @eighth_admin_required def print_block_rosters_view(request, block_id): if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_pdf(sched_act_ids, True) response.write(pdf_buffer.getvalue()) pdf_buffer.close() return response else: try: block = EighthBlock.objects.get(id=block_id) schacts = EighthScheduledActivity.objects.filter(block=block).order_by("sponsors") schacts = sorted(schacts, key=lambda x: "{}".format(x.get_true_sponsors())) except (EighthBlock.DoesNotExist, EighthScheduledActivity.DoesNotExist): raise http.Http404 context = {"eighthblock": block, "admin_page_title": "Choose activities to print", "schacts": schacts} return render(request, "eighth/admin/choose_roster_activities.html", context)
block.delete() invalidate_model(EighthBlock) messages.success(request, "Successfully deleted block.") return redirect("eighth_admin_dashboard")
conditional_block
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import generate_roster_pdf from ...forms.admin.blocks import BlockForm, QuickBlockForm from ...models import EighthBlock, EighthScheduledActivity from ....auth.decorators import eighth_admin_required logger = logging.getLogger(__name__) @eighth_admin_required def add_block_view(request): if request.method == "POST" and "custom_block" in request.POST: form = QuickBlockForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Successfully added block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") request.session["add_block_form"] = pickle.dumps(form) date = None show_letters = None if "date" in request.GET: date = request.GET.get("date") if "date" in request.POST: date = request.POST.get("date") title_suffix = "" if date: date_format = re.compile(r'([0-9]{2})\/([0-9]{2})\/([0-9]{4})') fmtdate = date_format.sub(r'\3-\1-\2', date) logger.debug(fmtdate) title_suffix = " - {}".format(fmtdate) show_letters = True if "modify_blocks" in request.POST: letters = request.POST.getlist("blocks") current_letters = [] blocks_day = EighthBlock.objects.filter(date=fmtdate) for day in blocks_day: current_letters.append(day.block_letter) logger.debug(letters) logger.debug(current_letters) for l in letters: if len(l) == 0: continue if l not in current_letters: EighthBlock.objects.create(date=fmtdate, block_letter=l) messages.success(request, "Successfully added {} Block on {}".format(l, fmtdate)) for l in current_letters: if len(l) == 0: continue if l not in letters: EighthBlock.objects.get(date=fmtdate, block_letter=l).delete() messages.success(request, "Successfully removed {} Block on {}".format(l, fmtdate)) invalidate_model(EighthBlock) letters = [] visible_blocks = ["A", "B", "C", "D", "E", "F", "G", "H"] if show_letters: onday = EighthBlock.objects.filter(date=fmtdate) for l in visible_blocks: exists = onday.filter(block_letter=l) letters.append({"name": l, "exists": exists}) for blk in onday: if blk.block_letter not in visible_blocks: visible_blocks.append(blk.block_letter) letters.append({"name": blk.block_letter, "exists": True}) context = {"admin_page_title": "Add or Remove Blocks{}".format(title_suffix), "date": date, "letters": letters, "show_letters": show_letters, "add_block_form": QuickBlockForm} return render(request, "eighth/admin/add_block.html", context) @eighth_admin_required def edit_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": form = BlockForm(request.POST, instance=block) if form.is_valid(): form.save() invalidate_model(EighthBlock) messages.success(request, "Successfully edited block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") else: form = BlockForm(instance=block) context = {"form": form, "delete_url": reverse("eighth_admin_delete_block", args=[block_id]), "admin_page_title": "Edit Block"} return render(request, "eighth/admin/edit_form.html", context) @eighth_admin_required def delete_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": block.delete() invalidate_model(EighthBlock) messages.success(request, "Successfully deleted block.") return redirect("eighth_admin_dashboard") else: context = {"admin_page_title": "Delete Block", "item_name": str(block), "help_text": "Deleting this block will remove all records " "of it related to eighth period."} return render(request, "eighth/admin/delete_form.html", context) @eighth_admin_required def
(request, block_id): if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_pdf(sched_act_ids, True) response.write(pdf_buffer.getvalue()) pdf_buffer.close() return response else: try: block = EighthBlock.objects.get(id=block_id) schacts = EighthScheduledActivity.objects.filter(block=block).order_by("sponsors") schacts = sorted(schacts, key=lambda x: "{}".format(x.get_true_sponsors())) except (EighthBlock.DoesNotExist, EighthScheduledActivity.DoesNotExist): raise http.Http404 context = {"eighthblock": block, "admin_page_title": "Choose activities to print", "schacts": schacts} return render(request, "eighth/admin/choose_roster_activities.html", context)
print_block_rosters_view
identifier_name
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import generate_roster_pdf from ...forms.admin.blocks import BlockForm, QuickBlockForm from ...models import EighthBlock, EighthScheduledActivity from ....auth.decorators import eighth_admin_required logger = logging.getLogger(__name__) @eighth_admin_required def add_block_view(request): if request.method == "POST" and "custom_block" in request.POST: form = QuickBlockForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Successfully added block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") request.session["add_block_form"] = pickle.dumps(form) date = None show_letters = None if "date" in request.GET: date = request.GET.get("date") if "date" in request.POST: date = request.POST.get("date") title_suffix = "" if date: date_format = re.compile(r'([0-9]{2})\/([0-9]{2})\/([0-9]{4})') fmtdate = date_format.sub(r'\3-\1-\2', date) logger.debug(fmtdate) title_suffix = " - {}".format(fmtdate) show_letters = True if "modify_blocks" in request.POST: letters = request.POST.getlist("blocks") current_letters = [] blocks_day = EighthBlock.objects.filter(date=fmtdate) for day in blocks_day: current_letters.append(day.block_letter) logger.debug(letters) logger.debug(current_letters) for l in letters: if len(l) == 0: continue if l not in current_letters: EighthBlock.objects.create(date=fmtdate, block_letter=l) messages.success(request, "Successfully added {} Block on {}".format(l, fmtdate)) for l in current_letters: if len(l) == 0: continue if l not in letters: EighthBlock.objects.get(date=fmtdate, block_letter=l).delete() messages.success(request, "Successfully removed {} Block on {}".format(l, fmtdate)) invalidate_model(EighthBlock) letters = [] visible_blocks = ["A", "B", "C", "D", "E", "F", "G", "H"] if show_letters: onday = EighthBlock.objects.filter(date=fmtdate) for l in visible_blocks: exists = onday.filter(block_letter=l) letters.append({"name": l, "exists": exists}) for blk in onday: if blk.block_letter not in visible_blocks: visible_blocks.append(blk.block_letter) letters.append({"name": blk.block_letter, "exists": True}) context = {"admin_page_title": "Add or Remove Blocks{}".format(title_suffix), "date": date, "letters": letters, "show_letters": show_letters, "add_block_form": QuickBlockForm} return render(request, "eighth/admin/add_block.html", context) @eighth_admin_required def edit_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": form = BlockForm(request.POST, instance=block) if form.is_valid(): form.save() invalidate_model(EighthBlock) messages.success(request, "Successfully edited block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") else: form = BlockForm(instance=block) context = {"form": form, "delete_url": reverse("eighth_admin_delete_block", args=[block_id]), "admin_page_title": "Edit Block"} return render(request, "eighth/admin/edit_form.html", context) @eighth_admin_required def delete_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": block.delete() invalidate_model(EighthBlock) messages.success(request, "Successfully deleted block.") return redirect("eighth_admin_dashboard") else: context = {"admin_page_title": "Delete Block", "item_name": str(block), "help_text": "Deleting this block will remove all records " "of it related to eighth period."} return render(request, "eighth/admin/delete_form.html", context) @eighth_admin_required def print_block_rosters_view(request, block_id):
if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_pdf(sched_act_ids, True) response.write(pdf_buffer.getvalue()) pdf_buffer.close() return response else: try: block = EighthBlock.objects.get(id=block_id) schacts = EighthScheduledActivity.objects.filter(block=block).order_by("sponsors") schacts = sorted(schacts, key=lambda x: "{}".format(x.get_true_sponsors())) except (EighthBlock.DoesNotExist, EighthScheduledActivity.DoesNotExist): raise http.Http404 context = {"eighthblock": block, "admin_page_title": "Choose activities to print", "schacts": schacts} return render(request, "eighth/admin/choose_roster_activities.html", context)
identifier_body
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import generate_roster_pdf from ...forms.admin.blocks import BlockForm, QuickBlockForm from ...models import EighthBlock, EighthScheduledActivity from ....auth.decorators import eighth_admin_required logger = logging.getLogger(__name__) @eighth_admin_required def add_block_view(request): if request.method == "POST" and "custom_block" in request.POST: form = QuickBlockForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Successfully added block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") request.session["add_block_form"] = pickle.dumps(form) date = None show_letters = None if "date" in request.GET: date = request.GET.get("date") if "date" in request.POST: date = request.POST.get("date") title_suffix = "" if date: date_format = re.compile(r'([0-9]{2})\/([0-9]{2})\/([0-9]{4})') fmtdate = date_format.sub(r'\3-\1-\2', date) logger.debug(fmtdate) title_suffix = " - {}".format(fmtdate) show_letters = True if "modify_blocks" in request.POST: letters = request.POST.getlist("blocks") current_letters = [] blocks_day = EighthBlock.objects.filter(date=fmtdate) for day in blocks_day: current_letters.append(day.block_letter) logger.debug(letters) logger.debug(current_letters) for l in letters: if len(l) == 0: continue if l not in current_letters: EighthBlock.objects.create(date=fmtdate, block_letter=l) messages.success(request, "Successfully added {} Block on {}".format(l, fmtdate)) for l in current_letters: if len(l) == 0: continue if l not in letters: EighthBlock.objects.get(date=fmtdate, block_letter=l).delete() messages.success(request, "Successfully removed {} Block on {}".format(l, fmtdate)) invalidate_model(EighthBlock) letters = [] visible_blocks = ["A", "B", "C", "D", "E", "F", "G", "H"] if show_letters: onday = EighthBlock.objects.filter(date=fmtdate) for l in visible_blocks: exists = onday.filter(block_letter=l) letters.append({"name": l, "exists": exists}) for blk in onday: if blk.block_letter not in visible_blocks: visible_blocks.append(blk.block_letter) letters.append({"name": blk.block_letter, "exists": True}) context = {"admin_page_title": "Add or Remove Blocks{}".format(title_suffix), "date": date, "letters": letters, "show_letters": show_letters, "add_block_form": QuickBlockForm} return render(request, "eighth/admin/add_block.html", context) @eighth_admin_required def edit_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST":
form.save() invalidate_model(EighthBlock) messages.success(request, "Successfully edited block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") else: form = BlockForm(instance=block) context = {"form": form, "delete_url": reverse("eighth_admin_delete_block", args=[block_id]), "admin_page_title": "Edit Block"} return render(request, "eighth/admin/edit_form.html", context) @eighth_admin_required def delete_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": block.delete() invalidate_model(EighthBlock) messages.success(request, "Successfully deleted block.") return redirect("eighth_admin_dashboard") else: context = {"admin_page_title": "Delete Block", "item_name": str(block), "help_text": "Deleting this block will remove all records " "of it related to eighth period."} return render(request, "eighth/admin/delete_form.html", context) @eighth_admin_required def print_block_rosters_view(request, block_id): if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_pdf(sched_act_ids, True) response.write(pdf_buffer.getvalue()) pdf_buffer.close() return response else: try: block = EighthBlock.objects.get(id=block_id) schacts = EighthScheduledActivity.objects.filter(block=block).order_by("sponsors") schacts = sorted(schacts, key=lambda x: "{}".format(x.get_true_sponsors())) except (EighthBlock.DoesNotExist, EighthScheduledActivity.DoesNotExist): raise http.Http404 context = {"eighthblock": block, "admin_page_title": "Choose activities to print", "schacts": schacts} return render(request, "eighth/admin/choose_roster_activities.html", context)
form = BlockForm(request.POST, instance=block) if form.is_valid():
random_line_split
tooltip.d.ts
// Type definitions for iview 3.1.0 // Project: https://github.com/iview/iview // Definitions by: yangdan // Definitions: https://github.com/yangdan8/iview.git import Vue, { VNode } from 'vue';
/** * 显示的内容 * @default 空 */ content?: string | number; /** * 提示框出现的位置,可选值为 * top,top-start,top-end,bottom,bottom-start,bottom-end, * left,left-start,left-end,right,right-start,right-end * 2.12.0 版本开始支持自动识别 * @default bottom */ placement?: 'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end' | 'right' | 'right-start' | 'right-end'; /** * 是否禁用提示框 * @default false */ disabled?: boolean; /** * 延迟显示,单位毫秒 * @default 0 */ delay?: number; /** * 是否总是可见 * @default false */ always?: boolean; /** * 主题,可选值为 dark 或 light * @default dark */ theme?: string; /** * 最大宽度,超出最大值后,文本将自动换行,并两端对齐 */ 'max-width'?: string|number; /** * 出现位置的偏移量 * @default 0 */ offset?: number; /** * 是否将弹层放置于 body 内,在 Tabs、带有 fixed 的 Table 列内使用时, * 建议添加此属性,它将不受父级样式影响,从而达到更好的效果 * @default false */ transfer?: boolean; /** * 出现位置的偏移量 * @default { modifiers: { computeStyle:{ gpuAcceleration: false, }, preventOverflow :{ boundariesElement: 'window' } } } */ options?: object; /** * 在提示框显示时触发 */ $emit(eventName: 'on-popper-show'): this; /** * 在提示框消失时触发 */ $emit(eventName: 'on-popper-hide'): this; /** * slot插槽对象 */ $slots: { /** * 主体内容 */ '': VNode[]; /** * 提示框的内容,定义此 slot 时,会覆盖 props content。 */ content: VNode[]; }; }
export declare interface Tooltip extends Vue {
random_line_split
ProofTree.js
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; }
() { return this.newScope; } isEmpty() { return this.parent === null && this.children === []; } size() { if (this.isEmpty()) return 0; if (this.children.length) return 1 + this.children.map(c=>c.size()).reduce((acc, c)=>acc+c); return 1; } lastNumber() { return this.size(); } walk(fn) { fn(this); this.children.forEach(child => { child.walk(fn); }); } last() { if (this.children.length === 0) return this; var last = this; this.children.forEach(child => { if (!child.isAssumption()) { last = child.last(); } }); return last; } setLines() { var count = 1; this.walk((child) => { child.lineNumber = count; count ++; }); } root() { if (this.parent === null) return this; return this.parent.root(); } inScope(target) { if (this.lineNumber === target) { return true; } else { if (this.parent === null) return false; var child = null; var anySiblings = this.parent.children.some(child => { return !child.isAssumption() && (child.lineNumber === target) }) if (anySiblings) { return true; } return this.parent.inScope(target); } } // inScope(line1, line2, context=this.root()) { // // if (line1 === line2) return true; // if (line1 > line2) return false; // var line1Obj = context.line(line1); // var line2Obj = context.line(line2); // return this.inScope(line1Obj.lineNumber, line2Obj.parent.lineNumber, context); // } line(lineNumber) { var line = null; var count = 1; this.walk(child => { if (lineNumber === count) line = child; count ++; }); return line; } addLine(line) { line.parent = this.last(); line.parent.children.push(line); this.root().setLines(); } closeBox() { this.isSound = true; } addLineTo(line, lineNumber) { // line.parent = this.line() } addLineNewScope({equation, rule}) { var line = new ProofTree({ equation, rule, newScope: true }); line.parent = this.last(); this.children.push(line); line.root().setLines(); } } // Synonym as it reads better sometimes ProofTree.prototype.scope = ProofTree.prototype.line; export default ProofTree;
isAssumption
identifier_name
ProofTree.js
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; } isAssumption() { return this.newScope; } isEmpty() { return this.parent === null && this.children === []; } size() { if (this.isEmpty()) return 0; if (this.children.length) return 1 + this.children.map(c=>c.size()).reduce((acc, c)=>acc+c); return 1; } lastNumber() { return this.size(); } walk(fn) { fn(this); this.children.forEach(child => { child.walk(fn); }); } last() { if (this.children.length === 0) return this; var last = this; this.children.forEach(child => { if (!child.isAssumption()) { last = child.last(); } }); return last; } setLines() { var count = 1; this.walk((child) => { child.lineNumber = count; count ++; }); } root()
inScope(target) { if (this.lineNumber === target) { return true; } else { if (this.parent === null) return false; var child = null; var anySiblings = this.parent.children.some(child => { return !child.isAssumption() && (child.lineNumber === target) }) if (anySiblings) { return true; } return this.parent.inScope(target); } } // inScope(line1, line2, context=this.root()) { // // if (line1 === line2) return true; // if (line1 > line2) return false; // var line1Obj = context.line(line1); // var line2Obj = context.line(line2); // return this.inScope(line1Obj.lineNumber, line2Obj.parent.lineNumber, context); // } line(lineNumber) { var line = null; var count = 1; this.walk(child => { if (lineNumber === count) line = child; count ++; }); return line; } addLine(line) { line.parent = this.last(); line.parent.children.push(line); this.root().setLines(); } closeBox() { this.isSound = true; } addLineTo(line, lineNumber) { // line.parent = this.line() } addLineNewScope({equation, rule}) { var line = new ProofTree({ equation, rule, newScope: true }); line.parent = this.last(); this.children.push(line); line.root().setLines(); } } // Synonym as it reads better sometimes ProofTree.prototype.scope = ProofTree.prototype.line; export default ProofTree;
{ if (this.parent === null) return this; return this.parent.root(); }
identifier_body
ProofTree.js
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; } isAssumption() { return this.newScope; } isEmpty() { return this.parent === null && this.children === []; } size() { if (this.isEmpty()) return 0; if (this.children.length) return 1 + this.children.map(c=>c.size()).reduce((acc, c)=>acc+c); return 1; } lastNumber() { return this.size(); } walk(fn) { fn(this); this.children.forEach(child => { child.walk(fn); }); } last() { if (this.children.length === 0) return this; var last = this; this.children.forEach(child => { if (!child.isAssumption()) { last = child.last(); } }); return last; } setLines() { var count = 1; this.walk((child) => { child.lineNumber = count; count ++; }); } root() { if (this.parent === null) return this; return this.parent.root(); } inScope(target) { if (this.lineNumber === target) { return true; } else { if (this.parent === null) return false; var child = null; var anySiblings = this.parent.children.some(child => { return !child.isAssumption() && (child.lineNumber === target) }) if (anySiblings) {
} } // inScope(line1, line2, context=this.root()) { // // if (line1 === line2) return true; // if (line1 > line2) return false; // var line1Obj = context.line(line1); // var line2Obj = context.line(line2); // return this.inScope(line1Obj.lineNumber, line2Obj.parent.lineNumber, context); // } line(lineNumber) { var line = null; var count = 1; this.walk(child => { if (lineNumber === count) line = child; count ++; }); return line; } addLine(line) { line.parent = this.last(); line.parent.children.push(line); this.root().setLines(); } closeBox() { this.isSound = true; } addLineTo(line, lineNumber) { // line.parent = this.line() } addLineNewScope({equation, rule}) { var line = new ProofTree({ equation, rule, newScope: true }); line.parent = this.last(); this.children.push(line); line.root().setLines(); } } // Synonym as it reads better sometimes ProofTree.prototype.scope = ProofTree.prototype.line; export default ProofTree;
return true; } return this.parent.inScope(target);
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; import { RouterModule, PreloadAllModules } from '@angular/router'; import { DragulaModule } from 'ng2-dragula'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; /* * Platform and Environment providers/directives/pipes */ import { ENV_PROVIDERS } from './environment'; import { ROUTES } from './app.routes'; import { AUTHENTICATION_PARAMETER, AuthenticationParameter } from './authentication/parameter'; import { IAuthenticationService, AuthenticationService } from './authentication/service'; import { InstagramAuthenticationService } from './authentication/service/instagram'; // App is our top level component import { AppComponent } from './app.component'; import { APP_RESOLVER_PROVIDERS } from './app.resolver'; import { AppState, InternalStateType } from './app.service'; import { ScrapperComponent } from './scrapper'; import { MediaContainerComponent } from './scrapper/media'; import { RedirectComponent } from './redirect'; import { SettingsComponent } from './settings'; import { ElipsisDirective } from './scrapper/elipsis'; import '../styles/styles.scss'; import '../styles/headings.css'; // Application wide providers const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS, AppState ]; type StoreType = { state: InternalStateType, restoreInputValues: () => void, disposeOldHosts: () => void }; /** * `AppModule` is the main entry point into Angular2's bootstraping process */ @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, ScrapperComponent, MediaContainerComponent, RedirectComponent, SettingsComponent, ElipsisDirective ], imports: [ // import Angular's modules BrowserModule, FormsModule, HttpModule, DragulaModule, JsonpModule, RouterModule.forRoot(ROUTES, { preloadingStrategy: PreloadAllModules }), NgbModule.forRoot() ], providers: [ // expose our Services and Providers into Angular's dependency injection ENV_PROVIDERS, APP_PROVIDERS, { provide: AUTHENTICATION_PARAMETER, useValue: { clientId: '9a502ab143604ca3a677647eb062f310', redirectUrl: 'http://localhost:3000/redirect', responseType: 'token', scope: 'public_content' } }, { provide: IAuthenticationService, useClass: InstagramAuthenticationService } ] }) export class AppModule { constructor( public appRef: ApplicationRef, public appState: AppState ) {} public
(store: StoreType) { if (!store || !store.state) { return; } console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state; // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues); } this.appRef.tick(); delete store.state; delete store.restoreInputValues; } public hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement); // save state const state = this.appState._state; store.state = state; // recreate root elements store.disposeOldHosts = createNewHosts(cmpLocation); // save input values store.restoreInputValues = createInputTransfer(); // remove styles removeNgStyles(); } public hmrAfterDestroy(store: StoreType) { // display new elements store.disposeOldHosts(); delete store.disposeOldHosts; } }
hmrOnInit
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; import { RouterModule, PreloadAllModules } from '@angular/router'; import { DragulaModule } from 'ng2-dragula'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; /* * Platform and Environment providers/directives/pipes */ import { ENV_PROVIDERS } from './environment'; import { ROUTES } from './app.routes'; import { AUTHENTICATION_PARAMETER, AuthenticationParameter } from './authentication/parameter'; import { IAuthenticationService, AuthenticationService } from './authentication/service'; import { InstagramAuthenticationService } from './authentication/service/instagram'; // App is our top level component import { AppComponent } from './app.component'; import { APP_RESOLVER_PROVIDERS } from './app.resolver'; import { AppState, InternalStateType } from './app.service'; import { ScrapperComponent } from './scrapper'; import { MediaContainerComponent } from './scrapper/media'; import { RedirectComponent } from './redirect'; import { SettingsComponent } from './settings'; import { ElipsisDirective } from './scrapper/elipsis'; import '../styles/styles.scss'; import '../styles/headings.css'; // Application wide providers const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS, AppState ]; type StoreType = { state: InternalStateType, restoreInputValues: () => void, disposeOldHosts: () => void }; /** * `AppModule` is the main entry point into Angular2's bootstraping process */ @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, ScrapperComponent, MediaContainerComponent, RedirectComponent, SettingsComponent, ElipsisDirective ], imports: [ // import Angular's modules BrowserModule, FormsModule, HttpModule, DragulaModule, JsonpModule, RouterModule.forRoot(ROUTES, { preloadingStrategy: PreloadAllModules }), NgbModule.forRoot() ], providers: [ // expose our Services and Providers into Angular's dependency injection ENV_PROVIDERS, APP_PROVIDERS, { provide: AUTHENTICATION_PARAMETER, useValue: { clientId: '9a502ab143604ca3a677647eb062f310', redirectUrl: 'http://localhost:3000/redirect', responseType: 'token', scope: 'public_content' } }, { provide: IAuthenticationService, useClass: InstagramAuthenticationService } ] }) export class AppModule { constructor( public appRef: ApplicationRef, public appState: AppState )
public hmrOnInit(store: StoreType) { if (!store || !store.state) { return; } console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state; // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues); } this.appRef.tick(); delete store.state; delete store.restoreInputValues; } public hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement); // save state const state = this.appState._state; store.state = state; // recreate root elements store.disposeOldHosts = createNewHosts(cmpLocation); // save input values store.restoreInputValues = createInputTransfer(); // remove styles removeNgStyles(); } public hmrAfterDestroy(store: StoreType) { // display new elements store.disposeOldHosts(); delete store.disposeOldHosts; } }
{}
identifier_body
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; import { RouterModule, PreloadAllModules } from '@angular/router'; import { DragulaModule } from 'ng2-dragula'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; /* * Platform and Environment providers/directives/pipes */ import { ENV_PROVIDERS } from './environment'; import { ROUTES } from './app.routes'; import { AUTHENTICATION_PARAMETER, AuthenticationParameter } from './authentication/parameter'; import { IAuthenticationService, AuthenticationService } from './authentication/service'; import { InstagramAuthenticationService } from './authentication/service/instagram'; // App is our top level component import { AppComponent } from './app.component'; import { APP_RESOLVER_PROVIDERS } from './app.resolver'; import { AppState, InternalStateType } from './app.service'; import { ScrapperComponent } from './scrapper'; import { MediaContainerComponent } from './scrapper/media'; import { RedirectComponent } from './redirect'; import { SettingsComponent } from './settings'; import { ElipsisDirective } from './scrapper/elipsis'; import '../styles/styles.scss'; import '../styles/headings.css'; // Application wide providers const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS, AppState ]; type StoreType = { state: InternalStateType, restoreInputValues: () => void, disposeOldHosts: () => void }; /** * `AppModule` is the main entry point into Angular2's bootstraping process */ @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, ScrapperComponent, MediaContainerComponent, RedirectComponent, SettingsComponent, ElipsisDirective ], imports: [ // import Angular's modules BrowserModule, FormsModule, HttpModule, DragulaModule, JsonpModule, RouterModule.forRoot(ROUTES, { preloadingStrategy: PreloadAllModules }), NgbModule.forRoot() ], providers: [ // expose our Services and Providers into Angular's dependency injection ENV_PROVIDERS, APP_PROVIDERS, { provide: AUTHENTICATION_PARAMETER, useValue: { clientId: '9a502ab143604ca3a677647eb062f310', redirectUrl: 'http://localhost:3000/redirect', responseType: 'token', scope: 'public_content' } }, { provide: IAuthenticationService, useClass: InstagramAuthenticationService } ] }) export class AppModule { constructor( public appRef: ApplicationRef, public appState: AppState ) {} public hmrOnInit(store: StoreType) { if (!store || !store.state) { return; } console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state;
} this.appRef.tick(); delete store.state; delete store.restoreInputValues; } public hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement); // save state const state = this.appState._state; store.state = state; // recreate root elements store.disposeOldHosts = createNewHosts(cmpLocation); // save input values store.restoreInputValues = createInputTransfer(); // remove styles removeNgStyles(); } public hmrAfterDestroy(store: StoreType) { // display new elements store.disposeOldHosts(); delete store.disposeOldHosts; } }
// set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues);
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; import { RouterModule, PreloadAllModules } from '@angular/router'; import { DragulaModule } from 'ng2-dragula'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; /* * Platform and Environment providers/directives/pipes */ import { ENV_PROVIDERS } from './environment'; import { ROUTES } from './app.routes'; import { AUTHENTICATION_PARAMETER, AuthenticationParameter } from './authentication/parameter'; import { IAuthenticationService, AuthenticationService } from './authentication/service'; import { InstagramAuthenticationService } from './authentication/service/instagram'; // App is our top level component import { AppComponent } from './app.component'; import { APP_RESOLVER_PROVIDERS } from './app.resolver'; import { AppState, InternalStateType } from './app.service'; import { ScrapperComponent } from './scrapper'; import { MediaContainerComponent } from './scrapper/media'; import { RedirectComponent } from './redirect'; import { SettingsComponent } from './settings'; import { ElipsisDirective } from './scrapper/elipsis'; import '../styles/styles.scss'; import '../styles/headings.css'; // Application wide providers const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS, AppState ]; type StoreType = { state: InternalStateType, restoreInputValues: () => void, disposeOldHosts: () => void }; /** * `AppModule` is the main entry point into Angular2's bootstraping process */ @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, ScrapperComponent, MediaContainerComponent, RedirectComponent, SettingsComponent, ElipsisDirective ], imports: [ // import Angular's modules BrowserModule, FormsModule, HttpModule, DragulaModule, JsonpModule, RouterModule.forRoot(ROUTES, { preloadingStrategy: PreloadAllModules }), NgbModule.forRoot() ], providers: [ // expose our Services and Providers into Angular's dependency injection ENV_PROVIDERS, APP_PROVIDERS, { provide: AUTHENTICATION_PARAMETER, useValue: { clientId: '9a502ab143604ca3a677647eb062f310', redirectUrl: 'http://localhost:3000/redirect', responseType: 'token', scope: 'public_content' } }, { provide: IAuthenticationService, useClass: InstagramAuthenticationService } ] }) export class AppModule { constructor( public appRef: ApplicationRef, public appState: AppState ) {} public hmrOnInit(store: StoreType) { if (!store || !store.state)
console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state; // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues); } this.appRef.tick(); delete store.state; delete store.restoreInputValues; } public hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement); // save state const state = this.appState._state; store.state = state; // recreate root elements store.disposeOldHosts = createNewHosts(cmpLocation); // save input values store.restoreInputValues = createInputTransfer(); // remove styles removeNgStyles(); } public hmrAfterDestroy(store: StoreType) { // display new elements store.disposeOldHosts(); delete store.disposeOldHosts; } }
{ return; }
conditional_block
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] extern crate ipc_channel; extern crate msg; #[macro_use] extern crate serde_derive; pub extern crate rust_webvr as webvr; mod webvr_traits; pub use webvr::VRDisplayData as WebVRDisplayData; pub use webvr::VRDisplayCapabilities as WebVRDisplayCapabilities; pub use webvr::VRDisplayEvent as WebVRDisplayEvent; pub use webvr::VRDisplayEventReason as WebVRDisplayEventReason; pub use webvr::VREye as WebVREye; pub use webvr::VREyeParameters as WebVREyeParameters; pub use webvr::VRFieldOfView as WebVRFieldOfView; pub use webvr::VRFrameData as WebVRFrameData; pub use webvr::VRLayer as WebVRLayer;
pub use webvr::VRStageParameters as WebVRStageParameters; pub use webvr_traits::{WebVRMsg, WebVRResult};
pub use webvr::VRPose as WebVRPose;
random_line_split
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase from cloudscape.common.utils import JSONTemplate from cloudscape.engine.api.auth.key import APIKey from cloudscape.engine.api.auth.acl import ACLGateway from cloudscape.common.utils import valid, invalid from cloudscape.engine.api.auth.token import APIToken from cloudscape.engine.api.app.auth.models import DBAuthEndpoints from cloudscape.engine.api.app.user.models import DBUserDetails # Configuration / Logger CONF = config.parse() LOG = logger.create('cloudscape.engine.api.core.request', CONF.server.log) def dispatch(request): """ The entry point for all API requests. Called for all endpoints from the Django URLs file. Creates a new instance of the EndpointManager class, and returns any HTTP response to the client that opened the API request. :param request: The Django request object :type request: object :rtype: object """ try: # Return the response from the endpoint handler return EndpointManager(request).handler() # Critical server error except Exception as e: LOG.exception('Internal server error: %s' % str(e)) # Return a 500 error return HttpResponseServerError('Internal server error, please contact your administrator.') class EndpointManager: """ The endpoint request manager class. Serves as the entry point for all API request, both for authentication requests, and already authenticated requests. Constructs the base API class, loads API utilities, and performs a number of other functions to prepare the API for the incoming request. The EndpointManager class is instantiated by the dispatch method, which is called by the Django URLs module file. It is initialized with the Django request object. """ def __init__(self, request): self.request_raw = request # Request properties self.method = None self.request = None self.endpoint = None self.action = None self.path = None # Request endpoint handler self.handler_obj = None # API parameters self.api_name = None self.api_mod = None self.api_class = None self.api_user = None self.api_group = None # API base object self.api_base = None # Request error def _req_error(self, err): err_response = { 'message': 'An error occured when processing the API request', 'endpoint': self.endpoint, 'error': err } LOG.error('%s:%s' % (self.endpoint, err)) return HttpResponse(json.dumps(err_response), content_type='application/json', status=400) def _authenticate(self): """ Authenticate the API request. """ # Set the API user and group self.api_user = self.request['api_user'] self.api_group = None if not ('api_group' in self.request) else self.request['api_group'] LOG.info('Authenticating API user: %s, group=%s' % (self.api_user, repr(self.api_group))) # Authenticate key for token requests if self.endpoint == 'auth/get': auth_status = APIKey().validate(self.request) if not auth_status['valid']: return self._req_error(auth_status['content']) LOG.info('API key authentication successfull for user: %s' % self.api_user) # Authenticate token for API requests else: if not APIToken().validate(self.request): return self._req_error('Failed to validate API token for user \'%s\'' % self.api_user) LOG.info('API token authentication successfull for user: %s' % self.api_user) # Check for a user account if DBUserDetails.objects.filter(username=self.api_user).count(): # If no API group was supplied if not self.api_group: return self._req_error('User accounts must supply a group UUID when making a request using the <api_group> parameter') # Make sure the group exists and the user is a member is_member = False for group in DBUserDetails.objects.get(username=self.api_user).get_groups(): if group['uuid'] == self.api_group: is_member = True break # If the user is not a member of the group if not is_member: return self._req_error('User account <%s> is not a member of group <%s>' % (self.api_user, self.api_group)) # Validate the request def _validate(self): # Request body / method self.request = json.loads(self.request_raw.body) self.method = self.request_raw.META['REQUEST_METHOD'] # Make sure a request action is set if not 'action' in self.request: return self._req_error('Request body requires an <action> parameter for endpoint pathing') self.action = self.request['action'] # Get the request path self.path = re.compile('^\/(.*$)').sub(r'\g<1>', self.request_raw.META['PATH_INFO']) # Set the request endpoint self.endpoint = '%s/%s' % (self.path, self.action) # Map the path to a module, class, and API name self.handler_obj = EndpointMapper(self.endpoint, self.method).handler() if not self.handler_obj['valid']: return self._req_error(self.handler_obj['content']) # Validate the request body request_err = JSONTemplate(self.handler_obj['content']['api_map']).validate(self.request) if request_err: return self._req_error(request_err) # Set the handler objects self.api_name = self.handler_obj['content']['api_name'] self.api_mod = self.handler_obj['content']['api_mod'] self.api_class = self.handler_obj['content']['api_class'] self.api_utils = self.handler_obj['content']['api_utils'] def handler(self): """ The endpoint manager request handler. Performs a number of validation steps before passing off the request to the API utility class. 1.) Looks for the base required request parameters 2.) Maps the endpoint and request action to an API utility and validates the request body 3.) Authenticates the user and API key/token 4.) Initializes any required Socket.IO connections for web clients 5.) Launches the API utility class to process the request 6.) Returns either an HTTP response with the status of the request """ # Parse the request try: validate_err = self._validate() if validate_err: return validate_err except Exception as e: LOG.exception('Exception while validating request: %s' % str(e)) return self._req_error('Internal server error, failed to validate the request') # Authenticate the request try: auth_err = self._authenticate() if auth_err: return auth_err except Exception as e: LOG.exception('Exception while authenticating the request: %s' % str(e)) return self._req_error('Internal server error, failed to authenticate the request') # Check the request against ACLs acl_gateway = ACLGateway(self.request, self.endpoint, self.api_user) # If the user is not authorized for this endpoint/object combination if not acl_gateway.authorized:
# Set up the API base try: # Create an instance of the APIBase and run the constructor api_obj = APIBase( name = self.api_name, endpoint = self.endpoint, utils = self.api_utils, acl = acl_gateway ).construct(self.request_raw) # Make sure the construct ran successfully if not api_obj['valid']: return self._req_error(api_obj['content']) # Set the API base object for endpoint utilities self.api_base = api_obj['content'] # Failed to setup the APIBase except Exception as e: LOG.exception('Failed to set up API base: %s' % str(e)) return self._req_error('Internal server, failed to set up API base') # Load the handler module and class handler_mod = importlib.import_module(self.api_mod) handler_class = getattr(handler_mod, self.api_class) handler_inst = handler_class(self.api_base) # Launch the request handler and return the response try: response = handler_inst.launch() # Critical error when running handler except Exception as e: LOG.exception('Exeption while running API handler: %s' % str(e)) return self._req_error('Encountered API handler error') # Close any open SocketIO connections self.api_base.socket.disconnect() # Return either a valid or invalid request response if response['valid']: return self.api_base.log.success(response['content'], response['data']) return self.api_base.log.error(code=response['code'], log_msg=response['content']) class EndpointMapper: """ API class used to construct the endpoint map. Scans the endpoint request templates in the API templates directory to construct a map used to load required utilities and modules, as well as validate the request for each endpoint. Each map also contains ACL parameters used when constructing the ACL database tables. """ def __init__(self, endpoint=None, method=None): """ Construct the EndpointMapper class. @param endpoint: The endpoint path @type endpoint: str @param method: The request method @type method: str """ self.endpoint = endpoint self.method = method self.map = {} def _merge_auth(self,j,e): """ Helper method used to merge token authentication parameters into the endpoint request map. Mainly so I don't have to redundantly include the same code in every map. Also makes modification much easier. """ # Ignore the authentication endpoint, as this is used to retrieve the token if e == 'auth/get': return # Required / optional connection parameters j['root']['_required'].extend(['api_user', 'api_token', 'action']) j['root']['_optional'].extend(['api_group']) # Connection parameter types t = { 'api_user': 'str', 'api_token': 'str', 'action': 'str', 'api_group': 'uuid4' } for k,v in t.iteritems(): j['root']['_children'][k] = { '_type': v } def _merge_socket(self,j): """ Merge request parameters for web socket request. Used for handling connections being passed along by the Socket.IO API proxy. """ # Load the socket request validator map sv = json.loads(open('%s/socket.json' % T_BASE, 'r').read()) # Make sure the '_children' key exists if not '_children' in j['root']: j['root']['_children'] = {} # Merge the socket parameters map j['root']['_children']['socket'] = sv j['root']['_optional'].append('socket') def _build_map(self): """ Load all endpoint definitions. """ for endpoint in list(DBAuthEndpoints.objects.all().values()): # Try to load the request map try: endpoint_rmap = json.loads(endpoint['rmap']) # Map base object rmap_base = { 'root': endpoint_rmap } # Merge the web socket request validator self._merge_socket(rmap_base) # Merge the authentication request validation parameters self._merge_auth(rmap_base, endpoint['name']) # Load the endpoint request handler module string self.map[endpoint['name']] = { 'module': endpoint['mod'], 'class': endpoint['cls'], 'name': endpoint['name'], 'desc': endpoint['desc'], 'method': endpoint['method'], 'utils': None if not endpoint['utils'] else json.loads(endpoint['utils']), 'json': rmap_base } # Error constructing request map, skip to next endpoint map except Exception as e: LOG.exception('Failed to load request map for endpoint <%s>: %s ' % (endpoint['name'], str(e))) continue # All template maps constructed return valid(LOG.info('Constructed API template map')) def handler(self): """ Main method for constructing and returning the endpoint map. @return valid|invalid """ map_rsp = self._build_map() if not map_rsp['valid']: return map_rsp # Request path missing if not self.endpoint: return invalid(LOG.error('Missing request endpoint')) # Invalid request path if not self.endpoint in self.map: return invalid(LOG.error('Unsupported request endpoint: <%s>' % self.endpoint)) # Verify the request method if self.method != self.map[self.endpoint]['method']: return invalid(LOG.error('Unsupported request method <%s> for endpoint <%s>' % (self.method, self.endpoint))) # Get the API module, class handler, and name self.handler_obj = { 'api_mod': self.map[self.endpoint]['module'], 'api_class': self.map[self.endpoint]['class'], 'api_name': self.map[self.endpoint]['name'], 'api_utils': self.map[self.endpoint]['utils'], 'api_map': self.map[self.endpoint]['json'] } LOG.info('Parsed handler object for API endpoint <%s>: %s' % (self.endpoint, self.handler_obj)) # Return the handler module path return valid(self.handler_obj)
return self._req_error(acl_gateway.auth_error)
random_line_split
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase from cloudscape.common.utils import JSONTemplate from cloudscape.engine.api.auth.key import APIKey from cloudscape.engine.api.auth.acl import ACLGateway from cloudscape.common.utils import valid, invalid from cloudscape.engine.api.auth.token import APIToken from cloudscape.engine.api.app.auth.models import DBAuthEndpoints from cloudscape.engine.api.app.user.models import DBUserDetails # Configuration / Logger CONF = config.parse() LOG = logger.create('cloudscape.engine.api.core.request', CONF.server.log) def dispatch(request): """ The entry point for all API requests. Called for all endpoints from the Django URLs file. Creates a new instance of the EndpointManager class, and returns any HTTP response to the client that opened the API request. :param request: The Django request object :type request: object :rtype: object """ try: # Return the response from the endpoint handler return EndpointManager(request).handler() # Critical server error except Exception as e: LOG.exception('Internal server error: %s' % str(e)) # Return a 500 error return HttpResponseServerError('Internal server error, please contact your administrator.') class EndpointManager: """ The endpoint request manager class. Serves as the entry point for all API request, both for authentication requests, and already authenticated requests. Constructs the base API class, loads API utilities, and performs a number of other functions to prepare the API for the incoming request. The EndpointManager class is instantiated by the dispatch method, which is called by the Django URLs module file. It is initialized with the Django request object. """ def __init__(self, request): self.request_raw = request # Request properties self.method = None self.request = None self.endpoint = None self.action = None self.path = None # Request endpoint handler self.handler_obj = None # API parameters self.api_name = None self.api_mod = None self.api_class = None self.api_user = None self.api_group = None # API base object self.api_base = None # Request error def _req_error(self, err): err_response = { 'message': 'An error occured when processing the API request', 'endpoint': self.endpoint, 'error': err } LOG.error('%s:%s' % (self.endpoint, err)) return HttpResponse(json.dumps(err_response), content_type='application/json', status=400) def _authenticate(self): """ Authenticate the API request. """ # Set the API user and group self.api_user = self.request['api_user'] self.api_group = None if not ('api_group' in self.request) else self.request['api_group'] LOG.info('Authenticating API user: %s, group=%s' % (self.api_user, repr(self.api_group))) # Authenticate key for token requests if self.endpoint == 'auth/get': auth_status = APIKey().validate(self.request) if not auth_status['valid']: return self._req_error(auth_status['content']) LOG.info('API key authentication successfull for user: %s' % self.api_user) # Authenticate token for API requests else: if not APIToken().validate(self.request): return self._req_error('Failed to validate API token for user \'%s\'' % self.api_user) LOG.info('API token authentication successfull for user: %s' % self.api_user) # Check for a user account if DBUserDetails.objects.filter(username=self.api_user).count(): # If no API group was supplied if not self.api_group: return self._req_error('User accounts must supply a group UUID when making a request using the <api_group> parameter') # Make sure the group exists and the user is a member is_member = False for group in DBUserDetails.objects.get(username=self.api_user).get_groups(): if group['uuid'] == self.api_group: is_member = True break # If the user is not a member of the group if not is_member: return self._req_error('User account <%s> is not a member of group <%s>' % (self.api_user, self.api_group)) # Validate the request def _validate(self): # Request body / method self.request = json.loads(self.request_raw.body) self.method = self.request_raw.META['REQUEST_METHOD'] # Make sure a request action is set if not 'action' in self.request: return self._req_error('Request body requires an <action> parameter for endpoint pathing') self.action = self.request['action'] # Get the request path self.path = re.compile('^\/(.*$)').sub(r'\g<1>', self.request_raw.META['PATH_INFO']) # Set the request endpoint self.endpoint = '%s/%s' % (self.path, self.action) # Map the path to a module, class, and API name self.handler_obj = EndpointMapper(self.endpoint, self.method).handler() if not self.handler_obj['valid']: return self._req_error(self.handler_obj['content']) # Validate the request body request_err = JSONTemplate(self.handler_obj['content']['api_map']).validate(self.request) if request_err: return self._req_error(request_err) # Set the handler objects self.api_name = self.handler_obj['content']['api_name'] self.api_mod = self.handler_obj['content']['api_mod'] self.api_class = self.handler_obj['content']['api_class'] self.api_utils = self.handler_obj['content']['api_utils'] def handler(self): """ The endpoint manager request handler. Performs a number of validation steps before passing off the request to the API utility class. 1.) Looks for the base required request parameters 2.) Maps the endpoint and request action to an API utility and validates the request body 3.) Authenticates the user and API key/token 4.) Initializes any required Socket.IO connections for web clients 5.) Launches the API utility class to process the request 6.) Returns either an HTTP response with the status of the request """ # Parse the request try: validate_err = self._validate() if validate_err: return validate_err except Exception as e: LOG.exception('Exception while validating request: %s' % str(e)) return self._req_error('Internal server error, failed to validate the request') # Authenticate the request try: auth_err = self._authenticate() if auth_err: return auth_err except Exception as e: LOG.exception('Exception while authenticating the request: %s' % str(e)) return self._req_error('Internal server error, failed to authenticate the request') # Check the request against ACLs acl_gateway = ACLGateway(self.request, self.endpoint, self.api_user) # If the user is not authorized for this endpoint/object combination if not acl_gateway.authorized: return self._req_error(acl_gateway.auth_error) # Set up the API base try: # Create an instance of the APIBase and run the constructor api_obj = APIBase( name = self.api_name, endpoint = self.endpoint, utils = self.api_utils, acl = acl_gateway ).construct(self.request_raw) # Make sure the construct ran successfully if not api_obj['valid']: return self._req_error(api_obj['content']) # Set the API base object for endpoint utilities self.api_base = api_obj['content'] # Failed to setup the APIBase except Exception as e: LOG.exception('Failed to set up API base: %s' % str(e)) return self._req_error('Internal server, failed to set up API base') # Load the handler module and class handler_mod = importlib.import_module(self.api_mod) handler_class = getattr(handler_mod, self.api_class) handler_inst = handler_class(self.api_base) # Launch the request handler and return the response try: response = handler_inst.launch() # Critical error when running handler except Exception as e: LOG.exception('Exeption while running API handler: %s' % str(e)) return self._req_error('Encountered API handler error') # Close any open SocketIO connections self.api_base.socket.disconnect() # Return either a valid or invalid request response if response['valid']: return self.api_base.log.success(response['content'], response['data']) return self.api_base.log.error(code=response['code'], log_msg=response['content']) class EndpointMapper: """ API class used to construct the endpoint map. Scans the endpoint request templates in the API templates directory to construct a map used to load required utilities and modules, as well as validate the request for each endpoint. Each map also contains ACL parameters used when constructing the ACL database tables. """ def __init__(self, endpoint=None, method=None): """ Construct the EndpointMapper class. @param endpoint: The endpoint path @type endpoint: str @param method: The request method @type method: str """ self.endpoint = endpoint self.method = method self.map = {} def _merge_auth(self,j,e): """ Helper method used to merge token authentication parameters into the endpoint request map. Mainly so I don't have to redundantly include the same code in every map. Also makes modification much easier. """ # Ignore the authentication endpoint, as this is used to retrieve the token if e == 'auth/get': return # Required / optional connection parameters j['root']['_required'].extend(['api_user', 'api_token', 'action']) j['root']['_optional'].extend(['api_group']) # Connection parameter types t = { 'api_user': 'str', 'api_token': 'str', 'action': 'str', 'api_group': 'uuid4' } for k,v in t.iteritems(): j['root']['_children'][k] = { '_type': v } def _merge_socket(self,j): """ Merge request parameters for web socket request. Used for handling connections being passed along by the Socket.IO API proxy. """ # Load the socket request validator map sv = json.loads(open('%s/socket.json' % T_BASE, 'r').read()) # Make sure the '_children' key exists if not '_children' in j['root']: j['root']['_children'] = {} # Merge the socket parameters map j['root']['_children']['socket'] = sv j['root']['_optional'].append('socket') def _build_map(self): """ Load all endpoint definitions. """ for endpoint in list(DBAuthEndpoints.objects.all().values()): # Try to load the request map
# All template maps constructed return valid(LOG.info('Constructed API template map')) def handler(self): """ Main method for constructing and returning the endpoint map. @return valid|invalid """ map_rsp = self._build_map() if not map_rsp['valid']: return map_rsp # Request path missing if not self.endpoint: return invalid(LOG.error('Missing request endpoint')) # Invalid request path if not self.endpoint in self.map: return invalid(LOG.error('Unsupported request endpoint: <%s>' % self.endpoint)) # Verify the request method if self.method != self.map[self.endpoint]['method']: return invalid(LOG.error('Unsupported request method <%s> for endpoint <%s>' % (self.method, self.endpoint))) # Get the API module, class handler, and name self.handler_obj = { 'api_mod': self.map[self.endpoint]['module'], 'api_class': self.map[self.endpoint]['class'], 'api_name': self.map[self.endpoint]['name'], 'api_utils': self.map[self.endpoint]['utils'], 'api_map': self.map[self.endpoint]['json'] } LOG.info('Parsed handler object for API endpoint <%s>: %s' % (self.endpoint, self.handler_obj)) # Return the handler module path return valid(self.handler_obj)
try: endpoint_rmap = json.loads(endpoint['rmap']) # Map base object rmap_base = { 'root': endpoint_rmap } # Merge the web socket request validator self._merge_socket(rmap_base) # Merge the authentication request validation parameters self._merge_auth(rmap_base, endpoint['name']) # Load the endpoint request handler module string self.map[endpoint['name']] = { 'module': endpoint['mod'], 'class': endpoint['cls'], 'name': endpoint['name'], 'desc': endpoint['desc'], 'method': endpoint['method'], 'utils': None if not endpoint['utils'] else json.loads(endpoint['utils']), 'json': rmap_base } # Error constructing request map, skip to next endpoint map except Exception as e: LOG.exception('Failed to load request map for endpoint <%s>: %s ' % (endpoint['name'], str(e))) continue
conditional_block
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase from cloudscape.common.utils import JSONTemplate from cloudscape.engine.api.auth.key import APIKey from cloudscape.engine.api.auth.acl import ACLGateway from cloudscape.common.utils import valid, invalid from cloudscape.engine.api.auth.token import APIToken from cloudscape.engine.api.app.auth.models import DBAuthEndpoints from cloudscape.engine.api.app.user.models import DBUserDetails # Configuration / Logger CONF = config.parse() LOG = logger.create('cloudscape.engine.api.core.request', CONF.server.log) def dispatch(request): """ The entry point for all API requests. Called for all endpoints from the Django URLs file. Creates a new instance of the EndpointManager class, and returns any HTTP response to the client that opened the API request. :param request: The Django request object :type request: object :rtype: object """ try: # Return the response from the endpoint handler return EndpointManager(request).handler() # Critical server error except Exception as e: LOG.exception('Internal server error: %s' % str(e)) # Return a 500 error return HttpResponseServerError('Internal server error, please contact your administrator.') class EndpointManager: """ The endpoint request manager class. Serves as the entry point for all API request, both for authentication requests, and already authenticated requests. Constructs the base API class, loads API utilities, and performs a number of other functions to prepare the API for the incoming request. The EndpointManager class is instantiated by the dispatch method, which is called by the Django URLs module file. It is initialized with the Django request object. """ def __init__(self, request): self.request_raw = request # Request properties self.method = None self.request = None self.endpoint = None self.action = None self.path = None # Request endpoint handler self.handler_obj = None # API parameters self.api_name = None self.api_mod = None self.api_class = None self.api_user = None self.api_group = None # API base object self.api_base = None # Request error def _req_error(self, err):
def _authenticate(self): """ Authenticate the API request. """ # Set the API user and group self.api_user = self.request['api_user'] self.api_group = None if not ('api_group' in self.request) else self.request['api_group'] LOG.info('Authenticating API user: %s, group=%s' % (self.api_user, repr(self.api_group))) # Authenticate key for token requests if self.endpoint == 'auth/get': auth_status = APIKey().validate(self.request) if not auth_status['valid']: return self._req_error(auth_status['content']) LOG.info('API key authentication successfull for user: %s' % self.api_user) # Authenticate token for API requests else: if not APIToken().validate(self.request): return self._req_error('Failed to validate API token for user \'%s\'' % self.api_user) LOG.info('API token authentication successfull for user: %s' % self.api_user) # Check for a user account if DBUserDetails.objects.filter(username=self.api_user).count(): # If no API group was supplied if not self.api_group: return self._req_error('User accounts must supply a group UUID when making a request using the <api_group> parameter') # Make sure the group exists and the user is a member is_member = False for group in DBUserDetails.objects.get(username=self.api_user).get_groups(): if group['uuid'] == self.api_group: is_member = True break # If the user is not a member of the group if not is_member: return self._req_error('User account <%s> is not a member of group <%s>' % (self.api_user, self.api_group)) # Validate the request def _validate(self): # Request body / method self.request = json.loads(self.request_raw.body) self.method = self.request_raw.META['REQUEST_METHOD'] # Make sure a request action is set if not 'action' in self.request: return self._req_error('Request body requires an <action> parameter for endpoint pathing') self.action = self.request['action'] # Get the request path self.path = re.compile('^\/(.*$)').sub(r'\g<1>', self.request_raw.META['PATH_INFO']) # Set the request endpoint self.endpoint = '%s/%s' % (self.path, self.action) # Map the path to a module, class, and API name self.handler_obj = EndpointMapper(self.endpoint, self.method).handler() if not self.handler_obj['valid']: return self._req_error(self.handler_obj['content']) # Validate the request body request_err = JSONTemplate(self.handler_obj['content']['api_map']).validate(self.request) if request_err: return self._req_error(request_err) # Set the handler objects self.api_name = self.handler_obj['content']['api_name'] self.api_mod = self.handler_obj['content']['api_mod'] self.api_class = self.handler_obj['content']['api_class'] self.api_utils = self.handler_obj['content']['api_utils'] def handler(self): """ The endpoint manager request handler. Performs a number of validation steps before passing off the request to the API utility class. 1.) Looks for the base required request parameters 2.) Maps the endpoint and request action to an API utility and validates the request body 3.) Authenticates the user and API key/token 4.) Initializes any required Socket.IO connections for web clients 5.) Launches the API utility class to process the request 6.) Returns either an HTTP response with the status of the request """ # Parse the request try: validate_err = self._validate() if validate_err: return validate_err except Exception as e: LOG.exception('Exception while validating request: %s' % str(e)) return self._req_error('Internal server error, failed to validate the request') # Authenticate the request try: auth_err = self._authenticate() if auth_err: return auth_err except Exception as e: LOG.exception('Exception while authenticating the request: %s' % str(e)) return self._req_error('Internal server error, failed to authenticate the request') # Check the request against ACLs acl_gateway = ACLGateway(self.request, self.endpoint, self.api_user) # If the user is not authorized for this endpoint/object combination if not acl_gateway.authorized: return self._req_error(acl_gateway.auth_error) # Set up the API base try: # Create an instance of the APIBase and run the constructor api_obj = APIBase( name = self.api_name, endpoint = self.endpoint, utils = self.api_utils, acl = acl_gateway ).construct(self.request_raw) # Make sure the construct ran successfully if not api_obj['valid']: return self._req_error(api_obj['content']) # Set the API base object for endpoint utilities self.api_base = api_obj['content'] # Failed to setup the APIBase except Exception as e: LOG.exception('Failed to set up API base: %s' % str(e)) return self._req_error('Internal server, failed to set up API base') # Load the handler module and class handler_mod = importlib.import_module(self.api_mod) handler_class = getattr(handler_mod, self.api_class) handler_inst = handler_class(self.api_base) # Launch the request handler and return the response try: response = handler_inst.launch() # Critical error when running handler except Exception as e: LOG.exception('Exeption while running API handler: %s' % str(e)) return self._req_error('Encountered API handler error') # Close any open SocketIO connections self.api_base.socket.disconnect() # Return either a valid or invalid request response if response['valid']: return self.api_base.log.success(response['content'], response['data']) return self.api_base.log.error(code=response['code'], log_msg=response['content']) class EndpointMapper: """ API class used to construct the endpoint map. Scans the endpoint request templates in the API templates directory to construct a map used to load required utilities and modules, as well as validate the request for each endpoint. Each map also contains ACL parameters used when constructing the ACL database tables. """ def __init__(self, endpoint=None, method=None): """ Construct the EndpointMapper class. @param endpoint: The endpoint path @type endpoint: str @param method: The request method @type method: str """ self.endpoint = endpoint self.method = method self.map = {} def _merge_auth(self,j,e): """ Helper method used to merge token authentication parameters into the endpoint request map. Mainly so I don't have to redundantly include the same code in every map. Also makes modification much easier. """ # Ignore the authentication endpoint, as this is used to retrieve the token if e == 'auth/get': return # Required / optional connection parameters j['root']['_required'].extend(['api_user', 'api_token', 'action']) j['root']['_optional'].extend(['api_group']) # Connection parameter types t = { 'api_user': 'str', 'api_token': 'str', 'action': 'str', 'api_group': 'uuid4' } for k,v in t.iteritems(): j['root']['_children'][k] = { '_type': v } def _merge_socket(self,j): """ Merge request parameters for web socket request. Used for handling connections being passed along by the Socket.IO API proxy. """ # Load the socket request validator map sv = json.loads(open('%s/socket.json' % T_BASE, 'r').read()) # Make sure the '_children' key exists if not '_children' in j['root']: j['root']['_children'] = {} # Merge the socket parameters map j['root']['_children']['socket'] = sv j['root']['_optional'].append('socket') def _build_map(self): """ Load all endpoint definitions. """ for endpoint in list(DBAuthEndpoints.objects.all().values()): # Try to load the request map try: endpoint_rmap = json.loads(endpoint['rmap']) # Map base object rmap_base = { 'root': endpoint_rmap } # Merge the web socket request validator self._merge_socket(rmap_base) # Merge the authentication request validation parameters self._merge_auth(rmap_base, endpoint['name']) # Load the endpoint request handler module string self.map[endpoint['name']] = { 'module': endpoint['mod'], 'class': endpoint['cls'], 'name': endpoint['name'], 'desc': endpoint['desc'], 'method': endpoint['method'], 'utils': None if not endpoint['utils'] else json.loads(endpoint['utils']), 'json': rmap_base } # Error constructing request map, skip to next endpoint map except Exception as e: LOG.exception('Failed to load request map for endpoint <%s>: %s ' % (endpoint['name'], str(e))) continue # All template maps constructed return valid(LOG.info('Constructed API template map')) def handler(self): """ Main method for constructing and returning the endpoint map. @return valid|invalid """ map_rsp = self._build_map() if not map_rsp['valid']: return map_rsp # Request path missing if not self.endpoint: return invalid(LOG.error('Missing request endpoint')) # Invalid request path if not self.endpoint in self.map: return invalid(LOG.error('Unsupported request endpoint: <%s>' % self.endpoint)) # Verify the request method if self.method != self.map[self.endpoint]['method']: return invalid(LOG.error('Unsupported request method <%s> for endpoint <%s>' % (self.method, self.endpoint))) # Get the API module, class handler, and name self.handler_obj = { 'api_mod': self.map[self.endpoint]['module'], 'api_class': self.map[self.endpoint]['class'], 'api_name': self.map[self.endpoint]['name'], 'api_utils': self.map[self.endpoint]['utils'], 'api_map': self.map[self.endpoint]['json'] } LOG.info('Parsed handler object for API endpoint <%s>: %s' % (self.endpoint, self.handler_obj)) # Return the handler module path return valid(self.handler_obj)
err_response = { 'message': 'An error occured when processing the API request', 'endpoint': self.endpoint, 'error': err } LOG.error('%s:%s' % (self.endpoint, err)) return HttpResponse(json.dumps(err_response), content_type='application/json', status=400)
identifier_body
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase from cloudscape.common.utils import JSONTemplate from cloudscape.engine.api.auth.key import APIKey from cloudscape.engine.api.auth.acl import ACLGateway from cloudscape.common.utils import valid, invalid from cloudscape.engine.api.auth.token import APIToken from cloudscape.engine.api.app.auth.models import DBAuthEndpoints from cloudscape.engine.api.app.user.models import DBUserDetails # Configuration / Logger CONF = config.parse() LOG = logger.create('cloudscape.engine.api.core.request', CONF.server.log) def dispatch(request): """ The entry point for all API requests. Called for all endpoints from the Django URLs file. Creates a new instance of the EndpointManager class, and returns any HTTP response to the client that opened the API request. :param request: The Django request object :type request: object :rtype: object """ try: # Return the response from the endpoint handler return EndpointManager(request).handler() # Critical server error except Exception as e: LOG.exception('Internal server error: %s' % str(e)) # Return a 500 error return HttpResponseServerError('Internal server error, please contact your administrator.') class EndpointManager: """ The endpoint request manager class. Serves as the entry point for all API request, both for authentication requests, and already authenticated requests. Constructs the base API class, loads API utilities, and performs a number of other functions to prepare the API for the incoming request. The EndpointManager class is instantiated by the dispatch method, which is called by the Django URLs module file. It is initialized with the Django request object. """ def __init__(self, request): self.request_raw = request # Request properties self.method = None self.request = None self.endpoint = None self.action = None self.path = None # Request endpoint handler self.handler_obj = None # API parameters self.api_name = None self.api_mod = None self.api_class = None self.api_user = None self.api_group = None # API base object self.api_base = None # Request error def _req_error(self, err): err_response = { 'message': 'An error occured when processing the API request', 'endpoint': self.endpoint, 'error': err } LOG.error('%s:%s' % (self.endpoint, err)) return HttpResponse(json.dumps(err_response), content_type='application/json', status=400) def _authenticate(self): """ Authenticate the API request. """ # Set the API user and group self.api_user = self.request['api_user'] self.api_group = None if not ('api_group' in self.request) else self.request['api_group'] LOG.info('Authenticating API user: %s, group=%s' % (self.api_user, repr(self.api_group))) # Authenticate key for token requests if self.endpoint == 'auth/get': auth_status = APIKey().validate(self.request) if not auth_status['valid']: return self._req_error(auth_status['content']) LOG.info('API key authentication successfull for user: %s' % self.api_user) # Authenticate token for API requests else: if not APIToken().validate(self.request): return self._req_error('Failed to validate API token for user \'%s\'' % self.api_user) LOG.info('API token authentication successfull for user: %s' % self.api_user) # Check for a user account if DBUserDetails.objects.filter(username=self.api_user).count(): # If no API group was supplied if not self.api_group: return self._req_error('User accounts must supply a group UUID when making a request using the <api_group> parameter') # Make sure the group exists and the user is a member is_member = False for group in DBUserDetails.objects.get(username=self.api_user).get_groups(): if group['uuid'] == self.api_group: is_member = True break # If the user is not a member of the group if not is_member: return self._req_error('User account <%s> is not a member of group <%s>' % (self.api_user, self.api_group)) # Validate the request def _validate(self): # Request body / method self.request = json.loads(self.request_raw.body) self.method = self.request_raw.META['REQUEST_METHOD'] # Make sure a request action is set if not 'action' in self.request: return self._req_error('Request body requires an <action> parameter for endpoint pathing') self.action = self.request['action'] # Get the request path self.path = re.compile('^\/(.*$)').sub(r'\g<1>', self.request_raw.META['PATH_INFO']) # Set the request endpoint self.endpoint = '%s/%s' % (self.path, self.action) # Map the path to a module, class, and API name self.handler_obj = EndpointMapper(self.endpoint, self.method).handler() if not self.handler_obj['valid']: return self._req_error(self.handler_obj['content']) # Validate the request body request_err = JSONTemplate(self.handler_obj['content']['api_map']).validate(self.request) if request_err: return self._req_error(request_err) # Set the handler objects self.api_name = self.handler_obj['content']['api_name'] self.api_mod = self.handler_obj['content']['api_mod'] self.api_class = self.handler_obj['content']['api_class'] self.api_utils = self.handler_obj['content']['api_utils'] def handler(self): """ The endpoint manager request handler. Performs a number of validation steps before passing off the request to the API utility class. 1.) Looks for the base required request parameters 2.) Maps the endpoint and request action to an API utility and validates the request body 3.) Authenticates the user and API key/token 4.) Initializes any required Socket.IO connections for web clients 5.) Launches the API utility class to process the request 6.) Returns either an HTTP response with the status of the request """ # Parse the request try: validate_err = self._validate() if validate_err: return validate_err except Exception as e: LOG.exception('Exception while validating request: %s' % str(e)) return self._req_error('Internal server error, failed to validate the request') # Authenticate the request try: auth_err = self._authenticate() if auth_err: return auth_err except Exception as e: LOG.exception('Exception while authenticating the request: %s' % str(e)) return self._req_error('Internal server error, failed to authenticate the request') # Check the request against ACLs acl_gateway = ACLGateway(self.request, self.endpoint, self.api_user) # If the user is not authorized for this endpoint/object combination if not acl_gateway.authorized: return self._req_error(acl_gateway.auth_error) # Set up the API base try: # Create an instance of the APIBase and run the constructor api_obj = APIBase( name = self.api_name, endpoint = self.endpoint, utils = self.api_utils, acl = acl_gateway ).construct(self.request_raw) # Make sure the construct ran successfully if not api_obj['valid']: return self._req_error(api_obj['content']) # Set the API base object for endpoint utilities self.api_base = api_obj['content'] # Failed to setup the APIBase except Exception as e: LOG.exception('Failed to set up API base: %s' % str(e)) return self._req_error('Internal server, failed to set up API base') # Load the handler module and class handler_mod = importlib.import_module(self.api_mod) handler_class = getattr(handler_mod, self.api_class) handler_inst = handler_class(self.api_base) # Launch the request handler and return the response try: response = handler_inst.launch() # Critical error when running handler except Exception as e: LOG.exception('Exeption while running API handler: %s' % str(e)) return self._req_error('Encountered API handler error') # Close any open SocketIO connections self.api_base.socket.disconnect() # Return either a valid or invalid request response if response['valid']: return self.api_base.log.success(response['content'], response['data']) return self.api_base.log.error(code=response['code'], log_msg=response['content']) class EndpointMapper: """ API class used to construct the endpoint map. Scans the endpoint request templates in the API templates directory to construct a map used to load required utilities and modules, as well as validate the request for each endpoint. Each map also contains ACL parameters used when constructing the ACL database tables. """ def __init__(self, endpoint=None, method=None): """ Construct the EndpointMapper class. @param endpoint: The endpoint path @type endpoint: str @param method: The request method @type method: str """ self.endpoint = endpoint self.method = method self.map = {} def
(self,j,e): """ Helper method used to merge token authentication parameters into the endpoint request map. Mainly so I don't have to redundantly include the same code in every map. Also makes modification much easier. """ # Ignore the authentication endpoint, as this is used to retrieve the token if e == 'auth/get': return # Required / optional connection parameters j['root']['_required'].extend(['api_user', 'api_token', 'action']) j['root']['_optional'].extend(['api_group']) # Connection parameter types t = { 'api_user': 'str', 'api_token': 'str', 'action': 'str', 'api_group': 'uuid4' } for k,v in t.iteritems(): j['root']['_children'][k] = { '_type': v } def _merge_socket(self,j): """ Merge request parameters for web socket request. Used for handling connections being passed along by the Socket.IO API proxy. """ # Load the socket request validator map sv = json.loads(open('%s/socket.json' % T_BASE, 'r').read()) # Make sure the '_children' key exists if not '_children' in j['root']: j['root']['_children'] = {} # Merge the socket parameters map j['root']['_children']['socket'] = sv j['root']['_optional'].append('socket') def _build_map(self): """ Load all endpoint definitions. """ for endpoint in list(DBAuthEndpoints.objects.all().values()): # Try to load the request map try: endpoint_rmap = json.loads(endpoint['rmap']) # Map base object rmap_base = { 'root': endpoint_rmap } # Merge the web socket request validator self._merge_socket(rmap_base) # Merge the authentication request validation parameters self._merge_auth(rmap_base, endpoint['name']) # Load the endpoint request handler module string self.map[endpoint['name']] = { 'module': endpoint['mod'], 'class': endpoint['cls'], 'name': endpoint['name'], 'desc': endpoint['desc'], 'method': endpoint['method'], 'utils': None if not endpoint['utils'] else json.loads(endpoint['utils']), 'json': rmap_base } # Error constructing request map, skip to next endpoint map except Exception as e: LOG.exception('Failed to load request map for endpoint <%s>: %s ' % (endpoint['name'], str(e))) continue # All template maps constructed return valid(LOG.info('Constructed API template map')) def handler(self): """ Main method for constructing and returning the endpoint map. @return valid|invalid """ map_rsp = self._build_map() if not map_rsp['valid']: return map_rsp # Request path missing if not self.endpoint: return invalid(LOG.error('Missing request endpoint')) # Invalid request path if not self.endpoint in self.map: return invalid(LOG.error('Unsupported request endpoint: <%s>' % self.endpoint)) # Verify the request method if self.method != self.map[self.endpoint]['method']: return invalid(LOG.error('Unsupported request method <%s> for endpoint <%s>' % (self.method, self.endpoint))) # Get the API module, class handler, and name self.handler_obj = { 'api_mod': self.map[self.endpoint]['module'], 'api_class': self.map[self.endpoint]['class'], 'api_name': self.map[self.endpoint]['name'], 'api_utils': self.map[self.endpoint]['utils'], 'api_map': self.map[self.endpoint]['json'] } LOG.info('Parsed handler object for API endpoint <%s>: %s' % (self.endpoint, self.handler_obj)) # Return the handler module path return valid(self.handler_obj)
_merge_auth
identifier_name
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { this._rules = []; if (form == null) { throw new ArgumentNullException('form'); } this._form = form; this.name = name; } Object.defineProperty(Field.prototype, "name", { get: function () { return this._name; }, set: function (name) { this._name = name; }, enumerable: true, configurable: true }); Field.prototype.addRule = function () { var args = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { args[_i] = arguments[_i + 0]; } return this.insertRule.apply(this, [this._rules.length].concat(args)); }; Field.prototype.insertRule = function (idx, rule) { var args = []; for (var _i = 0; _i < (arguments.length - 2); _i++) { args[_i] = arguments[_i + 2]; } if (idx < 0) { idx = this._rules.length + idx + 1; } if (_.isString(rule)) { this._rules.splice(idx, 0, new RuleObject(rule, null, null, args)); } else if (!_.isUndefined(rule.validate)) { var name = Arr.get(args, 0, null); args = args.splice(0, 1); this._rules.splice(idx, 0, new RuleObject(name, null, rule, args)); } else if (_.isFunction(rule)) { this._rules.splice(idx, 0, new RuleObject(null, rule, null, args)); } else { throw new ArgumentException('rule', 'rule parameter must be string or function.'); } return this; }; Field.prototype.removeRule = function (rule) { var idx; while ((idx = this.findRule(rule)) >= 0) { delete this._rules[idx]; } return this; }; Field.prototype.validate = function (v, result) { var _this = this; var rules = Enumerable.from(this._rules); var error = null; var validated = true; var validatedValue = v; rules.forEach(function (rule) { if (validated) { var args = { value: validatedValue, result: result, parameters: rule.arguments, form: _this._form }; var result = rule.validate(_this, args); if (_.isBoolean(result)) { validated = validated && result; } else { validatedValue = result; } if (!validated) { error = { field: _this, rule: rule.name, value: validatedValue, arguments: rule.arguments }; } } }); return { hasError: !validated, error: error, validatedValue: validatedValue }; }; Field.prototype.findRule = function (rule) { if (_.isString(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.name == rule; }); } else if (_.isFunction(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.validator == rule; }); } return -1; }; Object.defineProperty(Field.prototype, "form", { get: function () { return this._form; }, enumerable: true, configurable: true }); return Field; })(); var RuleObject = (function () { function RuleObject(name, func, validator, arguments) {
RuleObject.prototype.validate = function (field, args) { if (this.function != null) { return this.function.apply(field, [args.value].concat(this.arguments)); } else if (this.validator != null) { return this.validator.validate(args); } else { var validator = field.form.getValidator(this.name); if (!validator) { throw new Exception('Rule:' + this.name + " is not found."); } return validator.validate(args); } }; return RuleObject; })(); module.exports = Field; //# sourceMappingURL=Field.js.map
this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; }
identifier_body
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { this._rules = []; if (form == null) { throw new ArgumentNullException('form'); } this._form = form; this.name = name; } Object.defineProperty(Field.prototype, "name", { get: function () { return this._name; }, set: function (name) { this._name = name; }, enumerable: true, configurable: true }); Field.prototype.addRule = function () { var args = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { args[_i] = arguments[_i + 0]; } return this.insertRule.apply(this, [this._rules.length].concat(args)); }; Field.prototype.insertRule = function (idx, rule) { var args = []; for (var _i = 0; _i < (arguments.length - 2); _i++) { args[_i] = arguments[_i + 2]; } if (idx < 0) { idx = this._rules.length + idx + 1; } if (_.isString(rule)) { this._rules.splice(idx, 0, new RuleObject(rule, null, null, args)); } else if (!_.isUndefined(rule.validate)) { var name = Arr.get(args, 0, null); args = args.splice(0, 1); this._rules.splice(idx, 0, new RuleObject(name, null, rule, args)); } else if (_.isFunction(rule)) { this._rules.splice(idx, 0, new RuleObject(null, rule, null, args)); } else { throw new ArgumentException('rule', 'rule parameter must be string or function.'); } return this; }; Field.prototype.removeRule = function (rule) { var idx; while ((idx = this.findRule(rule)) >= 0) { delete this._rules[idx]; } return this; }; Field.prototype.validate = function (v, result) { var _this = this; var rules = Enumerable.from(this._rules); var error = null; var validated = true; var validatedValue = v; rules.forEach(function (rule) { if (validated) { var args = { value: validatedValue, result: result, parameters: rule.arguments, form: _this._form }; var result = rule.validate(_this, args); if (_.isBoolean(result)) { validated = validated && result; } else {
if (!validated) { error = { field: _this, rule: rule.name, value: validatedValue, arguments: rule.arguments }; } } }); return { hasError: !validated, error: error, validatedValue: validatedValue }; }; Field.prototype.findRule = function (rule) { if (_.isString(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.name == rule; }); } else if (_.isFunction(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.validator == rule; }); } return -1; }; Object.defineProperty(Field.prototype, "form", { get: function () { return this._form; }, enumerable: true, configurable: true }); return Field; })(); var RuleObject = (function () { function RuleObject(name, func, validator, arguments) { this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; } RuleObject.prototype.validate = function (field, args) { if (this.function != null) { return this.function.apply(field, [args.value].concat(this.arguments)); } else if (this.validator != null) { return this.validator.validate(args); } else { var validator = field.form.getValidator(this.name); if (!validator) { throw new Exception('Rule:' + this.name + " is not found."); } return validator.validate(args); } }; return RuleObject; })(); module.exports = Field; //# sourceMappingURL=Field.js.map
validatedValue = result; }
conditional_block
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { this._rules = []; if (form == null) { throw new ArgumentNullException('form'); } this._form = form; this.name = name; } Object.defineProperty(Field.prototype, "name", { get: function () { return this._name; }, set: function (name) { this._name = name; }, enumerable: true, configurable: true }); Field.prototype.addRule = function () { var args = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { args[_i] = arguments[_i + 0]; } return this.insertRule.apply(this, [this._rules.length].concat(args)); }; Field.prototype.insertRule = function (idx, rule) { var args = []; for (var _i = 0; _i < (arguments.length - 2); _i++) { args[_i] = arguments[_i + 2]; } if (idx < 0) { idx = this._rules.length + idx + 1; } if (_.isString(rule)) { this._rules.splice(idx, 0, new RuleObject(rule, null, null, args)); } else if (!_.isUndefined(rule.validate)) { var name = Arr.get(args, 0, null); args = args.splice(0, 1); this._rules.splice(idx, 0, new RuleObject(name, null, rule, args)); } else if (_.isFunction(rule)) { this._rules.splice(idx, 0, new RuleObject(null, rule, null, args)); } else { throw new ArgumentException('rule', 'rule parameter must be string or function.'); } return this; }; Field.prototype.removeRule = function (rule) { var idx; while ((idx = this.findRule(rule)) >= 0) { delete this._rules[idx]; } return this; }; Field.prototype.validate = function (v, result) { var _this = this; var rules = Enumerable.from(this._rules); var error = null; var validated = true; var validatedValue = v; rules.forEach(function (rule) { if (validated) { var args = { value: validatedValue, result: result, parameters: rule.arguments, form: _this._form }; var result = rule.validate(_this, args); if (_.isBoolean(result)) { validated = validated && result; } else { validatedValue = result; } if (!validated) { error = { field: _this, rule: rule.name, value: validatedValue, arguments: rule.arguments }; } } }); return { hasError: !validated, error: error, validatedValue: validatedValue }; }; Field.prototype.findRule = function (rule) { if (_.isString(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.name == rule; }); } else if (_.isFunction(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.validator == rule; }); } return -1; }; Object.defineProperty(Field.prototype, "form", { get: function () { return this._form; }, enumerable: true, configurable: true });
})(); var RuleObject = (function () { function RuleObject(name, func, validator, arguments) { this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; } RuleObject.prototype.validate = function (field, args) { if (this.function != null) { return this.function.apply(field, [args.value].concat(this.arguments)); } else if (this.validator != null) { return this.validator.validate(args); } else { var validator = field.form.getValidator(this.name); if (!validator) { throw new Exception('Rule:' + this.name + " is not found."); } return validator.validate(args); } }; return RuleObject; })(); module.exports = Field; //# sourceMappingURL=Field.js.map
return Field;
random_line_split
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { this._rules = []; if (form == null) { throw new ArgumentNullException('form'); } this._form = form; this.name = name; } Object.defineProperty(Field.prototype, "name", { get: function () { return this._name; }, set: function (name) { this._name = name; }, enumerable: true, configurable: true }); Field.prototype.addRule = function () { var args = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { args[_i] = arguments[_i + 0]; } return this.insertRule.apply(this, [this._rules.length].concat(args)); }; Field.prototype.insertRule = function (idx, rule) { var args = []; for (var _i = 0; _i < (arguments.length - 2); _i++) { args[_i] = arguments[_i + 2]; } if (idx < 0) { idx = this._rules.length + idx + 1; } if (_.isString(rule)) { this._rules.splice(idx, 0, new RuleObject(rule, null, null, args)); } else if (!_.isUndefined(rule.validate)) { var name = Arr.get(args, 0, null); args = args.splice(0, 1); this._rules.splice(idx, 0, new RuleObject(name, null, rule, args)); } else if (_.isFunction(rule)) { this._rules.splice(idx, 0, new RuleObject(null, rule, null, args)); } else { throw new ArgumentException('rule', 'rule parameter must be string or function.'); } return this; }; Field.prototype.removeRule = function (rule) { var idx; while ((idx = this.findRule(rule)) >= 0) { delete this._rules[idx]; } return this; }; Field.prototype.validate = function (v, result) { var _this = this; var rules = Enumerable.from(this._rules); var error = null; var validated = true; var validatedValue = v; rules.forEach(function (rule) { if (validated) { var args = { value: validatedValue, result: result, parameters: rule.arguments, form: _this._form }; var result = rule.validate(_this, args); if (_.isBoolean(result)) { validated = validated && result; } else { validatedValue = result; } if (!validated) { error = { field: _this, rule: rule.name, value: validatedValue, arguments: rule.arguments }; } } }); return { hasError: !validated, error: error, validatedValue: validatedValue }; }; Field.prototype.findRule = function (rule) { if (_.isString(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.name == rule; }); } else if (_.isFunction(rule)) { return Enumerable.from(this._rules).indexOf(function (v) { return v.validator == rule; }); } return -1; }; Object.defineProperty(Field.prototype, "form", { get: function () { return this._form; }, enumerable: true, configurable: true }); return Field; })(); var RuleObject = (function () { function Ru
ame, func, validator, arguments) { this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; } RuleObject.prototype.validate = function (field, args) { if (this.function != null) { return this.function.apply(field, [args.value].concat(this.arguments)); } else if (this.validator != null) { return this.validator.validate(args); } else { var validator = field.form.getValidator(this.name); if (!validator) { throw new Exception('Rule:' + this.name + " is not found."); } return validator.validate(args); } }; return RuleObject; })(); module.exports = Field; //# sourceMappingURL=Field.js.map
leObject(n
identifier_name
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class TukeysFilter(BaseTask): def __init__(self, config, logger, options): super(TukeysFilter, self).__init__(config, logger, resource={'metric_sink': 'RedisSink', 'output_sink': 'GraphiteSink'}) self.namespace = 'TukeysFilter' self.service = options['service'] self.params = options['params'] def read(self): quantile_25 = self.params['quantile_25'] quantile_75 = self.params['quantile_75'] metrics = self.params['metrics'] delay = self.params.get('offset', 0) maximum_delay = self.params.get('maximum_delay', 600) # read metrics from metric_sink quantile_25 = [i for i in self.metric_sink.iread(quantile_25)] quantile_75 = [i for i in self.metric_sink.iread(quantile_75)] metrics = [i for i in self.metric_sink.iread(metrics)] if not (len(quantile_25) * len(quantile_75) * len(metrics)): self.logger.error( 'No data found for quantile/to be checked metrics. Exiting') return None # sort TimeSeriesTuples by timestamp quantile_25 = sorted(quantile_25, key=lambda tup: tup.timestamp) quantile_75 = sorted(quantile_75, key=lambda tup: tup.timestamp) metrics = sorted(metrics, key=lambda tup: (tup.name, tup.timestamp)) # find closest datapoint to now() (corrected by delay) if not too old time_now = time() - delay quantile_25 = get_closest_datapoint(quantile_25, time_now) if time_now - quantile_25.timestamp > maximum_delay: self.logger.error('Quantile25 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_25.timestamp, quantile_25.name)) return None quantile_25 = quantile_25.value quantile_75 = get_closest_datapoint(quantile_75, time_now) if time_now - quantile_75.timestamp > maximum_delay:
quantile_75 = quantile_75.value if quantile_25 > quantile_75: self.logger.error('Inconsistent Quantile Values (Q25: %f, Q75: %f). Exiting' % ( quantile_25, quantile_75)) return None # group by metric (e.g. instance) first and find then closest datapoint distribution = {} grouped = itertools.groupby(metrics, key=lambda tup: tup.name) for key, metrics in grouped: closest_datapoint = get_closest_datapoint( [metric for metric in metrics], time_now) if time_now - closest_datapoint.timestamp < maximum_delay: distribution[key] = closest_datapoint.value if len(distribution) == 0: self.logger.error('No Distribution Values. Exiting') return None return quantile_25, quantile_75, distribution def process(self, data): quantile_25, quantile_75, distribution = data iqr_scaling = self.params.get('iqr_scaling', 1.5) iqr = quantile_75 - quantile_25 lower_limit = quantile_25 - iqr_scaling * iqr upper_limit = quantile_75 + iqr_scaling * iqr if 'static_lower_threshold' in self.params: lower_limit = max( lower_limit, self.params['static_lower_threshold']) if 'static_upper_threshold' in self.params: upper_limit = min( upper_limit, self.params['static_upper_threshold']) states = {} for metric, value in distribution.iteritems(): if value > upper_limit: states[metric] = 1.0 elif value < lower_limit: states[metric] = -1.0 else: states[metric] = 0.0 return quantile_25, quantile_75, states def write(self, data): quantile_25, quantile_75, states = data prefix = '%s.%s' % (self.namespace, self.service) count = len(states) invalid = 0 now = int(time()) tuples = [] for name, state in states.iteritems(): if state: invalid += 1 name = extract_service_name(name) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, name), now, state)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_25'), now, quantile_25)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_75'), now, quantile_75)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'count'), now, count)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'invalid'), now, invalid)) self.output_sink.write(tuples) def run(self): data = self.read() if data: state = self.process(data) self.write(state) return True else: return None
self.logger.error('Quantile75 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_75.timestamp, quantile_75.name)) return None
conditional_block
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class TukeysFilter(BaseTask): def __init__(self, config, logger, options): super(TukeysFilter, self).__init__(config, logger, resource={'metric_sink': 'RedisSink', 'output_sink': 'GraphiteSink'}) self.namespace = 'TukeysFilter' self.service = options['service'] self.params = options['params'] def read(self): quantile_25 = self.params['quantile_25'] quantile_75 = self.params['quantile_75'] metrics = self.params['metrics'] delay = self.params.get('offset', 0) maximum_delay = self.params.get('maximum_delay', 600) # read metrics from metric_sink quantile_25 = [i for i in self.metric_sink.iread(quantile_25)] quantile_75 = [i for i in self.metric_sink.iread(quantile_75)] metrics = [i for i in self.metric_sink.iread(metrics)] if not (len(quantile_25) * len(quantile_75) * len(metrics)): self.logger.error( 'No data found for quantile/to be checked metrics. Exiting') return None # sort TimeSeriesTuples by timestamp quantile_25 = sorted(quantile_25, key=lambda tup: tup.timestamp) quantile_75 = sorted(quantile_75, key=lambda tup: tup.timestamp) metrics = sorted(metrics, key=lambda tup: (tup.name, tup.timestamp)) # find closest datapoint to now() (corrected by delay) if not too old time_now = time() - delay quantile_25 = get_closest_datapoint(quantile_25, time_now) if time_now - quantile_25.timestamp > maximum_delay: self.logger.error('Quantile25 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_25.timestamp, quantile_25.name)) return None quantile_25 = quantile_25.value quantile_75 = get_closest_datapoint(quantile_75, time_now) if time_now - quantile_75.timestamp > maximum_delay: self.logger.error('Quantile75 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_75.timestamp, quantile_75.name)) return None quantile_75 = quantile_75.value if quantile_25 > quantile_75: self.logger.error('Inconsistent Quantile Values (Q25: %f, Q75: %f). Exiting' % ( quantile_25, quantile_75)) return None # group by metric (e.g. instance) first and find then closest datapoint distribution = {} grouped = itertools.groupby(metrics, key=lambda tup: tup.name) for key, metrics in grouped: closest_datapoint = get_closest_datapoint( [metric for metric in metrics], time_now) if time_now - closest_datapoint.timestamp < maximum_delay: distribution[key] = closest_datapoint.value if len(distribution) == 0: self.logger.error('No Distribution Values. Exiting') return None return quantile_25, quantile_75, distribution def process(self, data): quantile_25, quantile_75, distribution = data iqr_scaling = self.params.get('iqr_scaling', 1.5) iqr = quantile_75 - quantile_25 lower_limit = quantile_25 - iqr_scaling * iqr upper_limit = quantile_75 + iqr_scaling * iqr if 'static_lower_threshold' in self.params: lower_limit = max( lower_limit, self.params['static_lower_threshold']) if 'static_upper_threshold' in self.params: upper_limit = min( upper_limit, self.params['static_upper_threshold']) states = {} for metric, value in distribution.iteritems(): if value > upper_limit: states[metric] = 1.0 elif value < lower_limit: states[metric] = -1.0 else: states[metric] = 0.0 return quantile_25, quantile_75, states def write(self, data): quantile_25, quantile_75, states = data prefix = '%s.%s' % (self.namespace, self.service) count = len(states) invalid = 0 now = int(time()) tuples = [] for name, state in states.iteritems(): if state: invalid += 1 name = extract_service_name(name) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, name), now, state)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_25'), now, quantile_25)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_75'), now, quantile_75)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'count'), now, count)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'invalid'), now, invalid)) self.output_sink.write(tuples) def run(self):
data = self.read() if data: state = self.process(data) self.write(state) return True else: return None
identifier_body
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class TukeysFilter(BaseTask): def __init__(self, config, logger, options): super(TukeysFilter, self).__init__(config, logger, resource={'metric_sink': 'RedisSink', 'output_sink': 'GraphiteSink'}) self.namespace = 'TukeysFilter' self.service = options['service'] self.params = options['params'] def read(self): quantile_25 = self.params['quantile_25'] quantile_75 = self.params['quantile_75'] metrics = self.params['metrics'] delay = self.params.get('offset', 0) maximum_delay = self.params.get('maximum_delay', 600) # read metrics from metric_sink quantile_25 = [i for i in self.metric_sink.iread(quantile_25)] quantile_75 = [i for i in self.metric_sink.iread(quantile_75)] metrics = [i for i in self.metric_sink.iread(metrics)] if not (len(quantile_25) * len(quantile_75) * len(metrics)): self.logger.error( 'No data found for quantile/to be checked metrics. Exiting') return None # sort TimeSeriesTuples by timestamp quantile_25 = sorted(quantile_25, key=lambda tup: tup.timestamp) quantile_75 = sorted(quantile_75, key=lambda tup: tup.timestamp) metrics = sorted(metrics, key=lambda tup: (tup.name, tup.timestamp)) # find closest datapoint to now() (corrected by delay) if not too old time_now = time() - delay quantile_25 = get_closest_datapoint(quantile_25, time_now) if time_now - quantile_25.timestamp > maximum_delay: self.logger.error('Quantile25 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_25.timestamp, quantile_25.name)) return None quantile_25 = quantile_25.value quantile_75 = get_closest_datapoint(quantile_75, time_now) if time_now - quantile_75.timestamp > maximum_delay: self.logger.error('Quantile75 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_75.timestamp, quantile_75.name)) return None quantile_75 = quantile_75.value if quantile_25 > quantile_75: self.logger.error('Inconsistent Quantile Values (Q25: %f, Q75: %f). Exiting' % ( quantile_25, quantile_75)) return None # group by metric (e.g. instance) first and find then closest datapoint distribution = {} grouped = itertools.groupby(metrics, key=lambda tup: tup.name) for key, metrics in grouped: closest_datapoint = get_closest_datapoint( [metric for metric in metrics], time_now) if time_now - closest_datapoint.timestamp < maximum_delay: distribution[key] = closest_datapoint.value if len(distribution) == 0: self.logger.error('No Distribution Values. Exiting') return None return quantile_25, quantile_75, distribution def process(self, data): quantile_25, quantile_75, distribution = data iqr_scaling = self.params.get('iqr_scaling', 1.5) iqr = quantile_75 - quantile_25 lower_limit = quantile_25 - iqr_scaling * iqr upper_limit = quantile_75 + iqr_scaling * iqr if 'static_lower_threshold' in self.params: lower_limit = max( lower_limit, self.params['static_lower_threshold']) if 'static_upper_threshold' in self.params: upper_limit = min( upper_limit, self.params['static_upper_threshold']) states = {} for metric, value in distribution.iteritems(): if value > upper_limit: states[metric] = 1.0 elif value < lower_limit: states[metric] = -1.0 else: states[metric] = 0.0 return quantile_25, quantile_75, states def write(self, data): quantile_25, quantile_75, states = data prefix = '%s.%s' % (self.namespace, self.service) count = len(states) invalid = 0 now = int(time()) tuples = [] for name, state in states.iteritems():
if state: invalid += 1 name = extract_service_name(name) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, name), now, state)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_25'), now, quantile_25)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_75'), now, quantile_75)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'count'), now, count)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'invalid'), now, invalid)) self.output_sink.write(tuples) def run(self): data = self.read() if data: state = self.process(data) self.write(state) return True else: return None
random_line_split
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class
(BaseTask): def __init__(self, config, logger, options): super(TukeysFilter, self).__init__(config, logger, resource={'metric_sink': 'RedisSink', 'output_sink': 'GraphiteSink'}) self.namespace = 'TukeysFilter' self.service = options['service'] self.params = options['params'] def read(self): quantile_25 = self.params['quantile_25'] quantile_75 = self.params['quantile_75'] metrics = self.params['metrics'] delay = self.params.get('offset', 0) maximum_delay = self.params.get('maximum_delay', 600) # read metrics from metric_sink quantile_25 = [i for i in self.metric_sink.iread(quantile_25)] quantile_75 = [i for i in self.metric_sink.iread(quantile_75)] metrics = [i for i in self.metric_sink.iread(metrics)] if not (len(quantile_25) * len(quantile_75) * len(metrics)): self.logger.error( 'No data found for quantile/to be checked metrics. Exiting') return None # sort TimeSeriesTuples by timestamp quantile_25 = sorted(quantile_25, key=lambda tup: tup.timestamp) quantile_75 = sorted(quantile_75, key=lambda tup: tup.timestamp) metrics = sorted(metrics, key=lambda tup: (tup.name, tup.timestamp)) # find closest datapoint to now() (corrected by delay) if not too old time_now = time() - delay quantile_25 = get_closest_datapoint(quantile_25, time_now) if time_now - quantile_25.timestamp > maximum_delay: self.logger.error('Quantile25 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_25.timestamp, quantile_25.name)) return None quantile_25 = quantile_25.value quantile_75 = get_closest_datapoint(quantile_75, time_now) if time_now - quantile_75.timestamp > maximum_delay: self.logger.error('Quantile75 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_75.timestamp, quantile_75.name)) return None quantile_75 = quantile_75.value if quantile_25 > quantile_75: self.logger.error('Inconsistent Quantile Values (Q25: %f, Q75: %f). Exiting' % ( quantile_25, quantile_75)) return None # group by metric (e.g. instance) first and find then closest datapoint distribution = {} grouped = itertools.groupby(metrics, key=lambda tup: tup.name) for key, metrics in grouped: closest_datapoint = get_closest_datapoint( [metric for metric in metrics], time_now) if time_now - closest_datapoint.timestamp < maximum_delay: distribution[key] = closest_datapoint.value if len(distribution) == 0: self.logger.error('No Distribution Values. Exiting') return None return quantile_25, quantile_75, distribution def process(self, data): quantile_25, quantile_75, distribution = data iqr_scaling = self.params.get('iqr_scaling', 1.5) iqr = quantile_75 - quantile_25 lower_limit = quantile_25 - iqr_scaling * iqr upper_limit = quantile_75 + iqr_scaling * iqr if 'static_lower_threshold' in self.params: lower_limit = max( lower_limit, self.params['static_lower_threshold']) if 'static_upper_threshold' in self.params: upper_limit = min( upper_limit, self.params['static_upper_threshold']) states = {} for metric, value in distribution.iteritems(): if value > upper_limit: states[metric] = 1.0 elif value < lower_limit: states[metric] = -1.0 else: states[metric] = 0.0 return quantile_25, quantile_75, states def write(self, data): quantile_25, quantile_75, states = data prefix = '%s.%s' % (self.namespace, self.service) count = len(states) invalid = 0 now = int(time()) tuples = [] for name, state in states.iteritems(): if state: invalid += 1 name = extract_service_name(name) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, name), now, state)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_25'), now, quantile_25)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_75'), now, quantile_75)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'count'), now, count)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'invalid'), now, invalid)) self.output_sink.write(tuples) def run(self): data = self.read() if data: state = self.process(data) self.write(state) return True else: return None
TukeysFilter
identifier_name
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.checkout.scm.scm_mock import MockSCM from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot from webkitpy.common.net.web_mock import MockWeb from webkitpy.common.system.systemhost_mock import MockSystemHost # New-style ports need to move down into webkitpy.common. from webkitpy.layout_tests.port.factory import PortFactory from webkitpy.layout_tests.port.test import add_unit_tests_to_mock_filesystem class MockHost(MockSystemHost): def __init__(self, log_executive=False, executive_throws_when_run=None, initialize_scm_by_default=True, web=None, scm=None): MockSystemHost.__init__(self, log_executive, executive_throws_when_run) add_unit_tests_to_mock_filesystem(self.filesystem) self.web = web or MockWeb() self._scm = scm # FIXME: we should never initialize the SCM by default, since the real # object doesn't either. This has caused at least one bug (see bug 89498). if initialize_scm_by_default: self.initialize_scm() self.buildbot = MockBuildBot() # Note: We're using a real PortFactory here. Tests which don't wish to depend # on the list of known ports should override this with a MockPortFactory. self.port_factory = PortFactory(self) def initialize_scm(self, patch_directories=None): if not self._scm: self._scm = MockSCM(filesystem=self.filesystem, executive=self.executive) # Various pieces of code (wrongly) call filesystem.chdir(checkout_root). # Making the checkout_root exist in the mock filesystem makes that chdir not raise. self.filesystem.maybe_make_directory(self._scm.checkout_root) def
(self): return self._scm def scm_for_path(self, path): # FIXME: consider supporting more than one SCM so that we can do more comprehensive testing. self.initialize_scm() return self._scm def checkout(self): return self._checkout
scm
identifier_name
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.checkout.scm.scm_mock import MockSCM from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot from webkitpy.common.net.web_mock import MockWeb from webkitpy.common.system.systemhost_mock import MockSystemHost # New-style ports need to move down into webkitpy.common. from webkitpy.layout_tests.port.factory import PortFactory from webkitpy.layout_tests.port.test import add_unit_tests_to_mock_filesystem class MockHost(MockSystemHost): def __init__(self, log_executive=False, executive_throws_when_run=None, initialize_scm_by_default=True, web=None, scm=None): MockSystemHost.__init__(self, log_executive, executive_throws_when_run) add_unit_tests_to_mock_filesystem(self.filesystem) self.web = web or MockWeb() self._scm = scm # FIXME: we should never initialize the SCM by default, since the real # object doesn't either. This has caused at least one bug (see bug 89498). if initialize_scm_by_default:
self.buildbot = MockBuildBot() # Note: We're using a real PortFactory here. Tests which don't wish to depend # on the list of known ports should override this with a MockPortFactory. self.port_factory = PortFactory(self) def initialize_scm(self, patch_directories=None): if not self._scm: self._scm = MockSCM(filesystem=self.filesystem, executive=self.executive) # Various pieces of code (wrongly) call filesystem.chdir(checkout_root). # Making the checkout_root exist in the mock filesystem makes that chdir not raise. self.filesystem.maybe_make_directory(self._scm.checkout_root) def scm(self): return self._scm def scm_for_path(self, path): # FIXME: consider supporting more than one SCM so that we can do more comprehensive testing. self.initialize_scm() return self._scm def checkout(self): return self._checkout
self.initialize_scm()
conditional_block
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.checkout.scm.scm_mock import MockSCM from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot from webkitpy.common.net.web_mock import MockWeb from webkitpy.common.system.systemhost_mock import MockSystemHost # New-style ports need to move down into webkitpy.common. from webkitpy.layout_tests.port.factory import PortFactory from webkitpy.layout_tests.port.test import add_unit_tests_to_mock_filesystem class MockHost(MockSystemHost): def __init__(self, log_executive=False, executive_throws_when_run=None, initialize_scm_by_default=True, web=None, scm=None): MockSystemHost.__init__(self, log_executive, executive_throws_when_run) add_unit_tests_to_mock_filesystem(self.filesystem) self.web = web or MockWeb() self._scm = scm # FIXME: we should never initialize the SCM by default, since the real # object doesn't either. This has caused at least one bug (see bug 89498). if initialize_scm_by_default: self.initialize_scm() self.buildbot = MockBuildBot() # Note: We're using a real PortFactory here. Tests which don't wish to depend # on the list of known ports should override this with a MockPortFactory. self.port_factory = PortFactory(self) def initialize_scm(self, patch_directories=None): if not self._scm: self._scm = MockSCM(filesystem=self.filesystem, executive=self.executive) # Various pieces of code (wrongly) call filesystem.chdir(checkout_root). # Making the checkout_root exist in the mock filesystem makes that chdir not raise. self.filesystem.maybe_make_directory(self._scm.checkout_root) def scm(self): return self._scm def scm_for_path(self, path): # FIXME: consider supporting more than one SCM so that we can do more comprehensive testing. self.initialize_scm()
return self._scm def checkout(self): return self._checkout
random_line_split
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.checkout.scm.scm_mock import MockSCM from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot from webkitpy.common.net.web_mock import MockWeb from webkitpy.common.system.systemhost_mock import MockSystemHost # New-style ports need to move down into webkitpy.common. from webkitpy.layout_tests.port.factory import PortFactory from webkitpy.layout_tests.port.test import add_unit_tests_to_mock_filesystem class MockHost(MockSystemHost): def __init__(self, log_executive=False, executive_throws_when_run=None, initialize_scm_by_default=True, web=None, scm=None): MockSystemHost.__init__(self, log_executive, executive_throws_when_run) add_unit_tests_to_mock_filesystem(self.filesystem) self.web = web or MockWeb() self._scm = scm # FIXME: we should never initialize the SCM by default, since the real # object doesn't either. This has caused at least one bug (see bug 89498). if initialize_scm_by_default: self.initialize_scm() self.buildbot = MockBuildBot() # Note: We're using a real PortFactory here. Tests which don't wish to depend # on the list of known ports should override this with a MockPortFactory. self.port_factory = PortFactory(self) def initialize_scm(self, patch_directories=None): if not self._scm: self._scm = MockSCM(filesystem=self.filesystem, executive=self.executive) # Various pieces of code (wrongly) call filesystem.chdir(checkout_root). # Making the checkout_root exist in the mock filesystem makes that chdir not raise. self.filesystem.maybe_make_directory(self._scm.checkout_root) def scm(self): return self._scm def scm_for_path(self, path): # FIXME: consider supporting more than one SCM so that we can do more comprehensive testing.
def checkout(self): return self._checkout
self.initialize_scm() return self._scm
identifier_body