forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
up.go
1546 lines (1366 loc) · 55.5 KB
/
up.go
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package docker
import (
"bytes"
"fmt"
"io"
"net"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/blang/semver"
cliconfig "github.com/docker/docker/cli/config"
dockerclient "github.com/docker/engine-api/client"
"github.com/docker/engine-api/types/versions"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
kclientcmd "k8s.io/client-go/tools/clientcmd"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
configapi "github.com/openshift/origin/pkg/cmd/server/api"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
"github.com/openshift/origin/pkg/cmd/util/variable"
"github.com/openshift/origin/pkg/oc/bootstrap/docker/dockerhelper"
"github.com/openshift/origin/pkg/oc/bootstrap/docker/dockermachine"
"github.com/openshift/origin/pkg/oc/bootstrap/docker/errors"
"github.com/openshift/origin/pkg/oc/bootstrap/docker/host"
"github.com/openshift/origin/pkg/oc/bootstrap/docker/openshift"
"github.com/openshift/origin/pkg/oc/cli/util/clientcmd"
osclientcmd "github.com/openshift/origin/pkg/oc/cli/util/clientcmd"
)
const (
// CmdUpRecommendedName is the recommended command name
CmdUpRecommendedName = "up"
initialUser = "developer"
initialPassword = "developer"
initialProjectName = "myproject"
initialProjectDisplay = "My Project"
initialProjectDesc = "Initial developer project"
defaultRedirectClient = "openshift-web-console"
developmentRedirectURI = "https://localhost:9000"
dockerAPIVersion122 = "1.22"
)
var (
cmdUpLong = templates.LongDesc(`
Starts an OpenShift cluster using Docker containers, provisioning a registry, router,
initial templates, and a default project.
This command will attempt to use an existing connection to a Docker daemon. Before running
the command, ensure that you can execute docker commands successfully (i.e. 'docker ps').
Optionally, the command can create a new Docker machine for OpenShift using the VirtualBox
driver when the --create-machine argument is specified. The machine will be named 'openshift'
by default. To name the machine differently, use the --docker-machine=NAME argument. If the
--docker-machine=NAME argument is specified, but --create-machine is not, the command will attempt
to find an existing docker machine with that name and start it if it's not running.
By default, the OpenShift cluster will be setup to use a routing suffix that ends in nip.io.
This is to allow dynamic host names to be created for routes. An alternate routing suffix
can be specified using the --routing-suffix flag.
A public hostname can also be specified for the server with the --public-hostname flag.`)
cmdUpExample = templates.Examples(`
# Start OpenShift on a new docker machine named 'openshift'
%[1]s --create-machine
# Start OpenShift using a specific public host name
%[1]s --public-hostname=my.address.example.com
# Start OpenShift and preserve data and config between restarts
%[1]s --host-data-dir=/mydata --use-existing-config
# Use a different set of images
%[1]s --image="registry.example.com/origin" --version="v1.1"
# Specify which set of image streams to use
%[1]s --image-streams=centos7`)
imageStreams = map[string]string{
"centos7": "examples/image-streams/image-streams-centos7.json",
"rhel7": "examples/image-streams/image-streams-rhel7.json",
}
// defaultImageStreams is the default key for the above imageStreams mapping.
// It should be set during build via -ldflags.
defaultImageStreams string
templateLocations = map[string]string{
"mongodb": "examples/db-templates/mongodb-persistent-template.json",
"mariadb": "examples/db-templates/mariadb-persistent-template.json",
"mysql": "examples/db-templates/mysql-persistent-template.json",
"postgresql": "examples/db-templates/postgresql-persistent-template.json",
"cakephp quickstart": "examples/quickstarts/cakephp-mysql-persistent.json",
"dancer quickstart": "examples/quickstarts/dancer-mysql-persistent.json",
"django quickstart": "examples/quickstarts/django-postgresql-persistent.json",
"nodejs quickstart": "examples/quickstarts/nodejs-mongodb-persistent.json",
"rails quickstart": "examples/quickstarts/rails-postgresql-persistent.json",
"jenkins pipeline persistent": "examples/jenkins/jenkins-persistent-template.json",
"sample pipeline": "examples/jenkins/pipeline/samplepipeline.yaml",
}
// internalTemplateLocations are templates that will be registered in an internal namespace. These
// templates are compatible with both vN and vN-1 clusters. If they are not, they should be moved
// into the internalCurrent and internalPrevious maps.
internalTemplateLocations = map[string]string{
"service catalog": "examples/service-catalog/service-catalog.yaml",
"template service broker rbac": "install/templateservicebroker/rbac-template.yaml",
"template service broker registration": "install/service-catalog-broker-resources/template-service-broker-registration.yaml",
}
// internalCurrentTemplateLocations are templates that will be registered in an internal namespace.
// These templates are for the current version of openshift (vN), for when the client version matches
// the cluster version.
internalCurrentTemplateLocations = map[string]string{
"web console server template": "install/origin-web-console/console-template.yaml",
"web console server rbac": "install/origin-web-console/rbac-template.yaml",
"template service broker apiserver": "install/templateservicebroker/apiserver-template.yaml",
}
// internalPreviousTemplateLocations are templates that will be registered in an internal namespace.
// These templates are for the previous version of openshift (vN-1) to provide N-1 support for older
// clusters from a newer client.
internalPreviousTemplateLocations = map[string]string{
"template service broker apiserver": "install/templateservicebroker/previous/apiserver-template.yaml",
}
// loggingTemplateLocations are templates that will be registered in an internal namespace
// when logging is requested
loggingTemplateLocations = map[string]string{
"logging": "examples/logging/logging-deployer.yaml",
}
adminTemplateLocations = map[string]string{
"prometheus": "examples/prometheus/prometheus.yaml",
"heapster standalone": "examples/heapster/heapster-standalone.yaml",
}
openshiftVersion36 = semver.MustParse("3.6.0")
openshiftVersion37 = semver.MustParse("3.7.0")
openshiftVersion39 = semver.MustParse("3.9.0")
)
// NewCmdUp creates a command that starts OpenShift on Docker with reasonable defaults
func NewCmdUp(name, fullName string, f *osclientcmd.Factory, out, errout io.Writer) *cobra.Command {
config := &ClientStartConfig{
CommonStartConfig: CommonStartConfig{
Out: out,
UsePorts: openshift.DefaultPorts,
PortForwarding: defaultPortForwarding(),
DNSPort: openshift.DefaultDNSPort,
checkAlternatePorts: true,
},
}
cmd := &cobra.Command{
Use: name,
Short: "Start OpenShift on Docker with reasonable defaults",
Long: cmdUpLong,
Example: fmt.Sprintf(cmdUpExample, fullName),
Run: func(c *cobra.Command, args []string) {
kcmdutil.CheckErr(config.Complete(f, c))
kcmdutil.CheckErr(config.Validate(out, errout))
if err := config.Start(out); err != nil {
os.Exit(1)
}
},
}
config.Bind(cmd.Flags())
return cmd
}
// taskFunc is a function that executes a start task
type taskFunc func(io.Writer) error
// conditionFunc determines whether a task should be run on start
type conditionFunc func() bool
// task is a named task for the start process
type task struct {
name string
fn taskFunc
condition conditionFunc
stdOut bool // true if task's output should go directly to stdout
}
func simpleTask(name string, fn taskFunc) task {
return task{name: name, fn: fn}
}
func conditionalTask(name string, fn taskFunc, condition conditionFunc) task {
return task{name: name, fn: fn, condition: condition}
}
type CommonStartConfig struct {
ImageVersion string
Image string
ImageStreams string
DockerMachine string
ShouldCreateDockerMachine bool
SkipRegistryCheck bool
ShouldInstallMetrics bool
ShouldInstallLogging bool
ShouldInstallServiceCatalog bool
PortForwarding bool
Out io.Writer
Tasks []task
HostName string
LocalConfigDir string
UseExistingConfig bool
Environment []string
ServerLogLevel int
HostVolumesDir string
HostConfigDir string
HostDataDir string
UsePorts []int
DNSPort int
ServerIP string
AdditionalIPs []string
UseNsenterMount bool
PublicHostname string
RoutingSuffix string
HostPersistentVolumesDir string
HTTPProxy string
HTTPSProxy string
NoProxy []string
CACert string
PVCount int
dockerClient dockerhelper.Interface
dockerHelper *dockerhelper.Helper
hostHelper *host.HostHelper
openshiftHelper *openshift.Helper
factory *clientcmd.Factory
originalFactory *clientcmd.Factory
command *cobra.Command
usingDefaultImages bool
usingDefaultOpenShiftImage bool
checkAlternatePorts bool
isRHDocker bool
shouldInitializeData *bool
shouldCreateUser *bool
containerNetworkErr chan error
}
func (c *CommonStartConfig) addTask(t task) {
c.Tasks = append(c.Tasks, t)
}
func (config *CommonStartConfig) Bind(flags *pflag.FlagSet) {
flags.BoolVar(&config.ShouldCreateDockerMachine, "create-machine", false, "Create a Docker machine if one doesn't exist")
flags.StringVar(&config.DockerMachine, "docker-machine", "", "Specify the Docker machine to use")
flags.StringVar(&config.ImageVersion, "version", "", "Specify the tag for OpenShift images")
flags.StringVar(&config.Image, "image", variable.DefaultImagePrefix, "Specify the images to use for OpenShift")
flags.StringVar(&config.ImageStreams, "image-streams", defaultImageStreams, "Specify which image streams to use, centos7|rhel7")
flags.BoolVar(&config.SkipRegistryCheck, "skip-registry-check", false, "Skip Docker daemon registry check")
flags.StringVar(&config.PublicHostname, "public-hostname", "", "Public hostname for OpenShift cluster")
flags.StringVar(&config.RoutingSuffix, "routing-suffix", "", "Default suffix for server routes")
flags.BoolVar(&config.UseExistingConfig, "use-existing-config", false, "Use existing configuration if present")
flags.StringVar(&config.HostConfigDir, "host-config-dir", host.DefaultConfigDir, "Directory on Docker host for OpenShift configuration")
flags.StringVar(&config.HostVolumesDir, "host-volumes-dir", host.DefaultVolumesDir, "Directory on Docker host for OpenShift volumes")
flags.StringVar(&config.HostDataDir, "host-data-dir", "", "Directory on Docker host for OpenShift data. If not specified, etcd data will not be persisted on the host.")
flags.StringVar(&config.HostPersistentVolumesDir, "host-pv-dir", host.DefaultPersistentVolumesDir, "Directory on host for OpenShift persistent volumes")
flags.BoolVar(&config.PortForwarding, "forward-ports", config.PortForwarding, "Use Docker port-forwarding to communicate with origin container. Requires 'socat' locally.")
flags.IntVar(&config.ServerLogLevel, "server-loglevel", 0, "Log level for OpenShift server")
flags.StringArrayVarP(&config.Environment, "env", "e", config.Environment, "Specify a key-value pair for an environment variable to set on OpenShift container")
flags.BoolVar(&config.ShouldInstallMetrics, "metrics", false, "Install metrics (experimental)")
flags.BoolVar(&config.ShouldInstallLogging, "logging", false, "Install logging (experimental)")
flags.BoolVar(&config.ShouldInstallServiceCatalog, "service-catalog", false, "Install service catalog (experimental).")
flags.StringVar(&config.HTTPProxy, "http-proxy", "", "HTTP proxy to use for master and builds")
flags.StringVar(&config.HTTPSProxy, "https-proxy", "", "HTTPS proxy to use for master and builds")
flags.StringArrayVar(&config.NoProxy, "no-proxy", config.NoProxy, "List of hosts or subnets for which a proxy should not be used")
}
// Validate validates that required fields in StartConfig have been populated
func (c *CommonStartConfig) Validate(out io.Writer) error {
if len(c.Tasks) == 0 {
return fmt.Errorf("no startup tasks to execute")
}
return nil
}
// Start runs the start tasks ensuring that they are executed in sequence
func (c *CommonStartConfig) Start(out io.Writer) error {
taskPrinter := NewTaskPrinter(out)
for _, task := range c.Tasks {
if task.condition != nil && !task.condition() {
continue
}
taskPrinter.StartTask(task.name)
w := taskPrinter.TaskWriter()
err := task.fn(w)
if err != nil {
taskPrinter.Failure(err)
return err
}
taskPrinter.Success()
}
return nil
}
// ClientStartConfig is the configuration for the client start command
type ClientStartConfig struct {
CommonStartConfig
}
func (config *ClientStartConfig) Bind(flags *pflag.FlagSet) {
config.CommonStartConfig.Bind(flags)
}
func (c *CommonStartConfig) Complete(f *osclientcmd.Factory, cmd *cobra.Command) error {
c.originalFactory = f
c.command = cmd
if len(c.ImageVersion) == 0 {
c.ImageVersion = defaultImageVersion()
}
c.addTask(simpleTask("Checking OpenShift client", c.CheckOpenShiftClient))
c.addTask(conditionalTask("Create Docker machine", c.CreateDockerMachine, func() bool { return c.ShouldCreateDockerMachine }))
// Get a Docker client.
// If a Docker machine was specified, make sure that the machine is running.
// Otherwise, use environment variables.
c.addTask(simpleTask("Checking Docker client", c.GetDockerClient))
// Check that we have the minimum Docker version available to run OpenShift
c.addTask(simpleTask("Checking Docker version", c.CheckDockerVersion))
// Check for an OpenShift container. If one exists and is running, exit.
// If one exists but not running, delete it.
c.addTask(simpleTask("Checking for existing OpenShift container", c.CheckExistingOpenShiftContainer))
// Ensure that the OpenShift Docker image is available.
// If not present, pull it.
t := simpleTask(fmt.Sprintf("Checking for %s image", c.openshiftImage()), c.CheckOpenShiftImage)
t.stdOut = true
c.addTask(t)
// Ensure that the Docker daemon has the right --insecure-registry argument.
// If not, then exit.
if !c.SkipRegistryCheck {
c.addTask(simpleTask("Checking Docker daemon configuration", c.CheckDockerInsecureRegistry))
}
// Ensure that ports used by OpenShift are available on the host machine
c.addTask(simpleTask("Checking for available ports", c.CheckAvailablePorts))
// Check whether the Docker host has the right binaries to use Kubernetes' nsenter mounter
// If not, use a shared volume to mount volumes on OpenShift
c.addTask(simpleTask("Checking type of volume mount", c.CheckNsenterMounter))
// Ensure that host directories exist.
// If not using the nsenter mounter, create a volume share on the host machine to
// mount OpenShift volumes.
c.addTask(simpleTask("Creating host directories", c.EnsureHostDirectories))
// Determine an IP to use for OpenShift.
// The result is that c.ServerIP will be populated with
// the IP that will be used on the client configuration file.
// The c.ServerIP will be set to a specific IP when:
// 1 - DOCKER_HOST is populated with a particular tcp:// type of address
// 2 - a docker-machine has been specified
// 3 - 127.0.0.1 is not working and an alternate IP has been found
// Otherwise, the default c.ServerIP will be 127.0.0.1 which is what
// will get stored in the client's config file. The reason for this is that
// the client config will not depend on the machine's current IP address which
// could change over time.
//
// c.AdditionalIPs will be populated with additional IPs that should be
// included in the server's certificate. These include any IPs that are currently
// assigned to the Docker host (hostname -I)
// Each IP is tested to ensure that it can be accessed from the current client
c.addTask(simpleTask("Finding server IP", c.DetermineServerIP))
return nil
}
// Complete initializes fields based on command parameters and execution environment
func (c *ClientStartConfig) Complete(f *osclientcmd.Factory, cmd *cobra.Command) error {
if err := c.CommonStartConfig.Complete(f, cmd); err != nil {
return err
}
// Check if the openshift server version is sufficient to run the service catalog.
// Do this first so we can fail quickly if it's not.
c.addTask(conditionalTask("Checking service catalog version requirements", c.CheckServiceCatalogPrereqVersion, func() bool {
return c.ShouldInstallServiceCatalog
}))
// Create an OpenShift configuration and start a container that uses it.
c.addTask(simpleTask("Starting OpenShift container", c.StartOpenShift))
// Add default redirect URIs to an OAuthClient to enable local web-console development.
c.addTask(conditionalTask("Adding default OAuthClient redirect URIs", c.EnsureDefaultRedirectURIs, c.ShouldInitializeData))
// Install a registry
c.addTask(conditionalTask("Installing registry", c.InstallRegistry, c.ShouldInitializeData))
// Install a router
c.addTask(conditionalTask("Installing router", c.InstallRouter, c.ShouldInitializeData))
// Install metrics
c.addTask(conditionalTask("Installing metrics", c.InstallMetrics, func() bool {
return c.ShouldInstallMetrics && c.ShouldInitializeData()
}))
// Import default image streams
c.addTask(conditionalTask("Importing image streams", c.ImportImageStreams, c.ShouldInitializeData))
// Import templates
c.addTask(conditionalTask("Importing templates", c.ImportTemplates, c.ShouldInitializeData))
// Import internal templates
c.addTask(conditionalTask("Importing internal templates", c.ImportInternalTemplates, c.ShouldInitializeData))
// Import logging templates
c.addTask(conditionalTask("Importing logging templates", c.ImportLoggingTemplates, func() bool {
return c.ShouldInstallLogging && c.ShouldInitializeData()
}))
// Install logging
c.addTask(conditionalTask("Installing logging", c.InstallLogging, func() bool {
return c.ShouldInstallLogging && c.ShouldInitializeData()
}))
// Install service catalog
c.addTask(conditionalTask("Installing service catalog", c.InstallServiceCatalog, func() bool {
return c.ShouldInstallServiceCatalog && c.ShouldInitializeData()
}))
// Install template service broker if our version is high enough
c.addTask(conditionalTask("Installing template service broker", c.InstallTemplateServiceBroker, func() bool {
return c.ShouldInstallServiceCatalog && c.ShouldInitializeData()
}))
// Register the TSB w/ the SC if requested. This is done even when reusing a config because
// the TSB registration is not persisted.
c.addTask(conditionalTask("Registering template service broker with service catalog", c.RegisterTemplateServiceBroker, func() bool {
return c.ShouldInstallServiceCatalog
}))
// Install the web console. Do this after the template service broker is installed so that
// the console can discover that the broker is running on startup.
c.addTask(conditionalTask("Installing web console", c.InstallWebConsole, func() bool {
serverVersion, _ := c.OpenShiftHelper().ServerVersion()
return clusterVersionIsCurrent(serverVersion) && c.ShouldInitializeData()
}))
// Login with an initial default user
c.addTask(conditionalTask("Login to server", c.Login, c.ShouldCreateUser))
// Create an initial project
c.addTask(conditionalTask(fmt.Sprintf("Creating initial project %q", initialProjectName), c.CreateProject, c.ShouldCreateUser))
// Remove temporary directory
c.addTask(simpleTask("Removing temporary directory", c.RemoveTemporaryDirectory))
// Check container networking (only when loglevel > 0)
if glog.V(1) {
c.addTask(simpleTask("Checking container networking", c.CheckContainerNetworking))
}
// Display server information
c.addTask(simpleTask("Server Information", c.ServerInfo))
return nil
}
// Validate validates that required fields in StartConfig have been populated
func (c *ClientStartConfig) Validate(out, errout io.Writer) error {
cmdutil.WarnAboutCommaSeparation(errout, c.Environment, "--env")
if len(c.Tasks) == 0 {
return fmt.Errorf("no startup tasks to execute")
}
return nil
}
// Start runs the start tasks ensuring that they are executed in sequence
func (c *ClientStartConfig) Start(out io.Writer) error {
var detailedOut io.Writer
// When loglevel > 0, just use stdout to write all messages
if glog.V(1) {
detailedOut = out
} else {
fmt.Fprintf(out, "Starting OpenShift using %s ...\n", c.openshiftImage())
detailedOut = &bytes.Buffer{}
}
taskPrinter := NewTaskPrinter(detailedOut)
startError := func() error {
for _, task := range c.Tasks {
if task.condition != nil && !task.condition() {
continue
}
taskPrinter.StartTask(task.name)
w := taskPrinter.TaskWriter()
if task.stdOut && !bool(glog.V(1)) {
w = io.MultiWriter(w, out)
}
err := task.fn(w)
if err != nil {
taskPrinter.Failure(err)
return err
}
taskPrinter.Success()
}
return nil
}()
if startError != nil {
if !bool(glog.V(1)) {
fmt.Fprintf(out, "%s", detailedOut.(*bytes.Buffer).String())
}
return startError
}
if !bool(glog.V(1)) {
c.ServerInfo(out)
}
return nil
}
func defaultPortForwarding() bool {
// Defaults to true if running on Mac, with no DOCKER_HOST defined
return runtime.GOOS == "darwin" && len(os.Getenv("DOCKER_HOST")) == 0
}
const defaultDockerMachineName = "openshift"
func defaultImageVersion() string {
return variable.OverrideVersion.LastSemanticVersion()
}
// CreateDockerMachine will create a new Docker machine to run OpenShift
func (c *CommonStartConfig) CreateDockerMachine(out io.Writer) error {
if len(c.DockerMachine) == 0 {
c.DockerMachine = defaultDockerMachineName
}
fmt.Fprintf(out, "Creating docker-machine %s\n", c.DockerMachine)
return dockermachine.NewBuilder().Name(c.DockerMachine).Create()
}
// CheckOpenShiftClient ensures that the client can be configured
// for the new server
func (c *CommonStartConfig) CheckOpenShiftClient(out io.Writer) error {
kubeConfig := os.Getenv("KUBECONFIG")
if len(kubeConfig) == 0 {
return nil
}
var (
kubeConfigError error
f *os.File
)
_, err := os.Stat(kubeConfig)
switch {
case os.IsNotExist(err):
err = os.MkdirAll(filepath.Dir(kubeConfig), 0755)
if err != nil {
kubeConfigError = fmt.Errorf("cannot make directory: %v", err)
break
}
f, err = os.Create(kubeConfig)
if err != nil {
kubeConfigError = fmt.Errorf("cannot create file: %v", err)
break
}
f.Close()
case err == nil:
f, err = os.OpenFile(kubeConfig, os.O_RDWR, 0644)
if err != nil {
kubeConfigError = fmt.Errorf("cannot open %s for write: %v", kubeConfig, err)
break
}
f.Close()
default:
kubeConfigError = fmt.Errorf("cannot access %s: %v", kubeConfig, err)
}
if kubeConfigError != nil {
return errors.ErrKubeConfigNotWriteable(kubeConfig, kubeConfigError)
}
return nil
}
// GetDockerClient obtains a new Docker client from the environment or
// from a Docker machine, starting it if necessary
func (c *CommonStartConfig) GetDockerClient(out io.Writer) error {
client, err := getDockerClient(out, c.DockerMachine, true)
if err != nil {
return err
}
c.dockerClient = client
return nil
}
// getDockerClient obtains a new Docker client from the environment or
// from a Docker machine, starting it if necessary and permitted
func getDockerClient(out io.Writer, dockerMachine string, canStartDockerMachine bool) (dockerhelper.Interface, error) {
if len(dockerMachine) > 0 {
glog.V(2).Infof("Getting client for Docker machine %q", dockerMachine)
client, err := getDockerMachineClient(dockerMachine, out, canStartDockerMachine)
if err != nil {
return nil, errors.ErrNoDockerMachineClient(dockerMachine, err)
}
return client, nil
}
dockerTLSVerify := os.Getenv("DOCKER_TLS_VERIFY")
dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
if len(dockerTLSVerify) > 0 && len(dockerCertPath) == 0 {
dockerCertPath = cliconfig.Dir()
os.Setenv("DOCKER_CERT_PATH", dockerCertPath)
}
if glog.V(4) {
dockerHost := os.Getenv("DOCKER_HOST")
if len(dockerHost) == 0 && len(dockerTLSVerify) == 0 && len(dockerCertPath) == 0 {
glog.Infof("No Docker environment variables found. Will attempt default socket.")
}
if len(dockerHost) > 0 {
glog.Infof("Will try Docker connection with host (DOCKER_HOST) %q", dockerHost)
} else {
glog.Infof("No Docker host (DOCKER_HOST) configured. Will attempt default socket.")
}
if len(dockerTLSVerify) > 0 {
glog.Infof("DOCKER_TLS_VERIFY=%s", dockerTLSVerify)
}
if len(dockerCertPath) > 0 {
glog.Infof("DOCKER_CERT_PATH=%s", dockerCertPath)
}
}
// FIXME: Workaround for docker engine API client on OS X - sets the default to
// the wrong DOCKER_HOST string
if runtime.GOOS == "darwin" {
dockerHost := os.Getenv("DOCKER_HOST")
if len(dockerHost) == 0 {
os.Setenv("DOCKER_HOST", "unix:///var/run/docker.sock")
}
}
host := os.Getenv("DOCKER_HOST")
if len(host) == 0 {
host = dockerclient.DefaultDockerHost
}
engineAPIClient, err := dockerclient.NewEnvClient()
if err != nil {
return nil, errors.ErrNoDockerClient(err)
}
return dockerhelper.NewClient(host, engineAPIClient), nil
}
// CheckExistingOpenShiftContainer checks the state of an OpenShift container.
// If one is already running, it throws an error.
// If one exists, it removes it so a new one can be created.
func (c *CommonStartConfig) CheckExistingOpenShiftContainer(out io.Writer) error {
container, running, err := c.DockerHelper().GetContainerState(openshift.OpenShiftContainer)
if err != nil {
return errors.NewError("unexpected error while checking OpenShift container state").WithCause(err)
}
if running {
return errors.NewError("OpenShift is already running").WithSolution("To start OpenShift again, stop the current cluster:\n$ %s\n", strings.Join(cmdutil.SiblingCommand(c.command, "down"), " "))
}
if container != nil {
err = c.DockerHelper().RemoveContainer(openshift.OpenShiftContainer)
if err != nil {
return errors.NewError("cannot delete existing OpenShift container").WithCause(err)
}
fmt.Fprintf(out, "Deleted existing OpenShift container\n")
}
return nil
}
// CheckOpenShiftImage checks whether the OpenShift image exists.
// If not it tells the Docker daemon to pull it.
func (c *CommonStartConfig) CheckOpenShiftImage(out io.Writer) error {
return c.DockerHelper().CheckAndPull(c.openshiftImage(), out)
}
// CheckDockerInsecureRegistry checks to see if the Docker daemon has an appropriate insecure registry argument set so that our services can access the registry
func (c *CommonStartConfig) CheckDockerInsecureRegistry(out io.Writer) error {
configured, hasEntries, err := c.DockerHelper().InsecureRegistryIsConfigured()
if err != nil {
return err
}
if !configured {
if hasEntries {
return errors.ErrInvalidInsecureRegistryArgument()
}
return errors.ErrNoInsecureRegistryArgument()
}
return nil
}
// CheckNsenterMounter checks whether the Docker host can use the nsenter mounter from Kubernetes.
// Otherwise, a shared volume is needed in Docker
func (c *CommonStartConfig) CheckNsenterMounter(out io.Writer) error {
useNsenterMount, err := c.HostHelper().CanUseNsenterMounter()
if err != nil {
return err
}
if useNsenterMount && c.isRHDocker {
c.UseNsenterMount = true
fmt.Fprintf(out, "Using nsenter mounter for OpenShift volumes\n")
} else {
c.UseNsenterMount = false
fmt.Fprintf(out, "Using Docker shared volumes for OpenShift volumes\n")
}
return nil
}
// CheckDockerVersion checks that the appropriate Docker version is installed based on whether we are using the nsenter mounter
// or shared volumes for OpenShift
func (c *CommonStartConfig) CheckDockerVersion(out io.Writer) error {
ver, isRHDocker, err := c.DockerHelper().APIVersion()
if err != nil {
glog.V(2).Infof("Failed to check Docker API version: %v", err)
fmt.Fprintf(out, "WARNING: Cannot verify Docker version\n")
return nil
}
c.isRHDocker = isRHDocker
glog.V(5).Infof("Checking that docker API version is at least %v", dockerAPIVersion122)
if versions.LessThan(ver, dockerAPIVersion122) {
fmt.Fprintf(out, "WARNING: Docker version is %v, it needs to be >= %v\n", ver, dockerAPIVersion122)
}
return nil
}
func (c *CommonStartConfig) EnsureHostDirectories(io.Writer) error {
return c.HostHelper().EnsureHostDirectories(!c.UseNsenterMount)
}
// EnsureDefaultRedirectURIs merges a default URL to an auth client's RedirectURIs array
func (c *ClientStartConfig) EnsureDefaultRedirectURIs(out io.Writer) error {
factory, err := c.Factory()
if err != nil {
return err
}
oauthClient, err := factory.OpenshiftInternalOAuthClient()
if err != nil {
return err
}
webConsoleOAuth, err := oauthClient.Oauth().OAuthClients().Get(defaultRedirectClient, metav1.GetOptions{})
if err != nil {
if kerrors.IsNotFound(err) {
fmt.Fprintf(out, "Unable to find OAuthClient %q\n", defaultRedirectClient)
return nil
}
// announce fetch error without interrupting remaining tasks
suggestedCmd := fmt.Sprintf("oc patch %s/%s -p '{%q:[%q]}'", "oauthclient", defaultRedirectClient, "redirectURIs", developmentRedirectURI)
errMsg := fmt.Sprintf("Unable to fetch OAuthClient %q.\nTo manually add a development redirect URI, run %q\n", defaultRedirectClient, suggestedCmd)
fmt.Fprintf(out, "%s\n", errMsg)
return nil
}
// ensure the default redirect URI is not already present
redirects := sets.NewString(webConsoleOAuth.RedirectURIs...)
if redirects.Has(developmentRedirectURI) {
return nil
}
webConsoleOAuth.RedirectURIs = append(webConsoleOAuth.RedirectURIs, developmentRedirectURI)
_, err = oauthClient.Oauth().OAuthClients().Update(webConsoleOAuth)
if err != nil {
// announce error without interrupting remaining tasks
suggestedCmd := fmt.Sprintf("oc patch %s/%s -p '{%q:[%q]}'", "oauthclient", defaultRedirectClient, "redirectURIs", developmentRedirectURI)
errMsg := fmt.Sprintf("Unable to add development redirect URI to the %q OAuthClient.\nTo manually add it, run %q\n", defaultRedirectClient, suggestedCmd)
fmt.Fprintf(out, "%s\n", errMsg)
return nil
}
return nil
}
// CheckAvailablePorts ensures that ports used by OpenShift are available on the Docker host
func (c *CommonStartConfig) CheckAvailablePorts(out io.Writer) error {
if !c.checkAlternatePorts {
err := c.OpenShiftHelper().TestPorts(openshift.DefaultPorts)
if err == nil {
return nil
}
return errors.NewError("a port needed by OpenShift is not available").WithCause(err)
}
err := c.OpenShiftHelper().TestPorts(openshift.AllPorts)
if err == nil {
return nil
}
if !openshift.IsPortsNotAvailableErr(err) {
return err
}
unavailable := sets.NewInt(openshift.UnavailablePorts(err)...)
if unavailable.HasAny(openshift.BasePorts...) {
return errors.NewError("a port needed by OpenShift is not available").WithCause(err)
}
if unavailable.Has(openshift.DefaultDNSPort) {
if unavailable.Has(openshift.AlternateDNSPort) {
return errors.NewError("a port needed by OpenShift is not available").WithCause(err)
}
c.DNSPort = openshift.AlternateDNSPort
fmt.Fprintf(out, "WARNING: Binding DNS on port %d instead of 53, which may not be resolvable from all clients.\n", openshift.AlternateDNSPort)
}
for _, port := range openshift.RouterPorts {
if unavailable.Has(port) {
fmt.Fprintf(out, "WARNING: Port %d is already in use and may cause routing issues for applications.\n", port)
}
}
return nil
}
// DetermineServerIP gets an appropriate IP address to communicate with the OpenShift server
func (c *CommonStartConfig) DetermineServerIP(out io.Writer) error {
ip, err := c.determineIP(out)
if err != nil {
return errors.NewError("cannot determine a server IP to use").WithCause(err)
}
c.ServerIP = ip
fmt.Fprintf(out, "Using %s as the server IP\n", c.ServerIP)
c.AdditionalIPs, err = c.determineAdditionalIPs(c.ServerIP)
if err != nil {
return errors.NewError("cannot determine additional IPs").WithCause(err)
}
glog.V(4).Infof("Additional server IPs: %v", c.AdditionalIPs)
return nil
}
// updateNoProxy will add some default values to the NO_PROXY setting if they are not present
func (c *ClientStartConfig) updateNoProxy() {
values := []string{"127.0.0.1", c.ServerIP, "localhost", openshift.RegistryServiceIP, openshift.ServiceCatalogServiceIP, "172.30.0.0/8"}
ipFromServer, err := c.OpenShiftHelper().ServerIP()
if err == nil {
values = append(values, ipFromServer)
}
noProxySet := sets.NewString(c.NoProxy...)
for _, v := range values {
if !noProxySet.Has(v) {
noProxySet.Insert(v)
c.NoProxy = append(c.NoProxy, v)
}
}
}
// StartOpenShift starts the OpenShift container
func (c *ClientStartConfig) StartOpenShift(out io.Writer) error {
var err error
if len(c.HTTPProxy) > 0 || len(c.HTTPSProxy) > 0 {
c.updateNoProxy()
}
dockerRoot, err := c.DockerHelper().DockerRoot()
if err != nil {
return err
}
opt := &openshift.StartOptions{
ServerIP: c.ServerIP,
AdditionalIPs: c.AdditionalIPs,
RoutingSuffix: c.RoutingSuffix,
UseSharedVolume: !c.UseNsenterMount,
Images: c.imageFormat(),
HostVolumesDir: c.HostVolumesDir,
HostConfigDir: c.HostConfigDir,
HostDataDir: c.HostDataDir,
HostPersistentVolumesDir: c.HostPersistentVolumesDir,
UseExistingConfig: c.UseExistingConfig,
Environment: c.Environment,
LogLevel: c.ServerLogLevel,
DNSPort: c.DNSPort,
PortForwarding: c.PortForwarding,
HTTPProxy: c.HTTPProxy,
HTTPSProxy: c.HTTPSProxy,
NoProxy: c.NoProxy,
DockerRoot: dockerRoot,
ServiceCatalog: c.ShouldInstallServiceCatalog,
}
if c.ShouldInstallMetrics {
opt.MetricsHost = openshift.MetricsHost(c.RoutingSuffix, c.ServerIP)
}
if c.ShouldInstallLogging {
opt.LoggingHost = openshift.LoggingHost(c.RoutingSuffix, c.ServerIP)
}
c.LocalConfigDir, err = c.OpenShiftHelper().Start(opt, out)
if err != nil {
return err
}
serverIP, err := c.OpenShiftHelper().ServerIP()
if err != nil {
return err
}
// Start a container networking test
c.containerNetworkErr = make(chan error)
go func() {
c.containerNetworkErr <- c.OpenShiftHelper().TestContainerNetworking(serverIP)
}()
// Setup persistent storage
_, kClient, err := c.Clients()
if err != nil {
return err
}
factory, err := c.Factory()
if err != nil {
return err
}
authorizationClient, err := factory.OpenshiftInternalAuthorizationClient()
if err != nil {
return err
}
securityClient, err := factory.OpenshiftInternalSecurityClient()
if err != nil {
return err
}
// Remove any duplicate nodes
err = c.OpenShiftHelper().CheckNodes(kClient)
if err != nil {
return err
}
err = c.OpenShiftHelper().SetupPersistentStorage(authorizationClient.Authorization(), kClient, securityClient, c.HostPersistentVolumesDir, c.HostPersistentVolumesDir)
if err != nil {
return err
}
return nil
}
func (c *ClientStartConfig) CheckContainerNetworking(out io.Writer) error {
serverIP, err := c.OpenShiftHelper().ServerIP()
if err != nil {
return err
}
networkErr := <-c.containerNetworkErr
if networkErr != nil {
return errors.NewError("containers cannot communicate with the OpenShift master").
WithDetails("The cluster was started. However, the container networking test failed.").
WithSolution(
fmt.Sprintf("Ensure that access to ports tcp/8443, udp/53 and udp/8053 is allowed on %s.\n"+
"You may need to open these ports on your machine's firewall.", serverIP)).
WithCause(networkErr)
}
return nil
}
func (c *CommonStartConfig) imageFormat() string {
return fmt.Sprintf("%s-${component}:%s", c.Image, c.ImageVersion)
}
// InstallRegistry installs the OpenShift registry on the server
func (c *ClientStartConfig) InstallRegistry(out io.Writer) error {
_, kubeClient, err := c.Clients()
if err != nil {
return err
}
f, err := c.Factory()
if err != nil {
return err
}
return c.OpenShiftHelper().InstallRegistry(kubeClient, f, c.LocalConfigDir, c.imageFormat(), c.HostPersistentVolumesDir, out, os.Stderr)
}
// InstallRouter installs a default router on the server
func (c *ClientStartConfig) InstallRouter(out io.Writer) error {
_, kubeClient, err := c.Clients()
if err != nil {
return err
}
f, err := c.Factory()
if err != nil {
return err
}
return c.OpenShiftHelper().InstallRouter(kubeClient, f, c.LocalConfigDir, c.imageFormat(), c.ServerIP, c.PortForwarding, out, os.Stderr)
}
// InstallWebConsole installs the OpenShift web console on the server
func (c *ClientStartConfig) InstallWebConsole(out io.Writer) error {
f, err := c.Factory()
if err != nil {
return err
}
masterURL := c.OpenShiftHelper().Master(c.ServerIP)
if len(c.PublicHostname) > 0 {