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