Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

""" 

Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> 

This file is part of RockStor. 

 

RockStor is free software; you can redistribute it and/or modify 

it under the terms of the GNU General Public License as published 

by the Free Software Foundation; either version 2 of the License, 

or (at your option) any later version. 

 

RockStor is distributed in the hope that it will be useful, but 

WITHOUT ANY WARRANTY; without even the implied warranty of 

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 

General Public License for more details. 

 

You should have received a copy of the GNU General Public License 

along with this program. If not, see <http://www.gnu.org/licenses/>. 

""" 

 

import json 

from django.db import transaction 

from rest_framework.exceptions import NotFound 

from rest_framework.response import Response 

from storageadmin.models import (NetworkConnection, NetworkDevice, 

                                 EthernetConnection, TeamConnection, 

                                 BondConnection) 

from smart_manager.models import Service 

from storageadmin.util import handle_exception 

from storageadmin.serializers import (NetworkDeviceSerializer, 

                                      NetworkConnectionSerializer) 

from system import network 

import rest_framework_custom as rfc 

 

import logging 

logger = logging.getLogger(__name__) 

 

MIN_MTU = 1500 

MAX_MTU = 9000 

DEFAULT_MTU = MIN_MTU 

 

 

class NetworkMixin(object): 

    # Runners for teams. @todo: support basic defaults + custom configuration. 

    # @todo: lacp doesn't seem to be activating 

    runners = { 

        'broadcast': '{ "runner": {"name": "broadcast"}}', 

        'roundrobin': '{ "runner": {"name": "roundrobin"}}', 

        'activebackup': '{ "runner": {"name": "activebackup"}}', 

        'loadbalance': '{ "runner": {"name": "loadbalance"}}', 

        'lacp': '{ "runner": {"name": "lacp"}}', 

    } 

    team_profiles = ('broadcast', 'roundrobin', 'activebackup', 'loadbalance', 

                     'lacp') 

    bond_profiles = ('balance-rr', 'active-backup', 'balance-xor', 'broadcast', 

                     '802.3ad', 'balance-tlb', 'balance-alb') 

 

    @staticmethod 

    @transaction.atomic 

    def _update_or_create_ctype(co, ctype, config): 

        if (ctype == '802-3-ethernet'): 

            try: 

                eco = EthernetConnection.objects.get(connection=co) 

                eco.mac = config['mac'] 

                eco.cloned_mac = config['cloned_mac'] 

                eco.mtu = config['mtu'] 

                eco.save() 

            except EthernetConnection.DoesNotExist: 

                EthernetConnection.objects.create(connection=co, **config) 

        elif (ctype == 'team'): 

            try: 

                tco = TeamConnection.objects.get(connection=co) 

                tco.name = co.name 

                tco.config = config['config'] 

                tco.save() 

            except TeamConnection.DoesNotExist: 

                TeamConnection.objects.create(connection=co, **config) 

        elif (ctype == 'bond'): 

            try: 

                bco = BondConnection.objects.get(connection=co) 

                bco.name = co.name 

                bco.config = config['config'] 

                bco.save() 

            except BondConnection.DoesNotExist: 

                BondConnection.objects.create(connection=co, **config) 

        else: 

            logger.error('Unknown ctype: %s config: %s' % (ctype, config)) 

 

    @staticmethod 

    @transaction.atomic 

    def _update_master(co, config, defer_list=None): 

        if ('master' not in config): 

            return config 

        try: 

            co.master = NetworkConnection.objects.get(name=config['master']) 

        except (NetworkConnection.DoesNotExist, 

                NetworkConnection.MultipleObjectsReturned): 

            if (not isinstance(defer_list, list)): 

                raise 

            defer_list.append({'uuid': co.uuid, 'master': config['master']}) 

        del(config['master']) 

 

    @classmethod 

    @transaction.atomic 

    def _refresh_connections(cls): 

        cmap = network.connections() 

        defer_master_updates = [] 

        for nco in NetworkConnection.objects.all(): 

            if (nco.uuid not in cmap): 

                nco.delete() 

                continue 

            config = cmap[nco.uuid] 

            if ('ctype' in config): 

                ctype = config['ctype'] 

                cls._update_or_create_ctype(nco, ctype, config[ctype]) 

                del(config[ctype]) 

                del(config['ctype']) 

            cls._update_master(nco, config, defer_master_updates) 

            NetworkConnection.objects.filter(uuid=nco.uuid).update(**config) 

            del cmap[nco.uuid] 

        for uuid in cmap: 

            # new connections not yet in administrative state. 

            config = cmap[uuid] 

            config['uuid'] = uuid 

            ctype = ctype_d = None 

            if ('ctype' in config): 

                ctype = config['ctype'] 

                ctype_d = config[ctype] 

                del(config[ctype]) 

                del(config['ctype']) 

            if ('master' in config): 

                defer_master_updates.append({'uuid': uuid, 'master': 

                                             config['master']}) 

                del(config['master']) 

            nco = NetworkConnection.objects.create(**config) 

            if (ctype is not None): 

                cls._update_or_create_ctype(nco, ctype, ctype_d) 

        for e in defer_master_updates: 

            slave_co = NetworkConnection.objects.get(uuid=e['uuid']) 

            try: 

                slave_co.master = NetworkConnection.objects.get(name=e['master'])  # noqa E501 

            except (NetworkConnection.DoesNotExist, 

                    NetworkConnection.MultipleObjectsReturned) as e: 

                logger.exception(e) 

            slave_co.save() 

 

    @staticmethod 

    @transaction.atomic 

    def _refresh_devices(): 

        dmap = network.devices() 

 

        def update_connection(dconfig): 

            if ('connection' in dconfig): 

                try: 

                    dconfig['connection'] = NetworkConnection.objects.get( 

                        name=dconfig['connection']) 

                except (NetworkConnection.DoesNotExist, 

                        NetworkConnection.MultipleObjectsReturned) as e: 

                    logger.exception(e) 

                    dconfig['connection'] = None 

 

        for ndo in NetworkDevice.objects.all(): 

            if (ndo.name not in dmap): 

                ndo.delete() 

                continue 

            dconfig = dmap[ndo.name] 

            update_connection(dconfig) 

            NetworkDevice.objects.filter(name=ndo.name).update(**dconfig) 

            del dmap[ndo.name] 

        for dev in dmap: 

            dconfig = dmap[dev] 

            dconfig['name'] = dev 

            update_connection(dconfig) 

            NetworkDevice.objects.create(**dconfig) 

 

 

