forked from rackspace/php-opencloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoadBalancer.php
752 lines (665 loc) · 21.9 KB
/
LoadBalancer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
<?php
/**
* Copyright 2012-2014 Rackspace US, Inc.
*
* 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.
*/
namespace OpenCloud\LoadBalancer\Resource;
use OpenCloud\Common\Exceptions;
use OpenCloud\Common\Log\Logger;
use OpenCloud\Common\Resource\PersistentResource;
use OpenCloud\DNS\Resource\HasPtrRecordsInterface;
use OpenCloud\LoadBalancer\Enum\NodeCondition;
use OpenCloud\LoadBalancer\Enum\IpType;
use OpenCloud\LoadBalancer\Enum\NodeType;
/**
* A load balancer is a logical device which belongs to a cloud account. It is
* used to distribute workloads between multiple back-end systems or services,
* based on the criteria defined as part of its configuration.
*/
class LoadBalancer extends PersistentResource implements HasPtrRecordsInterface
{
public $id;
/**
* Name of the load balancer to create. The name must be 128 characters or
* less in length, and all UTF-8 characters are valid.
*
* @var string
*/
public $name;
/**
* Port of the service which is being load balanced.
*
* @var string
*/
public $port;
/**
* Protocol of the service which is being load balanced.
*
* @var string
*/
public $protocol;
/**
* Type of virtual IP to add along with the creation of a load balancer.
*
* @var array|Collection
*/
public $virtualIps = array();
/**
* Nodes to be added to the load balancer.
*
* @var array|Collection
*/
public $nodes = array();
/**
* The access list management feature allows fine-grained network access
* controls to be applied to the load balancer's virtual IP address.
*
* @var Collection
*/
public $accessList;
/**
* Algorithm that defines how traffic should be directed between back-end nodes.
*
* @var Algorithm
*/
public $algorithm;
/**
* Enables or disables HTTP to HTTPS redirection for the load balancer.
*
* @var bool
*/
public $httpsRedirect;
/**
* Current connection logging configuration.
*
* @var ConnectionLogging
*/
public $connectionLogging;
/**
* Specifies limits on the number of connections per IP address to help
* mitigate malicious or abusive traffic to your applications.
*
* @var ConnectionThrottle
*/
public $connectionThrottle;
/**
* The type of health monitor check to perform to ensure that the service is
* performing properly.
*
* @var HealthMonitor
*/
public $healthMonitor;
/**
* Forces multiple requests, of the same protocol, from clients to be
* directed to the same node.
*
* @var SessionPersistance
*/
public $sessionPersistence;
/**
* Information (metadata) that can be associated with each load balancer for
* the client's personal use.
*
* @var array|Metadata
*/
public $metadata = array();
/**
* The timeout value for the load balancer and communications with its nodes.
* Defaults to 30 seconds with a maximum of 120 seconds.
*
* @var int
*/
public $timeout;
public $created;
public $updated;
public $status;
public $nodeCount;
public $sourceAddresses;
public $cluster;
protected static $json_name = 'loadBalancer';
protected static $url_resource = 'loadbalancers';
protected $associatedResources = array(
'certificateMapping' => 'CertificateMapping',
'node' => 'Node',
'virtualIp' => 'VirtualIp',
'connectionLogging' => 'ConnectionLogging',
'healthMonitor' => 'HealthMonitor',
'sessionPersistance' => 'SessionPersistance'
);
protected $associatedCollections = array(
'certificateMappings' => 'CertificateMapping',
'nodes' => 'Node',
'virtualIps' => 'VirtualIp',
'accessList' => 'Access'
);
protected $createKeys = array(
'name',
'port',
'protocol',
'virtualIps',
'nodes',
'accessList',
'algorithm',
'connectionLogging',
'connectionThrottle',
'healthMonitor',
'sessionPersistence',
'httpsRedirect'
);
/**
* This method creates a Node object and adds it to a list of Nodes
* to be added to the LoadBalancer. This method will not add the nodes
* directly to the load balancer itself; it stores them in an array and
* the nodes are added later, in one of two ways:
*
* * for a new load balancer, the nodes are added as part of the create() method call
* * for an existing load balancer, you must call the addNodes() method
*
* @param string $address the IP address of the node
* @param integer $port the port # of the node
* @param boolean $condition the initial condition of the node
* @param string $type either PRIMARY or SECONDARY
* @param integer $weight the node weight (for round-robin)
*
* @throws \InvalidArgumentException
* @return void
*/
public function addNode(
$address,
$port,
$condition = NodeCondition::ENABLED,
$type = null,
$weight = null
) {
$allowedConditions = array(
NodeCondition::ENABLED,
NodeCondition::DISABLED,
NodeCondition::DRAINING
);
if (!in_array($condition, $allowedConditions)) {
throw new \InvalidArgumentException(sprintf(
"Invalid condition. It must one of the following: %s",
implode(', ', $allowedConditions)
));
}
$allowedTypes = array(NodeType::PRIMARY, NodeType::SECONDARY);
if ($type && !in_array($type, $allowedTypes)) {
throw new \InvalidArgumentException(sprintf(
"Invalid type. It must one of the following: %s",
implode(', ', $allowedTypes)
));
}
if ($weight && !is_numeric($weight)) {
throw new \InvalidArgumentException('Invalid weight. You must supply a numeric type');
}
// queue it
$this->nodes[] = $this->node(array(
'address' => $address,
'port' => $port,
'condition' => $condition,
'type' => $type,
'weight' => $weight
));
}
/**
* Creates currently added nodes by sending them to the API
*
* @return array of {@see \Guzzle\Http\Message\Response} objects
* @throws \OpenCloud\Common\Exceptions\MissingValueError
*/
public function addNodes()
{
if (empty($this->nodes)) {
throw new Exceptions\MissingValueError(
'Cannot add nodes; no nodes are defined'
);
}
$requestData = array('nodes' => array());
/** @var Node $node */
foreach ($this->nodes as $node) {
// Only add the node if it is new
if (null === $node->getId()) {
$nodeJson = $node->createJson();
$requestData['nodes'][] = $nodeJson['nodes'][0];
}
}
$request = $this->getClient()->post($node->getUrl(), self::getJsonHeader(), json_encode($requestData));
return $this->getClient()->send($request);
}
/**
* Remove a node from this load-balancer
*
* @param int $id id of the node
* @return \Guzzle\Http\Message\Response
*/
public function removeNode($nodeId)
{
return $this->node($nodeId)->delete();
}
/**
* Adds a virtual IP to the load balancer. You can use the strings 'PUBLIC'
* or 'SERVICENET' to indicate the public or internal networks, or you can
* pass the `Id` of an existing IP address.
*
* @param string $id either 'public' or 'servicenet' or an ID of an
* existing IP address
* @param integer $ipVersion either null, 4, or 6 (both, IPv4, or IPv6)
* @return void
*/
public function addVirtualIp($type = IpType::PUBLIC_TYPE, $ipVersion = null)
{
$object = new \stdClass();
switch (strtoupper($type)) {
case IpType::PUBLIC_TYPE:
case IpType::SERVICENET_TYPE:
$object->type = strtoupper($type);
break;
default:
$object->id = $type;
break;
}
if ($ipVersion) {
switch ($ipVersion) {
case 4:
$object->ipVersion = IpType::IPv4;
break;
case 6:
$object->ipVersion = IpType::IPv6;
break;
default:
throw new Exceptions\DomainError(sprintf(
'Value [%s] for ipVersion is not valid',
$ipVersion
));
}
}
/**
* If the load balancer exists, we want to add it immediately.
* If not, we add it to the virtualIps list and add it when the load
* balancer is created.
*/
if ($this->Id()) {
$virtualIp = $this->virtualIp();
$virtualIp->type = $type;
$virtualIp->ipVersion = $object->ipVersion;
return $virtualIp->create();
} else {
// queue it
$this->virtualIps[] = $object;
}
return true;
}
/**
* Returns a Node
*
* @return \OpenCloud\LoadBalancer\Resource\Node
*/
public function node($id = null)
{
return $this->getService()->resource('Node', $id, $this);
}
/**
* returns a Collection of Nodes
*
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function nodeList()
{
return $this->getService()->resourceList('Node', null, $this);
}
/**
* Returns a NodeEvent object
*
* @return \OpenCloud\LoadBalancer\Resource\NodeEvent
*/
public function nodeEvent()
{
return $this->getService()->resource('NodeEvent', null, $this);
}
/**
* Returns a Collection of NodeEvents
*
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function nodeEventList()
{
return $this->getService()->resourceList('NodeEvent', null, $this);
}
/**
* Returns a single Virtual IP (not called publicly)
*
* @return \OpenCloud\LoadBalancer\Resource\VirtualIp
*/
public function virtualIp($data = null)
{
return $this->getService()->resource('VirtualIp', $data, $this);
}
/**
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function virtualIpList()
{
return $this->getService()->resourceList('VirtualIp', null, $this);
}
/**
* Returns a Certificate Mapping.
*
* @param int|array $id (Optional) Either a particular Certificate mapping ID, or an array of data about the
* mapping. An array can include these keys: hostName, privateKey, certificate,
* intermediateCertificate.
* @return \OpenCloud\LoadBalancer\Resource\CertificateMapping
*/
public function certificateMapping($id = null)
{
return $this->getService()->resource('CertificateMapping', $id, $this);
}
/**
* Returns a Collection of Certificate Mappings.
*
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function certificateMappingList()
{
return $this->getService()->resourceList('CertificateMapping', null, $this);
}
/**
* Creates a certificate mapping.
*
* @throws \OpenCloud\Common\Exceptions\MissingValueError
*
* @param string $hostName The domain name for the certificate.
* @param string $privateKey The private key for the certificate
* @param string $certificate The certificate itself.
* @param string $intermediateCertificate The intermediate certificate chain.
* @return array An array of \Guzzle\Http\Message\Response objects.
*/
public function addCertificateMapping(
$hostName,
$privateKey,
$certificate,
$intermediateCertificate = null
) {
$certificateMapping = $this->certificateMapping(
array(
'hostName' => $hostName,
'privateKey' => $privateKey,
'certificate' => $certificate,
'intermediateCertificate' => $intermediateCertificate
)
);
$json = json_encode($certificateMapping->createJson());
$request = $this->getClient()->post($certificateMapping->getUrl(), self::getJsonHeader(), $json);
return $this->getClient()->send($request);
}
/**
* Updates a certificate mapping.
*
* @param int $id ID of the certificate mapping.
* @param string $hostName (Optional) The domain name of the certificate.
* @param string $privateKey (Optional) The private key for the certificate.
* @param string $certificate The certificate itself.
* @param string $intermediateCertificate The intermediate certificate chain.
* @return array An array of \Guzzle\Http\Message\Response objects.
*/
public function updateCertificateMapping(
$id,
$hostName = null,
$privateKey = null,
$certificate = null,
$intermediateCertificate = null
) {
$certificateMapping = $this->certificateMapping($id);
return $certificateMapping->update(
array(
'hostName' => $hostName,
'privateKey' => $privateKey,
'certificate' => $certificate,
'intermediateCertificate' => $intermediateCertificate
)
);
}
/**
* Remove a certificate mapping.
*
* @param int $id ID of the certificate mapping.
* @return \Guzzle\Http\Message\Response
*/
public function removeCertificateMapping($id)
{
return $this->certificateMapping($id)->delete();
}
/**
* Return the session persistence resource
*
* @return \OpenCloud\LoadBalancer\Resource\SessionPersistence
*/
public function sessionPersistence()
{
return $this->getService()->resource('SessionPersistence', null, $this);
}
/**
* Returns the load balancer's error page object
*
* @return \OpenCloud\LoadBalancer\Resource\ErrorPage
*/
public function errorPage()
{
return $this->getService()->resource('ErrorPage', null, $this);
}
/**
* Returns the load balancer's health monitor object
*
* @return \OpenCloud\LoadBalancer\Resource\HealthMonitor
*/
public function healthMonitor()
{
return $this->getService()->resource('HealthMonitor', null, $this);
}
/**
* Returns statistics on the load balancer operation
*
* @return \OpenCloud\LoadBalancer\Resource\Stats
*/
public function stats()
{
return $this->getService()->resource('Stats', null, $this);
}
/**
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function usage()
{
return $this->getService()->resourceList('UsageRecord', null, $this);
}
/**
* Return an access resource
*
* @return \OpenCloud\LoadBalancer\Resource\Access
*/
public function access($data = null)
{
return $this->getService()->resource('Access', $data, $this);
}
/**
* Creates an access list. You must provide an array of \stdClass objects,
* each of which contains `type' and `address' properties. Valid types for
* the former are: "DENY" or "ALLOW". The address must be a valid IP
* address, either v4 or v6.
*
* @param stdClass[] $list
*
* @return \Guzzle\Http\Message\Response
*/
public function createAccessList(array $list)
{
$url = $this->getUrl();
$url->addPath('accesslist');
$json = json_encode($list);
$this->checkJsonError();
return $this->getClient()->post($url, self::getJsonHeader(), $json)->send();
}
/**
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function accessList()
{
return $this->getService()->resourceList('Access', null, $this);
}
/**
* Return a connection throttle resource
*
* @return \OpenCloud\LoadBalancer\Resource\ConnectionThrottle
*/
public function connectionThrottle()
{
return $this->getService()->resource('ConnectionThrottle', null, $this);
}
/**
* Find out whether connection logging is enabled for this load balancer
*
* @return bool Returns TRUE if enabled, FALSE if not
*/
public function hasConnectionLogging()
{
$url = clone $this->getUrl();
$url->addPath('connectionlogging');
$response = $this->getClient()->get($url)->send()->json();
return isset($response['connectionLogging']['enabled'])
&& $response['connectionLogging']['enabled'] === true;
}
/**
* Set the connection logging setting for this load balancer
*
* @param $bool Set to TRUE to enable, FALSE to disable
* @return \Guzzle\Http\Message\Response
*/
public function enableConnectionLogging($bool)
{
$url = clone $this->getUrl();
$url->addPath('connectionlogging');
$body = array('connectionLogging' => (bool) $bool);
return $this->getClient()->put($url, self::getJsonHeader(), $body)->send();
}
/**
* @deprecated
*/
public function connectionLogging()
{
$this->getLogger()->warning(Logger::deprecated(__METHOD__, 'hasConnectionLogging or enableConnectionLogging'));
}
/**
* Find out whether content caching is enabled for this load balancer
*
* @return bool Returns TRUE if enabled, FALSE if not
*/
public function hasContentCaching()
{
$url = clone $this->getUrl();
$url->addPath('contentcaching');
$response = $this->getClient()->get($url)->send()->json();
return isset($response['contentCaching']['enabled'])
&& $response['contentCaching']['enabled'] === true;
}
/**
* Set the content caching setting for this load balancer
*
* @param $bool Set to TRUE to enable, FALSE to disable
* @return \Guzzle\Http\Message\Response
*/
public function enableContentCaching($bool)
{
$url = clone $this->getUrl();
$url->addPath('contentcaching');
$body = array('contentCaching' => array('enabled' => (bool) $bool));
$body = json_encode($body);
$this->checkJsonError();
return $this->getClient()->put($url, self::getJsonHeader(), $body)->send();
}
/**
* @deprecated
*/
public function contentCaching()
{
$this->getLogger()->warning(sprintf(
'The %s method is deprecated, please use %s instead', __METHOD__, 'hasContentCaching or setContentCaching'));
}
/**
* Return a SSL Termination resource
*
* @return \OpenCloud\LoadBalancer\Resource\SSLTermination
*/
public function SSLTermination()
{
return $this->getService()->resource('SSLTermination', null, $this);
}
/**
* Return a metadata item
*
* @return \OpenCloud\LoadBalancer\Resource\Metadata
*/
public function metadata($data = null)
{
return $this->getService()->resource('Metadata', $data, $this);
}
/**
* Return a collection of metadata items
*
* @return \OpenCloud\Common\Collection\PaginatedIterator
*/
public function metadataList()
{
return $this->getService()->resourceList('Metadata', null, $this);
}
protected function createJson()
{
$element = (object) array();
foreach ($this->createKeys as $key) {
if ($key == 'nodes') {
foreach ($this->nodes as $node) {
$nodeObject = (object) array();
foreach ($node->createKeys as $key) {
if (!empty($node->$key)) {
$nodeObject->$key = $node->$key;
}
}
$element->nodes[] = (object) $nodeObject;
}
} elseif ($key == 'virtualIps') {
foreach ($this->virtualIps as $virtualIp) {
$element->virtualIps[] = $virtualIp;
}
} elseif (isset($this->$key)) {
$element->$key = $this->$key;
}
}
$object = (object) array($this->jsonName() => $element);
return $object;
}
protected function updateJson($params = array())
{
$updatableFields = array('name', 'algorithm', 'protocol', 'port', 'timeout', 'halfClosed', 'httpsRedirect');
$fields = array_keys($params);
foreach ($fields as $field) {
if (!in_array($field, $updatableFields)) {
throw new Exceptions\InvalidArgumentError("You cannot update $field.");
}
}
$object = new \stdClass();
$object->loadBalancer = new \stdClass();
foreach ($params as $name => $value) {
$object->loadBalancer->$name = $this->$name;
}
return $object;
}
}