File: adios2_campaign_manager.py

package info (click to toggle)
adios2 2.10.2%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 33,764 kB
  • sloc: cpp: 175,964; ansic: 160,510; f90: 14,630; yacc: 12,668; python: 7,275; perl: 7,126; sh: 2,825; lisp: 1,106; xml: 1,049; makefile: 579; lex: 557
file content (453 lines) | stat: -rwxr-xr-x 13,865 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#!/usr/bin/env python3

import argparse
import glob
import sqlite3
import zlib
import yaml
from dataclasses import dataclass
from datetime import datetime
from os import chdir, getcwd, remove, stat
from os.path import exists, isdir, expanduser
from re import sub
from socket import getfqdn
from time import time_ns

# from adios2.adios2_campaign_manager import *

ADIOS_ACA_VERSION = "0.1"

@dataclass
class UserOption:
    adios_campaign_store: str = None
    hostname: str = None
    verbose: int = 0


def ReadUserConfig():
    path = expanduser("~/.config/adios2/adios2.yaml")
    opts = UserOption()
    try:
        doc = {}
        with open(path) as f:
            doc = yaml.safe_load(f)
        camp = doc.get("Campaign")
        if isinstance(camp, dict):
            for key, value in camp.items():
                if key == "campaignstorepath":
                    opts.adios_campaign_store = expanduser(value)
                if key == "hostname":
                    opts.hostname = value
                if key == "verbose":
                    opts.verbose = value
    except FileNotFoundError:
        None
    return opts


def SetupArgs():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "command",
        help="Command: create/update/delete/info/list",
        choices=["create", "update", "delete", "info", "list"],
    )
    parser.add_argument(
        "campaign", help="Campaign name or path, with .aca or without", default=None, nargs="?"
    )
    parser.add_argument("--verbose", "-v", help="More verbosity", action="count", default=0)
    parser.add_argument(
        "--campaign_store", "-s", help="Path to local campaign store", default=None
    )
    parser.add_argument("--hostname", "-n", help="Host name unique for hosts in a campaign")
    parser.add_argument("-f", "--files", nargs="+", help="Add ADIOS files manually")
    args = parser.parse_args()

    # default values
    args.user_options = ReadUserConfig()

    if args.verbose == 0:
        args.verbose = args.user_options.verbose

    if args.campaign_store is None:
        args.campaign_store = args.user_options.adios_campaign_store

    if args.campaign_store is not None:
        while args.campaign_store[-1] == "/":
            args.campaign_store = args.campaign_store[:-1]

    if args.hostname is None:
        args.hostname = args.user_options.hostname

    args.CampaignFileName = args.campaign
    if args.campaign is not None:
        if not args.campaign.endswith(".aca"):
            args.CampaignFileName += ".aca"
        if (not exists(args.CampaignFileName) and
                not args.CampaignFileName.startswith("/") and
                args.campaign_store is not None):
            args.CampaignFileName = args.campaign_store + "/" + args.CampaignFileName

    if args.files is None:
        args.LocalCampaignDir = ".adios-campaign/"

    if args.verbose > 0:
        print(f"# Verbosity = {args.verbose}")
        print(f"# Command = {args.command}")
        print(f"# Campaign File Name = {args.CampaignFileName}")
        print(f"# Campaign Store = {args.campaign_store}")
    return args


def CheckCampaignStore(args):
    if args.campaign_store is not None and not isdir(args.campaign_store):
        print("ERROR: Campaign directory " + args.campaign_store + " does not exist", flush=True)
        exit(1)


def CheckLocalCampaignDir(args):
    if not isdir(args.LocalCampaignDir):
        print(
            "ERROR: Shot campaign data '" +
            args.LocalCampaignDir +
            "' does not exist. Run this command where the code was executed.",
            flush=True,
        )
        exit(1)


def IsADIOSDataset(dataset):
    if not isdir(dataset):
        return False
    if not exists(dataset + "/" + "md.idx"):
        return False
    if not exists(dataset + "/" + "data.0"):
        return False
    return True


def compressFile(f):
    compObj = zlib.compressobj()
    compressed = bytearray()
    blocksize = 1073741824  # 1GB #1024*1048576
    len_orig = 0
    len_compressed = 0
    block = f.read(blocksize)
    while block:
        len_orig += len(block)
        cBlock = compObj.compress(block)
        compressed += cBlock
        len_compressed += len(cBlock)
        block = f.read(blocksize)
    cBlock = compObj.flush()
    compressed += cBlock
    len_compressed += len(cBlock)

    return compressed, len_orig, len_compressed


def decompressBuffer(buf: bytearray):
    data = zlib.decompress(buf)
    return data


