Here are the examples of the python api flask.current_app.db.session taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
24 Examples
3
Example 1
def delete_tracker(tracker):
session = current_app.db.session('relengapi')
logger.info("deleting tracker with id: {}".format(tracker.task_id),
archiver_task=tracker.task_id)
session.delete(tracker)
session.commit()
3
Example 2
Project: build-relengapi Source File: __init__.py
def update_tracker_state(tracker, state):
session = current_app.db.session('relengapi')
logger.info("updating tracker with id: {} to state: {}".format(tracker.id, state),
archiver_task=tracker.task_id, archiver_task_state=state)
try:
tracker.state = state
session.commit()
except sa.exc.IntegrityError:
session.rollback()
3
Example 3
Project: build-relengapi Source File: __init__.py
@badpenny.periodic_task(seconds=TASK_TIME_OUT)
def cleanup_old_tasks(job_status):
"""delete any tracker task if it is older than the time a task can live for."""
session = current_app.db.session('relengapi')
expiry_cutoff = now() - datetime.timedelta(seconds=TASK_TIME_OUT)
table = tables.ArchiverTask
for tracker in session.query(table).order_by(table.created_at):
if tracker.created_at < expiry_cutoff:
delete_tracker(tracker)
else:
break
3
Example 4
Project: build-relengapi Source File: __init__.py
def renew_tracker_pending_expiry(tracker):
pending_expires_at = now() + datetime.timedelta(seconds=PENDING_EXPIRES_IN)
session = current_app.db.session('relengapi')
logger.info("renewing tracker {} with pending expiry: {}".format(
tracker.id, pending_expires_at), archiver_task=tracker.task_id)
tracker.pending_expires_at = pending_expires_at
session.commit()
3
Example 5
def sync_tasks(self):
"""Synchronize tasks defined in code into the DB"""
for task in badpenny.Task.list():
bpt = tables.BadpennyTask.as_unique(
current_app.db.session('relengapi'), name=task.name)
task.task_id = bpt.id
current_app.db.session('relengapi').commit()
3
Example 6
def _finish(self, successful):
self._update_job({
tables.BadpennyJob.completed_at: time.now(),
tables.BadpennyJob.successful: successful,
})
if self._log_output:
session = current_app.db.session('relengapi')
content = u'\n'.join(self._log_output)
l = tables.BadpennyJobLog(id=self.job_id, content=content)
session.add(l)
session.commit()
3
Example 7
@bp.route('/tasks/<task_name>/run-now', methods=['POST'])
@apimethod(rest.BadpennyJob, unicode)
@p.base.badpenny.run.require()
def run_task_now(task_name):
"""Force the given badpenny task to run now. This method requires the
``base.badpenny.run`` permission."""
t = tables.BadpennyTask.query.filter(
tables.BadpennyTask.name == task_name).first()
if not t:
raise NotFound
session = current_app.db.session('relengapi')
job = tables.BadpennyJob(task=t, created_at=time.now())
session.add(job)
session.commit()
execution.submit_job(task_name=t.name, job_id=job.id)
return job.to_jsonjob()
3
Example 8
Project: build-relengapi Source File: tasks.py
def add_task_to_history(loanid, msg):
session = current_app.db.session('relengapi')
l = session.query(Loans).get(loanid)
history = History(for_loan=l,
timestamp=tz.utcnow(),
msg=msg)
session.add(history)
session.commit()
logger.debug("Log_line: %s" % msg)
3
Example 9
Project: build-relengapi Source File: tasks.py
@task(bind=True, max_retries=None)
@add_to_history(
after="Marked loan as ACTIVE")
def mark_loan_status(self, loanid, status):
try:
session = current_app.db.session('relengapi')
l = session.query(Loans).get(loanid)
l.status = status
session.commit()
except Exception as exc:
self.retry(exc=exc)
3
Example 10
Project: build-relengapi Source File: grooming.py
@badpenny.periodic_task(seconds=600)
def check_pending_uploads(job_status):
"""Check for any pending uploads and verify them if found."""
session = current_app.db.session('relengapi')
for pu in tables.PendingUpload.query.all():
check_pending_upload(session, pu)
session.commit()
3
Example 11
Project: build-relengapi Source File: grooming.py
@celery.task
def check_file_pending_uploads(sha512):
"""Check for pending uploads for a single file"""
session = current_app.db.session('relengapi')
file = tables.File.query.filter(tables.File.sha512 == sha512).first()
if file:
for pu in file.pending_uploads:
check_pending_upload(session, pu)
session.commit()
3
Example 12
Project: build-relengapi Source File: test_grooming.py
def add_file_row(size, sha512, instances=[]):
session = current_app.db.session('relengapi')
file_row = tables.File(size=size, visibility='public', sha512=sha512)
session.add(file_row)
for region in instances:
session.add(tables.FileInstance(file=file_row, region=region))
session.commit()
return file_row
3
Example 13
Project: build-relengapi Source File: test_grooming.py
def add_pending_upload_and_file_row(size, sha512, expires, region):
session = current_app.db.session('relengapi')
file_row = tables.File(size=size, visibility='public', sha512=sha512)
pu_row = tables.PendingUpload(
file=file_row, expires=expires, region=region)
session.add(file_row)
session.commit()
return pu_row, file_row
3
Example 14
@bp.route('/trees/<path:tree_name>', methods=['PUT'])
@p.treestatus.admin.require()
@apimethod(None, unicode, body=types.JsonTree)
def make_tree(tree_name, body):
"""Make a new tree."""
session = current_app.db.session('relengapi')
if body.tree != tree_name:
raise BadRequest("Tree names must match")
t = model.DbTree(
tree=tree_name,
status=body.status,
reason=body.reason,
message_of_the_day=body.message_of_the_day)
try:
session.add(t)
session.commit()
except (sa.exc.IntegrityError, sa.exc.ProgrammingError):
raise BadRequest("tree already exists")
return None, 204
3
Example 15
@bp.route('/trees/<path:tree>', methods=['DELETE'])
@p.treestatus.admin.require()
@apimethod(None, unicode)
def kill_tree(tree):
"""Delete a tree."""
session = current_app.db.session('relengapi')
t = session.query(model.DbTree).get(tree)
if not t:
raise NotFound("No such tree")
session.delete(t)
# delete from logs and change stack, too
model.DbLog.query.filter_by(tree=tree).delete()
model.DbStatusChangeTree.query.filter_by(tree=tree).delete()
session.commit()
tree_cache_invalidate(tree)
return None, 204
0
Example 16
Project: build-relengapi Source File: cleanup.py
@badpenny.periodic_task(seconds=24 * 3600)
def cleanup_old_jobs(job_status):
session = current_app.db.session('relengapi')
Task = tables.BadpennyTask
Job = tables.BadpennyJob
old_job_days = current_app.config.get('BADPENNY_OLD_JOB_DAYS', 7)
old = time.now() - datetime.timedelta(days=old_job_days)
deleted = 0
for task in Task.query.all():
# Iterate until we find a job that's not too old. Only
# delete on the next iteration to avoid deleting the most
# recent job.
to_delete = None
for job in Job.query.filter(Job.task_id == task.id).order_by(Job.created_at):
if to_delete:
for log in to_delete.logs:
session.delete(log)
session.delete(to_delete)
to_delete = None
deleted += 1
if job.created_at < old:
to_delete = job
else:
break
if deleted:
logger.info("removed %d old jobs", deleted)
session.commit()
0
Example 17
def _update_job(self, update):
session = current_app.db.session('relengapi')
session.query(tables.BadpennyJob).filter(
tables.BadpennyJob.id == self.job_id).update(update)
session.commit()
0
Example 18
Project: build-relengapi Source File: tasks.py
@task(bind=True, max_retries=None)
@add_to_history(
before="Identifying FQDN and IP of {args[1]}",
after="Acquired FQDN and IP")
def fixup_machine(self, machine, loanid):
try:
fqdn = socket.getfqdn("%s.build.mozilla.org" % machine)
ipaddress = socket.gethostbyname("%s.build.mozilla.org" % machine)
session = current_app.db.session('relengapi')
m = Machines.as_unique(session,
fqdn=fqdn,
ipaddress=ipaddress)
# Re-check validity of fqdn and ip
if m.fqdn != fqdn:
m.fqdn = fqdn
if m.ipaddress != ipaddress:
m.ipaddress = ipaddress
l = session.query(Loans).get(loanid)
l.machine = m
session.commit()
except Exception as exc: # pylint: disable=W0703
logger.exception(exc)
self.retry(exc=exc)
0
Example 19
Project: build-relengapi Source File: tasks.py
@task(bind=True)
@add_to_history(
before="Filing the loan bug if needed",
after="Loan is tracked in bug {retval!s}")
def bmo_file_loan_bug(self, loanid, slavetype, *args, **kwargs):
try:
session = current_app.db.session('relengapi')
l = session.query(Loans).get(loanid)
if l.bug_id:
# Nothing to do, bug ID passed in
return l.bug_id
bmo_id = l.human.bugzilla
bug_id = bugzilla.create_loan_bug(loan_id=loanid,
slavetype=slavetype,
bugzilla_username=bmo_id)
if not bug_id:
raise ValueError("Unexpected result from bmo, retry")
l.bug_id = bug_id
session.commit()
return bug_id
except Exception as exc:
logger.exception(exc)
self.retry(exc=exc)
0
Example 20
Project: build-relengapi Source File: tasks.py
@task(bind=True)
@add_to_history(
after="Waiting for a human to perform {kwargs[action_name]} (id {retval!s})")
def register_action_needed(self, loanid, action_name):
if not action_name:
raise ValueError("must supply an action name")
try:
session = current_app.db.session('relengapi')
l = session.query(Loans).get(loanid)
if action_name == "add_to_vpn":
action_message = (
"Add user (%s) and machine (%s) to the VPN. "
"Following https://wiki.mozilla.org/ReleaseEngineering/How_To/Update_VPN_ACL"
% (l.human.ldap, l.machine.fqdn)
)
elif action_name == "create_aws_system":
action_message = (
"Create an aws machine for %s of the type requested (see loan history)."
" Following "
"https://wiki.mozilla.org/ReleaseEngineering/How_To/Loan_a_Slave#AWS_machines"
% (l.human.ldap,)
)
elif action_name == "clean_secrets":
action_message = (
"Clean secrets from the machine. See instructions at "
"https://wiki.mozilla.org/ReleaseEngineering/How_To/Loan_a_Slave#Cleaning"
)
elif action_name == "notify_complete":
action_message = (
"Notify the loanee in e-mail and the loan bug (Bug %s) that the loan is ready. "
"See template text for both in "
"https://wiki.mozilla.org/ReleaseEngineering/How_To/Loan_a_Slave#Notifying"
% l.bug_id
)
elif action_name == "gpo_switch":
action_message = (
"Need to switch host (%s) to be in the Loaner GPO group. Follow "
"https://wiki.mozilla.org/ReleaseEngineering/How_To/Loan_a_Slave"
"#t-xp32-ix.2C_t-w732-ix.2C_t-w864-ix.2C_w64-ix-slave "
"for more information"
% (l.machine.fqdn)
)
else:
raise ValueError("Invalid action name")
action = ManualActions(for_loan=l,
timestamp_start=tz.utcnow(),
msg=action_message)
session.add(action)
session.commit()
return action.id
except ValueError:
raise # Don't indefinitely retry in this case
except Exception as exc:
self.retry(exc=exc)
0
Example 21
Project: build-relengapi Source File: usermonitor.py
@badpenny.periodic_task(3600)
def monitor_users(job_status):
# for every user token, examine the token's permission map and the user's
# permissions. If the token has more permissions than the user, disable
# the token.
session = current_app.db.session('relengapi')
for token in session.query(tables.Token).filter(tables.Token.typ == 'usr'):
token_perms = set(token.permissions)
user_perms = current_app.authz.get_user_permissions(token.user)
if user_perms is None:
disable = True
else:
if token_perms - user_perms:
disable = True
else:
disable = False
perm_str = ', '.join(str(p) for p in token.permissions)
log = logger.bind(token_typ=token.typ, token_id=token.id,
token_user=token.user, token_permissions=perm_str, mozdef=True)
if disable and not token.disabled:
logmsg = "Disabling {} token #{} for user {} with permissions {}".format(
token.typ, token.id, token.user, perm_str)
log.info(logmsg)
job_status.log_message(logmsg)
token.disabled = True
elif not disable and token.disabled:
logmsg = "Re-enabling {} token #{} for user {} with permissions {}".format(
token.typ, token.id, token.user, perm_str)
log.info(logmsg)
job_status.log_message(logmsg)
token.disabled = False
session.commit()
0
Example 22
@bp.route('/file/sha512/<digest>', methods=['PATCH'])
@p.tooltool.manage.require()
@api.apimethod(types.File, unicode, body=[{unicode: unicode}])
def patch_file(digest, body):
"""Make administrative changes to an existing file. The body is a list of
changes to apply, each represented by a JSON object.
The object ``{"op": "delete_instances"}`` will cause all instances of the
file to be deleted. The file record itself will not be deleted, as it is
still a part of one or more upload batches, but until and unless someone
uploads a new copy, the content will not be available for download.
If the change has op ``"set_visibility"``, then the file's visibility will
be set to the value given by the change's ``visibility`` attribute. For
example, ``{"op": "set_visibility", "visibility": "internal"}`` will mark a
file as "internal" after someone has accidentally uploaded it with public
visibility.
The returned File instance contains an ``instances`` attribute showing any
changes."""
session = current_app.db.session('relengapi')
file = session.query(tables.File).filter(tables.File.sha512 == digest).first()
if not file:
raise NotFound
for change in body:
if 'op' not in change:
raise BadRequest("no op")
if change['op'] == 'delete_instances':
key_name = util.keyname(digest)
cfg = current_app.config.get('TOOLTOOL_REGIONS')
for i in file.instances:
conn = current_app.aws.connect_to('s3', i.region)
bucket = conn.get_bucket(cfg[i.region])
bucket.delete_key(key_name)
session.delete(i)
elif change['op'] == 'set_visibility':
if change['visibility'] not in ('internal', 'public'):
raise BadRequest("bad visibility level")
file.visibility = change['visibility']
else:
raise BadRequest("unknown op")
session.commit()
return file.to_json(include_instances=True)
0
Example 23
Project: build-relengapi Source File: __init__.py
@bp.route('/stack/<int:id>', methods=['DELETE'])
@p.treestatus.sheriff.require()
@apimethod(None, int, int)
def revert_change(id, revert=None):
"""
Remove the given change from the undo stack.
With ``?revert=1`` This applies the settings that were
present before the change to the affected trees.
With ``?revert=0`` or omitting the revert keyword, it merely removes
the change from the stack without changing the settings on the tree.
"""
if revert not in (0, 1, None):
raise BadRequest("Unexpected value for 'revert'")
session = current_app.db.session('relengapi')
ch = session.query(model.DbStatusChange).get(id)
if not ch:
raise NotFound
if revert:
for chtree in ch.trees:
last_state = json.loads(chtree.last_state)
tree = model.DbTree.query.get(chtree.tree)
if tree is None:
# if there's no tree to update, don't worry about it
pass
update_tree_status(
session, tree,
status=last_state['status'],
reason=last_state['reason'])
session.delete(ch)
session.commit()
return None, 204
0
Example 24
Project: build-relengapi Source File: __init__.py
@bp.route('/trees', methods=['PATCH'])
@p.treestatus.sheriff.require()
@apimethod(None, body=types.JsonTreeUpdate)
def update_trees(body):
"""
Update trees' status.
If the update indicates that the previous state should be saved, then a new
change will be added to the stack containing the previous status and
reason. In this case, both reason and status must be supplied.
The `tags` property must not be empty if `status` is `closed`.
"""
session = current_app.db.session('relengapi')
trees = [session.query(model.DbTree).get(t) for t in body.trees]
if not all(trees):
raise NotFound("one or more trees not found")
if body.status == 'closed' and not body.tags:
raise BadRequest("tags are required when closing a tree")
if body.remember:
if body.status is Unset or body.reason is Unset:
raise BadRequest("must specify status and reason to remember the change")
# add a new stack entry with the new and existing states
ch = model.DbStatusChange(
who=str(current_user),
reason=body.reason,
when=relengapi_time.now(),
status=body.status)
for tree in trees:
stt = model.DbStatusChangeTree(
tree=tree.tree,
last_state=json.dumps(
{'status': tree.status, 'reason': tree.reason}))
ch.trees.append(stt)
session.add(ch)
# update the trees as requested
def unset_to_none(x):
return x if x is not Unset else None
new_status = unset_to_none(body.status)
new_reason = unset_to_none(body.reason)
new_motd = unset_to_none(body.message_of_the_day)
new_tags = unset_to_none(body.tags) or []
for tree in trees:
update_tree_status(session, tree,
status=new_status,
reason=new_reason,
message_of_the_day=new_motd,
tags=new_tags)
session.commit()
return None, 204