Skip to content

Commit 0efe85d

Browse files
committed
crm# 250228-003676 pids
1 parent d4ac540 commit 0efe85d

9 files changed

Lines changed: 64 additions & 30 deletions

File tree

pitschi/db/crud.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,16 +93,16 @@ def get_datasets(db: Session, username: str):
9393

9494
def get_datasets_from_original(db: Session, username: str, origmachine: str, origpath: str):
9595
return db.query(models.Dataset).\
96-
filter(models.Dataset.origionalmachine == origmachine).\
97-
filter(models.Dataset.origionalpath == origpath).\
96+
filter(models.Dataset.originalmachine == origmachine).\
97+
filter(models.Dataset.originalpath == origpath).\
9898
join(models.Dataset.booking).\
9999
filter(or_(models.Booking.username == username, models.Booking.assistant == username)).all()
100100

101101
def get_datasets_from_one_machine(db: Session, username: str, origmachine: str, date: datetime.date):
102102
return db.query(models.Dataset).\
103103
filter(and_(func.date(models.Dataset.modified) >= date),\
104104
(func.date(models.Dataset.modified) <= date )).\
105-
filter(models.Dataset.origionalmachine == origmachine).\
105+
filter(models.Dataset.originalmachine == origmachine).\
106106
join(models.Dataset.booking).\
107107
filter(models.Booking.username == username).all()
108108

@@ -314,7 +314,7 @@ def get_core(db: Session, coreid: int):
314314
return db.query(models.Core).\
315315
filter(models.Core.id == coreid).first()
316316

317-
def create_core(db: Session, system: schemas.Core):
317+
def create_core(db: Session, core: schemas.Core):
318318
"""
319319
Create a PPMS core, or update if needed
320320
"""
@@ -344,6 +344,13 @@ def get_system(db: Session, systemid: int):
344344
return db.query(models.System).\
345345
filter(models.System.id == systemid).first()
346346

347+
def get_system_pid(db: Session, systemid: int):
348+
return db.query(models.System).\
349+
filter(models.System.id == systemid).first().pid
350+
351+
def get_system_ror(db: Session, systemid: int):
352+
return get_core(db, get_system(db, systemid).coreid).rorid
353+
347354
def get_system_byname(db: Session, systemname: str):
348355
return db.query(models.System).\
349356
filter(models.System.name == systemname).first()

pitschi/db/models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ class PUser(Base):
4444
class Dataset(Base):
4545
__tablename__ = 'dataset'
4646
id = Column(Integer, primary_key=True, index=True)
47-
origionalmachine = Column(String, unique=False, primary_key=False, index=False, nullable=False)
48-
origionalpath = Column(String, unique=False, primary_key=False, index=False, nullable=False)
47+
originalmachine = Column(String, unique=False, primary_key=False, index=False, nullable=False)
48+
originalpath = Column(String, unique=False, primary_key=False, index=False, nullable=False)
4949
networkpath = Column(String, unique=False, primary_key=False, index=False, nullable=False)
5050
relpathfromrootcollection = Column(String, unique=False, primary_key=False, index=False, nullable=False)
5151
name = Column(String, unique=False, primary_key=False, index=False, nullable=False)

pitschi/db/schemas.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ class Config:
6767
#################################
6868
class DatasetBase(BaseModel):
6969
relpathfromrootcollection: str # /folder1/folder2 # get q collectio nfrom project
70-
origionalmachine: str
71-
origionalpath: str # C:\dekstop\folder1\folder2
70+
originalmachine: str
71+
originalpath: str # C:\dekstop\folder1\folder2
7272
networkpath: str # \\data.qbi.uq.edu.au\CMM4CEED-Q3504\folder1\folder2
7373
name: str
7474
received: Optional[datetime.datetime]

pitschi/ppms.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,24 @@ def get_daily_training(date: datetime.date):
140140
return sessions
141141

142142

143+
def get_cores():
144+
coreids = json.loads(config.get('ppms', 'coreids'))
145+
logger.debug(f'get cores for core ids: {",".join(str(c) for c in coreids)}')
146+
url = f"{config.get('ppms', 'ppms_url')}API2/"
147+
payload=f"outformat=json&apikey={config.get('ppms', 'api2_key')}&action=Report2169"
148+
headers = {
149+
'Content-Type': 'application/x-www-form-urlencoded'
150+
}
151+
response = requests.request("POST", url, headers=headers, data=payload)
152+
if response.ok:
153+
if response.status_code != 204:
154+
cores = response.json(strict=False)
155+
if type(cores) == list and len(cores) > 0:
156+
return [c for c in cores if c.get('Core ID') in coreids]
157+
logger.warning(f'response status_code={response.status_code}, text="{response.text}"')
158+
return []
159+
160+
143161
def get_system_pids():
144162
logger.debug(f'get all system pids')
145163
url = f"{config.get('ppms', 'ppms_url')}API2/"
@@ -158,7 +176,8 @@ def get_system_pids():
158176