def AddFileToArchive(args: dict, filename: str, cur: sqlite3.Cursor, dsID: int):
    compressed = 1
    try:
        f = open(filename, "rb")
        compressed_data, len_orig, len_compressed = compressFile(f)

    except IOError:
        print(f"ERROR While reading file {filename}")
        return

    statres = stat(filename)
    ct = statres.st_ctime_ns

    cur.execute(
        "insert into bpfile "
        "(bpdatasetid, name, compression, lenorig, lencompressed, ctime, data) "
        "values (?, ?, ?, ?, ?, ?, ?) "
        "on conflict (bpdatasetid, name) do update "
        "set compression = ?, lenorig = ?, lencompressed = ?, ctime = ?, data = ?",
        (
            dsID,
            filename,
            compressed,
            len_orig,
            len_compressed,
            ct,
            compressed_data,
            compressed,
            len_orig,
            len_compressed,
            ct,
            compressed_data,
        ),
    )


def AddDatasetToArchive(hostID: int, dirID: int, dataset: str, cur: sqlite3.Cursor) -> int:
    statres = stat(dataset)
    ct = statres.st_ctime_ns
    select_cmd = (
        "select rowid from bpdataset "
        f"where hostid = {hostID} and dirid = {dirID} and name = '{dataset}'"
    )
    res = cur.execute(select_cmd)
    row = res.fetchone()
    if row is not None:
        rowID = row[0]
        print(
            f"Found dataset {dataset} in database on host {hostID} "
            f"in dir {dirID}, rowid = {rowID}"
        )
    else:
        print(f"Add dataset {dataset} to archive")
        curDS = cur.execute(
            "insert into bpdataset (hostid, dirid, name, ctime) values (?, ?, ?, ?)",
            (hostID, dirID, dataset, ct),
        )
        rowID = curDS.lastrowid
        # print(
        #     f"Inserted bpdataset {dataset} in database on host {hostID}"
        #     f" in dir {dirID}, rowid = {rowID}"
        # )
    return rowID


def ProcessFiles(args: dict, cur: sqlite3.Cursor, hostID: int, dirID: int):
    for entry in args.files:
        print(f"Process entry {entry}:")
        dsID = 0
        dataset = entry
        if IsADIOSDataset(dataset):
            dsID = AddDatasetToArchive(hostID, dirID, dataset, cur)
            cwd = getcwd()
            chdir(dataset)
            mdFileList = glob.glob("*md.*")
            profileList = glob.glob("profiling.json")
            files = mdFileList + profileList
            for f in files:
                AddFileToArchive(args, f, cur, dsID)
            chdir(cwd)
        else:
            print(f"WARNING: Dataset {dataset} is not an ADIOS dataset. Skip")


def GetHostName():
    host = getfqdn()
    if host.startswith("login"):
        host = sub("^login[0-9]*\\.", "", host)
    if host.startswith("batch"):
        host = sub("^batch[0-9]*\\.", "", host)
    if args.hostname is None:
        shorthost = host.split(".")[0]
    else:
        shorthost = args.user_options.hostname
    return host, shorthost


def AddHostName(longHostName, shortHostName):
    res = cur.execute('select rowid from host where hostname = "' + shortHostName + '"')
    row = res.fetchone()
    if row is not None:
        hostID = row[0]
        print(f"Found host {shortHostName} in database, rowid = {hostID}")
    else:
        curHost = cur.execute("insert into host values (?, ?)", (shortHostName, longHostName))
        hostID = curHost.lastrowid
        print(f"Inserted host {shortHostName} into database, rowid = {hostID}")
    return hostID


def MergeDBFiles(dbfiles: list):
    # read db files here
    result = list()
    for f1 in dbfiles:
        try:
            con = sqlite3.connect(f1)
        except sqlite3.Error as e:
            print(e)

        cur = con.cursor()
        try:
            cur.execute("select  * from bpfiles")
        except sqlite3.Error as e:
            print(e)
        record = cur.fetchall()
        for item in record:
            result.append(item[0])
        cur.close()
    return result


def AddDirectory(hostID: int, path: str) -> int:
    res = cur.execute(
        "select rowid from directory where hostid = " + str(hostID) + ' and name = "' + path + '"'
    )
    row = res.fetchone()
    if row is not None:
        dirID = row[0]
        print(f"Found directory {path} with hostID {hostID} in database, rowid = {dirID}")
    else:
        curDirectory = cur.execute("insert into directory values (?, ?)", (hostID, path))
        dirID = curDirectory.lastrowid
        print(f"Inserted directory {path} into database, rowid = {dirID}")
    return dirID


