Best Testkube code snippet using config.Get
start.go
Source:start.go
...145 // preflight checks (after start)146 preflightChecksAfterStartingHost(hostVm.Driver)147 // Adding active profile information to all instance config148 addActiveProfileInformation()149 ip, _ := hostVm.Driver.GetIP()150 if proxyConfig.IsEnabled() {151 // once we know the IP, we need to make sure it is not proxied in a proxy environment152 proxyConfig.AddNoProxy(ip)153 proxyConfig.ApplyToEnvironment()154 }155 applyDockerEnvToProcessEnv(libMachineClient)156 err := clusterup.EnsureHostDirectoriesExist(hostVm, getRequiredHostDirectories())157 if err != nil {158 atexit.ExitWithMessage(1, fmt.Sprintf("Error creating required host directories: %v", err))159 }160 autoMountHostFolders(hostVm.Driver)161 requestedOpenShiftVersion := viper.GetString(configCmd.OpenshiftVersion.Name)162 if !isRestart {163 importContainerImages(hostVm.Driver, libMachineClient, requestedOpenShiftVersion)164 }165 ocPath := cmdUtil.CacheOc(clusterup.DetermineOcVersion(requestedOpenShiftVersion))166 clusterUpConfig := &clusterup.ClusterUpConfig{167 OpenShiftVersion: requestedOpenShiftVersion,168 MachineName: constants.MachineName,169 Ip: ip,170 Port: constants.APIServerPort,171 RoutingSuffix: getDefaultRoutingPrefix(ip),172 HostPvDir: viper.GetString(configCmd.HostPvDir.Name),173 User: minishiftConstants.DefaultUser,174 Project: minishiftConstants.DefaultProject,175 KubeConfigPath: constants.KubeConfigPath,176 OcPath: ocPath,177 AddonEnv: viper.GetStringSlice(cmdUtil.AddOnEnv),178 PublicHostname: viper.GetString(configCmd.PublicHostname.Name),179 }180 clusterUpParams := determineClusterUpParameters(clusterUpConfig)181 fmt.Println("-- OpenShift cluster will be configured with ...")182 fmt.Println(" Version:", requestedOpenShiftVersion)183 err = clusterup.ClusterUp(clusterUpConfig, clusterUpParams, &util.RealRunner{})184 if err != nil {185 atexit.ExitWithMessage(1, fmt.Sprintf("Error during 'cluster up' execution: %v", err))186 }187 if !IsOpenShiftRunning(hostVm.Driver) {188 atexit.ExitWithMessage(1, "OpenShift provisioning failed. origin container failed to start.")189 }190 if !isRestart {191 postClusterUp(hostVm, clusterUpConfig)192 exportContainerImages(hostVm.Driver, libMachineClient, requestedOpenShiftVersion)193 }194 if isRestart {195 err = cmdUtil.SetOcContext(minishiftConfig.AllInstancesConfig.ActiveProfile)196 if err != nil {197 fmt.Println(fmt.Sprintf("Could not set oc CLI context for: %s", profileActions.GetActiveProfile()))198 }199 }200}201// postClusterUp performs configuration action which only need to be run after an initial provision of OpenShift.202// On subsequent VM restarts these actions can be skipped.203func postClusterUp(hostVm *host.Host, clusterUpConfig *clusterup.ClusterUpConfig) {204 sshCommander := provision.GenericSSHCommander{Driver: hostVm.Driver}205 err := clusterup.PostClusterUp(clusterUpConfig, sshCommander, addon.GetAddOnManager())206 if err != nil {207 atexit.ExitWithMessage(1, fmt.Sprintf("Error during post cluster up configuration: %v", err))208 }209}210// getRequiredHostDirectories returns a list of directories we need to ensure exist on the VM.211func getRequiredHostDirectories() []string {212 return []string{213 viper.GetString(configCmd.HostConfigDir.Name),214 viper.GetString(configCmd.HostDataDir.Name),215 viper.GetString(configCmd.HostVolumeDir.Name),216 viper.GetString(configCmd.HostPvDir.Name),217 }218}219func handleProxies() *util.ProxyConfig {220 proxyConfig, err := util.NewProxyConfig(viper.GetString(cmdUtil.HttpProxy), viper.GetString(cmdUtil.HttpsProxy), viper.GetString(configCmd.NoProxyList.Name))221 if err != nil {222 atexit.ExitWithMessage(1, err.Error())223 }224 if proxyConfig.IsEnabled() {225 proxyConfig.ApplyToEnvironment()226 dockerEnv = append(dockerEnv, proxyConfig.ProxyConfig()...)227 shellProxyEnv += strings.Join(proxyConfig.ProxyConfig(), " ")228 // It could be that the proxy config is retrieved from the environment. To make sure that229 // proxy settings are properly passed to cluster up we need to explicitly set the values.230 if proxyConfig.HttpProxy() != "" {231 viper.Set(cmdUtil.HttpProxy, proxyConfig.HttpProxy())232 }233 if proxyConfig.HttpsProxy() != "" {234 viper.Set(cmdUtil.HttpsProxy, proxyConfig.HttpsProxy())235 }236 viper.Set(configCmd.NoProxyList.Name, proxyConfig.NoProxy())237 }238 return proxyConfig239}240// getSlice return slice for provided key otherwise nil241func getSlice(key string) []string {242 if viper.IsSet(key) {243 return viper.GetStringSlice(key)244 }245 return nil246}247func determineInsecureRegistry(key string) []string {248 s := getSlice(key)249 if s != nil {250 for _, v := range s {251 if v == defaultInsecureRegistry {252 return s253 }254 }255 }256 return append(s, defaultInsecureRegistry)257}258func startHost(libMachineClient *libmachine.Client) *host.Host {259 progressDots := progressdots.New()260 // Configuration used for creation/setup of the Virtual Machine261 machineConfig := &cluster.MachineConfig{262 MinikubeISO: determineIsoUrl(viper.GetString(configCmd.ISOUrl.Name)),263 ISOCacheDir: state.InstanceDirs.IsoCache,264 Memory: calculateMemorySize(viper.GetString(configCmd.Memory.Name)),265 CPUs: viper.GetInt(configCmd.CPUs.Name),266 DiskSize: calculateDiskSize(viper.GetString(configCmd.DiskSize.Name)),267 VMDriver: viper.GetString(configCmd.VmDriver.Name),268 DockerEnv: append(dockerEnv, getSlice(configCmd.DockerEnv.Name)...),269 DockerEngineOpt: getSlice(configCmd.DockerEngineOpt.Name),270 InsecureRegistry: determineInsecureRegistry(configCmd.InsecureRegistry.Name),271 RegistryMirror: getSlice(configCmd.RegistryMirror.Name),272 HostOnlyCIDR: viper.GetString(configCmd.HostOnlyCIDR.Name),273 ShellProxyEnv: shellProxyEnv,274 }275 fmt.Printf(" using '%s' hypervisor ...\n", machineConfig.VMDriver)276 var hostVm *host.Host277 // configuration with these settings only happen on create278 isRestart := cmdUtil.VMExists(libMachineClient, constants.MachineName)279 if !isRestart {280 fmt.Println("-- Minishift VM will be configured with ...")281 fmt.Println(" Memory: ", units.HumanSize(float64((machineConfig.Memory/units.KiB)*units.GB)))282 fmt.Println(" vCPUs : ", machineConfig.CPUs)283 fmt.Println(" Disk size:", units.HumanSize(float64(machineConfig.DiskSize*units.MB)))284 }285 // Experimental features286 if minishiftConfig.EnableExperimental {287 networkSettings := minishiftNetwork.NetworkSettings{288 Device: viper.GetString(configCmd.NetworkDevice.Name),289 IPAddress: viper.GetString(configCmd.IPAddress.Name),290 Netmask: viper.GetString(configCmd.Netmask.Name),291 Gateway: viper.GetString(configCmd.Gateway.Name),292 DNS1: viper.GetString(configCmd.NameServer.Name),293 }294 // Configure networking on startup only works on Hyper-V295 if networkSettings.IPAddress != "" {296 minishiftNetwork.ConfigureNetworking(constants.MachineName, machineConfig.VMDriver, networkSettings)297 }298 }299 cacheMinishiftISO(machineConfig)300 fmt.Print("-- Starting Minishift VM ...")301 progressDots.Start()302 start := func() (err error) {303 hostVm, err = cluster.StartHost(libMachineClient, *machineConfig)304 if err != nil {305 fmt.Print(" FAIL ")306 glog.Errorf("Error starting the VM: %s. Retrying.\n", err)307 }308 return err309 }310 err := util.Retry(3, start)311 if err != nil {312 atexit.ExitWithMessage(1, fmt.Sprintf("Error starting the VM: %v", err))313 }314 progressDots.Stop()315 fmt.Println(" OK")316 return hostVm317}318func autoMountHostFolders(driver drivers.Driver) {319 if hostfolder.IsAutoMount() && hostfolder.IsHostfoldersDefined() {320 hostfolder.MountHostfolders(driver)321 }322}323func addActiveProfileInformation() {324 if constants.ProfileName != profileActions.GetActiveProfile() {325 fmt.Println(fmt.Sprintf("-- Switching active profile to '%s'", constants.ProfileName))326 err := profileActions.SetActiveProfile(constants.ProfileName)327 if err != nil {328 atexit.ExitWithMessage(1, err.Error())329 }330 }331}332func importContainerImages(driver drivers.Driver, api libmachine.API, openShiftVersion string) {333 if !viper.GetBool(configCmd.ImageCaching.Name) {334 return335 }336 images := viper.GetStringSlice(configCmd.CacheImages.Name)337 for _, coreImage := range image.GetOpenShiftImageNames(openShiftVersion) {338 if !stringUtils.Contains(images, coreImage) {339 images = append(images, coreImage)340 }341 }342 envMap, err := cluster.GetHostDockerEnv(api)343 if err != nil {344 atexit.ExitWithMessage(1, fmt.Sprintf("Error determining Docker settings for image import: %v", err))345 }346 handler := getImageHandler(driver, envMap)347 config := &image.ImageCacheConfig{348 HostCacheDir: state.InstanceDirs.ImageCache,349 CachedImages: images,350 Out: os.Stdout,351 }352 _, err = handler.ImportImages(config)353 if err != nil {354 fmt.Println(fmt.Sprintf(" WARN: At least one image could not be imported. Error: %s ", err.Error()))355 }356}357func getImageHandler(driver drivers.Driver, envMap map[string]string) image.ImageHandler {358 handler, err := image.NewOciImageHandler(driver, envMap)359 if err != nil {360 atexit.ExitWithMessage(1, fmt.Sprintf("Unable to create image handler: %v", err))361 }362 return handler363}364// exportContainerImages exports the OpenShift images in a background process (by calling 'minishift image export')365func exportContainerImages(driver drivers.Driver, api libmachine.API, version string) {366 if !viper.GetBool(configCmd.ImageCaching.Name) {367 return368 }369 images := viper.GetStringSlice(configCmd.CacheImages.Name)370 for _, coreImage := range image.GetOpenShiftImageNames(version) {371 if !stringUtils.Contains(images, coreImage) {372 images = append(images, coreImage)373 }374 }375 envMap, err := cluster.GetHostDockerEnv(api)376 if err != nil {377 atexit.ExitWithMessage(1, fmt.Sprintf("Error determining Docker settings for image import: %v", err))378 }379 handler := getImageHandler(driver, envMap)380 config := &image.ImageCacheConfig{381 HostCacheDir: state.InstanceDirs.ImageCache,382 CachedImages: images,383 }384 if handler.AreImagesCached(config) {385 return386 }387 exportCmd, err := image.CreateExportCommand(version, constants.ProfileName, images)388 if err != nil {389 atexit.ExitWithMessage(1, fmt.Sprintf("Error creating export command: %v", err))390 }391 err = exportCmd.Start()392 if err != nil {393 atexit.ExitWithMessage(1, fmt.Sprintf("Error during export: %v", err))394 }395 fmt.Println(fmt.Sprintf("-- Exporting of OpenShift images is occuring in background process with pid %d.", exportCmd.Process.Pid))396}397func calculateMemorySize(memorySize string) int {398 if stringUtils.HasOnlyNumbers(memorySize) {399 memorySize += "MB"400 }401 // err := minishiftConfig.IsValidMemorySize(configCmd.Memory.Name, humanReadableSize)402 size, err := units.RAMInBytes(memorySize)403 if err != nil {404 fmt.Println()405 atexit.ExitWithMessage(1, fmt.Sprintf("Memory size is not valid: %v", err))406 }407 return int(size / units.MiB)408}409func calculateDiskSize(humanReadableSize string) int {410 if stringUtils.HasOnlyNumbers(humanReadableSize) {411 humanReadableSize += "MB"412 }413 // err := minishiftConfig.IsValidDiskSize(configCmd.DiskSize.Name, humanReadableSize)414 size, err := units.FromHumanSize(humanReadableSize)415 if err != nil {416 fmt.Println()417 atexit.ExitWithMessage(1, fmt.Sprintf("Disk size is not valid: %v", err))418 }419 return int(size / units.MB)420}421func determineIsoUrl(iso string) string {422 isoNotSpecified := ""423 switch strings.ToLower(iso) {424 case minishiftConstants.B2dIsoAlias, isoNotSpecified:425 iso = constants.DefaultB2dIsoUrl426 case minishiftConstants.CentOsIsoAlias:427 iso = constants.DefaultCentOsIsoUrl428 case minishiftConstants.MinikubeIsoAlias:429 iso = constants.DefaultMinikubeIsoURL430 default:431 if !(govalidator.IsURL(iso) || strings.HasPrefix(iso, "file:")) {432 fmt.Println()433 atexit.ExitWithMessage(1, unsupportedIsoUrlFormat)434 }435 }436 return iso437}438// initStartFlags creates the CLI flags which needs to be passed on to 'libmachine'439func initStartFlags() *flag.FlagSet {440 startFlagSet := flag.NewFlagSet(commandName, flag.ContinueOnError)441 startFlagSet.String(configCmd.VmDriver.Name, constants.DefaultVMDriver, fmt.Sprintf("The driver to use for the Minishift VM. Possible values: %v", constants.SupportedVMDrivers))442 startFlagSet.Int(configCmd.CPUs.Name, constants.DefaultCPUS, "Number of CPU cores to allocate to the Minishift VM.")443 startFlagSet.String(configCmd.Memory.Name, constants.DefaultMemory, "Amount of RAM to allocate to the Minishift VM. Use the format <size><unit>, where unit = MB or GB.")444 startFlagSet.String(configCmd.DiskSize.Name, constants.DefaultDiskSize, "Disk size to allocate to the Minishift VM. Use the format <size><unit>, where unit = MB or GB.")445 startFlagSet.String(configCmd.HostOnlyCIDR.Name, "192.168.99.1/24", "The CIDR to be used for the minishift VM. (Only supported with VirtualBox driver.)")446 startFlagSet.AddFlag(dockerEnvFlag)447 startFlagSet.AddFlag(dockerEngineOptFlag)448 startFlagSet.AddFlag(insecureRegistryFlag)449 startFlagSet.AddFlag(registryMirrorFlag)450 startFlagSet.AddFlag(cmdUtil.AddOnEnvFlag)451 if minishiftConfig.EnableExperimental && runtime.GOOS == "windows" {452 startFlagSet.String(configCmd.NetworkDevice.Name, "eth0", "Specify the network device to use for the IP address. Ignored if no IP address specified (experimental - Hyper-V only)")453 startFlagSet.String(configCmd.IPAddress.Name, "", "Specify IP address to assign to the instance (experimental - Hyper-V only)")454 startFlagSet.String(configCmd.Netmask.Name, "24", "Specify netmask to use for the IP address. Ignored if no IP address specified (experimental - Hyper-V only)")455 startFlagSet.String(configCmd.Gateway.Name, "", "Specify gateway to use for the instance. Ignored if no IP address specified (experimental - Hyper-V only)")456 startFlagSet.String(configCmd.NameServer.Name, "8.8.8.8", "Specify nameserver to use for the instance. Ignored if no IP address specified (experimental - Hyper-V only)")457 }458 if minishiftConfig.EnableExperimental {459 startFlagSet.String(configCmd.ISOUrl.Name, minishiftConstants.B2dIsoAlias, "Location of the minishift ISO. Can be an URL, file URI or one of the following short names: [b2d centos minikube].")460 } else {461 startFlagSet.String(configCmd.ISOUrl.Name, minishiftConstants.B2dIsoAlias, "Location of the minishift ISO. Can be an URL, file URI or one of the following short names: [b2d centos].")462 }463 return startFlagSet464}465// initClusterUpFlags creates the CLI flags which needs to be passed on to 'oc cluster up'466func initClusterUpFlags() *flag.FlagSet {467 clusterUpFlagSet := flag.NewFlagSet(commandName, flag.ContinueOnError)468 //clusterUpFlagSet.StringVar(&clusterUpConfig.Image, "image", "openshift/origin", "Specify the images to use for OpenShift")469 clusterUpFlagSet.Bool(configCmd.SkipRegistryCheck.Name, false, "Skip the Docker daemon registry check.")470 clusterUpFlagSet.String(configCmd.PublicHostname.Name, "", "Public hostname of the OpenShift cluster.")471 clusterUpFlagSet.String(configCmd.RoutingSuffix.Name, "", "Default suffix for the server routes.")472 clusterUpFlagSet.String(configCmd.HostConfigDir.Name, hostConfigDirectory, "Location of the OpenShift configuration on the Docker host.")473 clusterUpFlagSet.String(configCmd.HostVolumeDir.Name, hostVolumesDirectory, "Location of the OpenShift volumes on the Docker host.")474 clusterUpFlagSet.String(configCmd.HostDataDir.Name, hostDataDirectory, "Location of the OpenShift data on the Docker host. If not specified, etcd data will not be persisted on the host.")475 clusterUpFlagSet.String(configCmd.HostPvDir.Name, hostPvDirectory, "Directory on Docker host for OpenShift persistent volumes")476 clusterUpFlagSet.Int(configCmd.ServerLogLevel.Name, 0, "Log level for the OpenShift server.")477 clusterUpFlagSet.StringSliceVarP(&openShiftEnv, configCmd.OpenshiftEnv.Name, "e", []string{}, "Specify key-value pairs of environment variables to set on the OpenShift container.")478 clusterUpFlagSet.Bool(configCmd.Metrics.Name, false, "Install metrics (experimental)")479 clusterUpFlagSet.Bool(configCmd.Logging.Name, false, "Install logging (experimental)")480 clusterUpFlagSet.String(configCmd.OpenshiftVersion.Name, version.GetOpenShiftVersion(), fmt.Sprintf("The OpenShift version to run, eg. %s", version.GetOpenShiftVersion()))481 clusterUpFlagSet.String(configCmd.NoProxyList.Name, "", "List of hosts or subnets for which no proxy should be used.")482 clusterUpFlagSet.AddFlag(cmdUtil.HttpProxyFlag)483 clusterUpFlagSet.AddFlag(cmdUtil.HttpsProxyFlag)484 if minishiftConfig.EnableExperimental {485 clusterUpFlagSet.Bool(configCmd.ServiceCatalog.Name, false, "Install service catalog (experimental)")486 clusterUpFlagSet.String(configCmd.ExtraClusterUpFlags.Name, "", "Specify optional flags for use with 'cluster up' (unsupported)")487 }488 return clusterUpFlagSet489}490// initSubscriptionManagerFlags create the CLI flags which are needed for VM registration491func initSubscriptionManagerFlags() *flag.FlagSet {492 subscriptionManagerFlagSet := flag.NewFlagSet(commandName, flag.ContinueOnError)493 subscriptionManagerFlagSet.String(configCmd.Username.Name, "", "Username for the virtual machine registration.")494 subscriptionManagerFlagSet.String(configCmd.Password.Name, "", "Password for the virtual machine registration.")495 subscriptionManagerFlagSet.BoolVar(®istrationUtil.SkipRegistration, configCmd.SkipRegistration.Name, false, "Skip the virtual machine registration.")496 return subscriptionManagerFlagSet497}498// determineClusterUpParameters returns a map of flag names and values for the cluster up call.499func determineClusterUpParameters(config *clusterup.ClusterUpConfig) map[string]string {500 clusterUpParams := make(map[string]string)501 // Set default value for host config, data and volumes502 viper.Set(configCmd.HostConfigDir.Name, viper.GetString(configCmd.HostConfigDir.Name))503 viper.Set(configCmd.HostDataDir.Name, viper.GetString(configCmd.HostDataDir.Name))504 viper.Set(configCmd.HostVolumeDir.Name, viper.GetString(configCmd.HostVolumeDir.Name))505 viper.Set(configCmd.HostPvDir.Name, viper.GetString(configCmd.HostPvDir.Name))506 viper.Set(configCmd.RoutingSuffix.Name, config.RoutingSuffix)507 clusterUpFlagSet.VisitAll(func(flag *flag.Flag) {508 if viper.IsSet(flag.Name) {509 value := viper.GetString(flag.Name)510 key := flag.Name511 _, exists := minishiftToClusterUp[key]512 if exists {513 key = minishiftToClusterUp[key]514 }515 clusterUpParams[key] = value516 }517 })518 return clusterUpParams519}520func getDefaultRoutingPrefix(ip string) string {521 // prefer nip.io over xip.io. See GitHub issue #501522 if viper.IsSet(configCmd.RoutingSuffix.Name) {523 return viper.GetString(configCmd.RoutingSuffix.Name)524 } else {525 return ip + ".nip.io"526 }527}528func ensureNotRunning(client *libmachine.Client, machineName string) {529 if !cmdUtil.VMExists(client, machineName) {530 return531 }532 hostVm, err := client.Load(constants.MachineName)533 if err != nil {534 atexit.ExitWithMessage(1, err.Error())535 }536 if cmdUtil.IsHostRunning(hostVm.Driver) {537 atexit.ExitWithMessage(0, fmt.Sprintf("The '%s' VM is already running.", machineName))538 }539}540func validateOpenshiftVersion() {541 requestedVersion := viper.GetString(configCmd.OpenshiftVersion.Name)542 valid, err := openshiftVersion.IsGreaterOrEqualToBaseVersion(requestedVersion, constants.MinimumSupportedOpenShiftVersion)543 if err != nil {544 atexit.ExitWithMessage(1, err.Error())545 }546 if !valid {547 fmt.Printf("Minishift does not support OpenShift version %s. "+548 "You need to use a version >= %s\n", viper.GetString(configCmd.OpenshiftVersion.Name),549 constants.MinimumSupportedOpenShiftVersion)550 atexit.Exit(1)551 }552 // Make sure the version actually has a 'v' prefix. See https://github.com/minishift/minishift/issues/410553 if !strings.HasPrefix(requestedVersion, constants.VersionPrefix) {554 requestedVersion = constants.VersionPrefix + requestedVersion555 // this will make sure the right version is set in case the version comes from config file556 viper.Set(configCmd.OpenshiftVersion.Name, requestedVersion)557 // if the version was specified via the CLI we need to update the flag value558 startCmd.Flags().Lookup(configCmd.OpenshiftVersion.Name).Value.Set(requestedVersion)559 }560}561func setSubscriptionManagerParameters() {562 minishiftCluster.RegistrationParameters.Username = viper.GetString(configCmd.Username.Name)563 minishiftCluster.RegistrationParameters.Password = viper.GetString(configCmd.Password.Name)564 minishiftCluster.RegistrationParameters.IsTtySupported = util.IsTtySupported()565 minishiftCluster.RegistrationParameters.GetUsernameInteractive = getUsernameInteractive566 minishiftCluster.RegistrationParameters.GetPasswordInteractive = getPasswordInteractive567}568func getUsernameInteractive(message string) string {569 return util.ReadInputFromStdin(message)570}571func getPasswordInteractive(message string) string {572 return util.ReadPasswordFromStdin(message)573}574func applyDockerEnvToProcessEnv(libMachineClient *libmachine.Client) {575 // Making sure the required Docker environment variables are set to make 'cluster up' work576 envMap, err := cluster.GetHostDockerEnv(libMachineClient)577 for k, v := range envMap {578 os.Setenv(k, v)579 }580 if err != nil {581 atexit.ExitWithMessage(1, fmt.Sprintf("Error determining Docker settings: %v", err))582 }583}584func IsOpenShiftRunning(driver drivers.Driver) bool {585 sshCommander := provision.GenericSSHCommander{Driver: driver}586 dockerCommander := docker.NewVmDockerCommander(sshCommander)587 return openshift.IsRunning(dockerCommander)588}589func cacheMinishiftISO(config *cluster.MachineConfig) {590 if config.ShouldCacheMinikubeISO() {...
common.go
Source:common.go
...30)31// UndefinedParamValue defines what undefined parameters in the command line will initialise to32const UndefinedParamValue = ""33const CmdRoot = "core"34var mainLogger = flogging.MustGetLogger("main")35var logOutput = os.Stderr36var (37 defaultConnTimeout = 3 * time.Second38 // These function variables (xyzFnc) can be used to invoke corresponding xyz function39 // this will allow the invoking packages to mock these functions in their unit test cases40 // GetEndorserClientFnc is a function that returns a new endorser client connection41 // to the provided peer address using the TLS root cert file,42 // by default it is set to GetEndorserClient function43 GetEndorserClientFnc func(address, tlsRootCertFile string) (pb.EndorserClient, error)44 // GetPeerDeliverClientFnc is a function that returns a new deliver client connection45 // to the provided peer address using the TLS root cert file,46 // by default it is set to GetDeliverClient function47 GetPeerDeliverClientFnc func(address, tlsRootCertFile string) (pb.DeliverClient, error)48 // GetDeliverClientFnc is a function that returns a new deliver client connection49 // to the provided peer address using the TLS root cert file,50 // by default it is set to GetDeliverClient function51 GetDeliverClientFnc func(address, tlsRootCertFile string) (pb.Deliver_DeliverClient, error)52 // GetDefaultSignerFnc is a function that returns a default Signer(Default/PERR)53 // by default it is set to GetDefaultSigner function54 GetDefaultSignerFnc func() (msp.SigningIdentity, error)55 // GetBroadcastClientFnc returns an instance of the BroadcastClient interface56 // by default it is set to GetBroadcastClient function57 GetBroadcastClientFnc func() (BroadcastClient, error)58 // GetOrdererEndpointOfChainFnc returns orderer endpoints of given chain59 // by default it is set to GetOrdererEndpointOfChain function60 GetOrdererEndpointOfChainFnc func(chainID string, signer Signer,61 endorserClient pb.EndorserClient, cryptoProvider bccsp.BCCSP) ([]string, error)62 // GetClientCertificateFnc is a function that returns the client TLS certificate63 GetClientCertificateFnc func() (tls.Certificate, error)64)65type CommonClient struct {66 *comm.GRPCClient67 Address string68 sn string69}70func init() {71 GetEndorserClientFnc = GetEndorserClient72 GetDefaultSignerFnc = GetDefaultSigner73 GetBroadcastClientFnc = GetBroadcastClient74 GetOrdererEndpointOfChainFnc = GetOrdererEndpointOfChain75 GetDeliverClientFnc = GetDeliverClient76 GetPeerDeliverClientFnc = GetPeerDeliverClient77 GetClientCertificateFnc = GetClientCertificate78}79// InitConfig initializes viper config80func InitConfig(cmdRoot string) error {81 err := config.InitViper(nil, cmdRoot)82 if err != nil {83 return err84 }85 err = viper.ReadInConfig() // Find and read the config file86 if err != nil { // Handle errors reading the config file87 // The version of Viper we use claims the config type isn't supported when in fact the file hasn't been found88 // Display a more helpful message to avoid confusing the user.89 if strings.Contains(fmt.Sprint(err), "Unsupported Config Type") {90 return errors.New(fmt.Sprintf("Could not find config file. "+91 "Please make sure that FABRIC_CFG_PATH is set to a path "+92 "which contains %s.yaml", cmdRoot))93 } else {94 return errors.WithMessagef(err, "error when reading %s config file", cmdRoot)95 }96 }97 return nil98}99// InitCrypto initializes crypto for this peer100func InitCrypto(mspMgrConfigDir, localMSPID, localMSPType string) error {101 // Check whether msp folder exists102 fi, err := os.Stat(mspMgrConfigDir)103 if err != nil {104 return errors.Errorf("cannot init crypto, specified path \"%s\" does not exist or cannot be accessed: %v", mspMgrConfigDir, err)105 } else if !fi.IsDir() {106 return errors.Errorf("cannot init crypto, specified path \"%s\" is not a directory", mspMgrConfigDir)107 }108 // Check whether localMSPID exists109 if localMSPID == "" {110 return errors.New("the local MSP must have an ID")111 }112 // Init the BCCSP113 SetBCCSPKeystorePath()114 bccspConfig := factory.GetDefaultOpts()115 if err := viper.UnmarshalKey("peer.BCCSP", &bccspConfig); err != nil {116 return errors.WithMessage(err, "could not decode peer BCCSP configuration")117 }118 err = mspmgmt.LoadLocalMspWithType(mspMgrConfigDir, bccspConfig, localMSPID, localMSPType)119 if err != nil {120 return errors.WithMessagef(err, "error when setting up MSP of type %s from directory %s", localMSPType, mspMgrConfigDir)121 }122 return nil123}124// SetBCCSPKeystorePath sets the file keystore path for the SW BCCSP provider125// to an absolute path relative to the config file.126func SetBCCSPKeystorePath() {127 key := "peer.BCCSP.SW.FileKeyStore.KeyStore"128 if ksPath := config.GetPath(key); ksPath != "" {129 viper.Set(key, ksPath)130 }131}132// GetDefaultSigner return a default Signer(Default/PEER) for cli133func GetDefaultSigner() (msp.SigningIdentity, error) {134 signer, err := mspmgmt.GetLocalMSP(factory.GetDefault()).GetDefaultSigningIdentity()135 if err != nil {136 return nil, errors.WithMessage(err, "error obtaining the default signing identity")137 }138 return signer, err139}140// Signer defines the interface needed for signing messages141type Signer interface {142 Sign(msg []byte) ([]byte, error)143 Serialize() ([]byte, error)144}145// GetOrdererEndpointOfChain returns orderer endpoints of given chain146func GetOrdererEndpointOfChain(chainID string, signer Signer, endorserClient pb.EndorserClient, cryptoProvider bccsp.BCCSP) ([]string, error) {147 // query cscc for chain config block148 invocation := &pb.ChaincodeInvocationSpec{149 ChaincodeSpec: &pb.ChaincodeSpec{150 Type: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value["GOLANG"]),151 ChaincodeId: &pb.ChaincodeID{Name: "cscc"},152 Input: &pb.ChaincodeInput{Args: [][]byte{[]byte(cscc.GetChannelConfig), []byte(chainID)}},153 },154 }155 creator, err := signer.Serialize()156 if err != nil {157 return nil, errors.WithMessage(err, "error serializing identity for signer")158 }159 prop, _, err := protoutil.CreateProposalFromCIS(pcommon.HeaderType_CONFIG, "", invocation, creator)160 if err != nil {161 return nil, errors.WithMessage(err, "error creating GetChannelConfig proposal")162 }163 signedProp, err := protoutil.GetSignedProposal(prop, signer)164 if err != nil {165 return nil, errors.WithMessage(err, "error creating signed GetChannelConfig proposal")166 }167 proposalResp, err := endorserClient.ProcessProposal(context.Background(), signedProp)168 if err != nil {169 return nil, errors.WithMessage(err, "error endorsing GetChannelConfig")170 }171 if proposalResp == nil {172 return nil, errors.New("received nil proposal response")173 }174 if proposalResp.Response.Status != 0 && proposalResp.Response.Status != 200 {175 return nil, errors.Errorf("error bad proposal response %d: %s", proposalResp.Response.Status, proposalResp.Response.Message)176 }177 // parse config178 channelConfig := &pcommon.Config{}179 if err := proto.Unmarshal(proposalResp.Response.Payload, channelConfig); err != nil {180 return nil, errors.WithMessage(err, "error unmarshaling channel config")181 }182 bundle, err := channelconfig.NewBundle(chainID, channelConfig, cryptoProvider)183 if err != nil {184 return nil, errors.WithMessage(err, "error loading channel config")185 }186 return bundle.ChannelConfig().OrdererAddresses(), nil187}188// CheckLogLevel checks that a given log level string is valid189func CheckLogLevel(level string) error {190 if !flogging.IsValidLevel(level) {191 return errors.Errorf("invalid log level provided - %s", level)192 }193 return nil194}195func configFromEnv(prefix string) (address, override string, clientConfig comm.ClientConfig, err error) {196 address = viper.GetString(prefix + ".address")197 override = viper.GetString(prefix + ".tls.serverhostoverride")198 clientConfig = comm.ClientConfig{}199 connTimeout := viper.GetDuration(prefix + ".client.connTimeout")200 if connTimeout == time.Duration(0) {201 connTimeout = defaultConnTimeout202 }203 clientConfig.Timeout = connTimeout204 secOpts := comm.SecureOptions{205 UseTLS: viper.GetBool(prefix + ".tls.enabled"),206 RequireClientCert: viper.GetBool(prefix + ".tls.clientAuthRequired"),207 TimeShift: viper.GetDuration(prefix + ".tls.handshakeTimeShift"),208 }209 if secOpts.UseTLS {210 caPEM, res := ioutil.ReadFile(config.GetPath(prefix + ".tls.rootcert.file"))211 if res != nil {212 err = errors.WithMessage(res,213 fmt.Sprintf("unable to load %s.tls.rootcert.file", prefix))214 return215 }216 secOpts.ServerRootCAs = [][]byte{caPEM}217 }218 if secOpts.RequireClientCert {219 secOpts.Key, secOpts.Certificate, err = getClientAuthInfoFromEnv(prefix)220 if err != nil {221 return222 }223 }224 clientConfig.SecOpts = secOpts225 return226}227// getClientAuthInfoFromEnv reads client tls key file and cert file and returns the bytes for the files228func getClientAuthInfoFromEnv(prefix string) ([]byte, []byte, error) {229 keyPEM, err := ioutil.ReadFile(config.GetPath(prefix + ".tls.clientKey.file"))230 if err != nil {231 return nil, nil, errors.WithMessagef(err, "unable to load %s.tls.clientKey.file", prefix)232 }233 certPEM, err := ioutil.ReadFile(config.GetPath(prefix + ".tls.clientCert.file"))234 if err != nil {235 return nil, nil, errors.WithMessagef(err, "unable to load %s.tls.clientCert.file", prefix)236 }237 return keyPEM, certPEM, nil238}239func InitCmd(cmd *cobra.Command, args []string) {240 err := InitConfig(CmdRoot)241 if err != nil { // Handle errors reading the config file242 mainLogger.Errorf("Fatal error when initializing %s config : %s", CmdRoot, err)243 os.Exit(1)244 }245 // read in the legacy logging level settings and, if set,246 // notify users of the FABRIC_LOGGING_SPEC env variable247 var loggingLevel string248 if viper.GetString("logging_level") != "" {249 loggingLevel = viper.GetString("logging_level")250 } else {251 loggingLevel = viper.GetString("logging.level")252 }253 if loggingLevel != "" {254 mainLogger.Warning("CORE_LOGGING_LEVEL is no longer supported, please use the FABRIC_LOGGING_SPEC environment variable")255 }256 loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC")257 loggingFormat := os.Getenv("FABRIC_LOGGING_FORMAT")258 flogging.Init(flogging.Config{259 Format: loggingFormat,260 Writer: logOutput,261 LogSpec: loggingSpec,262 })263 // chaincode packaging does not require material from the local MSP264 if cmd.CommandPath() == "peer lifecycle chaincode package" {265 mainLogger.Debug("peer lifecycle chaincode package does not need to init crypto")266 return267 }268 // Init the MSP269 var mspMgrConfigDir = config.GetPath("peer.mspConfigPath")270 var mspID = viper.GetString("peer.localMspId")271 var mspType = viper.GetString("peer.localMspType")272 if mspType == "" {273 mspType = msp.ProviderTypeToString(msp.FABRIC)274 }275 err = InitCrypto(mspMgrConfigDir, mspID, mspType)276 if err != nil { // Handle errors reading the config file277 mainLogger.Errorf("Cannot run peer because %s", err.Error())278 os.Exit(1)279 }280}...
prow_test.go
Source:prow_test.go
...60 _, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Create(cm)61 assert.NoError(t, err)62 err = o.AddProwConfig()63 assert.NoError(t, err)64 cm, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})65 assert.NoError(t, err)66 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)67 assert.Equal(t, "debug", prowConfig.LogLevel)68 assert.NotEmpty(t, prowConfig.Presubmits["test/repo"])69}70func TestMergeProwPlugin(t *testing.T) {71 t.Parallel()72 o := TestOptions{}73 o.Setup()74 o.Kind = prow.Environment75 o.EnvironmentNamespace = "jx-staging"76 pluginConfig := &plugins.Configuration{}77 // pluginConfig.Welcome = plugins.Welcome{MessageTemplate: "okey dokey"}78 c, err := yaml.Marshal(pluginConfig)79 assert.NoError(t, err)80 data := make(map[string]string)81 data[prow.ProwPluginsFilename] = string(c)82 cm := &v1.ConfigMap{83 ObjectMeta: metav1.ObjectMeta{84 Name: prow.ProwPluginsConfigMapName,85 },86 Data: data,87 }88 _, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Create(cm)89 assert.NoError(t, err)90 err = o.AddProwPlugins()91 assert.NoError(t, err)92 cm, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwPluginsConfigMapName, metav1.GetOptions{})93 assert.NoError(t, err)94 yaml.Unmarshal([]byte(cm.Data[prow.ProwPluginsFilename]), &pluginConfig)95 // assert.Equal(t, "okey dokey", pluginConfig.Welcome.MessageTemplate)96 assert.Equal(t, "test/repo", pluginConfig.Approve[0].Repos[0])97}98func TestAddProwPlugin(t *testing.T) {99 t.Parallel()100 o := TestOptions{}101 o.Setup()102 o.Kind = prow.Environment103 o.EnvironmentNamespace = "jx-staging"104 o.Repos = append(o.Repos, "test/repo2")105 err := o.AddProwPlugins()106 assert.NoError(t, err)107 cm, err := o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwPluginsConfigMapName, metav1.GetOptions{})108 assert.NoError(t, err)109 pluginConfig := &plugins.Configuration{}110 yaml.Unmarshal([]byte(cm.Data[prow.ProwPluginsFilename]), &pluginConfig)111 assert.Equal(t, "test/repo", pluginConfig.Approve[0].Repos[0])112 assert.Equal(t, "test/repo2", pluginConfig.Approve[1].Repos[0])113}114func TestAddProwConfig(t *testing.T) {115 t.Parallel()116 o := TestOptions{}117 o.Setup()118 o.Kind = prow.Environment119 o.EnvironmentNamespace = "jx-staging"120 o.Repos = append(o.Repos, "test/repo2")121 err := o.AddProwConfig()122 assert.NoError(t, err)123 cm, err := o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})124 assert.NoError(t, err)125 prowConfig := &config.Config{}126 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)127 assert.NotEmpty(t, prowConfig.Presubmits["test/repo"])128 assert.NotEmpty(t, prowConfig.Presubmits["test/repo2"])129}130// make sure that rerunning addProwConfig replaces any modified changes in the configmap131func TestReplaceProwConfig(t *testing.T) {132 t.Parallel()133 o := TestOptions{}134 o.Setup()135 o.Kind = prow.Environment136 o.EnvironmentNamespace = "jx-staging"137 err := o.AddProwConfig()138 assert.NoError(t, err)139 // now modify the cm140 cm, err := o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})141 assert.NoError(t, err)142 prowConfig := &config.Config{}143 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)144 assert.Equal(t, 1, len(prowConfig.Tide.Queries[0].Repos))145 assert.Equal(t, 2, len(prowConfig.Tide.Queries[1].Repos))146 p := prowConfig.Presubmits["test/repo"]147 p[0].Agent = "foo"148 configYAML, err := yaml.Marshal(&prowConfig)149 assert.NoError(t, err)150 data := make(map[string]string)151 data[prow.ProwConfigFilename] = string(configYAML)152 cm = &v1.ConfigMap{153 Data: data,154 ObjectMeta: metav1.ObjectMeta{155 Name: prow.ProwConfigMapName,156 },157 }158 _, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Update(cm)159 // ensure the value was modified160 cm, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})161 assert.NoError(t, err)162 prowConfig = &config.Config{}163 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)164 p = prowConfig.Presubmits["test/repo"]165 assert.Equal(t, "foo", p[0].Agent)166 // generate the prow config again167 err = o.AddProwConfig()168 assert.NoError(t, err)169 // assert value is reset170 cm, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})171 assert.NoError(t, err)172 prowConfig = &config.Config{}173 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)174 assert.Equal(t, 1, len(prowConfig.Tide.Queries[0].Repos))175 assert.Equal(t, 2, len(prowConfig.Tide.Queries[1].Repos))176 p = prowConfig.Presubmits["test/repo"]177 assert.Equal(t, "knative-build", p[0].Agent)178 // add test/repo2179 o.Options.Repos = []string{"test/repo2"}180 o.Kind = prow.Application181 err = o.AddProwConfig()182 assert.NoError(t, err)183 cm, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})184 assert.NoError(t, err)185 prowConfig = &config.Config{}186 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)187 assert.Equal(t, 2, len(prowConfig.Tide.Queries[0].Repos))188 assert.Equal(t, 2, len(prowConfig.Tide.Queries[1].Repos))189 // add test/repo3190 o.Options.Repos = []string{"test/repo3"}191 o.Kind = prow.Application192 err = o.AddProwConfig()193 assert.NoError(t, err)194 cm, err = o.KubeClient.CoreV1().ConfigMaps(o.NS).Get(prow.ProwConfigMapName, metav1.GetOptions{})195 assert.NoError(t, err)196 prowConfig = &config.Config{}197 yaml.Unmarshal([]byte(cm.Data[prow.ProwConfigFilename]), &prowConfig)198 assert.Equal(t, 3, len(prowConfig.Tide.Queries[0].Repos))199 assert.Equal(t, 2, len(prowConfig.Tide.Queries[1].Repos))200}201func TestGetReleaseJobs(t *testing.T) {202 t.Parallel()203 o := TestOptions{}204 o.Setup()205 o.Options.Repos = []string{"test/repo"}206 o.Kind = prow.Application207 err := o.AddProwConfig()208 assert.NoError(t, err)209 // now lets get the release job210 names, err := o.GetReleaseJobs()211 assert.NotEmpty(t, names, err)212 assert.Equal(t, "test/repo/master", names[0])213}214func TestGetBuildSpec(t *testing.T) {215 t.Parallel()216 o := TestOptions{}217 o.Setup()218 o.Options.Repos = []string{"test/repo"}219 o.Kind = prow.Application220 err := o.AddProwConfig()221 assert.NoError(t, err)222 // now lets get the release job223 buildSpec, err := o.GetBuildSpec("test", "repo", "master")224 assert.NotEmpty(t, buildSpec, err)225}...
settings.go
Source:settings.go
...91 }92 var httpAddr string93 var baseURL string94 var websocketClientPort string95 httpAddrIP := viper.GetString("serverConfig.ServerAddr")96 httpAddrPort := viper.GetString("serverConfig.ServerPort")97 proxySet := viper.GetBool("reverseProxy.ProxyEnabled")98 websocketClientPort = strings.TrimLeft(viper.GetString("serverConfig.ServerPort"), ":") //Trimming off the colon in front of the port99 if proxySet {100 baseURL = viper.GetString("reverseProxy.BaseURL")101 fmt.Println("WebsocketClientPort", viper.GetString("serverConfig.ServerPort"))102 }103 seedRatioStop := viper.GetFloat64("serverConfig.SeedRatioStop")104 httpAddr = httpAddrIP + httpAddrPort105 pushBulletToken := viper.GetString("notifications.PushBulletToken")106 defaultMoveFolder := filepath.ToSlash(viper.GetString("serverConfig.DefaultMoveFolder")) //Converting the string literal into a filepath107 defaultMoveFolderAbs, err := filepath.Abs(defaultMoveFolder)108 if err != nil {109 fmt.Println("Failed creating absolute path for defaultMoveFolder", err)110 }111 torrentWatchFolder := filepath.ToSlash(viper.GetString("serverConfig.TorrentWatchFolder"))112 torrentWatchFolderAbs, err := filepath.Abs(torrentWatchFolder)113 if err != nil {114 fmt.Println("Failed creating absolute path for torrentWatchFolderAbs", err)115 }116 dataDir := filepath.ToSlash(viper.GetString("torrentClientConfig.DownloadDir")) //Converting the string literal into a filepath117 dataDirAbs, err := filepath.Abs(dataDir) //Converting to an absolute file path118 if err != nil {119 fmt.Println("Failed creating absolute path for dataDir", err)120 }121 var uploadRateLimiter *rate.Limiter122 var downloadRateLimiter *rate.Limiter123 uploadRate := viper.GetString("serverConfig.UploadRateLimit")124 downloadRate := viper.GetString("serverConfig.DownloadRateLimit")125 downloadRateLimiter, uploadRateLimiter = calculateRateLimiters(uploadRate, downloadRate)126 listenAddr := viper.GetString("torrentClientConfig.ListenAddr")127 disablePex := viper.GetBool("torrentClientConfig.DisablePEX")128 noDHT := viper.GetBool("torrentClientConfig.NoDHT")129 noUpload := viper.GetBool("torrentClientConfig.NoUpload")130 seed := viper.GetBool("torrentClientConfig.Seed")131 peerID := viper.GetString("torrentClientConfig.PeerID")132 disableUTP := viper.GetBool("torrentClientConfig.DisableUTP")133 disableTCP := viper.GetBool("torrentClientConfig.DisableTCP")134 disableIPv6 := viper.GetBool("torrentClientConfig.DisableIPv6")135 debug := viper.GetBool("torrentClientConfig.Debug")136 logLevelString := viper.GetString("serverConfig.LogLevel")137 logOutput := viper.GetString("serverConfig.LogOutput")138 var logLevel logrus.Level139 switch logLevelString { //Options = Debug 5, Info 4, Warn 3, Error 2, Fatal 1, Panic 0140 case "Panic":141 logLevel = 0142 case "Fatal":143 logLevel = 1144 case "Error":145 logLevel = 2146 case "Warn":147 logLevel = 3148 case "Info":149 logLevel = 4150 case "Debug":151 logLevel = 5152 default:153 logLevel = 3154 }155 dhtServerConfig := dht.ServerConfig{156 StartingNodes: dht.GlobalBootstrapAddrs,157 }158 if viper.IsSet("DHTConfig") {159 fmt.Println("Reading in custom DHT config")160 dhtServerConfig = dhtServerSettings(dhtServerConfig)161 }162 encryptionPolicy := torrent.EncryptionPolicy{163 DisableEncryption: viper.GetBool("EncryptionPolicy.DisableEncryption"),164 ForceEncryption: viper.GetBool("EncryptionPolicy.ForceEncryption"),165 PreferNoEncryption: viper.GetBool("EncryptionPolicy.PreferNoEncryption"),166 }167 tConfig := torrent.Config{168 DataDir: dataDirAbs,169 ListenAddr: listenAddr,170 DisablePEX: disablePex,171 NoDHT: noDHT,172 DHTConfig: dhtServerConfig,173 NoUpload: noUpload,174 Seed: seed,175 UploadRateLimiter: uploadRateLimiter,176 DownloadRateLimiter: downloadRateLimiter,177 PeerID: peerID,178 DisableUTP: disableUTP,179 DisableTCP: disableTCP,...
config.go
Source:config.go
...78// set of source adapter configuration parameters.79type EnvConfigAccessor interface {80 // Set the component name.81 SetComponent(string)82 // Get the URI where messages will be forwarded to.83 GetSink() string84 // Get the namespace of the adapter.85 GetNamespace() string86 // Get the name of the adapter.87 GetName() string88 // Get the parsed metrics.ExporterOptions.89 GetMetricsConfig() (*metrics.ExporterOptions, error)90 // Get the parsed logger.91 GetLogger() *zap.SugaredLogger92 SetupTracing(*zap.SugaredLogger) error93 GetCloudEventOverrides() (*duckv1.CloudEventOverrides, error)94 // GetLeaderElectionConfig returns leader election configuration.95 GetLeaderElectionConfig() (*kle.ComponentConfig, error)96 // Get the timeout to apply on a request to a sink97 GetSinktimeout() int98}99var _ EnvConfigAccessor = (*EnvConfig)(nil)100func (e *EnvConfig) SetComponent(component string) {101 e.Component = component102}103func (e *EnvConfig) GetMetricsConfig() (*metrics.ExporterOptions, error) {104 // Convert json metrics.ExporterOptions to metrics.ExporterOptions.105 metricsConfig, err := metrics.JSONToOptions(e.MetricsConfigJson)106 if err != nil {107 return nil, err108 }109 return metricsConfig, err110}111func (e *EnvConfig) GetLogger() *zap.SugaredLogger {112 if e.logger == nil {113 loggingConfig, err := logging.JSONToConfig(e.LoggingConfigJson)114 if err != nil {115 // Use default logging config.116 if loggingConfig, err = logging.NewConfigFromMap(map[string]string{}); err != nil {117 // If this fails, there is no recovering.118 panic(err)119 }120 }121 logger, _ := logging.NewLoggerFromConfig(loggingConfig, e.Component)122 e.logger = logger123 }124 return e.logger125}126func (e *EnvConfig) GetSink() string {127 return e.Sink128}129func (e *EnvConfig) GetNamespace() string {130 return e.Namespace131}132func (e *EnvConfig) GetName() string {133 return e.Name134}135func (e *EnvConfig) GetSinktimeout() int {136 if duration, err := strconv.Atoi(e.EnvSinkTimeout); err == nil {137 return duration138 }139 e.GetLogger().Warn("Sink timeout configuration is invalid, default to -1 (no timeout)")140 return -1141}142func (e *EnvConfig) SetupTracing(logger *zap.SugaredLogger) error {143 config, err := tracingconfig.JSONToTracingConfig(e.TracingConfigJson)144 if err != nil {145 logger.Warn("Tracing configuration is invalid, using the no-op default", zap.Error(err))146 }147 return tracing.SetupStaticPublishing(logger, "", config)148}149func (e *EnvConfig) GetCloudEventOverrides() (*duckv1.CloudEventOverrides, error) {150 var ceOverrides duckv1.CloudEventOverrides151 if len(e.CEOverrides) > 0 {152 err := json.Unmarshal([]byte(e.CEOverrides), &ceOverrides)153 if err != nil {154 return nil, err155 }156 }157 return &ceOverrides, nil158}159func (e *EnvConfig) GetLeaderElectionConfig() (*kle.ComponentConfig, error) {160 if e.LeaderElectionConfigJson == "" {161 return e.defaultLeaderElectionConfig(), nil162 }163 var config kle.ComponentConfig164 if err := json.Unmarshal([]byte(e.LeaderElectionConfigJson), &config); err != nil {165 return e.defaultLeaderElectionConfig(), err166 }167 config.Component = e.Component168 return &config, nil169}170func (e *EnvConfig) defaultLeaderElectionConfig() *kle.ComponentConfig {171 return &kle.ComponentConfig{172 Component: e.Component,173 Buckets: 1,174 LeaseDuration: 15 * time.Second,175 RenewDeadline: 10 * time.Second,176 RetryPeriod: 2 * time.Second,177 }178}179// LeaderElectionComponentConfigToJSON converts a ComponentConfig to a json string.180func LeaderElectionComponentConfigToJSON(cfg *kle.ComponentConfig) (string, error) {181 if cfg == nil {182 return "", nil183 }184 jsonCfg, err := json.Marshal(cfg)185 return string(jsonCfg), err186}187func GetSinkTimeout(logger *zap.SugaredLogger) int {188 str := os.Getenv(EnvSinkTimeout)189 if str != "" {190 var err error191 duration, err := strconv.Atoi(str)192 if err != nil || duration < 0 {193 if logger != nil {194 logger.Errorf("%s environment value is invalid. It must be a integer greater than zero. (got %s)", EnvSinkTimeout, str)195 }196 return -1197 }198 return duration199 }200 return -1201}...
config_test.go
Source:config_test.go
...35 password: z3u536 - username: lowly37 password: f!r3m338`39var configGetTests = []struct {40 Spec string41 Want string42 Err string43}{44 {"mapping.key1", "value1", ""},45 {"mapping.key2", "value2", ""},46 {"list[0]", "item1", ""},47 {"list[1]", "item2", ""},48 {"list", "", `yaml: list: type mismatch: "list" is yaml.List, want yaml.Scalar (at "$")`},49 {"list.0", "", `yaml: .list.0: type mismatch: ".list" is yaml.List, want yaml.Map (at ".0")`},50 {"config.server[0]", "www.google.com", ""},51 {"config.server[1]", "www.cnn.com", ""},52 {"config.server[2]", "www.example.com", ""},53 {"config.server[3]", "", `yaml: .config.server[3]: ".config.server[3]" not found`},54 {"config.listen[0]", "", `yaml: .config.listen[0]: ".config.listen" not found`},55 {"config.admin[0].username", "god", ""},56 {"config.admin[1].username", "lowly", ""},57 {"config.admin[2].username", "", `yaml: .config.admin[2].username: ".config.admin[2]" not found`},58}59func TestGet(t *testing.T) {60 config := Config(dummyConfigFile)61 for _, test := range configGetTests {62 got, err := config.Get(test.Spec)63 if want := test.Want; got != want {64 t.Errorf("Get(%q) = %q, want %q", test.Spec, got, want)65 }66 switch err {67 case nil:68 got = ""69 default:70 got = err.Error()71 }72 if want := test.Err; got != want {73 t.Errorf("Get(%q) error %#q, want %#q", test.Spec, got, want)74 }75 }76 i, err := config.GetInt("mapping.key3")77 if err != nil || i != 5 {78 t.Errorf("GetInt mapping.key3 wrong")79 }80 b, err := config.GetBool("mapping.key4")81 if err != nil || b != true {82 t.Errorf("GetBool mapping.key4 wrong")83 }84 b, err = config.GetBool("mapping.key5")85 if err != nil || b != false {86 t.Errorf("GetBool mapping.key5 wrong")87 }88}
Get
Using AI Code Generation
1import (2func main() {3 panic(fmt.Errorf("Fatal error config file: %s \n", err))4 }5 fmt.Println("Reading config file")6 fmt.Println("Name : ", viper.Get("name"))7 fmt.Println("Age : ", viper.Get("age"))8 fmt.Println("Address : ", viper.Get("address"))9}10import (11func main() {12 panic(fmt.Errorf("Fatal error config file: %s \n", err))13 }14 fmt.Println("Reading config file")15 fmt.Println("Name : ", viper.GetString("name"))16 fmt.Println("Age : ", viper.GetInt("age"))17 fmt.Println("Address : ", viper.GetString("address"))18}19import (20func main() {21 panic(fmt.Errorf("Fatal error config file: %s \n", err))22 }23 fmt.Println("Reading config file")24 fmt.Println("Name : ", viper.GetString("name
Get
Using AI Code Generation
1import "fmt"2import "github.com/astaxie/beego/config"3func main() {4 config, err := config.NewConfig("ini", "conf/app.conf")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(config.String("appname"))9 fmt.Println(config.String("httpport"))10 fmt.Println(config.String("runmode"))11 fmt.Println(config.String("autorender"))12 fmt.Println(config.String("copyrequestbody"))13 fmt.Println(config.String("sessionon"))14 fmt.Println(config.String("sessionprovider"))15 fmt.Println(config.String("sessionname"))16 fmt.Println(config.String("sessiongcmaxlifetime"))17 fmt.Println(config.String("sessionproviderconfig"))18 fmt.Println(config.String("sessioncookiehashkey"))19 fmt.Println(config.String("sessioncookiedomain"))20 fmt.Println(config.String("sessioncookiepath"))21 fmt.Println(config.String("sessioncookielifetime"))22 fmt.Println(config.String("sessioncookiehashfunc"))23 fmt.Println(config.String("sessioncookiehashkey"))
Get
Using AI Code Generation
1import (2func main() {3 panic(fmt.Errorf("Fatal error config file: %s \n", err))4 }5 fmt.Println(viper.GetString("username"))6 fmt.Println(viper.GetString("password"))7}
Get
Using AI Code Generation
1import (2func main() {3 panic(fmt.Errorf("Fatal error config file: %s \n", err))4 }5}6viper.Set(key, value)7import (8func main() {9 panic(fmt.Errorf("Fatal error config file: %s \n", err))10 }11 viper.Set("name", "Rajat Singh")
Get
Using AI Code Generation
1import (2func main() {3 configObj, err := config.NewConfig("ini", configFile)4 if err != nil {5 fmt.Println("new config failed, err:", err)6 }7 port, err := configObj.Int("server::port")8 if err != nil {9 fmt.Println("get port failed, err:", err)10 }11 fmt.Println("port:", port)12}13import (14func main() {15 configObj, err := config.NewConfig("ini", configFile)16 if err != nil {17 fmt.Println("new config failed, err:", err)18 }19 port, err := configObj.Int("server::port")20 if err != nil {21 fmt.Println("get port failed, err:", err)22 }23 fmt.Println("port:", port)24 section, err := configObj.GetSection("server")25 if err != nil {26 fmt.Println("get section failed, err:", err)27 }28 fmt.Println("section:", section)29}30import (31func main() {32 configObj, err := config.NewConfig("ini", configFile)33 if err != nil {34 fmt.Println("new config failed, err:", err)35 }36 port, err := configObj.Int("server::port")37 if err != nil {38 fmt.Println("get port failed, err:", err)39 }40 fmt.Println("port:", port)
Get
Using AI Code Generation
1import (2func main() {3 config.Get()4 fmt.Println("Hello, world.")5}6import (7func Get() {8 fmt.Println("Get method of config class")9}10./2.go:4: imported and not used: "config"11package github.com/xxx/config: code in directory /home/xxx/go/src/github.com/xxx/config expects import "config"
Get
Using AI Code Generation
1import (2func main() {3 c := config.NewConfig("config.ini")4 value := c.Get("key")5 fmt.Println(value)6}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!