summaryrefslogtreecommitdiffstats
path: root/deploy/restful.py
blob: 4d86da82ca8f7ddcc61dfebace3a54722242c14e (plain)
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

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
/*
 * Driver for USB ethernet port of Conexant CX82310-based ADSL routers
 * Copyright (C) 2010 by Ondrej Zary
 * some parts inspired by the cxacru driver
 *
 * This program 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.
 *
 * This program 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/>.
 */

#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/usb/usbnet.h>

enum cx82310_cmd {
	CMD_START		= 0x84,	/* no effect? */
	CMD_STOP		= 0x85,	/* no effect? */
	CMD_GET_STATUS		= 0x90,	/* returns nothing? */
	CMD_GET_MAC_ADDR	= 0x91,	/* read MAC address */
	CMD_GET_LINK_STATUS	= 0x92,	/* not useful, link is always up */
	CMD_ETHERNET_MODE	= 0x99,	/* unknown, needed during init */
};

enum cx82310_status {
	STATUS_UNDEFINED,
	STATUS_SUCCESS,
	STATUS_ERROR,
	STATUS_UNSUPPORTED,
	STATUS_UNIMPLEMENTED,
	STATUS_PARAMETER_ERROR,
	STATUS_DBG_LOOPBACK,
};

#define CMD_PACKET_SIZE	64
#define CMD_TIMEOUT	100
#define CMD_REPLY_RETRY 5

#define CX82310_MTU	1514
#define CMD_EP		0x01

/*
 * execute control command
 *  - optionally send some data (command parameters)
 *  - optionally wait for the reply
 *  - optionally read some data from the reply
 */
static int cx82310_cmd(struct usbnet *dev, enum cx82310_cmd cmd, bool reply,
		       u8 *wdata, int wlen, u8 *rdata, int rlen)
{
	int actual_len, retries, ret;
	struct usb_device *udev = dev->udev;
	u8 *buf = kzalloc(CMD_PACKET_SIZE, GFP_KERNEL);

	if (!buf)
		return -ENOMEM;

	/* create command packet */
	buf[0] = cmd;
	if (wdata)
		memcpy(buf + 4, wdata, min_t(int, wlen, CMD_PACKET_SIZE - 4));

	/* send command packet */
	ret = usb_bulk_msg(udev, usb_sndbulkpipe(udev, CMD_EP), buf,
			   CMD_PACKET_SIZE, &actual_len, CMD_TIMEOUT);
	if (ret < 0) {
		if (cmd != CMD_GET_LINK_STATUS)
			dev_err(&dev->udev->dev, "send command %#x: error %d\n",
				cmd, ret);
		goto end;
	}

	if (reply) {
		/* wait for reply, retry if it's empty */
		for (retries = 0; retries < CMD_REPLY_RETRY; retries++) {
			ret = usb_bulk_msg(udev, usb_rcvbulkpipe(udev, CMD_EP),
					   buf, CMD_PACKET_SIZE, &actual_len,
					   CMD_TIMEOUT);
			if (ret < 0) {
				if (cmd != CMD_GET_LINK_STATUS)
					dev_err(&dev->udev->dev,
						"reply receive error %d\n",
						ret);
				goto end;
			}
			if (actual_len > 0)
				break;
		}
		if (actual_len == 0) {
			dev_err(&dev->udev->dev, "no reply to command %#x\n",
				cmd);
			ret = -EIO;
			goto end;
		}
		if (buf[0] != cmd) {
			dev_err(&dev->udev->dev,
				"got reply to command %#x, expected: %#x\n",
				buf[0], cmd);
			ret = -EIO;
			goto end;
		}
		if (buf[1] != STATUS_SUCCESS) {
			dev_err(&dev->udev->dev, "command %#x failed: %#x\n",
				cmd, buf[1]);
			ret = -EIO;
			goto end;
		}
		if (rdata)
			memcpy(rdata, buf + 4,
			       min_t(int, rlen, CMD_PACKET_SIZE - 4));
	}
end:
	kfree(buf);
	return ret;
}

#define partial_len	data[0]		/* length of partial packet data */
#define partial_rem	data[1]		/* remaining (missing) data length */
#define partial_data	data[2]		/* partial packet data */