def Update(args: dict, cur: sqlite3.Cursor):
    longHostName, shortHostName = GetHostName()

    hostID = AddHostName(longHostName, shortHostName)

    rootdir = getcwd()
    dirID = AddDirectory(hostID, rootdir)
    con.commit()

    ProcessFiles(args, cur, hostID, dirID)

    con.commit()


def Create(args: dict, cur: sqlite3.Cursor):
    epoch = time_ns()
    cur.execute("create table info(id TEXT, name TEXT, version TEXT, ctime INT)")
    cur.execute(
        "insert into info values (?, ?, ?, ?)",
        ("ACA", "ADIOS Campaign Archive", ADIOS_ACA_VERSION, epoch),
    )
    cur.execute("create table host" + "(hostname TEXT PRIMARY KEY, longhostname TEXT)")
    cur.execute("create table directory" + "(hostid INT, name TEXT, PRIMARY KEY (hostid, name))")
    cur.execute(
        "create table bpdataset" +
        "(hostid INT, dirid INT, name TEXT, ctime INT" +
        ", PRIMARY KEY (hostid, dirid, name))"
    )
    cur.execute(
        "create table bpfile" +
        "(bpdatasetid INT, name TEXT, compression INT, lenorig INT" +
        ", lencompressed INT, ctime INT, data BLOB" +
        ", PRIMARY KEY (bpdatasetid, name))"
    )
    Update(args, cur)


def timestamp_to_datetime(timestamp: int) -> datetime:
    digits = len(str(int(timestamp)))
    t = float(timestamp)
    if digits > 18:
        t = t / 1000000000
    elif digits > 15:
        t = t / 1000000
    elif digits > 12:
        t = t / 1000
    return datetime.fromtimestamp(t)


def Info(args: dict, cur: sqlite3.Cursor):
    res = cur.execute("select id, name, version, ctime from info")
    info = res.fetchone()
    t = timestamp_to_datetime(info[3])
    print(f"{info[1]}, version {info[2]}, created on {t}")

    res = cur.execute("select rowid, hostname, longhostname from host")
    hosts = res.fetchall()
    for host in hosts:
        print(f"hostname = {host[1]}   longhostname = {host[2]}")
        res2 = cur.execute(
            'select rowid, name from directory where hostid = "' + str(host[0]) + '"'
        )
        dirs = res2.fetchall()
        for dir in dirs:
            print(f"    dir = {dir[1]}")
            res3 = cur.execute(
                'select rowid, name, ctime from bpdataset where hostid = "' +
                str(host[0]) +
                '" and dirid = "' +
                str(dir[0]) +
                '"'
            )
            bpdatasets = res3.fetchall()
            for bpdataset in bpdatasets:
                t = timestamp_to_datetime(bpdataset[2])
                print(f"        dataset = {bpdataset[1]}     created on {t}")


def List():
    path = args.campaign
    if path is None:
        if args.campaign_store is None:
            print("ERROR: Set --campaign_store for this command")
            return 1
        path = args.campaign_store
    else:
        while path[-1] == "/":
            path = path[:-1]

    # List the local campaign store
    acaList = glob.glob(path + "/**/*.aca", recursive=True)
    if len(acaList) == 0:
        print("There are no campaign archives in  " + path)
        return 2
    else:
        startCharPos = len(path) + 1
        for f in acaList:
            print(f[startCharPos:])
    return 0


def Delete():
    if exists(args.CampaignFileName):
        print(f"Delete archive {args.CampaignFileName}")
        remove(args.CampaignFileName)
        return 0
    else:
        print(f"ERROR: archive {args.CampaignFileName} does not exist")
        return 1


if __name__ == "__main__":
    args = SetupArgs()
    CheckCampaignStore(args)

    if args.command == "list":
        exit(List())

    if args.command == "delete":
        exit(Delete())

    if args.command == "create":
        print("Create archive")
        if exists(args.CampaignFileName):
            print(f"ERROR: archive {args.CampaignFileName} already exist")
            exit(1)
    elif args.command == "update" or args.command == "info":
        print(f"{args.command} archive")
        if not exists(args.CampaignFileName):
            print(f"ERROR: archive {args.CampaignFileName} does not exist")
            exit(1)

    con = sqlite3.connect(args.CampaignFileName)
    cur = con.cursor()

    if args.command == "info":
        Info(args, cur)
    else:
        if args.files is None:
            CheckLocalCampaignDir(args)
            # List the local campaign directory
            dbFileList = glob.glob(args.LocalCampaignDir + "/*.db")
            if len(dbFileList) == 0:
                print("There are no campaign data files in  " + args.LocalCampaignDir)
                exit(2)
            args.files = MergeDBFiles(dbFileList)

        if args.command == "create":
            Create(args, cur)
        elif args.command == "update":
            Update(args, cur)

    cur.close()
    con.close()