class NetworkDeviceListView(rfc.GenericView, NetworkMixin): 

    serializer_class = NetworkDeviceSerializer 

 

    def get_queryset(self, *args, **kwargs): 

        with self._handle_exception(self.request): 

            self._refresh_devices() 

            # don't return unmanaged devices return 

            # NetworkDevice.objects.filter(~Q(state='10 (unmanaged)')) 

            return NetworkDevice.objects.all() 

 

 

class NetworkConnectionListView(rfc.GenericView, NetworkMixin): 

    serializer_class = NetworkConnectionSerializer 

    ctypes = ('ethernet', 'team', 'bond') 

 

    # ethtool is the default link watcher. 

 

    config_methods = ('auto', 'manual') 

 

    def get_queryset(self, *args, **kwargs): 

        with self._handle_exception(self.request): 

            self._refresh_connections() 

            return NetworkConnection.objects.all() 

 

    @staticmethod 

    def _validate_devices(devices, request, size=2): 

        if (not isinstance(devices, list)): 

            raise Exception('devices must be a list') 

        if (len(devices) < size): 

            raise Exception('A minimum of %d devices are required' % size) 

        for d in devices: 

            try: 

                NetworkDevice.objects.get(name=d) 

                # if device belongs to another connection, change it. 

            except NetworkDevice.DoesNotExist: 

                e_msg = ('Unknown network device(%s)' % d) 

                handle_exception(Exception(e_msg), request) 

        return devices 

 

    @transaction.atomic 

    def post(self, request): 

        with self._handle_exception(request): 

            ipaddr = gateway = dns_servers = search_domains = None 

            name = request.data.get('name') 

            if (NetworkConnection.objects.filter(name=name).exists()): 

                e_msg = ('Connection name(%s) is already in use. Choose a ' 

                         'different name.' % name) 

                handle_exception(Exception(e_msg), request) 

 

            # auto of manual 

            method = request.data.get('method') 

            if (method not in self.config_methods): 

                e_msg = ('Unsupported config method(%s). Supported ones ' 

                         'include: %s' % (method, self.config_methods)) 

                handle_exception(Exception(e_msg), request) 

            if (method == 'manual'): 

                # ipaddr is of the format <IP>/<netmask>. eg: 

                # 192.168.1.2/24. If netmask is not given, it defaults to 32. 

                ipaddr = request.data.get('ipaddr') 

                gateway = request.data.get('gateway', None) 

                dns_servers = request.data.get('dns_servers', None) 

                search_domains = request.data.get('search_domains', None) 

 

            # connection type can be one of ethernet, team or bond 

            ctype = request.data.get('ctype') 

            if (ctype not in self.ctypes): 

                e_msg = ('Unsupported connection type(%s). Supported ones ' 

                         'include: %s' % (ctype, self.ctypes)) 

                handle_exception(Exception(e_msg), request) 

            devices = request.data.get('devices', None) 

            if (ctype == 'team'): 

                # gather required input for team 

                team_profile = request.data.get('team_profile') 

                if (team_profile not in self.team_profiles): 

                    e_msg = ('Unsupported team profile(%s). Supported ones ' 

                             'include: %s' % 

                             (team_profile, self.team_profiles)) 

                    handle_exception(Exception(e_msg), request) 

                self._validate_devices(devices, request) 

                network.new_team_connection(name, self.runners[team_profile], 

                                            devices, ipaddr, gateway, 

                                            dns_servers, search_domains) 

 

            elif (ctype == 'ethernet'): 

                device = request.data.get('device') 

                self._validate_devices([device], request, size=1) 

                network.new_ethernet_connection(name, device, ipaddr, gateway, 

                                                dns_servers, search_domains) 

 

            elif (ctype == 'bond'): 

                bond_profile = request.data.get('bond_profile') 

                if (bond_profile not in self.bond_profiles): 

                    e_msg = ('Unsupported bond profile(%s). Supported ones ' 

                             'include: %s' 

                             % (bond_profile, self.bond_profiles)) 

                    handle_exception(Exception(e_msg), request) 

                self._validate_devices(devices, request) 

                network.new_bond_connection(name, bond_profile, devices, 

                                            ipaddr, gateway, dns_servers, 

                                            search_domains) 

 

            return Response() 

 

 

