xref: /spdk/scripts/perf/nvmf/run_nvmf.py (revision ae7b5890ef728af40bd233a5011b924c482603bf)
1#!/usr/bin/env python3
2
3import os
4import re
5import sys
6import json
7import paramiko
8import zipfile
9import threading
10import subprocess
11import itertools
12import time
13import uuid
14import rpc
15import rpc.client
16from common import *
17
18
19class Server:
20    def __init__(self, name, username, password, mode, nic_ips, transport):
21        self.name = name
22        self.mode = mode
23        self.username = username
24        self.password = password
25        self.nic_ips = nic_ips
26        self.transport = transport.lower()
27
28        if not re.match("^[A-Za-z0-9]*$", name):
29            self.log_print("Please use a name which contains only letters or numbers")
30            sys.exit(1)
31
32    def log_print(self, msg):
33        print("[%s] %s" % (self.name, msg), flush=True)
34
35
36class Target(Server):
37    def __init__(self, name, username, password, mode, nic_ips, transport="rdma", use_null_block=False, sar_settings=None):
38        super(Target, self).__init__(name, username, password, mode, nic_ips, transport)
39        self.null_block = bool(use_null_block)
40        self.enable_sar = False
41        if sar_settings:
42            self.enable_sar, self.sar_delay, self.sar_interval, self.sar_count = sar_settings
43
44        self.script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
45        self.spdk_dir = os.path.abspath(os.path.join(self.script_dir, "../../../"))
46
47    def zip_spdk_sources(self, spdk_dir, dest_file):
48        self.log_print("Zipping SPDK source directory")
49        fh = zipfile.ZipFile(dest_file, "w", zipfile.ZIP_DEFLATED)
50        for root, directories, files in os.walk(spdk_dir, followlinks=True):
51            for file in files:
52                fh.write(os.path.relpath(os.path.join(root, file)))
53        fh.close()
54        self.log_print("Done zipping")
55
56    def read_json_stats(self, file):
57        with open(file, "r") as json_data:
58            data = json.load(json_data)
59            job_pos = 0  # job_post = 0 because using aggregated results
60
61            # Check if latency is in nano or microseconds to choose correct dict key
62            def get_lat_unit(key_prefix, dict_section):
63                # key prefix - lat, clat or slat.
64                # dict section - portion of json containing latency bucket in question
65                # Return dict key to access the bucket and unit as string
66                for k, v in dict_section.items():
67                    if k.startswith(key_prefix):
68                        return k, k.split("_")[1]
69
70            read_iops = float(data["jobs"][job_pos]["read"]["iops"])
71            read_bw = float(data["jobs"][job_pos]["read"]["bw"])
72            lat_key, lat_unit = get_lat_unit("lat", data["jobs"][job_pos]["read"])
73            read_avg_lat = float(data["jobs"][job_pos]["read"][lat_key]["mean"])
74            read_min_lat = float(data["jobs"][job_pos]["read"][lat_key]["min"])
75            read_max_lat = float(data["jobs"][job_pos]["read"][lat_key]["max"])
76            clat_key, clat_unit = get_lat_unit("clat", data["jobs"][job_pos]["read"])
77            read_p99_lat = float(data["jobs"][job_pos]["read"][clat_key]["percentile"]["99.000000"])
78
79            if "ns" in lat_unit:
80                read_avg_lat, read_min_lat, read_max_lat = [x / 1000 for x in [read_avg_lat, read_min_lat, read_max_lat]]
81            if "ns" in clat_unit:
82                read_p99_lat = read_p99_lat / 1000
83
84            write_iops = float(data["jobs"][job_pos]["write"]["iops"])
85            write_bw = float(data["jobs"][job_pos]["write"]["bw"])
86            lat_key, lat_unit = get_lat_unit("lat", data["jobs"][job_pos]["write"])
87            write_avg_lat = float(data["jobs"][job_pos]["write"][lat_key]["mean"])
88            write_min_lat = float(data["jobs"][job_pos]["write"][lat_key]["min"])
89            write_max_lat = float(data["jobs"][job_pos]["write"][lat_key]["max"])
90            clat_key, clat_unit = get_lat_unit("clat", data["jobs"][job_pos]["write"])
91            write_p99_lat = float(data["jobs"][job_pos]["write"][clat_key]["percentile"]["99.000000"])
92
93            if "ns" in lat_unit:
94                write_avg_lat, write_min_lat, write_max_lat = [x / 1000 for x in [write_avg_lat, write_min_lat, write_max_lat]]
95            if "ns" in clat_unit:
96                write_p99_lat = write_p99_lat / 1000
97
98        return [read_iops, read_bw, read_avg_lat, read_min_lat, read_max_lat, read_p99_lat,
99                write_iops, write_bw, write_avg_lat, write_min_lat, write_max_lat, write_p99_lat]
100
101    def parse_results(self, results_dir, initiator_count=None, run_num=None):
102        files = os.listdir(results_dir)
103        fio_files = filter(lambda x: ".fio" in x, files)
104        json_files = [x for x in files if ".json" in x]
105
106        # Create empty results file
107        csv_file = "nvmf_results.csv"
108        with open(os.path.join(results_dir, csv_file), "w") as fh:
109            header_line = ",".join(["Name",
110                                    "read_iops", "read_bw", "read_avg_lat_us",
111                                    "read_min_lat_us", "read_max_lat_us", "read_p99_lat_us",
112                                    "write_iops", "write_bw", "write_avg_lat_us",
113                                    "write_min_lat_us", "write_max_lat_us", "write_p99_lat_us"])
114            fh.write(header_line + "\n")
115        rows = set()
116
117        for fio_config in fio_files:
118            self.log_print("Getting FIO stats for %s" % fio_config)
119            job_name, _ = os.path.splitext(fio_config)
120
121            # If "_CPU" exists in name - ignore it
122            # Initiators for the same job could have diffrent num_cores parameter
123            job_name = re.sub(r"_\d+CPU", "", job_name)
124            job_result_files = [x for x in json_files if job_name in x]
125            self.log_print("Matching result files for current fio config:")
126            for j in job_result_files:
127                self.log_print("\t %s" % j)
128
129            # There may have been more than 1 initiator used in test, need to check that
130            # Result files are created so that string after last "_" separator is server name
131            inits_names = set([os.path.splitext(x)[0].split("_")[-1] for x in job_result_files])
132            inits_avg_results = []
133            for i in inits_names:
134                self.log_print("\tGetting stats for initiator %s" % i)
135                # There may have been more than 1 test run for this job, calculate average results for initiator
136                i_results = [x for x in job_result_files if i in x]
137
138                separate_stats = []
139                for r in i_results:
140                    stats = self.read_json_stats(os.path.join(results_dir, r))
141                    separate_stats.append(stats)
142                    self.log_print(stats)
143
144                z = [sum(c) for c in zip(*separate_stats)]
145                z = [c/len(separate_stats) for c in z]
146                inits_avg_results.append(z)
147
148                self.log_print("\tAverage results for initiator %s" % i)
149                self.log_print(z)
150
151            # Sum average results of all initiators running this FIO job
152            self.log_print("\tTotal results for %s from all initiators" % fio_config)
153            for a in inits_avg_results:
154                self.log_print(a)
155            total = ["{0:.3f}".format(sum(c)) for c in zip(*inits_avg_results)]
156            rows.add(",".join([job_name, *total]))
157
158        # Save results to file
159        for row in rows:
160            with open(os.path.join(results_dir, csv_file), "a") as fh:
161                fh.write(row + "\n")
162        self.log_print("You can find the test results in the file %s" % os.path.join(results_dir, csv_file))
163
164    def measure_sar(self, results_dir, sar_file_name):
165        self.log_print("Waiting %d delay before measuring SAR stats" % self.sar_delay)
166        time.sleep(self.sar_delay)
167        out = subprocess.check_output("sar -P ALL %s %s" % (self.sar_interval, self.sar_count), shell=True).decode(encoding="utf-8")
168        with open(os.path.join(results_dir, sar_file_name), "w") as fh:
169            for line in out.split("\n"):
170                if "Average" in line and "CPU" in line:
171                    self.log_print("Summary CPU utilization from SAR:")
172                    self.log_print(line)
173                if "Average" in line and "all" in line:
174                    self.log_print(line)
175            fh.write(out)
176
177
178class Initiator(Server):
179    def __init__(self, name, username, password, mode, nic_ips, ip, transport="rdma", nvmecli_dir=None, workspace="/tmp/spdk"):
180        super(Initiator, self).__init__(name, username, password, mode, nic_ips, transport)
181        self.ip = ip
182        self.spdk_dir = workspace
183
184        if nvmecli_dir:
185            self.nvmecli_bin = os.path.join(nvmecli_dir, "nvme")
186        else:
187            self.nvmecli_bin = "nvme"  # Use system-wide nvme-cli
188
189        self.ssh_connection = paramiko.SSHClient()
190        self.ssh_connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
191        self.ssh_connection.connect(self.ip, username=self.username, password=self.password)
192        self.remote_call("sudo rm -rf %s/nvmf_perf" % self.spdk_dir)
193        self.remote_call("mkdir -p %s" % self.spdk_dir)
194
195    def __del__(self):
196        self.ssh_connection.close()
197
198    def put_file(self, local, remote_dest):
199        ftp = self.ssh_connection.open_sftp()
200        ftp.put(local, remote_dest)
201        ftp.close()
202
203    def get_file(self, remote, local_dest):
204        ftp = self.ssh_connection.open_sftp()
205        ftp.get(remote, local_dest)
206        ftp.close()
207
208    def remote_call(self, cmd):
209        stdin, stdout, stderr = self.ssh_connection.exec_command(cmd)
210        out = stdout.read().decode(encoding="utf-8")
211        err = stderr.read().decode(encoding="utf-8")
212        return out, err
213
214    def copy_result_files(self, dest_dir):
215        self.log_print("Copying results")
216
217        if not os.path.exists(dest_dir):
218            os.mkdir(dest_dir)
219
220        # Get list of result files from initiator and copy them back to target
221        stdout, stderr = self.remote_call("ls %s/nvmf_perf" % self.spdk_dir)
222        file_list = stdout.strip().split("\n")
223
224        for file in file_list:
225            self.get_file(os.path.join(self.spdk_dir, "nvmf_perf", file),
226                          os.path.join(dest_dir, file))
227        self.log_print("Done copying results")
228
229    def discover_subsystems(self, address_list, subsys_no):
230        num_nvmes = range(0, subsys_no)
231        nvme_discover_output = ""
232        for ip, subsys_no in itertools.product(address_list, num_nvmes):
233            self.log_print("Trying to discover: %s:%s" % (ip, 4420 + subsys_no))
234            nvme_discover_cmd = ["sudo",
235                                 "%s" % self.nvmecli_bin,
236                                 "discover", "-t %s" % self.transport,
237                                 "-s %s" % (4420 + subsys_no),
238                                 "-a %s" % ip]
239            nvme_discover_cmd = " ".join(nvme_discover_cmd)
240
241            stdout, stderr = self.remote_call(nvme_discover_cmd)
242            if stdout:
243                nvme_discover_output = nvme_discover_output + stdout
244
245        subsystems = re.findall(r'trsvcid:\s(\d+)\s+'  # get svcid number
246                                r'subnqn:\s+([a-zA-Z0-9\.\-\:]+)\s+'  # get NQN id
247                                r'traddr:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',  # get IP address
248                                nvme_discover_output)  # from nvme discovery output
249        subsystems = filter(lambda x: x[-1] in address_list, subsystems)
250        subsystems = list(set(subsystems))
251        subsystems.sort(key=lambda x: x[1])
252        self.log_print("Found matching subsystems on target side:")
253        for s in subsystems:
254            self.log_print(s)
255
256        return subsystems
257
258    def gen_fio_config(self, rw, rwmixread, block_size, io_depth, subsys_no, num_jobs=None, ramp_time=0, run_time=10):
259        fio_conf_template = """
260[global]
261ioengine={ioengine}
262{spdk_conf}
263thread=1
264group_reporting=1
265direct=1
266
267norandommap=1
268rw={rw}
269rwmixread={rwmixread}
270bs={block_size}
271iodepth={io_depth}
272time_based=1
273ramp_time={ramp_time}
274runtime={run_time}
275"""
276        if "spdk" in self.mode:
277            subsystems = self.discover_subsystems(self.nic_ips, subsys_no)
278            bdev_conf = self.gen_spdk_bdev_conf(subsystems)
279            self.remote_call("echo '%s' > %s/bdev.conf" % (bdev_conf, self.spdk_dir))
280            ioengine = "%s/examples/bdev/fio_plugin/fio_plugin" % self.spdk_dir
281            spdk_conf = "spdk_conf=%s/bdev.conf" % self.spdk_dir
282            filename_section = self.gen_fio_filename_conf(subsystems)
283        else:
284            ioengine = "libaio"
285            spdk_conf = ""
286            filename_section = self.gen_fio_filename_conf()
287
288        fio_config = fio_conf_template.format(ioengine=ioengine, spdk_conf=spdk_conf,
289                                              rw=rw, rwmixread=rwmixread, block_size=block_size,
290                                              io_depth=io_depth, ramp_time=ramp_time, run_time=run_time)
291        if num_jobs:
292            fio_config = fio_config + "numjobs=%s" % num_jobs
293        fio_config = fio_config + filename_section
294
295        fio_config_filename = "%s_%s_%s_m_%s" % (block_size, io_depth, rw, rwmixread)
296        if hasattr(self, "num_cores"):
297            fio_config_filename += "_%sCPU" % self.num_cores
298        fio_config_filename += ".fio"
299
300        self.remote_call("mkdir -p %s/nvmf_perf" % self.spdk_dir)
301        self.remote_call("echo '%s' > %s/nvmf_perf/%s" % (fio_config, self.spdk_dir, fio_config_filename))
302        self.log_print("Created FIO Config:")
303        self.log_print(fio_config)
304
305        return os.path.join(self.spdk_dir, "nvmf_perf", fio_config_filename)
306
307    def run_fio(self, fio_config_file, run_num=None):
308        job_name, _ = os.path.splitext(fio_config_file)
309        self.log_print("Starting FIO run for job: %s" % job_name)
310        if run_num:
311            for i in range(1, run_num + 1):
312                output_filename = job_name + "_run_" + str(i) + "_" + self.name + ".json"
313                cmd = "sudo /usr/src/fio/fio %s --output-format=json --output=%s" % (fio_config_file, output_filename)
314                output, error = self.remote_call(cmd)
315                self.log_print(output)
316                self.log_print(error)
317        else:
318            output_filename = job_name + "_" + self.name + ".json"
319            cmd = "sudo /usr/src/fio/fio %s --output-format=json --output=%s" % (fio_config_file, output_filename)
320            output, error = self.remote_call(cmd)
321            self.log_print(output)
322            self.log_print(error)
323        self.log_print("FIO run finished. Results in: %s" % output_filename)
324
325
326class KernelTarget(Target):
327    def __init__(self, name, username, password, mode, nic_ips,
328                 use_null_block=False, sar_settings=None, transport="rdma", nvmet_dir=None, **kwargs):
329        super(KernelTarget, self).__init__(name, username, password, mode, nic_ips,
330                                           transport, use_null_block, sar_settings)
331
332        if nvmet_dir:
333            self.nvmet_bin = os.path.join(nvmet_dir, "nvmetcli")
334        else:
335            self.nvmet_bin = "nvmetcli"
336
337    def __del__(self):
338        nvmet_command(self.nvmet_bin, "clear")
339
340    def kernel_tgt_gen_nullblock_conf(self, address):
341        nvmet_cfg = {
342            "ports": [],
343            "hosts": [],
344            "subsystems": [],
345        }
346
347        nvmet_cfg["subsystems"].append({
348            "allowed_hosts": [],
349            "attr": {
350                "allow_any_host": "1",
351                "version": "1.3"
352            },
353            "namespaces": [
354                {
355                    "device": {
356                        "path": "/dev/nullb0",
357                        "uuid": "%s" % uuid.uuid4()
358                    },
359                    "enable": 1,
360                    "nsid": 1
361                }
362            ],
363            "nqn": "nqn.2018-09.io.spdk:cnode1"
364        })
365
366        nvmet_cfg["ports"].append({
367            "addr": {
368                "adrfam": "ipv4",
369                "traddr": address,
370                "trsvcid": "4420",
371                "trtype": "%s" % self.transport,
372            },
373            "portid": 1,
374            "referrals": [],
375            "subsystems": ["nqn.2018-09.io.spdk:cnode1"]
376        })
377        with open("kernel.conf", 'w') as fh:
378            fh.write(json.dumps(nvmet_cfg, indent=2))
379
380    def kernel_tgt_gen_subsystem_conf(self, nvme_list, address_list):
381
382        nvmet_cfg = {
383            "ports": [],
384            "hosts": [],
385            "subsystems": [],
386        }
387
388        # Split disks between NIC IP's
389        disks_per_ip = int(len(nvme_list) / len(address_list))
390        disk_chunks = [nvme_list[i * disks_per_ip:disks_per_ip + disks_per_ip * i] for i in range(0, len(address_list))]
391
392        subsys_no = 1
393        port_no = 0
394        for ip, chunk in zip(address_list, disk_chunks):
395            for disk in chunk:
396                nvmet_cfg["subsystems"].append({
397                    "allowed_hosts": [],
398                    "attr": {
399                        "allow_any_host": "1",
400                        "version": "1.3"
401                    },
402                    "namespaces": [
403                        {
404                            "device": {
405                                "path": disk,
406                                "uuid": "%s" % uuid.uuid4()
407                            },
408                            "enable": 1,
409                            "nsid": subsys_no
410                        }
411                    ],
412                    "nqn": "nqn.2018-09.io.spdk:cnode%s" % subsys_no
413                })
414
415                nvmet_cfg["ports"].append({
416                    "addr": {
417                        "adrfam": "ipv4",
418                        "traddr": ip,
419                        "trsvcid": "%s" % (4420 + port_no),
420                        "trtype": "%s" % self.transport
421                    },
422                    "portid": subsys_no,
423                    "referrals": [],
424                    "subsystems": ["nqn.2018-09.io.spdk:cnode%s" % subsys_no]
425                })
426                subsys_no += 1
427                port_no += 1
428
429        with open("kernel.conf", "w") as fh:
430            fh.write(json.dumps(nvmet_cfg, indent=2))
431        pass
432
433    def tgt_start(self):
434        self.log_print("Configuring kernel NVMeOF Target")
435
436        if self.null_block:
437            print("Configuring with null block device.")
438            if len(self.nic_ips) > 1:
439                print("Testing with null block limited to single RDMA NIC.")
440                print("Please specify only 1 IP address.")
441                exit(1)
442            self.subsys_no = 1
443            self.kernel_tgt_gen_nullblock_conf(self.nic_ips[0])
444        else:
445            print("Configuring with NVMe drives.")
446            nvme_list = get_nvme_devices()
447            self.kernel_tgt_gen_subsystem_conf(nvme_list, self.nic_ips)
448            self.subsys_no = len(nvme_list)
449
450        nvmet_command(self.nvmet_bin, "clear")
451        nvmet_command(self.nvmet_bin, "restore kernel.conf")
452        self.log_print("Done configuring kernel NVMeOF Target")
453
454
455class SPDKTarget(Target):
456    def __init__(self, name, username, password, mode, nic_ips, num_cores, num_shared_buffers=4096,
457                 use_null_block=False, sar_settings=None, transport="rdma", **kwargs):
458        super(SPDKTarget, self).__init__(name, username, password, mode, nic_ips, transport, use_null_block, sar_settings)
459        self.num_cores = num_cores
460        self.num_shared_buffers = num_shared_buffers
461
462    def spdk_tgt_configure(self):
463        self.log_print("Configuring SPDK NVMeOF target via RPC")
464        numa_list = get_used_numa_nodes()
465
466        # Create RDMA transport layer
467        rpc.nvmf.nvmf_create_transport(self.client, trtype=self.transport, num_shared_buffers=self.num_shared_buffers)
468        self.log_print("SPDK NVMeOF transport layer:")
469        rpc.client.print_dict(rpc.nvmf.get_nvmf_transports(self.client))
470
471        if self.null_block:
472            nvme_section = self.spdk_tgt_add_nullblock()
473            subsystems_section = self.spdk_tgt_add_subsystem_conf(self.nic_ips, req_num_disks=1)
474        else:
475            nvme_section = self.spdk_tgt_add_nvme_conf()
476            subsystems_section = self.spdk_tgt_add_subsystem_conf(self.nic_ips)
477        self.log_print("Done configuring SPDK NVMeOF Target")
478
479    def spdk_tgt_add_nullblock(self):
480        self.log_print("Adding null block bdev to config via RPC")
481        rpc.bdev.construct_null_bdev(self.client, 102400, 4096, "Nvme0n1")
482        self.log_print("SPDK Bdevs configuration:")
483        rpc.client.print_dict(rpc.bdev.get_bdevs(self.client))
484
485    def spdk_tgt_add_nvme_conf(self, req_num_disks=None):
486        self.log_print("Adding NVMe bdevs to config via RPC")
487
488        bdfs = get_nvme_devices_bdf()
489        bdfs = [b.replace(":", ".") for b in bdfs]
490
491        if req_num_disks:
492            if req_num_disks > len(bdfs):
493                self.log_print("ERROR: Requested number of disks is more than available %s" % len(bdfs))
494                sys.exit(1)
495            else:
496                bdfs = bdfs[0:req_num_disks]
497
498        for i, bdf in enumerate(bdfs):
499            rpc.bdev.construct_nvme_bdev(self.client, name="Nvme%s" % i, trtype="PCIe", traddr=bdf)
500
501        self.log_print("SPDK Bdevs configuration:")
502        rpc.client.print_dict(rpc.bdev.get_bdevs(self.client))
503
504    def spdk_tgt_add_subsystem_conf(self, ips=None, req_num_disks=None):
505        self.log_print("Adding subsystems to config")
506        if not req_num_disks:
507            req_num_disks = get_nvme_devices_count()
508
509        # Distribute bdevs between provided NICs
510        num_disks = range(1, req_num_disks + 1)
511        disks_per_ip = int(len(num_disks) / len(ips))
512        disk_chunks = [num_disks[i * disks_per_ip:disks_per_ip + disks_per_ip * i] for i in range(0, len(ips))]
513
514        # Create subsystems, add bdevs to namespaces, add listeners
515        for ip, chunk in zip(ips, disk_chunks):
516            for c in chunk:
517                nqn = "nqn.2018-09.io.spdk:cnode%s" % c
518                serial = "SPDK00%s" % c
519                bdev_name = "Nvme%sn1" % (c - 1)
520                rpc.nvmf.nvmf_subsystem_create(self.client, nqn, serial,
521                                               allow_any_host=True, max_namespaces=8)
522                rpc.nvmf.nvmf_subsystem_add_ns(self.client, nqn, bdev_name)
523
524                rpc.nvmf.nvmf_subsystem_add_listener(self.client, nqn,
525                                                     trtype=self.transport,
526                                                     traddr=ip,
527                                                     trsvcid="4420",
528                                                     adrfam="ipv4")
529
530        self.log_print("SPDK NVMeOF subsystem configuration:")
531        rpc.client.print_dict(rpc.nvmf.get_nvmf_subsystems(self.client))
532
533    def tgt_start(self):
534        self.subsys_no = get_nvme_devices_count()
535        self.log_print("Starting SPDK NVMeOF Target process")
536        nvmf_app_path = os.path.join(self.spdk_dir, "app/nvmf_tgt/nvmf_tgt")
537        command = " ".join([nvmf_app_path, "-m", self.num_cores])
538        proc = subprocess.Popen(command, shell=True)
539        self.pid = os.path.join(self.spdk_dir, "nvmf.pid")
540
541        with open(self.pid, "w") as fh:
542            fh.write(str(proc.pid))
543        self.nvmf_proc = proc
544        self.log_print("SPDK NVMeOF Target PID=%s" % self.pid)
545        self.log_print("Waiting for spdk to initilize...")
546        while True:
547            if os.path.exists("/var/tmp/spdk.sock"):
548                break
549            time.sleep(1)
550        self.client = rpc.client.JSONRPCClient("/var/tmp/spdk.sock")
551
552        self.spdk_tgt_configure()
553
554    def __del__(self):
555        if hasattr(self, "nvmf_proc"):
556            try:
557                self.nvmf_proc.terminate()
558                self.nvmf_proc.wait()
559            except Exception as e:
560                self.log_print(e)
561                self.nvmf_proc.kill()
562                self.nvmf_proc.communicate()
563
564
565class KernelInitiator(Initiator):
566    def __init__(self, name, username, password, mode, nic_ips, ip, transport, **kwargs):
567        super(KernelInitiator, self).__init__(name, username, password, mode, nic_ips, ip, transport)
568
569    def __del__(self):
570        self.ssh_connection.close()
571
572    def kernel_init_connect(self, address_list, subsys_no):
573        subsystems = self.discover_subsystems(address_list, subsys_no)
574        self.log_print("Below connection attempts may result in error messages, this is expected!")
575        for subsystem in subsystems:
576            self.log_print("Trying to connect %s %s %s" % subsystem)
577            self.remote_call("sudo %s connect -t %s -s %s -n %s -a %s -i 8" % (self.nvmecli_bin, self.transport, *subsystem))
578            time.sleep(2)
579
580    def kernel_init_disconnect(self, address_list, subsys_no):
581        subsystems = self.discover_subsystems(address_list, subsys_no)
582        for subsystem in subsystems:
583            self.remote_call("sudo %s disconnect -n %s" % (self.nvmecli_bin, subsystem[1]))
584            time.sleep(1)
585
586    def gen_fio_filename_conf(self):
587        out, err = self.remote_call("lsblk -o NAME -nlp")
588        nvme_list = [x for x in out.split("\n") if "nvme" in x]
589
590        filename_section = ""
591        for i, nvme in enumerate(nvme_list):
592            filename_section = "\n".join([filename_section,
593                                          "[filename%s]" % i,
594                                          "filename=%s" % nvme])
595
596        return filename_section
597
598
599class SPDKInitiator(Initiator):
600    def __init__(self, name, username, password, mode, nic_ips, ip, num_cores=None, transport="rdma", **kwargs):
601        super(SPDKInitiator, self).__init__(name, username, password, mode, nic_ips, ip, transport)
602        if num_cores:
603            self.num_cores = num_cores
604
605    def install_spdk(self, local_spdk_zip):
606        self.put_file(local_spdk_zip, "/tmp/spdk_drop.zip")
607        self.log_print("Copied sources zip from target")
608        self.remote_call("unzip -qo /tmp/spdk_drop.zip -d %s" % self.spdk_dir)
609
610        self.log_print("Sources unpacked")
611        self.remote_call("cd %s; git submodule update --init; ./configure --with-rdma --with-fio=/usr/src/fio;"
612                         "make clean; make -j$(($(nproc)*2))" % self.spdk_dir)
613
614        self.log_print("SPDK built")
615        self.remote_call("sudo %s/scripts/setup.sh" % self.spdk_dir)
616
617    def gen_spdk_bdev_conf(self, remote_subsystem_list):
618        header = "[Nvme]"
619        row_template = """  TransportId "trtype:{transport} adrfam:IPv4 traddr:{ip} trsvcid:{svc} subnqn:{nqn}" Nvme{i}"""
620
621        bdev_rows = [row_template.format(transport=self.transport,
622                                         svc=x[0],
623                                         nqn=x[1],
624                                         ip=x[2],
625                                         i=i) for i, x in enumerate(remote_subsystem_list)]
626        bdev_rows = "\n".join(bdev_rows)
627        bdev_section = "\n".join([header, bdev_rows])
628        return bdev_section
629
630    def gen_fio_filename_conf(self, remote_subsystem_list):
631        subsystems = [str(x) for x in range(0, len(remote_subsystem_list))]
632
633        # If num_cpus exists then limit FIO to this number of CPUs
634        # Otherwise - each connected subsystem gets its own CPU
635        if hasattr(self, 'num_cores'):
636            self.log_print("Limiting FIO workload execution to %s cores" % self.num_cores)
637            threads = range(0, int(self.num_cores))
638        else:
639            threads = range(0, len(subsystems))
640
641        n = int(len(subsystems) / len(threads))
642
643        filename_section = ""
644        for t in threads:
645            header = "[filename%s]" % t
646            disks = "\n".join(["filename=Nvme%sn1" % x for x in subsystems[n * t:n + n * t]])
647            filename_section = "\n".join([filename_section, header, disks])
648
649        return filename_section
650
651
652if __name__ == "__main__":
653    spdk_zip_path = "/tmp/spdk.zip"
654    target_results_dir = "/tmp/results"
655
656    if (len(sys.argv) > 1):
657        config_file_path = sys.argv[1]
658    else:
659        script_full_dir = os.path.dirname(os.path.realpath(__file__))
660        config_file_path = os.path.join(script_full_dir, "config.json")
661
662    print("Using config file: %s" % config_file_path)
663    with open(config_file_path, "r") as config:
664        data = json.load(config)
665
666    initiators = []
667    fio_cases = []
668
669    for k, v in data.items():
670        if "target" in k:
671            if data[k]["mode"] == "spdk":
672                target_obj = SPDKTarget(name=k, **data["general"], **v)
673            elif data[k]["mode"] == "kernel":
674                target_obj = KernelTarget(name=k, **data["general"], **v)
675        elif "initiator" in k:
676            if data[k]["mode"] == "spdk":
677                init_obj = SPDKInitiator(name=k, **data["general"], **v)
678            elif data[k]["mode"] == "kernel":
679                init_obj = KernelInitiator(name=k, **data["general"], **v)
680            initiators.append(init_obj)
681        elif "fio" in k:
682            fio_workloads = itertools.product(data[k]["bs"],
683                                              data[k]["qd"],
684                                              data[k]["rw"])
685
686            fio_run_time = data[k]["run_time"]
687            fio_ramp_time = data[k]["ramp_time"]
688            fio_rw_mix_read = data[k]["rwmixread"]
689            fio_run_num = data[k]["run_num"] if "run_num" in data[k].keys() else None
690            fio_num_jobs = data[k]["num_jobs"] if "num_jobs" in data[k].keys() else None
691        else:
692            continue
693
694    # Copy and install SPDK on remote initiators
695    target_obj.zip_spdk_sources(target_obj.spdk_dir, spdk_zip_path)
696    threads = []
697    for i in initiators:
698        if i.mode == "spdk":
699            t = threading.Thread(target=i.install_spdk, args=(spdk_zip_path,))
700            threads.append(t)
701            t.start()
702    for t in threads:
703        t.join()
704
705    target_obj.tgt_start()
706
707    # Poor mans threading
708    # Run FIO tests
709    for block_size, io_depth, rw in fio_workloads:
710        threads = []
711        configs = []
712        for i in initiators:
713            if i.mode == "kernel":
714                i.kernel_init_connect(i.nic_ips, target_obj.subsys_no)
715
716            cfg = i.gen_fio_config(rw, fio_rw_mix_read, block_size, io_depth, target_obj.subsys_no,
717                                   fio_num_jobs, fio_ramp_time, fio_run_time)
718            configs.append(cfg)
719
720        for i, cfg in zip(initiators, configs):
721            t = threading.Thread(target=i.run_fio, args=(cfg, fio_run_num))
722            threads.append(t)
723        if target_obj.enable_sar:
724            sar_file_name = "_".join([str(block_size), str(rw), str(io_depth), "sar"])
725            sar_file_name = ".".join([sar_file_name, "txt"])
726            t = threading.Thread(target=target_obj.measure_sar, args=(target_results_dir, sar_file_name))
727            threads.append(t)
728
729        for t in threads:
730            t.start()
731        for t in threads:
732            t.join()
733
734        for i in initiators:
735            if i.mode == "kernel":
736                i.kernel_init_disconnect(i.nic_ips, target_obj.subsys_no)
737            i.copy_result_files(target_results_dir)
738
739    target_obj.parse_results(target_results_dir)
740