desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Queries the UserAppServer to see which application ids the named user
is an administrator on.
Args:
email: A str indicating the e-mail address of the user whose data we we
wish to query. If None is provided instead of a str, then we use the
currently logged-in user.
Returns:
A list of strs, where each str represents a... | def get_owned_apps(self, email=None):
| if (email is None):
user = users.get_current_user()
if (not user):
return []
email = user.email()
user_data = self.query_user_data(email)
user_data_match = re.search(self.USER_APP_LIST_REGEX, user_data)
if user_data_match:
return user_data_match.group(1).split... |
'Searches through our cache or queries the UserAppServer for the data it
stores for the given user.
Args:
email: A str that contains the e-mail address for the user whose
information we want to retrieve.
Returns:
A str containing the user\'s data, or the empty string if their data could
not be retrieved.'
| def query_user_data(self, email):
| if (email in self.cache['query_user_data']):
return self.cache['query_user_data'][email]
try:
user_data = self.get_uaserver().get_user_data(email, GLOBAL_SECRET_KEY)
self.cache['query_user_data'][email] = user_data
return user_data
except Exception as err:
logging.exc... |
'Checks if a user is a cloud administrator.
Args:
email: A str containing the e-mail address of the user that may be a cloud
admin, or None (in which case, we use the e-mail address of the
currently logged-in user).
Returns:
True if the user is a cloud admin, and False otherwise (including the case
when no user is logg... | def is_user_cloud_admin(self, email=None):
| if (email is None):
user = users.get_current_user()
if (not user):
return False
email = user.email()
user_data = self.query_user_data(email)
if re.search(self.CLOUD_ADMIN_REGEX, user_data):
return True
else:
return False
|
'Checks if the user can upload Google App Engine applications via the
AppDashboard.
Args:
email: A str containing the e-mail address of the user that may be a cloud
admin, or None (in which case, we use the e-mail address of the
currently logged-in user).
Returns:
True if the user is authorized to upload Google App Eng... | def can_upload_apps(self, email=None):
| if (email is None):
user = users.get_current_user()
if (not user):
return False
email = user.email()
return ('upload_app' in self.get_user_capabilities(email))
|
'Creates a new user account, by making both a standard login and an
XMPP login account.
Args:
email: A str containing the e-mail address of the new user.
password: A str containing the cleartext password for the new user.
response: A webapp2 response that the new user\'s logged in cookie
should be set in.
Returns:
True... | def create_new_user(self, email, password, response, account_type='xmpp_user'):
| try:
uaserver = self.get_uaserver()
encrypted_pass = LocalState.encrypt_password(email, password)
result = uaserver.commit_new_user(email, encrypted_pass, account_type, GLOBAL_SECRET_KEY)
if (result != 'true'):
raise AppHelperException(result)
username_regex = re.... |
'Queries the UserAppServer to retrieve a list of apps that the
user is an admin of.
Args:
email: A str containing the e-mail address of the user who we should
login as.
Returns:
A list of strs, each the name of an app the user is an admin of.'
| def get_user_app_list(self, email):
| user_data = self.query_user_data(email)
app_re = re.search(self.USER_APP_LIST_REGEX, user_data)
if app_re:
apps_list = app_re.group(1).split(self.APP_DELIMITER)
return apps_list
return []
|
'Creates a new cookie indicating that this user is logged in and sets it
in their session.
Args:
email: A str containing the e-mail address of the user who we should
login as.
apps_list: A list of strs, each the name of an app the user is an admin
of.
response: A webapp2 response that the new user\'s logged in cookie
s... | def set_appserver_cookie(self, email, apps_list, response):
| apps = self.LOGIN_COOKIE_APPS_SEPARATOR.join(apps_list)
if AppDashboardHelper.USE_SHIBBOLETH:
response.set_cookie(self.DEV_APPSERVER_LOGIN_COOKIE, value=self.get_cookie_value(email, apps), domain=AppDashboardHelper.SHIBBOLETH_COOKIE_DOMAIN, expires=(datetime.datetime.now() + datetime.timedelta(days=1)))... |
'Look at the user\'s login cookie and return the list of apps that
they are an owner of.
The login cookie\'s value has the form: "email:nick:apps:hash". The email
is the login email of the user, the nick is the assigned nickname for the
user, the apps is a comma seperate list of app that this user is an owner
of, and ... | def get_cookie_app_list(self, request):
| if (self.DEV_APPSERVER_LOGIN_COOKIE in request.cookies):
cookie_value = urllib.unquote(request.cookies[self.DEV_APPSERVER_LOGIN_COOKIE])
if cookie_value:
cookie_parts = cookie_value.split(self.LOGIN_COOKIE_FIELD_SEPARATOR)
if (len(cookie_parts) > self.LOGIN_COOKIE_APPS_PART):... |
'Update the login cookie with the list of apps the user is an admin of.
Look at the user\'s login cookie and compare the list of apps that they are
an owner of to the list of apps passed in. The owned_apps parameter is
considered authoritative, and will overwrite the cookie values if they
differ.
Args:
owned_apps: A li... | def update_cookie_app_list(self, owned_apps, request, response):
| user = users.get_current_user()
if (not user):
return
email = user.email()
cookie_apps = self.get_cookie_app_list(request)
if (set(owned_apps) != set(cookie_apps)):
self.set_appserver_cookie(email, owned_apps, response)
return True
else:
return False
|
'Generates a hash corresponding to the given user\'s credentials.
It is a hashed string containing the email, nickname, and list of apps the
user is an admin of. We hash this information with the secret key (not known
to the user) to prevent users from tampering with their cookie to alter
who they are logged in as or w... | def get_cookie_value(self, email, apps):
| nick = re.search('^(.*)@', email).group(1)
hsh = self.get_appengine_hash(email, nick, apps)
return urllib.quote('{1}{0}{2}{0}{3}{0}{4}'.format(self.LOGIN_COOKIE_FIELD_SEPARATOR, email, nick, apps, hsh))
|
'Generates a hash of the user\'s credentials with the secret key, used to
ensure that the user doesn\'t forge their cookie (as its value would fail to
match this hash).
Args:
email: A str containing the e-mail address of the user to create a hash
for.
nick: The prefix of the user\'s e-mail address (everything before th... | def get_appengine_hash(self, email, nick, apps):
| return hashlib.sha1('{0}{1}{2}{3}'.format(email, nick, apps, GLOBAL_SECRET_KEY)).hexdigest()
|
'Create a login token and save it in the UserAppServer.
Args:
token: A str containing the name of the token to create (usually the email
address).
email: A str containing the e-mail address of the user to create the login
token for.'
| def create_token(self, token, email):
| try:
uaserver = self.get_uaserver()
uaserver.commit_new_token(token, email, self.TOKEN_EXPIRATION, GLOBAL_SECRET_KEY)
except Exception as err:
logging.exception(err)
|
'Remove the user\'s login cookie and invalidate the login token in
the AppScale deployment. This results in the user being logged out.
If the user is already logged out, nothing happens.
Args:
response: A webapp2 response that the user\'s logged in cookie should be
erased from.'
| def logout_user(self, response):
| user = users.get_current_user()
if user:
self.create_token('invalid', user.email())
if AppDashboardHelper.USE_SHIBBOLETH:
response.delete_cookie(self.DEV_APPSERVER_LOGIN_COOKIE, domain=AppDashboardHelper.SHIBBOLETH_COOKIE_DOMAIN)
else:
response.delete_cookie(self.... |
'Checks to see if the user has entered in a valid email and password,
logging the user in if they have.
Args:
email: A str containing the e-mail address of the user to login.
password: A str containing the cleartext password of the user to login.
response: A webapp2 response that the new user\'s logged in cookie
should... | def login_user(self, email, password, response):
| user_data = self.query_user_data(email)
server_re = re.search(self.USER_DATA_PASSWORD_REGEX, user_data)
if (not server_re):
logging.error('Failed Login: {0} regex failed'.format(email))
return False
server_pwd = server_re.group(1)
encrypted_pass = LocalState.encrypt_passw... |
'Queries the UserAppServer and return a list of all users in the system.
Returns:
A list of strings, where each string is a user\'s e-mail address.'
| def list_all_users(self):
| ret_list = []
try:
uas = self.get_uaserver()
all_users = uas.get_all_users(GLOBAL_SECRET_KEY)
all_users_list = all_users.split(self.USER_DELIMITER)
my_ip = self.get_head_node_ip()
for usr in all_users_list:
if re.search((('@' + my_ip) + '$'), usr):
... |
'Queries the UserAppServer and returns a list of all the users and the
permissions they have in the system.
Returns:
A list of dicts, where each dict contains the e-mail address and
authorizations that this user is granted in this AppScale deployment.'
| def list_all_users_permissions(self):
| ret_list = []
try:
all_users_list = self.list_all_users()
perm_items = self.get_all_permission_items()
for user in all_users_list:
usr_cap = {'email': user}
caps_list = self.get_user_capabilities(user)
for perm in perm_items:
if (perm i... |
'Returns a list of the capabilities that users can be granted.
Returns:
A list of strs, where each str is the name of a capability.'
| def get_all_permission_items(self):
| return ['upload_app']
|
'Grants the named capability to the specified user.
Args:
email: A str containing the e-mail address of the user who we wish to add
a capability for.
perm: A str containing the name of the capability to grant to the user.
Returns:
True if the permission was given to the user, and False otherwise.'
| def add_user_permissions(self, email, perm):
| try:
caps_list = self.get_user_capabilities(email)
uas = self.get_uaserver()
new_caps = caps_list
if (perm not in new_caps):
new_caps.append(perm)
else:
return True
ret = uas.set_capabilities(email, self.USER_CAPABILITIES_DELIMITER.join(new_cap... |
'Revokes a capability from the specified user.
Args:
email: A str containing the e-mail address of the user who we wish to
remove a permission from.
perm: A str containing the name of the permission to remove from the user.
Returns:
True if the permission was removed from the user, and False otherwise.'
| def remove_user_permissions(self, email, perm):
| try:
caps_list = self.get_user_capabilities(email)
uas = self.get_uaserver()
if (perm in caps_list):
caps_list.remove(perm)
else:
return True
ret = uas.set_capabilities(email, self.USER_CAPABILITIES_DELIMITER.join(caps_list), GLOBAL_SECRET_KEY)
... |
'Tells the AppController on this node to collect all log files we\'ve
accumulated so far in this AppScale deployment.
Returns:
A tuple containing two items. The first item is a bool that indicates if
we were able to tell the AppController to gather the logs successfully,
and the second item is a str that refers to the ... | def gather_logs(self):
| try:
acc = self.get_appcontroller_client()
uuid = acc.gather_logs()
return (True, uuid)
except Exception as err:
logging.exception(err)
return (False, '')
|
'Tells the AppController on this node to contact the machine running the
Datastore on it, and instruct it to generate Kind statistics, for later
viewing in the AppDashboard.
Returns:
\'OK\' if the request was successful, and in case of failures, the reason
why the failure occurred.'
| def run_groomer(self):
| try:
acc = self.get_appcontroller_client()
return acc.run_groomer()
except Exception as err:
logging.exception(err)
return str(err)
|
'Instructs the UserAppServer to set the given user\'s password to the
given value.
Args:
email: A string indicating the email address of the user whose password
should be reset.
password: A string containing the cleartext password that should be set
for the given user.
Returns:
A tuple containing a boolean and string. ... | def change_password(self, email, password):
| hashed_password = hashlib.sha1((email + password)).hexdigest()
try:
user_app_server = self.get_uaserver()
ret = user_app_server.change_password(email, hashed_password, GLOBAL_SECRET_KEY)
if (ret == 'true'):
return (True, 'The user password was successfully chan... |
'Creates a new AppDashboard, which will cache SOAP-exposed information
provided to us by the AppDashboardHelper.
Args:
helper: An AppDashboardHelper, which will perform SOAP calls to the
AppController whenever the AppDashboardData needs to update its caches.
If None is provided here, then the AppDashboardData will crea... | def __init__(self, helper=None):
| self.helper = (helper or AppDashboardHelper())
|
'Generates the Lookup Dictionary for a user.
Args:
user_info: The current user.
Returns:
A dictionary containing the layout information.'
| def build_dict(self, user_info):
| if user_info:
lookup_dict = {'cloud_stats': {'title': 'Cloud Statistics', 'link': '/status/cloud', 'is_admin_panel': True, 'template': 'status/cloud.html'}, 'database_stats': {'title': 'Database Information', 'is_admin_panel': True, 'template': 'apps/database.html'}, 'memcache_stats': {'title': 'Globa... |
'Retrieves an object from the datastore, referenced by its keyname.
ndb does provide a method of the same name that does this, but we ran into
issues mocking out both ModelName() and ModelName.get_by_id() in the same
unit test, so using this level of indirection lets us mock out both without
issues.
Args:
model: The nd... | def get_by_id(self, model, key_name):
| return model.get_by_id(key_name)
|
'Retrieves all objects from the datastore for a given model, or all of
the keys for those objects.
Args:
obj: The ndb.Model that the requested object belongs to.
keys_only: A bool that indicates that only keys should be returned,
instead of the actual objects.
Returns:
A list of keys (if keys_only is True), or a list o... | def get_all(self, obj, keys_only=False):
| return obj.query().fetch(keys_only=keys_only)
|
'Queries the AppController to learn about the currently running
AppScale deployment.
This method stores all information it learns about this deployment in
the Datastore, to speed up future accesses to this data.'
| def update_all(self):
| self.update_head_node_ip()
self.get_database_info()
self.update_users()
|
'Retrieves the URL where the AppMonitoring web service can be found in
this AppScale deployment (typically on the login node).
Returns:
A str that contains a URL where low-level monitoring information is
displayed to users.'
| def get_monitoring_url(self):
| return 'http://{0}:{1}'.format(self.get_head_node_ip(), self.MONITOR_PORT)
|
'Retrieves the URL where the Celery Flower web service can be found in
this AppScale deployment (typically on the login node).
Returns:
A str that contains a URL where low-level monitoring information is
displayed to users.'
| def get_flower_url(self):
| return 'http://{0}:{1}'.format(self.get_head_node_ip(), self.FLOWER_PORT)
|
'Retrieves the URL where the Monit Dashboard web service can be found in
this AppScale deployment.
Note that although a Monit Dashboard runs on each node, we will send users
to the one on the login node.
Returns:
A str that names the URL where the services on the login node can be
viewed, started, and stopped.'
| def get_monit_url(self):
| return 'http://{0}:{1}'.format(self.get_head_node_ip(), self.MONIT_PORT)
|
'Retrieves the IP address or FQDN where the machine running the
shadow service can be found, via the Datastore.
Returns:
A str containing the IP address or FQDN of the shadow node.'
| def get_head_node_ip(self):
| dashboard_root = self.get_by_id(DashboardDataRoot, self.ROOT_KEYNAME)
if (dashboard_root and (dashboard_root.head_node_ip is not None)):
return dashboard_root.head_node_ip
else:
return self.update_head_node_ip()
|
'Updates the Datastore with the IP address or FQDN of the node running
the shadow service.
This update is only performed if there is no data in the Datastore about the
current location of the head node, as this is unlikely to dynamically change
at this time.
Returns:
A str containing the IP address or FQDN of the shado... | def update_head_node_ip(self):
| dashboard_root = self.get_by_id(DashboardDataRoot, self.ROOT_KEYNAME)
if (dashboard_root and (dashboard_root.head_node_ip is not None)):
return dashboard_root.head_node_ip
try:
if (dashboard_root is None):
dashboard_root = DashboardDataRoot(id=self.ROOT_KEYNAME)
dashboard... |
'Queries the AppController to get request information for the given
application, storing it in the Datastore for later viewing.
Args:
app_id: A string, the application identifier.'
| def update_request_info(self, app_id):
| try:
request_info = self.helper.get_appcontroller_client().get_request_info(app_id)
timestamp = datetime.datetime.fromtimestamp(request_info.get('timestamp'))
lastHourDateTime = (timestamp - datetime.timedelta(hours=1))
old_requests_query = RequestInfo.query((RequestInfo.timestamp < ... |
'Queries the AppController for information about what datastore is used
to implement support for the Google App Engine Datastore API, placing this
info in the Datastore for later viewing.
This update is only performed if there is no data in the Datastore about the
current location of the head node, as this is unlikely ... | def get_database_info(self):
| dashboard_root = self.get_by_id(DashboardDataRoot, self.ROOT_KEYNAME)
if (dashboard_root and (dashboard_root.table is not None) and (dashboard_root.replication is not None)):
return {'table': dashboard_root.table, 'replication': dashboard_root.replication}
try:
acc = self.helper.get_appcontr... |
'Queries the UserAppServer for information every user account registered
in this AppScale deployment, storing this info in the Datastore for later
viewing.
Returns:
A list of UserInfo objects, where each UserInfo corresponds to a user
account registered in this AppScale deployment. This list will be empty if
there was ... | def update_users(self):
| user_list = []
try:
all_users_list = self.helper.list_all_users()
users_to_update = []
for email in all_users_list:
user_info = self.get_by_id(UserInfo, email)
if user_info:
is_user_cloud_admin = self.helper.is_user_cloud_admin(email)
... |
'Queries the UserAppServer to see which Google App Engine applications
the currently logged in user has administrative permissions on.
Returns:
A list of strs, where each str corresponds to an appid that this user
can administer. Returns an empty list if this user isn\'t logged in.'
| def get_owned_apps(self):
| user = users.get_current_user()
if (not user):
return []
email = user.email()
try:
user_info = self.get_by_id(UserInfo, email)
if user_info:
return user_info.owned_apps
else:
return []
except Exception as err:
logging.exception(err)
... |
'Queries the UserAppServer to see if the currently logged in user has the
authority to administer this AppScale deployment.
Returns:
True if the currently logged in user is a cloud administrator, and False
otherwise (or if the user isn\'t logged in).'
| def is_user_cloud_admin(self):
| user = users.get_current_user()
if (not user):
return False
try:
user_info = self.get_by_id(UserInfo, user.email())
if user_info:
return user_info.is_user_cloud_admin
else:
return False
except Exception as err:
logging.exception(err)
... |
'Queries the UserAppServer to see if the currently logged in user has the
authority to upload Google App Engine applications on this AppScale
deployment.
Returns:
True if the currently logged in user can upload Google App Engine
applications, and False otherwise (or if the user isn\'t logged in).'
| def can_upload_apps(self):
| user = users.get_current_user()
if (not user):
return False
try:
user_info = self.get_by_id(UserInfo, user.email())
if user_info:
return user_info.can_upload_apps
else:
return False
except Exception as err:
logging.exception(err)
re... |
'Saves user settings for customizing the UI of the Dashboard.
Args:
values: A dict that defines the layout of the dash page from
/ajax/layout/save.
user_info: The current user.'
| def set_dash_layout_settings(self, values=None, user_info=None):
| if (not user_info):
user = users.get_current_user()
if (not user):
return
email = user.email()
try:
user_info = self.get_by_id(UserInfo, email)
except Exception as err:
logging.exception(err)
pass
if user_info:
if (t... |
'Rebuilds the user\'s layout settings in case there is an update
to the lookup dictionary.
Args:
email: A str that indicates the e-mail address of the user logging in.'
| def rebuild_dash_layout_settings_dict(self, email=None):
| if (email is None):
return {}
try:
user_info = self.get_by_id(UserInfo, email)
if user_info:
try:
if user_info.dash_layout_settings:
lookup_dict = self.build_dict(user_info=user_info)
values = user_info.dash_layout_setti... |
'Queries the UserAppServer to see what settings the user has saved
for customizing the UI of the Dashboard.
Args:
user_info: The current user.
Returns:
A dictionary containing the customization layout.'
| def get_dash_layout_settings(self, user_info=None):
| if (not user_info):
user = users.get_current_user()
if (not user):
return {}
email = user.email()
try:
user_info = self.get_by_id(UserInfo, email)
except Exception as err:
logging.exception(err)
if user_info:
try:
if... |
'Queries our local AppController to get server-level information about
every server running in this AppScale deployment.
Returns:
A list of dicts, where each dict contains VM-level info (e.g., CPU,
memory, disk usage) about that machine. The empty list is returned if
there was a problem retrieving this information.'
| def get_status_info(self):
| cluster_stats = self.setUpClusterStats()
statuses = AppDashboardHelper().get_status_info()
test_statuses = []
for node in cluster_stats:
cpu_usage = (100.0 - node['cpu']['idle'])
total_memory = (node['memory']['available'] + node['memory']['used'])
memory_usage = round(((100.0 * ... |
'Queries the AppController to get instance information for a given app_id'
| def get_instance_info(self, app_id):
| self.setUpInstanceStats()
instance_info = AppDashboardHelper().get_instance_info('test1')
test1_instance_stats = [{'host': '1.1.1.1', 'port': 0, 'language': 'python'}, {'host': '1.1.1.1', 'port': 1, 'language': 'python'}, {'host': '1.1.1.1', 'port': 2, 'language': 'python'}]
self.assertEqual(instance_in... |
'Queries the AppController for information about which Google App Engine
applications are currently running, and if they are done loading, the URL
that they can be accessed at.
Returns:
A dict, where each key is a str indicating the name of a Google App Engine
application running in this deployment, and each value is e... | def get_application_info(self):
| application_info = {'test1': ['http://1.1.1.1:1', 'https://1.1.1.1:1'], 'test2': ['http://1.1.1.1:2', 'https://1.1.1.1:2']}
flexmock(AppDashboardHelper)
AppDashboardHelper.should_receive('get_login_host').and_return('1.1.1.1')
AppDashboardHelper.should_receive('get_app_ports').and_return([1, 1]).and_ret... |
'Main GET method. Reports the status of the server.'
| def get(self):
| self.write(json.dumps({'status': 'up'}))
|
'POST method that sends a request for action to the
corresponding deployment components.'
| def post(self):
| logging.debug('Task request received: {0}, {1}'.format(str(self.request), str(self.request.body)))
if (not self.request.body):
logging.info('Response from the AppScale Portal empty. No tasks to run.')
self.set_status(constants.HTTP_Codes.HTTP_OK)
re... |
'Initializes profile log for cluster node stats.
Renders header according to include_lists in advance and
creates base directory for node stats profile log.
Args:
include_lists: An instance of IncludeLists describing which fields
of node stats should be written to CSV log.'
| def __init__(self, include_lists=None):
| self._include_lists = include_lists
self._header = converter.get_stats_header(node_stats.NodeStatsSnapshot, self._include_lists)
helper.ensure_directory(PROFILE_LOG_DIR)
|
'Saves newly produced cluster node stats
to a list of CSV files (file per node).
Args:
nodes_stats_dict: A dict with node IP as key and list of
NodeStatsSnapshot as value.'
| def write(self, nodes_stats_dict):
| for (node_ip, snapshot) in nodes_stats_dict.iteritems():
with self._prepare_file(node_ip) as csv_file:
row = converter.stats_to_list(snapshot, self._include_lists)
csv.writer(csv_file).writerow(row)
|
'Prepares CSV file with name node/<node-IP>.csv
for appending new lines.
Args:
node_ip: A string representation of node IP.
Returns:
A file object opened for appending new data.'
| def _prepare_file(self, node_ip):
| node_dir = path.join(PROFILE_LOG_DIR, node_ip)
file_name = path.join(node_dir, 'node.csv')
if (not path.isfile(file_name)):
helper.ensure_directory(node_dir)
with open(file_name, 'w') as csv_file:
csv.writer(csv_file).writerow(self._header)
return open(file_name, 'a')
|
'Initializes profile log for cluster processes stats.
Renders header according to include_lists in advance and
creates base directory for processes stats profile log.
It also reads header of summary file (if it exists) to identify
order of columns.
Args:
include_lists: An instance of IncludeLists describing which field... | def __init__(self, include_lists=None):
| self._include_lists = include_lists
self._header = (['utc_timestamp'] + converter.get_stats_header(process_stats.ProcessStats, self._include_lists))
self.write_detailed_stats = False
helper.ensure_directory(PROFILE_LOG_DIR)
self._summary_file_name_template = 'summary-{resource}.csv'
self._summar... |
'Saves newly produced cluster processes stats to a list of CSV files.
One detailed file for each process on every node and 3 summary files.
Args:
processes_stats_dict: A dict with node IP as key and list of
ProcessesStatsSnapshot as value.'
| def write(self, processes_stats_dict):
| services_summary = collections.defaultdict(self.ServiceProcessesSummary)
for (node_ip, snapshot) in processes_stats_dict.iteritems():
for proc in snapshot.processes_stats:
service_name = proc.unified_service_name
if proc.application_id:
service_name = '{}-{}'.form... |
'Prepares CSV file with name processes/<node-IP>/<monit-name>.csv
for appending new lines.
Args:
node_ip: A string representation of node IP.
monit_name: A string name of process as it\'s shown in monit status.
Returns:
A file object opened for appending new data.'
| def _prepare_file(self, node_ip, monit_name):
| processes_dir = path.join(PROFILE_LOG_DIR, node_ip, 'processes')
file_name = path.join(processes_dir, '{}.csv'.format(monit_name))
if (not path.isfile(file_name)):
helper.ensure_directory(processes_dir)
with open(file_name, 'w') as csv_file:
csv.writer(csv_file).writerow(self._he... |
'Opens summary-cpu-time.csv file (other summary file would be fine)
and reads its header. Profiler needs to know order of columns previously
written to the summary.
Returns:
A list of column names: [\'utc_timestamp\', <service1>, <service2>, ..].'
| def _get_summary_columns(self):
| cpu_summary_file_name = self._get_summary_file_name('cpu_time')
if (not path.isfile(cpu_summary_file_name)):
return ['utc_timestamp']
with open(cpu_summary_file_name, 'r') as summary_file:
reader = csv.reader(summary_file)
return reader.next()
|
'Saves services summary for each resource (cpu, resident memory and
unique memory). Output is 3 files (one for each resource) which
have a column for each service + utc_timestamp column.
Args:
services_summary: A dict where key is name of service and value is
an instance of ServiceProcessesSummary.'
| def _save_summary(self, services_summary):
| old_summary_columns = self._get_summary_columns()
for attribute in attr.fields(self.ServiceProcessesSummary):
summary_file_name = self._get_summary_file_name(attribute.name)
if (len(old_summary_columns) == 1):
with open(summary_file_name, 'w') as new_summary:
csv.writ... |
'Initializes profile log for cluster processes stats.
Renders header according to include_lists in advance and
creates base directory for processes stats profile log.
It also reads header of summary file (if it exists) to identify
order of columns.
Args:
include_lists: An instance of IncludeLists describing which field... | def __init__(self, include_lists=None):
| self._include_lists = include_lists
self._header = (['utc_timestamp'] + converter.get_stats_header(proxy_stats.ProxyStats, self._include_lists))
self.write_detailed_stats = False
helper.ensure_directory(PROFILE_LOG_DIR)
self._summary_file_name_template = 'summary-{property}.csv'
self._summary_co... |
'Saves newly produced cluster proxies stats to a list of CSV files.
One detailed file for each proxy on every load balancer node
(if detailed stats is enabled) and three additional files
which summarize info about all cluster proxies.
Args:
proxies_stats_dict: A dict with node IP as key and list of
ProxyStatsSnapshot a... | def write(self, proxies_stats_dict):
| services_summary = collections.defaultdict(self.ServiceProxySummary)
for (node_ip, snapshot) in proxies_stats_dict.iteritems():
for proxy in snapshot.proxies_stats:
service_name = proxy.unified_service_name
if proxy.application_id:
service_name = '{}-{}'.format(se... |
'Prepares CSV file with name <node-IP>/<pxname>.csv
for appending new lines.
Args:
node_ip: A string representation of load balancer node IP.
pxname: A string name of proxy as it\'s shown haproxy stats.
Returns:
A file object opened for appending new data.'
| def _prepare_file(self, node_ip, pxname):
| proxies_dir = path.join(PROFILE_LOG_DIR, node_ip, 'proxies')
file_name = path.join(proxies_dir, '{}.csv'.format(pxname))
if (not path.isfile(file_name)):
helper.ensure_directory(proxies_dir)
with open(file_name, 'w') as csv_file:
csv.writer(csv_file).writerow(self._header)
re... |
'Opens summary file and reads its header.
Profiler needs to know order of columns previously written to the summary.
Returns:
A list of column names: [\'utc_timestamp\', <service1>, <service2>, ..].'
| def _get_summary_columns(self):
| reqs_summary_file_name = self._get_summary_file_name('requests_rate')
if (not path.isfile(reqs_summary_file_name)):
return ['utc_timestamp']
with open(reqs_summary_file_name, 'r') as summary_file:
reader = csv.reader(summary_file)
return reader.next()
|
'Saves services summary for each property (requests rate, errors and
sum of bytes in & out). Output is 3 files (one for each property) which
have a column for each service + utc_timestamp column.
Args:
services_summary: A dict where key is name of service and value is
an instance of ServiceProxySummary.'
| def _save_summary(self, services_summary):
| old_summary_columns = self._get_summary_columns()
for attribute in attr.fields(self.ServiceProxySummary):
summary_file_name = self._get_summary_file_name(attribute.name)
if (len(old_summary_columns) == 1):
with open(summary_file_name, 'w') as new_summary:
csv.writer(n... |
'Checks whether monit process corresponds to this service.
Args:
monit_name: A string, name of process as it\'s shown in monit status.
Returns:
True if monit_name corresponds to this service, False otherwise.'
| def recognize_monit_process(self, monit_name):
| return (self.monit_matcher.match(monit_name) is not None)
|
'Checks whether haproxy proxy corresponds to this service.
Args:
proxy_name: A string, name of proxy as it\'s shown in haproxy stats.
Returns:
True if proxy_name corresponds to this service, False otherwise.'
| def recognize_haproxy_proxy(self, proxy_name):
| return (self.haproxy_proxy_matcher.match(proxy_name) is not None)
|
'Parses monit_name and returns application ID if it was found.
Args:
monit_name: A string, name of process as it\'s shown in monit status.
Returns:
A string representing App ID, or None if it wasn\'t found.'
| def get_application_id_by_monit_name(self, monit_name):
| match = self.monit_matcher.match(monit_name)
if (not match):
return None
try:
return (match.group('app') if match else None)
except IndexError:
return None
|
'Parses monit_name and returns port if it was found.
Args:
monit_name: A string, name of process as it\'s shown in monit status.
Returns:
An integer representing port, or None if it wasn\'t found.'
| def get_port_by_monit_name(self, monit_name):
| match = self.monit_matcher.match(monit_name)
try:
port_group = (match.group('port') if match else None)
return (int(port_group) if port_group else None)
except IndexError:
return None
|
'Parses haproxy proxy and returns application ID if it was found.
Args:
pxname: A string, name of proxy as it\'s shown in haproxy stats.
Returns:
A string representing App ID, or None if it wasn\'t found.'
| def get_application_id_by_pxname(self, pxname):
| match = self.haproxy_proxy_matcher.match(pxname)
if (not match):
return None
try:
return (match.group('app') if match else None)
except IndexError:
return None
|
'Parses haproxy proxy and returns private IP and port if it was found.
Args:
svname: A string, name of server as it\'s shown in haproxy stats.
Returns:
A tuple (str:ip, int:port), None is used if IP or port wasn\'t found.'
| def get_ip_port_by_svname(self, svname):
| match = self.haproxy_server_matcher.match(svname)
if (not match):
return (None, None)
try:
ip = match.group('ip')
except IndexError:
ip = None
try:
port_group = match.group('port')
port = (int(port_group) if port_group else None)
except IndexError:
... |
'Class method which is used by include_list_name decorator when
new class is decorated with this. It saves all available attributes
for the entity_class to all_attributes dict.
Args:
list_name: A string representing name of include list.
entity_class: An @attr.s decorated class.'
| @classmethod
def register(cls, list_name, entity_class):
| cls.all_attributes[list_name] = collections.OrderedDict(((att, None) for att in attr.fields(entity_class)))
|
'Validates include lists and copies it to own data structures.
Args:
include_lists: A dict where key is a name of include list,
value is a list of fields to include.
Raises:
WrongIncludeLists if unknown field or unknown include list was found.'
| def __init__(self, include_lists):
| self._lists = {}
self._original_dict = include_lists
for (list_name, fields_to_include) in include_lists.iteritems():
try:
known_attributes = self.all_attributes[list_name]
except KeyError:
raise WrongIncludeLists('Include list "{name}" is unknown, avai... |
'Checks if there is any include list specified for stats_entity_class
and if none was found - returns all available attributes for the class,
otherwise returns only specified in include list.
Args:
stats_entity_class: An @attr.s decorated class, stats model.
Returns:
A list of attr.Attribute instances which should be i... | def get_included_attrs(self, stats_entity_class):
| try:
return self._lists[stats_entity_class._include_list_name]
except KeyError:
return self.all_attributes[stats_entity_class._include_list_name]
except AttributeError:
return attr.fields(stats_entity_class)
|
'Determines if include_lists (argument) contains all attributes
specified for this instance (self).
Args:
include_lists: An instance of IncludeLists to compare with.
Returns:
A boolean indicating if self if subset of include_lists.'
| def is_subset_of(self, include_lists):
| if (self is include_lists):
return True
for (list_name, include_list) in self._lists.iteritems():
corresponding_list = include_lists._lists.get(list_name)
if (corresponding_list is None):
return False
for attribute in include_list:
if (attribute not in cor... |
'Initializes instance of ProfilingManager.
Starts watching profiling configs in zookeeper.
Args:
zk_client: an instance of KazooClient - started zookeeper client.'
| def __init__(self, zk_client):
| self.nodes_profile_log = None
self.processes_profile_log = None
self.proxies_profile_log = None
self.nodes_profile_task = None
self.processes_profile_task = None
self.proxies_profile_task = None
def bridge_to_ioloop(update_function):
' Creates function which schedule e... |
'Handles new value of nodes profiling configs and
starts/stops profiling with proper parameters.
Args:
new_conf: a string representing new value of zookeeper node.
znode_stat: an instance if ZnodeStat.'
| def update_nodes_profiling_conf(self, new_conf, znode_stat):
| if (not new_conf):
logging.debug('No node stats profiling configs are specified yet')
return
logging.info('New nodes stats profiling configs: {}'.format(new_conf))
conf = json.loads(new_conf)
enabled = conf['enabled']
interval = conf['interval']
... |
'Handles new value of processes profiling configs and
starts/stops profiling with proper parameters.
Args:
new_conf: a string representing new value of zookeeper node.
znode_stat: an instance if ZnodeStat.'
| def update_processes_profiling_conf(self, new_conf, znode_stat):
| if (not new_conf):
logging.debug('No processes stats profiling configs are specified yet')
return
logging.info('New processes stats profiling configs: {}'.format(new_conf))
conf = json.loads(new_conf)
enabled = conf['enabled']
interval = conf['inte... |
'Handles new value of proxies profiling configs and
starts/stops profiling with proper parameters.
Args:
new_conf: a string representing new value of zookeeper node.
znode_stat: an instance if ZnodeStat.'
| def update_proxies_profiling_conf(self, new_conf, znode_stat):
| if (not new_conf):
logging.debug('No proxies stats profiling configs are specified yet')
return
logging.info('New proxies stats profiling configs: {}'.format(new_conf))
conf = json.loads(new_conf)
enabled = conf['enabled']
interval = conf['interval... |
'Makes concurrent asynchronous http calls to cluster nodes
and collects current stats. Local stats is got from local stats source.
Args:
newer_than: UTC timestamp, allow to use cached snapshot if it\'s newer.
include_lists: An instance of IncludeLists.
exclude_nodes: A list of node IPs to ignore when fetching stats.
Re... | @gen.coroutine
def get_current_async(self, newer_than=None, include_lists=None, exclude_nodes=None):
| exclude_nodes = (exclude_nodes or [])
start = time.time()
stats_or_error_per_node = (yield {node_ip: self._stats_from_node_async(node_ip, newer_than, include_lists) for node_ip in self.ips_getter() if (node_ip not in exclude_nodes)})
stats_per_node = {ip: snapshot_or_err for (ip, snapshot_or_err) in sta... |
'Method for building an instance of NodeStatsSnapshot.
It collects information about usage of main resource on the machine.
Returns:
An object of NodeStatsSnapshot with detailed explanation of resources used
on the machine'
| @staticmethod
def get_current():
| utc_timestamp = time.mktime(datetime.now().timetuple())
start = time.time()
private_ip = appscale_info.get_private_ip()
cpu_times = psutil.cpu_times()
cpu = NodeCPU(user=cpu_times.user, system=cpu_times.system, idle=cpu_times.idle, percent=psutil.cpu_percent(), count=psutil.cpu_count())
loadavg ... |
'Method for building a list of ProcessStats.
It parses output of `monit status` and generates ProcessStats object
for each monitored service.
Returns:
An instance ofProcessesStatsSnapshot.'
| @staticmethod
def get_current():
| start = time.time()
monit_status = subprocess.check_output('monit status', shell=True)
processes_stats = []
for match in MONIT_PROCESS_PATTERN.finditer(monit_status):
monit_name = match.group('name')
pid = int(match.group('pid'))
service = find_service_by_monit_name(monit_name... |
'Method which parses haproxy stats and returns detailed
proxy statistics for all proxies.
Returns:
An instance of ProxiesStatsSnapshot.'
| @staticmethod
def get_current():
| start = time.time()
csv_buf = get_stats()
csv_buf.seek(2)
table = csv.DictReader(csv_buf, delimiter=',')
if ProxiesStatsSource.first_run:
missed = (ALL_HAPROXY_FIELDS - set(table.fieldnames))
if missed:
logging.warn('HAProxy stats fields {} are missed. O... |
'Creates a new DeploymentConfigSection.
Args:
zk_client: A KazooClient.
section: A string specifying a configuration section name.'
| def __init__(self, zk_client, section):
| self.logger = logging.getLogger(self.__class__.__name__)
self.zk_client = zk_client
self.section_name = section
self.data = {}
self._stopped = False
self.section_node = '/appscale/config/{}'.format(section)
self.watch = zk_client.DataWatch(self.section_node, self._update_section)
|
'Restart the watch if it has been cancelled.'
| def ensure_watch(self):
| if self._stopped:
self._stopped = False
self.watch = self.zk_client.DataWatch(self.section_node, self._update_section)
|
'Updates the configuration data when the section node gets updated.
Args:
section_data: A JSON string specifying configuration data.'
| def _update_section(self, section_data, _):
| if (section_data is None):
self._stopped = True
return False
try:
self.data = json.loads(section_data)
except ValueError:
self.logger.error('Invalid deployment config for {}: {}'.format(self.section_name, section_data))
|
'Creates new DeploymentConfig object.
Args:
zk_client: A KazooClient.'
| def __init__(self, zk_client):
| self.logger = logging.getLogger(self.__class__.__name__)
self.update_lock = Lock()
self.state = ConfigStates.LOADING
self.config = {}
self.conn = zk_client
self.conn.add_listener(self._conn_listener)
self.conn.ensure_path(self.CONFIG_ROOT)
self.conn.ChildrenWatch(self.CONFIG_ROOT, func=s... |
'Handles changes in ZooKeeper connection state.
Args:
state: A string indicating the new state.'
| def _conn_listener(self, state):
| if (state == KazooState.LOST):
self.logger.warning('ZK connection lost')
if (state == KazooState.SUSPENDED):
self.logger.warning('ZK connection suspended')
else:
self.logger.info('ZK connection established')
|
'Fetches the data for a configuration node.
Args:
child: A string containing the ZooKeeper node to fetch.
Returns:
A dictionary containing configuration data.
Raises:
InaccessibleConfig if ZooKeeper is not accessible.'
| def _load_child(self, child):
| node = '/'.join([self.CONFIG_ROOT, child])
try:
(data, _) = self.conn.retry(self.conn.get, node)
except (KazooException, ZookeeperError):
raise ConfigInaccessible('ZooKeeper connection not available')
except NoNodeError:
return {}
try:
return json.loads(data)... |
'Updates configuration when it changes.
Args:
children: A list of ZooKeeper nodes.'
| def _update_config(self, children):
| with self.update_lock:
self.state = ConfigStates.LOADING
to_remove = [section for section in self.config if (section not in children)]
for section_name in to_remove:
del self.config[section_name]
for child in children:
if (child not in self.config):
... |
'Fetches the configuration for a given section.
Args:
section: A string specifying the section to fetch.
Returns:
A dictionary containing configuration data.
Raises:
InaccessibleConfig if ZooKeeper is inaccessible.'
| def get_config(self, section):
| while ((self.state == ConfigStates.LOADING) and (self.conn.state not in (KazooState.LOST, KazooState.SUSPENDED))):
time.sleep(TINY_WAIT)
if (self.state != ConfigStates.LOADED):
raise ConfigInaccessible('ZooKeeper connection not available')
with self.update_lock:
if (section ... |
'Close the ZooKeeper connection.'
| def close(self):
| self.conn.stop()
|
'Creates a UAClient instance.
Args:
host: A string specifying the location of the UAServer.
secret: A string specifying the deployment secret.'
| def __init__(self, host, secret):
| if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
self.secret = secret
self.server = SOAPProxy('https://{}:{}'.format(host, UA_SERVER_PORT))
|
'Grants a user admin privileges for an application.
Args:
email: A string specifying the user\'s email address.
app_id: A string specifying an application ID.
Raises:
UAException if the operation was not successful.'
| def add_admin_for_app(self, email, app_id):
| response = self.server.add_admin_for_app(email, app_id, self.secret)
if (response.lower() != 'true'):
raise UAException(response)
|
'Associates an application with a hostname and ports.
Args:
app_id: A string specifying an application ID.
host: A string specifying a hostname.
port: An integer specifying a port.
https_port: An integer specifying a port.'
| def add_instance(self, app_id, host, port, https_port):
| response = self.server.add_instance(app_id, host, port, https_port, self.secret)
if (response.lower() != 'true'):
raise UAException(response)
|
'Creates new project.
Args:
app_id: A string specifying an application ID.
email: A string specifying the user\'s email address.
language: A string specifying the project\'s language.'
| def commit_new_app(self, app_id, email, language):
| response = self.server.commit_new_app(app_id, email, language, self.secret)
if (response == EXISTING_PROJECT_MESSAGE):
return
if (response.lower() != 'true'):
raise UAException(response)
|
'Creates a new user.
Args:
email: A string specifying the user\'s email address.
hashed_pwd: A string containing a hashed password.
type: A string specifying the type of user to create.
Raises:
UAException if the commit was not successful.'
| def commit_new_user(self, email, hashed_pwd, type):
| response = self.server.commit_new_user(email, hashed_pwd, type, self.secret)
if (response.lower() != 'true'):
raise UAException(response)
|
'Deletes a user.
Args:
email: A string specifying the user\'s email address.
Raises:
UAException if the deletion was not successful.'
| def delete_user(self, email):
| response = self.server.delete_user(email, self.secret)
if (response.lower() != 'true'):
raise UAException(response)
|
'Disables a user.
Args:
email: A string specifying the user\'s email address.
Raises:
UAException if the operation was not successful.'
| def disable_user(self, email):
| response = self.server.disable_user(email, self.secret)
if (response.lower() != 'true'):
raise UAException(response)
|
'Checks if an application exists.
Args:
app_id: A string specifying an application ID.
Returns:
A boolean indicating whether or not the application exists.
Raises:
UAException when unable to determine if app exists.'
| def does_app_exist(self, app_id):
| response = self.server.does_app_exist(app_id, self.secret)
if (response.lower() not in ['true', 'false']):
raise UAException(response)
return (response.lower() == 'true')
|
'Checks if a user exists.
Args:
email: A string specifying an email address.
Returns:
A boolean indicating whether or not the user exists.
Raises:
UAException when unable to determine if user exist.'
| def does_user_exist(self, email):
| response = self.server.does_user_exist(email, self.secret)
if (response.lower() not in ['true', 'false']):
raise UAException(response)
return (response.lower() == 'true')
|
'Enables a project.
Args:
app_id: A string specifying an application ID.
Raises:
UAException when unable to enable project.'
| def enable_app(self, app_id):
| response = self.server.enable_app(app_id, self.secret)
already_enabled = 'Error: Trying to enable an application that is already enabled'
if ((response.lower() == 'true') or (response == already_enabled)):
return
raise UAException(response)
|
'Retrieves a list of all users.
Returns:
A list of string containing user email addresses.
Raises:
UAException if unable to retrieve list of users.'
| def get_all_users(self):
| response = self.server.get_all_users(self.secret)
if response.startswith('Error'):
raise UAException(response)
if response.startswith('____'):
response = response[4:]
return response.split(':')
|
'Retrieves application metadata.
Args:
app_id: A string specifying an application ID.
Returns:
A dictionary containing application metadata.
Raises:
UAException if unable to retrieve application metadata.'
| def get_app_data(self, app_id):
| response = self.server.get_app_data(app_id, self.secret)
try:
data = json.loads(response)
except ValueError:
raise UAException(response)
return data
|
'Retrieves user metadata.
Args:
email: A string specifying an email address.
Returns:
A string containing user metadata.'
| def get_user_data(self, email):
| return self.server.get_user_data(email, self.secret)
|
'Checks if an application is enabled.
Args:
app_id: A string specifying an application ID.
Returns:
A boolean indicating whether or not an application is enabled.'
| def is_app_enabled(self, app_id):
| response = self.server.is_app_enabled(app_id, self.secret)
return (response.lower() == 'true')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.