class NetworkConnectionDetailView(rfc.GenericView, NetworkMixin): 

    serializer_class = NetworkConnectionSerializer 

 

    def get(self, *args, **kwargs): 

        try: 

            data = NetworkConnection.objects.get(id=self.kwargs['id']) 

            sdata = NetworkConnectionSerializer(data) 

            return Response(sdata.data) 

        except NetworkConnection.DoesNotExist: 

            raise NotFound(detail=None) 

 

    @staticmethod 

    def _nco(request, id): 

        try: 

            return NetworkConnection.objects.get(id=id) 

        except NetworkConnection.DoesNotExist: 

            e_msg = ('Network connection(%s) does not exist.' % id) 

            handle_exception(Exception(e_msg), request) 

 

    @transaction.atomic 

    def put(self, request, id): 

 

        with self._handle_exception(request): 

            nco = self._nco(request, id) 

            method = request.data.get('method') 

            mtu = DEFAULT_MTU 

            try: 

                e_msg = ('mtu must be an integer in {} - {} range'.format( 

                    MIN_MTU, MAX_MTU)) 

                mtu = int(request.data.get('mtu', DEFAULT_MTU)) 

                if mtu < MIN_MTU or mtu > MAX_MTU: 

                    handle_exception(Exception(e_msg), request) 

            except ValueError: 

                handle_exception(Exception(e_msg), request) 

            ipaddr = gateway = dns_servers = search_domains = None 

            if (method == 'manual'): 

                ipaddr = request.data.get('ipaddr', None) 

                gateway = request.data.get('gateway', None) 

                dns_servers = request.data.get('dns_servers', None) 

                search_domains = request.data.get('search_domains', None) 

 

            if (nco.ctype == 'ethernet'): 

                device = nco.networkdevice_set.first().name 

                self._delete_connection(nco) 

                network.new_ethernet_connection(nco.name, device, ipaddr, 

                                                gateway, dns_servers, 

                                                search_domains, mtu) 

            elif (nco.ctype == 'team'): 

                team_profile = nco.team_profile 

                devices = [] 

                for child_nco in NetworkConnection.objects.filter(master=nco): 

                    devices.append(child_nco.networkdevice_set.first().name) 

 

                self._delete_connection(nco) 

                network.new_team_connection( 

                    nco.name, self.runners[team_profile], devices, ipaddr, 

                    gateway, dns_servers, search_domains, mtu) 

 

            return Response(NetworkConnectionSerializer(nco).data) 

 

    @staticmethod 

    def _delete_connection(nco): 

        for mnco in nco.networkconnection_set.all(): 

            network.delete_connection(mnco.uuid) 

        network.delete_connection(nco.uuid) 

        nco.delete() 

 

    @transaction.atomic 

    def delete(self, request, id): 

        with self._handle_exception(request): 

            nco = self._nco(request, id) 

            restricted = False 

            try: 

                so = Service.objects.get(name='rockstor') 

                config = json.loads(so.config) 

                if (config['network_interface'] == nco.name): 

                    restricted = True 

            except Exception as e: 

                logger.exception(e) 

            if (restricted): 

                e_msg = ('This connection(%s) is designated for ' 

                         'management and cannot be deleted. If you really ' 

                         'need to delete it, change the Rockstor service ' 

                         'configuration and try again.' % nco.name) 

                handle_exception(Exception(e_msg), request) 

            self._delete_connection(nco) 

            return Response() 

 

    @transaction.atomic 

    def post(self, request, id, switch): 

        # switch the connection up, down or reload. 

        with self._handle_exception(request): 

            nco = self._nco(request, id) 

            if (switch == 'up' and nco.ctype in ('team', 'bond')): 

                # order_by('name') because in some cases member interfaces must 

                # be brought up in order. eg: active-backup. 

                for mnco in nco.networkconnection_set.all().order_by('name'): 

                    logger.debug('upping %s %s' % (mnco.name, mnco.uuid)) 

                    network.toggle_connection(mnco.uuid, switch) 

            else: 

                network.toggle_connection(nco.uuid, switch) 

            return Response(NetworkConnectionSerializer(nco).data) 

 

 

class NetworkStateView(rfc.GenericView, NetworkMixin): 

    serializer_class = NetworkConnectionSerializer 

 

    def get_queryset(self, *args, **kwargs): 

        return NetworkConnection.objects.all() 

 

    def post(self, request): 

        with self._handle_exception(request): 

            self._refresh_connections() 

            self._refresh_devices() 

            ns = NetworkConnectionSerializer( 

                NetworkConnection.objects.all(), many=True) 

            return Response(ns.data)