159177

160178
def get_systems():
161-
logger.debug("get all systems")
179+
coreids = json.loads(config.get('ppms', 'coreids'))
180+
logger.debug(f'get systems for core ids: {",".join(str(c) for c in coreids)}')
162181
url = f"{config.get('ppms', 'ppms_url')}pumapi/"
163182
payload=f"apikey={config.get('ppms', 'ppms_key')}&action=getsystems"
164183
headers = {
@@ -175,10 +194,11 @@ def get_systems():
175194
for row in _csv_reader:
176195
if(len(row) > 3):
177196
_coreid = int(row[0])
178-
_systemid = int(row[1])
179-
_systemtype = row[2]
180-
_systemname = row[3]
181-
systems.append({'coreid': _coreid, 'systemid': _systemid, 'systemtype': _systemtype, 'systemname': _systemname})
197+
if _coreid in coreids:
198+
_systemid = int(row[1])
199+
_systemtype = row[2]
200+
_systemname = row[3]
201+
systems.append({'coreid': _coreid, 'systemid': _systemid, 'systemtype': _systemtype, 'systemname': _systemname})
182202
return systems
183203
logger.warning(f'response status_code={response.status_code}, text="{response.text}"')
184204
return []
@@ -205,7 +225,8 @@ def get_system_rights(systemid: int):
205225

206226

207227
def get_projects():
208-
logger.debug("get all projects")
228+
coreids = json.loads(config.get('ppms', 'coreids'))
229+
logger.debug(f'get projects for core ids: {",".join(str(c) for c in coreids)}')
209230
url = f"{config.get('ppms', 'ppms_url')}pumapi/"
210231
payload=f"apikey={config.get('ppms', 'ppms_key')}&action=getprojects&active=true&format=json"
211232
# payload=f"apikey={config.get('ppms', 'ppms_key')}&action=getprojects&format=json"
@@ -217,7 +238,7 @@ def get_projects():
217238
if response.status_code == 204:
218239
return []
219240
else:
220-
return response.json(strict=False)
241+
return [p for p in response.json(strict=False) if p.get('CoreFacilityRef') in coreids]
221242
else:
222243
return []
223244

@@ -285,7 +306,6 @@ def get_rdm_collection(coreid: int, projectid: int):
285306
return ""
286307

287308
def get_rdm_collections(coreid: int = None):
288-
logger.debug("@get_rdm_collections: get all rdm collections")
289309
url = f"{config.get('ppms', 'ppms_url')}API2/"
290310
headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
291311
action = config.get('ppms', 'qcollections_action')
@@ -295,6 +315,7 @@ def get_rdm_collections(coreid: int = None):
295315
coreids = json.loads(config.get('ppms', 'coreids'))
296316
else:
297317
coreids = [coreid]
318+
logger.debug(f'get rdm collections for core ids: {",".join(str(c) for c in coreids)}')
298319
for coreid in coreids:
299320
payload = f"apikey={config.get('ppms', 'api2_key')}&action={action}&coreid={coreid}&outformat=json"
300321
response = requests.request("POST", url, headers=headers, data=payload)

pitschi/routers/clowder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pitschi.config as config
99
import pitschi.utils as utils
1010
import pitschi.clowder_rest as clowderful
11-
import os, json
11+
import os
1212

1313
router = APIRouter()
1414
logger = logging.getLogger('pitschixapi')

pitschi/routers/ppms.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,8 @@ async def get_systems( systemid: int,
9090
headers={"WWW-Authenticate": "Basic"},
9191
)
9292
logger.debug(f"Querying systemid {systemid}")
93-
return pdb.crud.get_system(db, systemid)
93+
system = pdb.crud.get_system(db, systemid)
94+
if not system:
95+
return {}
96+
ror = pdb.crud.get_system_ror(db, systemid)
97+
return { 'id': system.id, 'coreid': system.coreid, 'type': system.type, 'name': system.name, 'pid': system.pid, 'ror': ror }

pitschi/routers/ppms_utils.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,8 @@ def get_db_user(db: Session, login: str = None, userid: int = None, coreid: int
7070
def sync_cores(db: Session):
7171
cores = get_cores()
7272
for core in cores:
73-
_id = core.get('Core ID')
7473
pdb.crud.create_core(db, pdb.schemas.Core(
75-
id = _id,
74+
id = core.get('Core ID'),
7675
institution = core.get('Institution'),
7776
shortname = core.get('Facility Short Name'),
7877
longname = core.get('Facility Long Name'),
@@ -182,8 +181,8 @@ def sync_ppms_projects(db: Session, alogger: logging.Logger = logger):
182181
id = _id,
183182
coreid = system.get('coreid'),
184183
type = system.get('systemtype'),
185-
name = system.get('systemname')),
186-
pid = pids.get(_id, '')
184+
name = system.get('systemname'),
185+
pid = pids.get(_id, ''))
187186
)
188187
sync_projects(db, alogger=alogger, alert=True)
189188
pdb.crud.set_stat(db, name='syncing_projects', value='False')

pitschi/routers/scheduledingest.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def ingest_dataset_to_clowder(db, dataset, project, logger):
101101
logger.error(f"@dataset {dataset} does not have any booking.: {dataset.bookingid}")
102102
return (False, ["Fail to find dataset booking"])
103103
_ds_metadata = {
104-
'system': dataset.origionalmachine,
104+
'system': dataset.originalmachine,
105105
'author': _dataset_booking.username,
106106
'projectid': _dataset_booking.projectid,
107107
'bookingid': _dataset_booking.id,
@@ -110,7 +110,7 @@ def ingest_dataset_to_clowder(db, dataset, project, logger):
110110
}
111111
clowderful.upload_dataset_metadata(_clowder_key, _clowder_api_url, _ds_info.get('id'), _ds_metadata)
112112
### add tags
113-
_ds_tags = [ dataset.origionalmachine, _dataset_booking.username, str(_dataset_booking.projectid) ]
113+
_ds_tags = [ dataset.originalmachine, _dataset_booking.username, str(_dataset_booking.projectid) ]
114114
clowderful.add_dataset_tags(_clowder_key, _clowder_api_url, _ds_info.get('id'), _ds_tags)
115115
else:
116116
found = False
@@ -284,8 +284,8 @@ def send_email(db, datasetinfo, result, messages):
284284
<p>Dear admins<br /></p>
285285
<p>The following dataset failed to ingest:</p>
286286
<ul>
287-
<li><b>Machine</b> {datasetinfo.origionalmachine}</li>
288-
<li><b>Location</b> {datasetinfo.origionalpath}</li>
287+
<li><b>Machine</b> {datasetinfo.originalmachine}</li>
288+
<li><b>Location</b> {datasetinfo.originalpath}</li>
289289
<li><b>Booking id:</b> {datasetinfo.booking.id}</li>
290290
<li><b>system id:</b> {datasetinfo.booking.systemid}</li>
291291
<li><b>username:</b> {datasetinfo.booking.username}</li>

pitschi/routers/sync_ppms_bookings.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from fastapi import APIRouter, Depends, status
55
from fastapi_utils.tasks import repeat_every
66
import pitschi.db as pdb
7-
from pitschi.ppms import get_daily_bookings, get_daily_training, get_booking_details
7+
from pitschi.ppms import get_system_pids, get_daily_bookings, get_daily_training, get_booking_details
88
from pitschi.routers import ppms_utils
99
from sqlalchemy.orm import Session
1010

@@ -31,6 +31,7 @@ def sync_ppms_bookings() -> None:
3131
logger.debug('query ppms bookings of today')
3232
_today_tz = datetime.datetime.now(pytz.timezone(config.get('ppms', 'timezone'))).date()
3333
_bookings = get_daily_bookings(_today_tz)
34+
pids = {p['System ID']: p['PID'] for p in get_system_pids() if p.get('PID')}
3435
logger.debug(f'bookings: {len(_bookings)}')
3536
# training sessions can have multiple records -- use the record with
3637
# 'Training organised by' == 'User full Name' to set booking project/user
@@ -46,13 +47,15 @@ def sync_ppms_bookings() -> None:
4647
continue
4748
_booking_details = _booking_details_list[0]
4849
_booking['systemId'] = None
49-
if _booking_details.get('systemId'):
50+
_id = _booking_details.get('systemId')
51+
if _id:
5052
try:
5153
_system = pdb.crud.create_system(db, pdb.schemas.System(
52-
id = _booking_details.get('systemId'),
54+
id = _id,
5355
coreid = _booking.get('coreid'),
5456
type = _booking_details.get('systemType'),
55-
name = _booking_details.get('systemName'))
57+
name = _booking_details.get('systemName'),
58+
pid = pids.get(_id, ''))
5659
)
5760
_booking['systemId'] = _system.id
5861
except:

0 commit comments

Comments
 (0)