static int cx82310_bind(struct usbnet *dev, struct usb_interface *intf)
{
	int ret;
	char buf[15];
	struct usb_device *udev = dev->udev;
	u8 link[3];
	int timeout = 50;

	/* avoid ADSL modems - continue only if iProduct is "USB NET CARD" */
	if (usb_string(udev, udev->descriptor.iProduct, buf
@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
# Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Compass api client library.
"""

import json
import logging
import requests

class Client(object):
    """compass restful api wrapper"""

    def __init__(self, url, headers=None, proxies=None, stream=None):
        logging.info('create api client %s', url)
        self.url_ = url
        self.session_ = requests.Session()

        if headers:
            self.session_.headers.update(headers)
        self.session_.headers.update({
            'Accept': 'application/json'
        })

        if proxies is not None:
            self.session_.proxies = proxies

        if stream is not None:
            self.session_.stream = stream

    def __del__(self):
        self.session_.close()

    @classmethod
    def _get_response(cls, resp):
        response_object = {}
        try:
            response_object = resp.json()
        except Exception as error:
            logging.error('failed to load object from %s: %s',
                          resp.url, resp.content)
            logging.exception(error)
            response_object['status'] = 'Json Parsing Failed'
            response_object['message'] = resp.content

        return resp.status_code, response_object

    def _get(self, req_url, data=None):
        url = '%s%s' % (self.url_, req_url)
        logging.debug('get %s with data %s', url, data)
        if data:
            resp = self.session_.get(url, params=data)
        else:
            resp = self.session_.get(url)

        return self._get_response(resp)

    def _post(self, req_url, data=None):
        url = '%s%s' % (self.url_, req_url)
        logging.debug('post %s with data %s', url, data)
        if data:
            resp = self.session_.post(url, json.dumps(data))
        else:
            resp = self.session_.post(url)

        return self._get_response(resp)

    def _put(self, req_url, data=None):
        """encapsulate put method."""
        url = '%s%s' % (self.url_, req_url)
        logging.debug('put %s with data %s', url, data)
        if data:
            resp = self.session_.put(url, json.dumps(data))
        else:
            resp = self.session_.put(url)

        return self._get_response(resp)

    def _patch(self, req_url, data=None):
        url = '%s%s' % (self.url_, req_url)
        logging.debug('patch %s with data %s', url, data)
        if data:
            resp = self.session_.patch(url, json.dumps(data))
        else:
            resp = self.session_.patch(url)

        return self._get_response(resp)

    def _delete(self, req_url):
        url = '%s%s' % (self.url_, req_url)
        logging.debug('delete %s', url)
        return self._get_response(self.session_.delete(url))

    def login(self, email, password):
        credential = {}
        credential['email'] = email
        credential['password'] = password
        return self._post('/users/login', data=credential)

    def get_token(self, email, password):
        credential = {}
        credential['email'] = email
        credential['password'] = password
        status, resp = self._post('/users/token', data=credential)
        if status < 400:
            self.session_.headers.update({'X-Auth-Token': resp['token']})
        return status, resp

    def get_users(self):
        users = self._get('/users')
        return users

    def list_switches(
            self,
            switch_ips=None,
            switch_ip_networks=None):
        """list switches."""
        params = {}
        if switch_ips:
            params['switchIp'] = switch_ips

        if switch_ip_networks:
            params['switchIpNetwork'] = switch_ip_networks

        switchlist = self._get('/switches', data=params)
        return switchlist

    def get_switch(self, switch_id):
        return self._get('/switches/%s' % switch_id)

    def add_switch(
            self,
            switch_ip,
            version=None,
            community=None,
            raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            data['ip'] = switch_ip
            data['credentials'] = {}
            if version:
                data['credentials']['version'] = version

            if community:
                data['credentials']['community'] = community

        return self._post('/switches', data=data)

    def update_switch(self, switch_id, state='initialized',
                      version='2c', community='public', raw_data={}):
        data = {}
        if raw_data:
            data = raw_data

        else:
            data['credentials'] = {}
            if version:
                data['credentials']['version'] = version

            if community:
                data['credentials']['community'] = community

            if state:
                data['state'] = state

        return self._put('/switches/%s' % switch_id, data=data)

    def delete_switch(self, switch_id):
        return self._delete('/switches/%s' % switch_id)

    def list_switch_machines(self, switch_id, port=None, vlans=None,
                             tag=None, location=None):
        data = {}
        if port:
            data['port'] = port

        if vlans:
            data['vlans'] = vlans

        if tag:
            data['tag'] = tag

        if location:
            data['location'] = location

        return self._get('/switches/%s/machines' % switch_id, data=data)

    def get_switch_machine(self, switch_id, machine_id):
        return self._get('/switches/%s/machines/%s' % (switch_id, machine_id))

    def list_switch_machines_hosts(self, switch_id, port=None, vlans=None,
                                   mac=None, tag=None, location=None,
                                   os_name=None, os_id=None):

        data = {}
        if port:
            data['port'] = port

        if vlans:
            data['vlans'] = vlans

        if mac:
            data['mac'] = mac

        if tag:
            data['tag'] = tag

        if location:
            data['location'] = location

        if os_name:
            data['os_name'] = os_name

        if os_id:
            data['os_id'] = os_id

        return self._get('/switches/%s/machines-hosts' % switch_id, data=data)

    def add_switch_machine(self, switch_id, mac=None, port=None,
                           vlans=None, ipmi_credentials=None,
                           tag=None, location=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if mac:
                data['mac'] = mac

            if port:
                data['port'] = port

            if vlans:
                data['vlans'] = vlans

            if ipmi_credentials:
                data['ipmi_credentials'] = ipmi_credentials

            if tag:
                data['tag'] = tag

            if location:
                data['location'] = location

        return self._post('/switches/%s/machines' % switch_id, data=data)

    def update_switch_machine(self, switch_id, machine_id, port=None,
                              vlans=None, ipmi_credentials=None, tag=None,
                              location=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if port:
                data['port'] = port

            if vlans:
                data['vlans'] = vlans

            if ipmi_credentials:
                data['ipmi_credentials'] = ipmi_credentials

            if tag:
                data['tag'] = tag

            if location:
                data['location'] = location

        return self._put('/switches/%s/machines/%s' %
                         (switch_id, machine_id), data=data)

    def delete_switch_machine(self, switch_id, machine_id):
        return self._delete('/switches/%s/machines/%s' %
                            (switch_id, machine_id))

    # test these
    def poll_switch(self, switch_id):
        data = {}
        data['find_machines'] = None
        return self._post('/switches/%s/action' % switch_id, data=data)

    def add_group_switch_machines(self, switch_id, group_machine_ids):
        data = {}
        data['add_machines'] = group_machine_ids
        return self._post('/switches/%s/action' % switch_id, data=data)

    def remove_group_switch_machines(self, switch_id, group_machine_ids):
        data = {}
        data['remove_machines'] = group_machine_ids
        return self._post('/switches/%s/action' % switch_id, data=data)

    def update_group_switch_machines(self, switch_id, group_machines):
        data = {}
        data['set_machines'] = group_machines
        return self._post('/switches/%s/action' % switch_id, data=data)
    # end

    def list_switchmachines(self, switch_ip_int=None, port=None, vlans=None,
                            mac=None, tag=None, location=None):
        data = {}
        if switch_ip_int:
            data['switch_ip_int'] = switch_ip_int

        if port:
            data['port'] = port

        if vlans:
            data['vlans'] = vlans

        if mac:
            data['mac'] = mac

        if tag:
            data['tag'] = tag

        if location:
            data['location'] = location

        return self._get('/switch-machines', data=data)

    def list_switchmachines_hosts(self, switch_ip_int=None, port=None,
                                  vlans=None, mac=None, tag=None,
                                  location=None, os_name=None, os_id=None):

        data = {}
        if switch_ip_int:
            data['switch_ip_int'] = switch_ip_int

        if port:
            data['port'] = port

        if vlans:
            data['vlans'] = vlans

        if mac:
            data['mac'] = mac

        if tag:
            data['tag'] = tag

        if location:
            data['location'] = location

        if os_name:
            data['os_name'] = os_name

        if os_id:
            data['os_id'] = os_id

        return self._get('/switches-machines-hosts', data=data)

    def show_switchmachine(self, switchmachine_id):
        return self._get('/switch-machines/%s' % switchmachine_id)

    def update_switchmachine(self, switchmachine_id,
                             port=None, vlans=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if port:
                data['port'] = port

            if vlans:
                data['vlans'] = vlans

        return self._put('/switch-machines/%s' % switchmachine_id, data=data)

    def patch_switchmachine(self, switchmachine_id,
                            vlans=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        elif vlans:
            data['vlans'] = vlans

        return self._patch('/switch-machines/%s' % switchmachine_id, data=data)

    def delete_switchmachine(self, switchmachine_id):
        return self._delete('/switch-machines/%s' % switchmachine_id)

    def list_machines(self, mac=None, tag=None, location=None):
        data = {}
        if mac:
            data['mac'] = mac

        if tag:
            data['tag'] = tag

        if location:
            data['location'] = location

        return self._get('/machines', data=data)

    def get_machine(self, machine_id):
        data = {}
        if id:
            data['id'] = id

        return self._get('/machines/%s' % machine_id, data=data)

    def update_machine(self, machine_id, ipmi_credentials=None, tag=None,
                       location=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if ipmi_credentials:
                data['ipmi_credentials'] = ipmi_credentials

            if tag:
                data['tag'] = tag

            if location:
                data['location'] = location

        return self._put('/machines/%s' % machine_id, data=data)

    def patch_machine(self, machine_id, ipmi_credentials=None,
                      tag=None, location=None,
                      raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if ipmi_credentials:
                data['ipmi_credentials'] = ipmi_credentials

            if tag:
                data['tag'] = tag

            if location:
                data['location'] = location

        return self._patch('/machines/%s' % machine_id, data=data)

    def delete_machine(self, machine_id):
        return self._delete('machines/%s' % machine_id)

    def list_subnets(self, subnet=None, name=None):
        data = {}
        if subnet:
            data['subnet'] = subnet

        if name:
            data['name'] = name

        return self._get('/subnets', data=data)

    def get_subnet(self, subnet_id):
        return self._get('/subnets/%s' % subnet_id)

    def add_subnet(self, subnet, name=None, raw_data=None):
        data = {}
        data['subnet'] = subnet
        if raw_data:
            data.update(raw_data)
        else:
            if name:
                data['name'] = name

        return self._post('/subnets', data=data)

    def update_subnet(self, subnet_id, subnet=None,
                      name=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if subnet:
                data['subnet'] = subnet

            if name:
                data['name'] = name

        return self._put('/subnets/%s' % subnet_id, data=data)

    def delete_subnet(self, subnet_id):
        return self._delete('/subnets/%s' % subnet_id)

    def list_adapters(self, name=None, distributed_system_name=None,
                      os_installer_name=None, package_installer_name=None):
        data = {}
        if name:
            data['name'] = name

        if distributed_system_name:
            data['distributed_system_name'] = distributed_system_name

        if os_installer_name:
            data['os_installer_name'] = os_installer_name

        if package_installer_name:
            data['package_installer_name'] = package_installer_name

        return self._get('/adapters', data=data)

    def get_adapter(self, adapter_id):
        return self._get('/adapters/%s' % adapter_id)

    def get_adapter_roles(self, adapter_id):
        return self._get('/adapters/%s/roles' % adapter_id)

    def get_adapter_metadata(self, adapter_id):
        return self._get('/adapters/%s/metadata' % adapter_id)

    def get_os_metadata(self, os_id):
        return self._get('/oses/%s/metadata' % os_id)

    def list_clusters(self, name=None, os_name=None,
                      distributed_system_name=None, owner=None,
                      adapter_id=None):
        data = {}
        if name:
            data['name'] = name

        if os_name:
            data['os_name'] = os_name

        if distributed_system_name:
            data['distributed_system_name'] = distributed_system_name

        if owner:
            data['owner'] = owner

        if adapter_id:
            data['adapter_id'] = adapter_id

        return self._get('/clusters', data=data)

    def get_cluster(self, cluster_id):
        return self._get('/clusters/%s' % cluster_id)

    def add_cluster(self, name, adapter_id, os_id,
                    flavor_id=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if flavor_id:
                data['flavor_id'] = flavor_id
            data['name'] = name
            data['adapter_id'] = adapter_id
            data['os_id'] = os_id

        return self._post('/clusters', data=data)

    def update_cluster(self, cluster_id, name=None,
                       reinstall_distributed_system=None,
                       raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if name:
                data['name'] = name

            if reinstall_distributed_system:
                data['reinstall_distributed_system'] = (
                    reinstall_distributed_system
                )
        return self._put('/clusters/%s' % cluster_id, data=data)

    def delete_cluster(self, cluster_id):
        return self._delete('/clusters/%s' % cluster_id)

    def get_cluster_config(self, cluster_id):
        return self._get('/clusters/%s/config' % cluster_id)

    def get_cluster_metadata(self, cluster_id):
        return self._get('/clusters/%s/metadata' % cluster_id)

    def update_cluster_config(self, cluster_id, os_config=None,
                              package_config=None, config_step=None,
                              raw_data=None):
        data = {}
        if raw_data:
            data = raw_data

        if os_config:
            data['os_config'] = os_config

        if package_config:
            data['package_config'] = package_config

        if config_step:
            data['config_step'] = config_step

        return self._put('/clusters/%s/config' % cluster_id, data=data)

    def patch_cluster_config(self, cluster_id, os_config=None,
                             package_config=None, config_step=None,
                             raw_data=None):
        data = {}
        if raw_data:
            data = raw_data

        if os_config:
            data['os_config'] = os_config

        if package_config:
            data['package_config'] = package_config

        if config_step:
            data['config_step'] = config_step

        return self._patch('/clusters/%s/config' % cluster_id, data=data)

    def delete_cluster_config(self, cluster_id):
        return self._delete('/clusters/%s/config' % cluster_id)

    # test these
    def add_hosts_to_cluster(self, cluster_id, hosts):
        data = {}
        data['add_hosts'] = hosts
        return self._post('/clusters/%s/action' % cluster_id, data=data)

    def set_hosts_in_cluster(self, cluster_id, hosts):
        data = {}
        data['set_hosts'] = hosts
        return self._post('/clusters/%s/action' % cluster_id, data=data)

    def remove_hosts_from_cluster(self, cluster_id, hosts):
        data = {}
        data['remove_hosts'] = hosts
        return self._post('/clusters/%s/action' % cluster_id, data=data)

    def review_cluster(self, cluster_id, review={}):
        data = {}
        data['review'] = review
        return self._post('/clusters/%s/action' % cluster_id, data=data)

    def deploy_cluster(self, cluster_id, deploy={}):
        data = {}
        data['deploy'] = deploy
        return self._post('/clusters/%s/action' % cluster_id, data=data)

    def get_cluster_state(self, cluster_id):
        return self._get('/clusters/%s/state' % cluster_id)

    def list_cluster_hosts(self, cluster_id):
        return self._get('/clusters/%s/hosts' % cluster_id)

    def list_clusterhosts(self):
        return self._get('/clusterhosts')

    def get_cluster_host(self, cluster_id, host_id):
        return self._get('/clusters/%s/hosts/%s' % (cluster_id, host_id))

    def get_clusterhost(self, clusterhost_id):
        return self._get('/clusterhosts/%s' % clusterhost_id)

    def add_cluster_host(self, cluster_id, machine_id=None, name=None,
                         reinstall_os=None, raw_data=None):
        data = {}
        data['machine_id'] = machine_id
        if raw_data:
            data.update(raw_data)
        else:
            if name:
                data['name'] = name

            if reinstall_os:
                data['reinstall_os'] = reinstall_os

        return self._post('/clusters/%s/hosts' % cluster_id, data=data)

    def delete_cluster_host(self, cluster_id, host_id):
        return self._delete('/clusters/%s/hosts/%s' %
                            (cluster_id, host_id))

    def delete_clusterhost(self, clusterhost_id):
        return self._delete('/clusterhosts/%s' % clusterhost_id)

    def get_cluster_host_config(self, cluster_id, host_id):
        return self._get('/clusters/%s/hosts/%s/config' %
                         (cluster_id, host_id))

    def get_clusterhost_config(self, clusterhost_id):
        return self._get('/clusterhosts/%s/config' % clusterhost_id)

    def update_cluster_host_config(self, cluster_id, host_id,
                                   os_config=None,
                                   package_config=None,
                                   raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if os_config:
                data['os_config'] = os_config

            if package_config:
                data['package_config'] = package_config

        return self._put('/clusters/%s/hosts/%s/config' %
                         (cluster_id, host_id), data=data)

    def update_clusterhost_config(self, clusterhost_id, os_config=None,
                                  package_config=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data

        else:
            if os_config:
                data['os_config'] = os_config

            if package_config:
                data['package_config'] = package_config

        return self._put('/clusterhosts/%s/config' % clusterhost_id,
                         data=data)

    def patch_cluster_host_config(self, cluster_id, host_id,
                                  os_config=None,
                                  package_config=None,
                                  raw_data=None):
        data = {}
        if raw_data:
            data = raw_data

        else:
            if os_config:
                data['os_config'] = os_config

            if package_config:
                data['package_config'] = package_config

        return self._patch('/clusters/%s/hosts/%s/config' %
                           (cluster_id, host_id), data=data)

    def patch_clusterhost_config(self, clusterhost_id, os_config=None,
                                 package_config=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data

        else:
            if os_config:
                data['os_config'] = os_config

            if package_config:
                data['package_config'] = package_config

        return self._patch('/clusterhosts/%s' % clusterhost_id, data=data)

    def delete_cluster_host_config(self, cluster_id, host_id):
        return self._delete('/clusters/%s/hosts/%s/config' %
                            (cluster_id, host_id))

    def delete_clusterhost_config(self, clusterhost_id):
        return self._delete('/clusterhosts/%s/config' % clusterhost_id)

    def get_cluster_host_state(self, cluster_id, host_id):
        return self._get('/clusters/%s/hosts/%s/state' %
                         (cluster_id, host_id))

    def update_cluster_host(self, cluster_id, host_id,
                            roles=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if roles:
                data['roles'] = roles

        return self._put('/clusters/%s/hosts/%s' %
                         (cluster_id, host_id), data=data)

    def update_clusterhost(self, clusterhost_id,
                           roles=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if roles:
                data['roles'] = roles

        return self._put('/clusterhosts/%s' % clusterhost_id, data=data)

    def patch_cluster_host(self, cluster_id, host_id,
                           roles=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if roles:
                data['roles'] = roles

        return self._patch('/clusters/%s/hosts/%s' %
                           (cluster_id, host_id), data=data)

    def patch_clusterhost(self, clusterhost_id,
                          roles=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if roles:
                data['roles'] = roles

        return self._patch('/clusterhosts/%s' % clusterhost_id, data=data)

    def get_clusterhost_state(self, clusterhost_id):
        return self._get('/clusterhosts/%s/state' % clusterhost_id)

    def update_cluster_host_state(self, cluster_id, host_id, state=None,
                                  percentage=None, message=None,
                                  raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if state:
                data['state'] = state

            if percentage:
                data['percentage'] = percentage

            if message:
                data['message'] = message

        return self._put('/clusters/%s/hosts/%s/state' % (cluster_id, host_id),
                         data=data)

    def update_clusterhost_state(self, clusterhost_id, state=None,
                                 percentage=None, message=None,
                                 raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if state:
                data['state'] = state

            if percentage:
                data['percentage'] = percentage

            if message:
                data['message'] = message

        return self._put('/clusterhosts/%s/state' % clusterhost_id, data=data)

    def list_hosts(self, name=None, os_name=None, owner=None, mac=None):
        data = {}
        if name:
            data['name'] = name

        if os_name:
            data['os_name'] = os_name

        if owner:
            data['owner'] = owner

        if mac:
            data['mac'] = mac

        return self._get('/hosts', data=data)

    def get_host(self, host_id):
        return self._get('/hosts/%s' % host_id)

    def list_machines_or_hosts(self, mac=None, tag=None,
                               location=None, os_name=None,
                               os_id=None):
        data = {}
        if mac:
            data['mac'] = mac

        if tag:
            data['tag'] = tag

        if location:
            data['location'] = location

        if os_name:
            data['os_name'] = os_name

        if os_id:
            data['os_id'] = os_id

        return self._get('/machines-hosts', data=data)

    def get_machine_or_host(self, host_id):
        return self._get('/machines-hosts/%s' % host_id)

    def update_host(self, host_id, name=None,
                    reinstall_os=None, raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if name:
                data['name'] = name

            if reinstall_os:
                data['reinstall_os'] = reinstall_os

        return self._put('/hosts/%s' % host_id, data=data)

    def delete_host(self, host_id):
        return self._delete('/hosts/%s' % host_id)

    def get_host_clusters(self, host_id):
        return self._get('/hosts/%s/clusters' % host_id)

    def get_host_config(self, host_id):
        return self._get('/hosts/%s/config' % host_id)

    def update_host_config(self, host_id, os_config, raw_data=None):
        data = {}
        data['os_config'] = os_config
        if raw_data:
            data.update(raw_data)

        return self._put('/hosts/%s/config' % host_id, data=data)

    def patch_host_config(self, host_id, os_config, raw_data=None):
        data = {}
        data['os_config'] = os_config
        if raw_data:
            data.update(raw_data)

        return self._patch('/hosts/%s/config' % host_id, data=data)

    def delete_host_config(self, host_id):
        return self._delete('/hosts/%s/config' % host_id)

    def list_host_networks(self, host_id, interface=None, ip=None,
                           subnet=None, is_mgmt=None, is_promiscuous=None):
        data = {}
        if interface:
            data['interface'] = interface

        if ip:
            data['ip'] = ip

        if subnet:
            data['subnet'] = subnet

        if is_mgmt:
            data['is_mgmt'] = is_mgmt

        if is_promiscuous:
            data['is_promiscuous'] = is_promiscuous

        return self._get('/hosts/%s/networks' % host_id, data=data)

    def list_all_host_networks(self, interface=None, ip=None, subnet=None,
                               is_mgmt=None, is_promiscuous=None):
        data = {}
        if interface:
            data['interface'] = interface

        if ip:
            data['ip'] = ip

        if subnet:
            data['subnet'] = subnet

        if is_mgmt:
            data['is_mgmt'] = is_mgmt

        if is_promiscuous:
            data['is_promiscuous'] = is_promiscuous

        return self._get('/host-networks', data=data)

    def get_host_network(self, host_id, host_network_id):
        return self._get('/hosts/%s/networks/%s' %
                         (host_id, host_network_id))

    def get_network_for_all_hosts(self, host_network_id):
        return self._get('/host-networks/%s' % host_network_id)

    def add_host_network(self, host_id, interface, ip, subnet_id,
                         is_mgmt=None, is_promiscuous=None,
                         raw_data=None):
        data = {}
        data['interface'] = interface
        data['ip'] = ip
        data['subnet_id'] = subnet_id
        if raw_data:
            data.update(raw_data)
        else:
            if is_mgmt:
                data['is_mgmt'] = is_mgmt

            if is_promiscuous:
                data['is_promiscuous'] = is_promiscuous

        return self._post('/hosts/%s/networks' % host_id, data=data)

    def update_host_network(self, host_id, host_network_id,
                            ip=None, subnet_id=None, subnet=None,
                            is_mgmt=None, is_promiscuous=None,
                            raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if ip:
                data['ip'] = ip

            if subnet_id:
                data['subnet_id'] = subnet_id

            if subnet:
                data['subnet'] = subnet

            if is_mgmt:
                data['is_mgmt'] = is_mgmt

            if is_promiscuous:
                data['is_promiscuous'] = is_promiscuous

        return self._put('/hosts/%s/networks/%s' %
                         (host_id, host_network_id), data=data)

    def update_hostnetwork(self, host_network_id, ip=None,
                           subnet_id=None, subnet=None,
                           is_mgmt=None, is_promiscuous=None,
                           raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if ip:
                data['ip'] = ip

            if subnet_id:
                data['subnet_id'] = subnet_id

            if subnet:
                data['subnet'] = subnet

            if is_mgmt:
                data['is_mgmt'] = is_mgmt

            if is_promiscuous:
                data['is_promiscuous'] = is_promiscuous

        return self._put('/host-networks/%s' % host_network_id,
                         data=data)

    def delete_host_network(self, host_id, host_network_id):
        return self._delete('/hosts/%s/networks/%s',
                            (host_id, host_network_id))

    def delete_hostnetwork(self, host_network_id):
        return self._delete('/host-networks/%s' % host_network_id)

    def get_host_state(self, host_id):
        return self._get('/hosts/%s/state' % host_id)

    def update_host_state(self, host_id, state=None,
                          percentage=None, message=None,
                          raw_data=None):
        data = {}
        if raw_data:
            data = raw_data
        else:
            if state:
                data['state'] = state

            if percentage:
                data['percentage'] = percentage

            if message:
                data['message'] = message

        return self._put('/hosts/%s/state' % host_id, date=data)

    def poweron_host(self, host_id):
        data = {}
        data['poweron'] = True

        return self._post('/hosts/%s/action' % host_id, data=data)

    def poweroff_host(self, host_id):
        data = {}
        data['poweroff'] = True

        return self._post('/hosts/%s/action' % host_id, data=data)

    def reset_host(self, host_id):
        data = {}
        data['reset'] = True

        return self._post('/hosts/%s/action' % host_id, data=data)

    def clusterhost_ready(self, clusterhost_name):
        data = {}
        data['ready'] = True

        return self._post('/clusterhosts/%s/state_internal' %
                          clusterhost_name, data=data)